<commit_before>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * 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 <gtest/gtest.h>
#include <iostream>
#include <string>
#include <thread>
#include <vector>
#include "cybertron/class_loader/class_loader.h"
#include "cybertron/class_loader/class_loader_manager.h"
#include "cybertron/cybertron.h"
#include "cybertron/test/class_loader/base.h"

const char LIBRARY_1[] = "libTestPlugins1.so";
const char LIBRARY_2[] = "libTestPlugins2.so";
using apollo::cybertron::class_loader::ClassLoader;
using apollo::cybertron::class_loader::ClassLoaderManager;
using apollo::cybertron::class_loader::utility::IsLibraryLoadedByAnybody;

TEST(ClassLoaderTest, createClassObj) {
  ClassLoader loader1(LIBRARY_1);
  EXPECT_EQ(LIBRARY_1, loader1.GetLibraryPath());
  auto rect_obj = loader1.CreateClassObj<Base>("Rect");
  EXPECT_TRUE(nullptr != rect_obj);
  if (rect_obj) {
    rect_obj->DoSomething();
  }
  EXPECT_EQ(nullptr, loader1.CreateClassObj<Base>("Xeee"));
  SUCCEED();
}

TEST(ClassLoaderTest, loadLibCounts) {
  ClassLoader loader1(LIBRARY_1);
  ASSERT_TRUE(loader1.IsLibraryLoaded());

  loader1.LoadLibrary();
  loader1.LoadLibrary();
  ASSERT_TRUE(loader1.IsLibraryLoaded());

  loader1.UnloadLibrary();
  ASSERT_TRUE(loader1.IsLibraryLoaded());

  loader1.UnloadLibrary();
  ASSERT_TRUE(loader1.IsLibraryLoaded());

  loader1.UnloadLibrary();
  ASSERT_FALSE(loader1.IsLibraryLoaded());

  loader1.UnloadLibrary();
  ASSERT_FALSE(loader1.IsLibraryLoaded());

  loader1.LoadLibrary();
  ASSERT_TRUE(loader1.IsLibraryLoaded());

  SUCCEED();
}

TEST(ClassLoaderTest, multiTimesLoadunload) {
  ClassLoader loader1(LIBRARY_1);
  ASSERT_TRUE(loader1.LoadLibrary());
  loader1.LoadLibrary();
  ASSERT_TRUE(IsLibraryLoadedByAnybody(LIBRARY_1));
  loader1.UnloadLibrary();
  ASSERT_TRUE(IsLibraryLoadedByAnybody(LIBRARY_1));
  loader1.UnloadLibrary();
  ASSERT_TRUE(IsLibraryLoadedByAnybody(LIBRARY_1));
  loader1.UnloadLibrary();
  ASSERT_FALSE(IsLibraryLoadedByAnybody(LIBRARY_1));

  return;
}

TEST(ClassLoaderManagerTest, testClassLoaderManager) {
  ClassLoaderManager loader_mgr;
  ASSERT_TRUE(loader_mgr.LoadLibrary(LIBRARY_1));
  ASSERT_TRUE(loader_mgr.LoadLibrary(LIBRARY_2));
  for (int i = 0; i < 2; ++i) {
    loader_mgr.CreateClassObj<Base>("Rect")->DoSomething();
    loader_mgr.CreateClassObj<Base>("Circle")->DoSomething();
    loader_mgr.CreateClassObj<Base>("Apple")->DoSomething();
  }

  auto pear_obj = loader_mgr.CreateClassObj<Base>("Pear", LIBRARY_2);
  EXPECT_TRUE(nullptr != pear_obj);
  pear_obj->DoSomething();

  auto null_obj = loader_mgr.CreateClassObj<Base>("Pear", LIBRARY_1);
  EXPECT_TRUE(nullptr == null_obj);
  auto null_obj1 = loader_mgr.CreateClassObj<Base>("ＣlassNull", "libNull.so");
  EXPECT_TRUE(nullptr == null_obj1);

  EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Rect"));
  EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Circle"));
  EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Triangle"));
  EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Star"));
  EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Apple"));
  EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Pear"));
  EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Banana"));
  EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Peach"));
  EXPECT_FALSE(loader_mgr.IsClassValid<Base>("Hamburger"));
  EXPECT_FALSE(loader_mgr.IsClassValid<Base>("Cake"));

  EXPECT_TRUE(loader_mgr.LoadLibrary(LIBRARY_1));
  SUCCEED();
}

void CreateObj(ClassLoaderManager* loader) {
  std::vector<std::string> classes = loader->GetValidClassNames<Base>();
  for (unsigned int i = 0; i < classes.size(); i++) {
    loader->CreateClassObj<Base>(classes[i])->DoSomething();
  }
}

TEST(ClassLoaderTest, createObjThreadSafety) {
  ClassLoaderManager loader_mgr;
  ASSERT_TRUE(loader_mgr.LoadLibrary(LIBRARY_1));
  ASSERT_TRUE(loader_mgr.IsLibraryValid(LIBRARY_1));

  std::vector<std::thread*> client_threads;

  for (unsigned int i = 0; i < 100; i++) {
    client_threads.emplace_back(new std::thread(std::bind(&CreateObj, &loader_mgr)));
  }

  for (unsigned int i = 0; i < client_threads.size(); i++) {
    client_threads[i]->join();
  }

  for (unsigned int i = 0; i < client_threads.size(); i++) {
    delete (client_threads[i]);
  }
}

void LoadLib(ClassLoaderManager* loaderMgr) {
  loaderMgr->LoadLibrary(LIBRARY_1);
  ASSERT_TRUE(loaderMgr->IsLibraryValid(LIBRARY_1));
}

TEST(ClassLoaderTest, loadLibThreadSafety) {
  ClassLoaderManager loaderMgr;
  std::vector<std::thread*> client_threads;

  for (unsigned int i = 0; i < 100; i++) {
    client_threads.emplace_back(new std::thread(std::bind(&LoadLib, &loaderMgr)));
  }

  for (unsigned int i = 0; i < client_threads.size(); i++) {
    client_threads[i]->join();
  }
  ASSERT_TRUE(loaderMgr.IsLibraryValid(LIBRARY_1));
  for (unsigned int i = 0; i < client_threads.size(); i++) {
    delete (client_threads[i]);
  }

  loaderMgr.UnloadAllLibrary();
  ASSERT_FALSE(loaderMgr.IsLibraryValid(LIBRARY_1));
}

class InvalidBaseClass {};

TEST(ClassLoaderTest, invalidBaseClass) {
  ClassLoader loader1(LIBRARY_1);
  ASSERT_FALSE(loader1.IsClassValid<InvalidBaseClass>("InvalidBaseClass"));
  if (loader1.IsClassValid<InvalidBaseClass>("Rect")) {
    FAIL() << "Rect is invalid for InvalidBaseClass";
  } else if (loader1.IsClassValid<Base>("Rect")) {
    SUCCEED();
    return;
  } else {
    FAIL() << "baseClass not valid for Rect";
  }
}

int main(int argc, char** argv) {
  apollo::cybertron::Init(argv[0]);
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>framework: change path of shared library used by unit test<commit_after>/******************************************************************************
 * Copyright 2018 The Apollo Authors. All Rights Reserved.
 *
 * 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 <gtest/gtest.h>
#include <iostream>
#include <string>
#include <thread>
#include <vector>

#include "cybertron/class_loader/class_loader.h"
#include "cybertron/class_loader/class_loader_manager.h"
#include "cybertron/cybertron.h"
#include "cybertron/test/class_loader/base.h"

namespace apollo {
namespace cybertron {
namespace class_loader {

using utility::IsLibraryLoadedByAnybody;

class ClassLoaderTest : public ::testing::Test {
 protected:
  ClassLoaderTest() {
    const char* cybertron_path = ::getenv("CYBERTRON_PATH");
    std::string test_path(cybertron_path);
    test_path += "/test/cybertron/unit_test/";
    library_1_ = test_path + "libTestPlugins1.so";
    library_2_ = test_path + "libTestPlugins2.so";
  }

  virtual ~ClassLoaderTest() {}

  virtual void SetUp() {}

  virtual void TearDown() {}

  class InvalidBaseClass {};

  void CreateObj(ClassLoaderManager* loader) {
    std::vector<std::string> classes = loader->GetValidClassNames<Base>();
    for (size_t i = 0; i < classes.size(); ++i) {
      loader->CreateClassObj<Base>(classes[i])->DoSomething();
    }
  }

  void LoadLib(ClassLoaderManager* loaderMgr) {
    loaderMgr->LoadLibrary(library_1_);
    ASSERT_TRUE(loaderMgr->IsLibraryValid(library_1_));
  }

  std::string library_1_;
  std::string library_2_;
};

TEST_F(ClassLoaderTest, createClassObj) {
  ClassLoader loader1(library_1_);
  EXPECT_EQ(library_1_, loader1.GetLibraryPath());
  auto rect_obj = loader1.CreateClassObj<Base>("Rect");
  EXPECT_TRUE(nullptr != rect_obj);
  if (rect_obj) {
    rect_obj->DoSomething();
  }
  EXPECT_EQ(nullptr, loader1.CreateClassObj<Base>("Xeee"));
  SUCCEED();
}

TEST_F(ClassLoaderTest, loadLibCounts) {
  ClassLoader loader1(library_1_);
  ASSERT_TRUE(loader1.IsLibraryLoaded());

  loader1.LoadLibrary();
  loader1.LoadLibrary();
  ASSERT_TRUE(loader1.IsLibraryLoaded());

  loader1.UnloadLibrary();
  ASSERT_TRUE(loader1.IsLibraryLoaded());

  loader1.UnloadLibrary();
  ASSERT_TRUE(loader1.IsLibraryLoaded());

  loader1.UnloadLibrary();
  ASSERT_FALSE(loader1.IsLibraryLoaded());

  loader1.UnloadLibrary();
  ASSERT_FALSE(loader1.IsLibraryLoaded());

  loader1.LoadLibrary();
  ASSERT_TRUE(loader1.IsLibraryLoaded());

  SUCCEED();
}

TEST_F(ClassLoaderTest, multiTimesLoadunload) {
  ClassLoader loader1(library_1_);
  ASSERT_TRUE(loader1.LoadLibrary());
  loader1.LoadLibrary();
  ASSERT_TRUE(IsLibraryLoadedByAnybody(library_1_));
  loader1.UnloadLibrary();
  ASSERT_TRUE(IsLibraryLoadedByAnybody(library_1_));
  loader1.UnloadLibrary();
  ASSERT_TRUE(IsLibraryLoadedByAnybody(library_1_));
  loader1.UnloadLibrary();
  ASSERT_FALSE(IsLibraryLoadedByAnybody(library_1_));

  return;
}

TEST_F(ClassLoaderTest, testClassLoaderManager) {
  ClassLoaderManager loader_mgr;
  ASSERT_TRUE(loader_mgr.LoadLibrary(library_1_));
  ASSERT_TRUE(loader_mgr.LoadLibrary(library_2_));
  for (int i = 0; i < 2; ++i) {
    loader_mgr.CreateClassObj<Base>("Rect")->DoSomething();
    loader_mgr.CreateClassObj<Base>("Circle")->DoSomething();
    loader_mgr.CreateClassObj<Base>("Apple")->DoSomething();
  }

  auto pear_obj = loader_mgr.CreateClassObj<Base>("Pear", library_2_);
  EXPECT_TRUE(nullptr != pear_obj);
  pear_obj->DoSomething();

  auto null_obj = loader_mgr.CreateClassObj<Base>("Pear", library_1_);
  EXPECT_TRUE(nullptr == null_obj);
  auto null_obj1 = loader_mgr.CreateClassObj<Base>("ＣlassNull", "libNull.so");
  EXPECT_TRUE(nullptr == null_obj1);

  EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Rect"));
  EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Circle"));
  EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Triangle"));
  EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Star"));
  EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Apple"));
  EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Pear"));
  EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Banana"));
  EXPECT_TRUE(loader_mgr.IsClassValid<Base>("Peach"));
  EXPECT_FALSE(loader_mgr.IsClassValid<Base>("Hamburger"));
  EXPECT_FALSE(loader_mgr.IsClassValid<Base>("Cake"));

  EXPECT_TRUE(loader_mgr.LoadLibrary(library_1_));
  SUCCEED();
}

TEST_F(ClassLoaderTest, createObjThreadSafety) {
  ClassLoaderManager loader_mgr;
  ASSERT_TRUE(loader_mgr.LoadLibrary(library_1_));
  ASSERT_TRUE(loader_mgr.IsLibraryValid(library_1_));

  std::vector<std::thread*> client_threads;

  for (unsigned int i = 0; i < 100; i++) {
    client_threads.emplace_back(new std::thread(
        std::bind(&ClassLoaderTest::CreateObj, this, &loader_mgr)));
  }

  for (unsigned int i = 0; i < client_threads.size(); i++) {
    client_threads[i]->join();
  }

  for (unsigned int i = 0; i < client_threads.size(); i++) {
    delete (client_threads[i]);
  }
}

TEST_F(ClassLoaderTest, loadLibThreadSafety) {
  ClassLoaderManager loaderMgr;
  std::vector<std::thread*> client_threads;

  for (unsigned int i = 0; i < 100; i++) {
    client_threads.emplace_back(new std::thread(
        std::bind(&ClassLoaderTest::LoadLib, this, &loaderMgr)));
  }

  for (unsigned int i = 0; i < client_threads.size(); i++) {
    client_threads[i]->join();
  }
  ASSERT_TRUE(loaderMgr.IsLibraryValid(library_1_));
  for (unsigned int i = 0; i < client_threads.size(); i++) {
    delete (client_threads[i]);
  }

  loaderMgr.UnloadAllLibrary();
  ASSERT_FALSE(loaderMgr.IsLibraryValid(library_1_));
}

TEST_F(ClassLoaderTest, invalidBaseClass) {
  ClassLoader loader1(library_1_);
  ASSERT_FALSE(loader1.IsClassValid<InvalidBaseClass>("InvalidBaseClass"));
  if (loader1.IsClassValid<InvalidBaseClass>("Rect")) {
    FAIL() << "Rect is invalid for InvalidBaseClass";
  } else if (loader1.IsClassValid<Base>("Rect")) {
    SUCCEED();
    return;
  } else {
    FAIL() << "baseClass not valid for Rect";
  }
}

}  // namespace class_loader
}  // namespace cybertron
}  // namespace apollo

int main(int argc, char** argv) {
  apollo::cybertron::Init(argv[0]);
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>/*                            Package   : libhex
 * boundingbox.cc             Created   : 2008/02/24
 *                            Author    : Alex Tingle
 *
 *    Copyright (C) 2008, Alex Tingle.
 *
 *    This file is part of the libhex application.
 *
 *    libhex is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation; either
 *    version 2.1 of the License, or (at your option) any later version.
 *
 *    libhex is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "hex.h"

#include <cmath>

namespace hex {

std::set<Hex*>
BoundingBox::hexes(void) const
{
  // FIXME: Correct this algorithm so that it only yields hexes that are
  // actually in the bbox - and includes all of the hexes that ARE.
  std::set<Hex*> result;
  for(int i=hex0->i; i<=hex1->i; ++i)
    for(int j=hex0->j; j<=hex1->j; ++j)
      result.insert(hex0->grid().hex(i,j));
  return result;
}

void BoundingBox::frame(void)
{
  point0.x -= (hex::I / 2.0);
  point0.y -= hex::K;
  point1.x += (hex::I / 2.0);
  point1.y += hex::K;
}

BoundingBox::BoundingBox(
    const Point& point0_, const Point& point1_,
    Hex* const hex0_, Hex* const hex1_
  )
  : point0( point0_ ),
    point1( point1_ ),
    hex0( hex0_ ),
    hex1( hex1_ )
{}

BoundingBox::BoundingBox(const Grid& grid, bool frame_)
{
  Hex* h0 = grid.hex(0,0);
  Hex* h1 = grid.hex( grid.cols()-1, grid.rows()-1 );
  *this = BoundingBox(h0,h1,frame_);
}

BoundingBox::BoundingBox(const std::set<Hex*>& a, bool frame_)
  throw (hex::invalid_argument)
{
  if(a.empty())
      throw hex::invalid_argument("BoundingBox(<empty set>)");
  int i0 = INT_MAX;
  int j0 = INT_MAX;
  int i1 = INT_MIN;
  int j1 = INT_MIN;
  for(std::set<Hex*>::const_iterator h=a.begin(); h!=a.end(); ++h)
  {
    i0 = std::min(i0,(**h).i);
    j0 = std::min(j0,(**h).j);
    i1 = std::max(i1,(**h).i);
    j1 = std::max(j1,(**h).j);
  }
  const Grid& g = (**a.begin()).grid();
  Hex* hex0 = g.hex(i0,j0);
  Hex* hex1 = g.hex(i1,j1);
  *this = BoundingBox(hex0,hex1,frame_);
}

BoundingBox::BoundingBox(const Grid& grid, const Point& p0, const Point& p1)
{
  int i0 = std::max( 0, int(p0.x)-1 ); // Calculate the boundary hexes.
  int j0 = std::max( 0, int(p0.y / hex::J) );
  int i1 = std::min( grid.cols()-1, int( ceil(p1.x) ) );
  int j1 = std::min( grid.rows()-1, int( ceil(p1.y / hex::J) ) );
  *this = BoundingBox(p0, p1, grid.hex(i0,j0), grid.hex(i1,j1));
}

BoundingBox::BoundingBox(Hex* hex0_, Hex* hex1_, bool frame_)
{
  Point p0 =hex0_->centre();
  Point p1 =hex1_->centre();
  if(hex1_->j != hex0_->j)
  {
    if( hex1_->j % 2 )
      p1.x += (hex::I/2.0);
    if( (hex0_->j % 2)==0 )
      p1.x += (hex::I/2.0);
  }
  *this = BoundingBox(p0, p1, hex0_, hex1_);
  if(frame_)
      frame();
}

} // end namespace hex
<commit_msg>Now compikes with GCC 4.4.<commit_after>/*                            Package   : libhex
 * boundingbox.cc             Created   : 2008/02/24
 *                            Author    : Alex Tingle
 *
 *    Copyright (C) 2008, Alex Tingle.
 *
 *    This file is part of the libhex application.
 *
 *    libhex is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License as published by the Free Software Foundation; either
 *    version 2.1 of the License, or (at your option) any later version.
 *
 *    libhex is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "hex.h"

#include <cmath>
#include <limits>

namespace hex {

std::set<Hex*>
BoundingBox::hexes(void) const
{
  // FIXME: Correct this algorithm so that it only yields hexes that are
  // actually in the bbox - and includes all of the hexes that ARE.
  std::set<Hex*> result;
  for(int i=hex0->i; i<=hex1->i; ++i)
    for(int j=hex0->j; j<=hex1->j; ++j)
      result.insert(hex0->grid().hex(i,j));
  return result;
}

void BoundingBox::frame(void)
{
  point0.x -= (hex::I / 2.0);
  point0.y -= hex::K;
  point1.x += (hex::I / 2.0);
  point1.y += hex::K;
}

BoundingBox::BoundingBox(
    const Point& point0_, const Point& point1_,
    Hex* const hex0_, Hex* const hex1_
  )
  : point0( point0_ ),
    point1( point1_ ),
    hex0( hex0_ ),
    hex1( hex1_ )
{}

BoundingBox::BoundingBox(const Grid& grid, bool frame_)
{
  Hex* h0 = grid.hex(0,0);
  Hex* h1 = grid.hex( grid.cols()-1, grid.rows()-1 );
  *this = BoundingBox(h0,h1,frame_);
}

BoundingBox::BoundingBox(const std::set<Hex*>& a, bool frame_)
  throw (hex::invalid_argument)
{
  if(a.empty())
      throw hex::invalid_argument("BoundingBox(<empty set>)");
  int i0 = std::numeric_limits<int>::max();
  int j0 = std::numeric_limits<int>::max();
  int i1 = std::numeric_limits<int>::min();
  int j1 = std::numeric_limits<int>::min();
  for(std::set<Hex*>::const_iterator h=a.begin(); h!=a.end(); ++h)
  {
    i0 = std::min(i0,(**h).i);
    j0 = std::min(j0,(**h).j);
    i1 = std::max(i1,(**h).i);
    j1 = std::max(j1,(**h).j);
  }
  const Grid& g = (**a.begin()).grid();
  Hex* hex0 = g.hex(i0,j0);
  Hex* hex1 = g.hex(i1,j1);
  *this = BoundingBox(hex0,hex1,frame_);
}

BoundingBox::BoundingBox(const Grid& grid, const Point& p0, const Point& p1)
{
  int i0 = std::max( 0, int(p0.x)-1 ); // Calculate the boundary hexes.
  int j0 = std::max( 0, int(p0.y / hex::J) );
  int i1 = std::min( grid.cols()-1, int( ceil(p1.x) ) );
  int j1 = std::min( grid.rows()-1, int( ceil(p1.y / hex::J) ) );
  *this = BoundingBox(p0, p1, grid.hex(i0,j0), grid.hex(i1,j1));
}

BoundingBox::BoundingBox(Hex* hex0_, Hex* hex1_, bool frame_)
{
  Point p0 =hex0_->centre();
  Point p1 =hex1_->centre();
  if(hex1_->j != hex0_->j)
  {
    if( hex1_->j % 2 )
      p1.x += (hex::I/2.0);
    if( (hex0_->j % 2)==0 )
      p1.x += (hex::I/2.0);
  }
  *this = BoundingBox(p0, p1, hex0_, hex1_);
  if(frame_)
      frame();
}

} // end namespace hex
<|endoftext|>


<commit_before>/*
 * Box2D QML plugin
 * Copyright (C) 2010 Nokia Corporation
 *
 * This file is part of the Box2D QML plugin.
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or (at
 * your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library;  If not, see <http://www.gnu.org/licenses/>.
 */

#include "box2dworld.h"

#include "box2dbody.h"
#include "box2dfixture.h"
#include "box2djoint.h"
#include "box2ddestructionlistener.h"

#include <QTimerEvent>

#include <Box2D.h>

class ContactEvent
{
public:
    enum Type {
        BeginContact,
        EndContact
    };

    Type type;
    Box2DFixture *fixtureA;
    Box2DFixture *fixtureB;
};

class ContactListener : public b2ContactListener
{
public:
    void BeginContact(b2Contact *contact);
    void EndContact(b2Contact *contact);

    void removeEvent(int index) { mEvents.removeAt(index); }
    void clearEvents() { mEvents.clear(); }
    const QList<ContactEvent> &events() { return mEvents; }

private:
    QList<ContactEvent> mEvents;
};

void ContactListener::BeginContact(b2Contact *contact)
{
    ContactEvent event;
    event.type = ContactEvent::BeginContact;
    event.fixtureA = toBox2DFixture(contact->GetFixtureA());
    event.fixtureB = toBox2DFixture(contact->GetFixtureB());
    mEvents.append(event);
}

void ContactListener::EndContact(b2Contact *contact)
{
    ContactEvent event;
    event.type = ContactEvent::EndContact;
    event.fixtureA = toBox2DFixture(contact->GetFixtureA());
    event.fixtureB = toBox2DFixture(contact->GetFixtureB());
    mEvents.append(event);
}

Box2DWorld::Box2DWorld(QDeclarativeItem *parent) :
    QDeclarativeItem(parent),
    mWorld(0),
    mContactListener(new ContactListener),
    mDestructionListener(new Box2DDestructionListener),
    mTimeStep(1.0f / 60.0f),
    mVelocityIterations(10),
    mPositionIterations(10),
    mFrameTime(1000 / 60),
    mGravity(qreal(0), qreal(-10)),
    mIsRunning(true),
    mAllowSleeping(true),
    mFps(0)
{
    connect(mDestructionListener, SIGNAL(fixtureDestroyed(Box2DFixture*)),
            this, SLOT(fixtureDestroyed(Box2DFixture*)));
}

Box2DWorld::~Box2DWorld()
{
    // Bodies must be deleted before the world
    foreach (Box2DBody *body, mBodies)
        delete body;
    mBodies.clear();

    delete mWorld;
    delete mContactListener;
    delete mDestructionListener;
}

void Box2DWorld::setAllowSleeping(bool allowSleeping)
{
    if (mAllowSleeping == allowSleeping)
        return;

    mAllowSleeping=allowSleeping;

    if (mWorld)
        mWorld->SetAllowSleeping(allowSleeping);

    emit allowSleepingChanged();
}

void Box2DWorld::setRunning(bool running)
{
    if (mIsRunning == running)
        return;

    mIsRunning = running;
    emit runningChanged();

    if (isComponentComplete()) {
        if (running)
            mTimer.start(mFrameTime, this);
        else
            mTimer.stop();
    }
}

void Box2DWorld::setGravity(const QPointF &gravity)
{
    if (mGravity == gravity)
        return;

    mGravity = gravity;
    if (mWorld)
        mWorld->SetGravity(b2Vec2(gravity.x(), gravity.y()));

    emit gravityChanged();
}

void Box2DWorld::componentComplete()
{
    QDeclarativeItem::componentComplete();

    const b2Vec2 gravity(mGravity.x(), mGravity.y());

    mWorld = new b2World(gravity);
    mWorld->SetContactListener(mContactListener);
    mWorld->SetDestructionListener(mDestructionListener);

    foreach (QGraphicsItem *child, childItems())
        if (Box2DBody *body = dynamic_cast<Box2DBody*>(child)) {
            registerBody(body);
            connect(body, SIGNAL(destroyed()), this, SLOT(unregisterBody()));
        } else if (Box2DJoint *joint = dynamic_cast<Box2DJoint*>(child)) {
            registerJoint(joint);
        }

    if (mIsRunning)
        mTimer.start(mFrameTime, this);
}

/**
 * Registers a Box2D body with this world. When the world component is
 * complete, it will initialize the body.
 */
void Box2DWorld::registerBody(Box2DBody *body)
{
    mBodies.append(body);
    body->initialize(mWorld);
}

/**
 * Unregisters a Box2D body from this world. Called when a dynamically
 * created Box2D body has been deleted.
 */
void Box2DWorld::unregisterBody()
{
    Box2DBody *body = static_cast<Box2DBody*>(sender());
    mBodies.removeOne(body);
}

void Box2DWorld::registerJoint(Box2DJoint *joint)
{
    joint->initialize(this);
}

void Box2DWorld::fixtureDestroyed(Box2DFixture *fixture)
{
    QList<ContactEvent> events = mContactListener->events();
    for (int i = events.count() - 1; i >= 0; i--) {
        if (events.at(i).fixtureA == fixture
                || events.at(i).fixtureB == fixture)
            mContactListener->removeEvent(i);
    }
}

void Box2DWorld::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == mTimer.timerId()) {
        mWorld->Step(mTimeStep, mVelocityIterations, mPositionIterations);
        foreach (Box2DBody *body, mBodies)
            body->synchronize();

        // Emit contact signals
        foreach (const ContactEvent &event, mContactListener->events()) {
            switch (event.type) {
            case ContactEvent::BeginContact:
                event.fixtureA->emitBeginContact(event.fixtureB);
                event.fixtureB->emitBeginContact(event.fixtureA);
                break;
            case ContactEvent::EndContact:
                event.fixtureA->emitEndContact(event.fixtureB);
                event.fixtureB->emitEndContact(event.fixtureA);
                break;
            }
        }
        mContactListener->clearEvents();

        // Emit signals for the current state of the contacts
        b2Contact *contact = mWorld->GetContactList();
        while (contact) {
            Box2DFixture *fixtureA = toBox2DFixture(contact->GetFixtureA());
            Box2DFixture *fixtureB = toBox2DFixture(contact->GetFixtureB());

            fixtureA->emitContactChanged(fixtureB);
            fixtureB->emitContactChanged(fixtureA);

            contact = contact->GetNext();
        }

        emit stepped();
    }

    QDeclarativeItem::timerEvent(event);
}

QVariant Box2DWorld::itemChange(GraphicsItemChange change,
                                const QVariant &value)
{
    if (isComponentComplete()) {
        if (change == ItemChildAddedChange) {
            QGraphicsItem *child = value.value<QGraphicsItem*>();
            if (Box2DBody *body = dynamic_cast<Box2DBody*>(child)) {
                registerBody(body);
                connect(body, SIGNAL(destroyed()), this, SLOT(unregisterBody()));
            } else if (Box2DJoint *joint = dynamic_cast<Box2DJoint*>(child)) {
                registerJoint(joint);
            }
        }
    }

    return QDeclarativeItem::itemChange(change, value);
}

void Box2DWorld::stop()
{
    setRunning(false);
}

void Box2DWorld::start()
{
    setRunning(true);
}

void Box2DWorld::resetVelocities()
{
    foreach (Box2DBody *body, mBodies)
        body->resetVelocities();
}

<commit_msg>Implement setter for reportFps<commit_after>/*
 * Box2D QML plugin
 * Copyright (C) 2010 Nokia Corporation
 *
 * This file is part of the Box2D QML plugin.
 *
 * This library is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or (at
 * your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library;  If not, see <http://www.gnu.org/licenses/>.
 */

#include "box2dworld.h"

#include "box2dbody.h"
#include "box2dfixture.h"
#include "box2djoint.h"
#include "box2ddestructionlistener.h"

#include <QTimerEvent>

#include <Box2D.h>

class ContactEvent
{
public:
    enum Type {
        BeginContact,
        EndContact
    };

    Type type;
    Box2DFixture *fixtureA;
    Box2DFixture *fixtureB;
};

class ContactListener : public b2ContactListener
{
public:
    void BeginContact(b2Contact *contact);
    void EndContact(b2Contact *contact);

    void removeEvent(int index) { mEvents.removeAt(index); }
    void clearEvents() { mEvents.clear(); }
    const QList<ContactEvent> &events() { return mEvents; }

private:
    QList<ContactEvent> mEvents;
};

void ContactListener::BeginContact(b2Contact *contact)
{
    ContactEvent event;
    event.type = ContactEvent::BeginContact;
    event.fixtureA = toBox2DFixture(contact->GetFixtureA());
    event.fixtureB = toBox2DFixture(contact->GetFixtureB());
    mEvents.append(event);
}

void ContactListener::EndContact(b2Contact *contact)
{
    ContactEvent event;
    event.type = ContactEvent::EndContact;
    event.fixtureA = toBox2DFixture(contact->GetFixtureA());
    event.fixtureB = toBox2DFixture(contact->GetFixtureB());
    mEvents.append(event);
}

Box2DWorld::Box2DWorld(QDeclarativeItem *parent) :
    QDeclarativeItem(parent),
    mWorld(0),
    mContactListener(new ContactListener),
    mDestructionListener(new Box2DDestructionListener),
    mTimeStep(1.0f / 60.0f),
    mVelocityIterations(10),
    mPositionIterations(10),
    mFrameTime(1000 / 60),
    mGravity(qreal(0), qreal(-10)),
    mIsRunning(true),
    mAllowSleeping(true),
    mFps(0)
{
    connect(mDestructionListener, SIGNAL(fixtureDestroyed(Box2DFixture*)),
            this, SLOT(fixtureDestroyed(Box2DFixture*)));
}

Box2DWorld::~Box2DWorld()
{
    // Bodies must be deleted before the world
    foreach (Box2DBody *body, mBodies)
        delete body;
    mBodies.clear();

    delete mWorld;
    delete mContactListener;
    delete mDestructionListener;
}

void Box2DWorld::setAllowSleeping(bool allowSleeping)
{
    if (mAllowSleeping == allowSleeping)
        return;

    mAllowSleeping=allowSleeping;

    if (mWorld)
        mWorld->SetAllowSleeping(allowSleeping);

    emit allowSleepingChanged();
}

void Box2DWorld::setRunning(bool running)
{
    if (mIsRunning == running)
        return;

    mIsRunning = running;
    emit runningChanged();

    if (isComponentComplete()) {
        if (running)
            mTimer.start(mFrameTime, this);
        else
            mTimer.stop();
    }
}

void Box2DWorld::setGravity(const QPointF &gravity)
{
    if (mGravity == gravity)
        return;

    mGravity = gravity;
    if (mWorld)
        mWorld->SetGravity(b2Vec2(gravity.x(), gravity.y()));

    emit gravityChanged();
}

void Box2DWorld::setReportFps(bool reportfps)
{
    if (mFps == reportfps )
        return;

    mFps = reportfps;
    emit reportFpsChanged();
}

void Box2DWorld::componentComplete()
{
    QDeclarativeItem::componentComplete();

    const b2Vec2 gravity(mGravity.x(), mGravity.y());

    mWorld = new b2World(gravity);
    mWorld->SetContactListener(mContactListener);
    mWorld->SetDestructionListener(mDestructionListener);

    foreach (QGraphicsItem *child, childItems())
        if (Box2DBody *body = dynamic_cast<Box2DBody*>(child)) {
            registerBody(body);
            connect(body, SIGNAL(destroyed()), this, SLOT(unregisterBody()));
        } else if (Box2DJoint *joint = dynamic_cast<Box2DJoint*>(child)) {
            registerJoint(joint);
        }

    if (mIsRunning)
        mTimer.start(mFrameTime, this);
}

/**
 * Registers a Box2D body with this world. When the world component is
 * complete, it will initialize the body.
 */
void Box2DWorld::registerBody(Box2DBody *body)
{
    mBodies.append(body);
    body->initialize(mWorld);
}

/**
 * Unregisters a Box2D body from this world. Called when a dynamically
 * created Box2D body has been deleted.
 */
void Box2DWorld::unregisterBody()
{
    Box2DBody *body = static_cast<Box2DBody*>(sender());
    mBodies.removeOne(body);
}

void Box2DWorld::registerJoint(Box2DJoint *joint)
{
    joint->initialize(this);
}

void Box2DWorld::fixtureDestroyed(Box2DFixture *fixture)
{
    QList<ContactEvent> events = mContactListener->events();
    for (int i = events.count() - 1; i >= 0; i--) {
        if (events.at(i).fixtureA == fixture
                || events.at(i).fixtureB == fixture)
            mContactListener->removeEvent(i);
    }
}

void Box2DWorld::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == mTimer.timerId()) {
        mWorld->Step(mTimeStep, mVelocityIterations, mPositionIterations);
        foreach (Box2DBody *body, mBodies)
            body->synchronize();

        // Emit contact signals
        foreach (const ContactEvent &event, mContactListener->events()) {
            switch (event.type) {
            case ContactEvent::BeginContact:
                event.fixtureA->emitBeginContact(event.fixtureB);
                event.fixtureB->emitBeginContact(event.fixtureA);
                break;
            case ContactEvent::EndContact:
                event.fixtureA->emitEndContact(event.fixtureB);
                event.fixtureB->emitEndContact(event.fixtureA);
                break;
            }
        }
        mContactListener->clearEvents();

        // Emit signals for the current state of the contacts
        b2Contact *contact = mWorld->GetContactList();
        while (contact) {
            Box2DFixture *fixtureA = toBox2DFixture(contact->GetFixtureA());
            Box2DFixture *fixtureB = toBox2DFixture(contact->GetFixtureB());

            fixtureA->emitContactChanged(fixtureB);
            fixtureB->emitContactChanged(fixtureA);

            contact = contact->GetNext();
        }

        emit stepped();
    }

    QDeclarativeItem::timerEvent(event);
}

QVariant Box2DWorld::itemChange(GraphicsItemChange change,
                                const QVariant &value)
{
    if (isComponentComplete()) {
        if (change == ItemChildAddedChange) {
            QGraphicsItem *child = value.value<QGraphicsItem*>();
            if (Box2DBody *body = dynamic_cast<Box2DBody*>(child)) {
                registerBody(body);
                connect(body, SIGNAL(destroyed()), this, SLOT(unregisterBody()));
            } else if (Box2DJoint *joint = dynamic_cast<Box2DJoint*>(child)) {
                registerJoint(joint);
            }
        }
    }

    return QDeclarativeItem::itemChange(change, value);
}

void Box2DWorld::stop()
{
    setRunning(false);
}

void Box2DWorld::start()
{
    setRunning(true);
}

void Box2DWorld::resetVelocities()
{
    foreach (Box2DBody *body, mBodies)
        body->resetVelocities();
}

<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkDataSet.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

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

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

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

=========================================================================*/
//
// DataSet methods
//
#include <math.h>
#include "vtkDataSet.h"
#include "vtkSource.h"

//----------------------------------------------------------------------------
// Constructor with default bounds (0,1, 0,1, 0,1).
vtkDataSet::vtkDataSet ()
{
  this->Bounds[0] = 0.0;
  this->Bounds[1] = 1.0;
  this->Bounds[2] = 0.0;
  this->Bounds[3] = 1.0;
  this->Bounds[4] = 0.0;
  this->Bounds[5] = 1.0;

  this->PointData = vtkPointData::New();
  this->CellData = vtkCellData::New();
}

//----------------------------------------------------------------------------
vtkDataSet::~vtkDataSet ()
{
  this->PointData->Delete();
  this->CellData->Delete();
}

//----------------------------------------------------------------------------
void vtkDataSet::Initialize()
{
  // We don't modify ourselves because the "ReleaseData" methods depend upon
  // no modification when initialized.
  vtkDataObject::Initialize();

  this->CellData->Initialize();
  this->PointData->Initialize();
}

//----------------------------------------------------------------------------
// Compute the data bounding box from data points.
void vtkDataSet::ComputeBounds()
{
  int j;
  vtkIdType i;
  float *x;

  if ( this->GetMTime() > this->ComputeTime )
    {
    this->Bounds[0] = this->Bounds[2] = this->Bounds[4] =  VTK_LARGE_FLOAT;
    this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_LARGE_FLOAT;
    for (i=0; i<this->GetNumberOfPoints(); i++)
      {
      x = this->GetPoint(i);
      for (j=0; j<3; j++)
        {
        if ( x[j] < this->Bounds[2*j] )
          {
          this->Bounds[2*j] = x[j];
          }
        if ( x[j] > this->Bounds[2*j+1] )
          {
          this->Bounds[2*j+1] = x[j];
          }
        }
      }

    this->ComputeTime.Modified();
    }
}

//----------------------------------------------------------------------------
void vtkDataSet::GetScalarRange(float range[2])
{
  vtkScalars *ptScalars, *cellScalars;
  ptScalars = this->PointData->GetScalars();
  cellScalars = this->CellData->GetScalars();

  if ( ptScalars && cellScalars)
    {
    float r1[2], r2[2];
    ptScalars->GetRange(r1);
    cellScalars->GetRange(r2);
    range[0] = (r1[0] < r2[0] ? r1[0] : r2[0]);
    range[1] = (r1[1] > r2[1] ? r1[1] : r2[1]);
    }
  else if ( ptScalars )
    {
    ptScalars->GetRange(range);
    }
  else if ( cellScalars )
    {
    cellScalars->GetRange(range);
    }
  else
    {
    range[0] = 0.0;
    range[1] = 1.0;
    }
}

//----------------------------------------------------------------------------
float *vtkDataSet::GetScalarRange()
{
  this->GetScalarRange(this->ScalarRange);
  return this->ScalarRange;
}

//----------------------------------------------------------------------------
// Return a pointer to the geometry bounding box in the form
// (xmin,xmax, ymin,ymax, zmin,zmax).
float *vtkDataSet::GetBounds()
{
  this->ComputeBounds();
  return this->Bounds;
}

//----------------------------------------------------------------------------
void vtkDataSet::GetBounds(float bounds[6])
{
  this->ComputeBounds();
  for (int i=0; i<6; i++)
    {
    bounds[i] = this->Bounds[i];
    }
}

//----------------------------------------------------------------------------
// Get the center of the bounding box.
float *vtkDataSet::GetCenter()
{
  this->ComputeBounds();
  for (int i=0; i<3; i++)
    {
    this->Center[i] = (this->Bounds[2*i+1] + this->Bounds[2*i]) / 2.0;
    }
  return this->Center;
}

//----------------------------------------------------------------------------
void vtkDataSet::GetCenter(float center[3])
{
  this->ComputeBounds();
  for (int i=0; i<3; i++)
    {
    center[i] = (this->Bounds[2*i+1] + this->Bounds[2*i]) / 2.0;
    }
}

//----------------------------------------------------------------------------
// Return the length of the diagonal of the bounding box.
float vtkDataSet::GetLength()
{
  double diff, l=0.0;
  int i;

  this->ComputeBounds();
  for (i=0; i<3; i++)
    {
    diff = this->Bounds[2*i+1] - this->Bounds[2*i];
    l += diff * diff;
    }

  return (float)sqrt(l);
}

//----------------------------------------------------------------------------
unsigned long int vtkDataSet::GetMTime()
{
  unsigned long mtime, result;

  result = vtkDataObject::GetMTime();
  if (this->Source)
    {
    mtime = this->Source->GetMTime();
    result = ( mtime > result ? mtime : result );
    }

  mtime = this->PointData->GetMTime();
  result = ( mtime > result ? mtime : result );

  mtime = this->CellData->GetMTime();
  return ( mtime > result ? mtime : result );
}

//----------------------------------------------------------------------------
vtkCell *vtkDataSet::FindAndGetCell (float x[3], vtkCell *cell,
                                     vtkIdType cellId, float tol2, int& subId,
                                     float pcoords[3], float *weights)
{
  int newCell = this->FindCell(x,cell,cellId,tol2,subId,pcoords,weights);
  if (newCell >= 0 )
    {
    cell = this->GetCell (newCell);
    }
  else
    {
    return NULL;
    }
  return cell;
}

//----------------------------------------------------------------------------
void vtkDataSet::GetCellNeighbors(vtkIdType cellId, vtkIdList *ptIds,
                                  vtkIdList *cellIds)
{
  vtkIdType i, numPts;
  vtkIdList *otherCells = vtkIdList::New();
  otherCells->Allocate(VTK_CELL_SIZE);

  // load list with candidate cells, remove current cell
  this->GetPointCells(ptIds->GetId(0), cellIds);
  cellIds->DeleteId(cellId);

  // now perform multiple intersections on list
  if ( cellIds->GetNumberOfIds() > 0 )
    {
    for ( numPts=ptIds->GetNumberOfIds(), i=1; i < numPts; i++)
      {
      this->GetPointCells(ptIds->GetId(i), otherCells);
      cellIds->IntersectWith(*otherCells);
      }
    }

  otherCells->Delete();
}

//----------------------------------------------------------------------------
void vtkDataSet::GetCellTypes(vtkCellTypes *types)
{
  vtkIdType cellId, numCells=this->GetNumberOfCells();
  unsigned char type;

  types->Reset();
  for (cellId=0; cellId < numCells; cellId++)
    {
    type = this->GetCellType(cellId);
    if ( ! types->IsType(type) )
      {
      types->InsertNextType(type);
      }
    }
}

//----------------------------------------------------------------------------
// Default implementation. This is very slow way to compute this information.
// Subclasses should override this method for efficiency.
void vtkDataSet::GetCellBounds(vtkIdType cellId, float bounds[6])
{
  vtkGenericCell *cell = vtkGenericCell::New();

  this->GetCell(cellId, cell);
  cell->GetBounds(bounds);

  cell->Delete();
}

//----------------------------------------------------------------------------
void vtkDataSet::Squeeze()
{
  this->CellData->Squeeze();
  this->PointData->Squeeze();
}

//----------------------------------------------------------------------------
unsigned long vtkDataSet::GetActualMemorySize()
{
  unsigned long size=this->vtkDataObject::GetActualMemorySize();
  size += this->PointData->GetActualMemorySize();
  size += this->CellData->GetActualMemorySize();
  return size;
}

//----------------------------------------------------------------------------
void vtkDataSet::ShallowCopy(vtkDataObject *dataObject)
{
  vtkDataSet *dataSet = vtkDataSet::SafeDownCast(dataObject);

  if ( dataSet != NULL )
    {
    this->InternalDataSetCopy(dataSet);
    this->CellData->ShallowCopy(dataSet->GetCellData());
    this->PointData->ShallowCopy(dataSet->GetPointData());
    }
  // Do superclass
  this->vtkDataObject::ShallowCopy(dataObject);
}

//----------------------------------------------------------------------------
void vtkDataSet::DeepCopy(vtkDataObject *dataObject)
{
  vtkDataSet *dataSet = vtkDataSet::SafeDownCast(dataObject);

  if ( dataSet != NULL )
    {
    this->InternalDataSetCopy(dataSet);
    this->CellData->DeepCopy(dataSet->GetCellData());
    this->PointData->DeepCopy(dataSet->GetPointData());
    }

  // Do superclass
  this->vtkDataObject::DeepCopy(dataObject);
}

//----------------------------------------------------------------------------
// This copies all the local variables (but not objects).
void vtkDataSet::InternalDataSetCopy(vtkDataSet *src)
{
  int idx;

  this->ComputeTime = src->ComputeTime;
  this->ScalarRange[0] = src->ScalarRange[0];
  this->ScalarRange[1] = src->ScalarRange[1];
  for (idx = 0; idx < 3; ++idx)
    {
    this->Bounds[2*idx] = src->Bounds[2*idx];
    this->Bounds[2*idx+1] = src->Bounds[2*idx+1];
    }
}

//----------------------------------------------------------------------------
void vtkDataSet::PrintSelf(ostream& os, vtkIndent indent)
{
  float *bounds;

  vtkDataObject::PrintSelf(os,indent);

  os << indent << "Number Of Points: " << this->GetNumberOfPoints() << "\n";
  os << indent << "Number Of Cells: " << this->GetNumberOfCells() << "\n";

  os << indent << "Cell Data:\n";
  this->CellData->PrintSelf(os,indent.GetNextIndent());

  os << indent << "Point Data:\n";
  this->PointData->PrintSelf(os,indent.GetNextIndent());

  bounds = this->GetBounds();
  os << indent << "Bounds: \n";
  os << indent << "  Xmin,Xmax: (" <<bounds[0] << ", " << bounds[1] << ")\n";
  os << indent << "  Ymin,Ymax: (" <<bounds[2] << ", " << bounds[3] << ")\n";
  os << indent << "  Zmin,Zmax: (" <<bounds[4] << ", " << bounds[5] << ")\n";
  os << indent << "Compute Time: " <<this->ComputeTime.GetMTime() << "\n";
  os << indent << "Release Data: " << (this->ReleaseDataFlag ? "On\n" : "Off\n");
}

<commit_msg>BUG: Range has to be initialized.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkDataSet.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

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

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

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

=========================================================================*/
//
// DataSet methods
//
#include <math.h>
#include "vtkDataSet.h"
#include "vtkSource.h"

//----------------------------------------------------------------------------
// Constructor with default bounds (0,1, 0,1, 0,1).
vtkDataSet::vtkDataSet ()
{
  this->Bounds[0] = 0.0;
  this->Bounds[1] = 1.0;
  this->Bounds[2] = 0.0;
  this->Bounds[3] = 1.0;
  this->Bounds[4] = 0.0;
  this->Bounds[5] = 1.0;

  this->PointData = vtkPointData::New();
  this->CellData = vtkCellData::New();
  this->ScalarRange[0] = 0.0;
  this->ScalarRange[1] = 1.0;
}

//----------------------------------------------------------------------------
vtkDataSet::~vtkDataSet ()
{
  this->PointData->Delete();
  this->CellData->Delete();
}

//----------------------------------------------------------------------------
void vtkDataSet::Initialize()
{
  // We don't modify ourselves because the "ReleaseData" methods depend upon
  // no modification when initialized.
  vtkDataObject::Initialize();

  this->CellData->Initialize();
  this->PointData->Initialize();
}

//----------------------------------------------------------------------------
// Compute the data bounding box from data points.
void vtkDataSet::ComputeBounds()
{
  int j;
  vtkIdType i;
  float *x;

  if ( this->GetMTime() > this->ComputeTime )
    {
    this->Bounds[0] = this->Bounds[2] = this->Bounds[4] =  VTK_LARGE_FLOAT;
    this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_LARGE_FLOAT;
    for (i=0; i<this->GetNumberOfPoints(); i++)
      {
      x = this->GetPoint(i);
      for (j=0; j<3; j++)
        {
        if ( x[j] < this->Bounds[2*j] )
          {
          this->Bounds[2*j] = x[j];
          }
        if ( x[j] > this->Bounds[2*j+1] )
          {
          this->Bounds[2*j+1] = x[j];
          }
        }
      }

    this->ComputeTime.Modified();
    }
}

//----------------------------------------------------------------------------
void vtkDataSet::GetScalarRange(float range[2])
{
  vtkScalars *ptScalars, *cellScalars;
  ptScalars = this->PointData->GetScalars();
  cellScalars = this->CellData->GetScalars();

  if ( ptScalars && cellScalars)
    {
    float r1[2], r2[2];
    ptScalars->GetRange(r1);
    cellScalars->GetRange(r2);
    range[0] = (r1[0] < r2[0] ? r1[0] : r2[0]);
    range[1] = (r1[1] > r2[1] ? r1[1] : r2[1]);
    }
  else if ( ptScalars )
    {
    ptScalars->GetRange(range);
    }
  else if ( cellScalars )
    {
    cellScalars->GetRange(range);
    }
  else
    {
    range[0] = 0.0;
    range[1] = 1.0;
    }
}

//----------------------------------------------------------------------------
float *vtkDataSet::GetScalarRange()
{
  this->GetScalarRange(this->ScalarRange);
  return this->ScalarRange;
}

//----------------------------------------------------------------------------
// Return a pointer to the geometry bounding box in the form
// (xmin,xmax, ymin,ymax, zmin,zmax).
float *vtkDataSet::GetBounds()
{
  this->ComputeBounds();
  return this->Bounds;
}

//----------------------------------------------------------------------------
void vtkDataSet::GetBounds(float bounds[6])
{
  this->ComputeBounds();
  for (int i=0; i<6; i++)
    {
    bounds[i] = this->Bounds[i];
    }
}

//----------------------------------------------------------------------------
// Get the center of the bounding box.
float *vtkDataSet::GetCenter()
{
  this->ComputeBounds();
  for (int i=0; i<3; i++)
    {
    this->Center[i] = (this->Bounds[2*i+1] + this->Bounds[2*i]) / 2.0;
    }
  return this->Center;
}

//----------------------------------------------------------------------------
void vtkDataSet::GetCenter(float center[3])
{
  this->ComputeBounds();
  for (int i=0; i<3; i++)
    {
    center[i] = (this->Bounds[2*i+1] + this->Bounds[2*i]) / 2.0;
    }
}

//----------------------------------------------------------------------------
// Return the length of the diagonal of the bounding box.
float vtkDataSet::GetLength()
{
  double diff, l=0.0;
  int i;

  this->ComputeBounds();
  for (i=0; i<3; i++)
    {
    diff = this->Bounds[2*i+1] - this->Bounds[2*i];
    l += diff * diff;
    }

  return (float)sqrt(l);
}

//----------------------------------------------------------------------------
unsigned long int vtkDataSet::GetMTime()
{
  unsigned long mtime, result;

  result = vtkDataObject::GetMTime();
  if (this->Source)
    {
    mtime = this->Source->GetMTime();
    result = ( mtime > result ? mtime : result );
    }

  mtime = this->PointData->GetMTime();
  result = ( mtime > result ? mtime : result );

  mtime = this->CellData->GetMTime();
  return ( mtime > result ? mtime : result );
}

//----------------------------------------------------------------------------
vtkCell *vtkDataSet::FindAndGetCell (float x[3], vtkCell *cell,
                                     vtkIdType cellId, float tol2, int& subId,
                                     float pcoords[3], float *weights)
{
  int newCell = this->FindCell(x,cell,cellId,tol2,subId,pcoords,weights);
  if (newCell >= 0 )
    {
    cell = this->GetCell (newCell);
    }
  else
    {
    return NULL;
    }
  return cell;
}

//----------------------------------------------------------------------------
void vtkDataSet::GetCellNeighbors(vtkIdType cellId, vtkIdList *ptIds,
                                  vtkIdList *cellIds)
{
  vtkIdType i, numPts;
  vtkIdList *otherCells = vtkIdList::New();
  otherCells->Allocate(VTK_CELL_SIZE);

  // load list with candidate cells, remove current cell
  this->GetPointCells(ptIds->GetId(0), cellIds);
  cellIds->DeleteId(cellId);

  // now perform multiple intersections on list
  if ( cellIds->GetNumberOfIds() > 0 )
    {
    for ( numPts=ptIds->GetNumberOfIds(), i=1; i < numPts; i++)
      {
      this->GetPointCells(ptIds->GetId(i), otherCells);
      cellIds->IntersectWith(*otherCells);
      }
    }

  otherCells->Delete();
}

//----------------------------------------------------------------------------
void vtkDataSet::GetCellTypes(vtkCellTypes *types)
{
  vtkIdType cellId, numCells=this->GetNumberOfCells();
  unsigned char type;

  types->Reset();
  for (cellId=0; cellId < numCells; cellId++)
    {
    type = this->GetCellType(cellId);
    if ( ! types->IsType(type) )
      {
      types->InsertNextType(type);
      }
    }
}

//----------------------------------------------------------------------------
// Default implementation. This is very slow way to compute this information.
// Subclasses should override this method for efficiency.
void vtkDataSet::GetCellBounds(vtkIdType cellId, float bounds[6])
{
  vtkGenericCell *cell = vtkGenericCell::New();

  this->GetCell(cellId, cell);
  cell->GetBounds(bounds);

  cell->Delete();
}

//----------------------------------------------------------------------------
void vtkDataSet::Squeeze()
{
  this->CellData->Squeeze();
  this->PointData->Squeeze();
}

//----------------------------------------------------------------------------
unsigned long vtkDataSet::GetActualMemorySize()
{
  unsigned long size=this->vtkDataObject::GetActualMemorySize();
  size += this->PointData->GetActualMemorySize();
  size += this->CellData->GetActualMemorySize();
  return size;
}

//----------------------------------------------------------------------------
void vtkDataSet::ShallowCopy(vtkDataObject *dataObject)
{
  vtkDataSet *dataSet = vtkDataSet::SafeDownCast(dataObject);

  if ( dataSet != NULL )
    {
    this->InternalDataSetCopy(dataSet);
    this->CellData->ShallowCopy(dataSet->GetCellData());
    this->PointData->ShallowCopy(dataSet->GetPointData());
    }
  // Do superclass
  this->vtkDataObject::ShallowCopy(dataObject);
}

//----------------------------------------------------------------------------
void vtkDataSet::DeepCopy(vtkDataObject *dataObject)
{
  vtkDataSet *dataSet = vtkDataSet::SafeDownCast(dataObject);

  if ( dataSet != NULL )
    {
    this->InternalDataSetCopy(dataSet);
    this->CellData->DeepCopy(dataSet->GetCellData());
    this->PointData->DeepCopy(dataSet->GetPointData());
    }

  // Do superclass
  this->vtkDataObject::DeepCopy(dataObject);
}

//----------------------------------------------------------------------------
// This copies all the local variables (but not objects).
void vtkDataSet::InternalDataSetCopy(vtkDataSet *src)
{
  int idx;

  this->ComputeTime = src->ComputeTime;
  this->ScalarRange[0] = src->ScalarRange[0];
  this->ScalarRange[1] = src->ScalarRange[1];
  for (idx = 0; idx < 3; ++idx)
    {
    this->Bounds[2*idx] = src->Bounds[2*idx];
    this->Bounds[2*idx+1] = src->Bounds[2*idx+1];
    }
}

//----------------------------------------------------------------------------
void vtkDataSet::PrintSelf(ostream& os, vtkIndent indent)
{
  float *bounds;

  vtkDataObject::PrintSelf(os,indent);

  os << indent << "Number Of Points: " << this->GetNumberOfPoints() << "\n";
  os << indent << "Number Of Cells: " << this->GetNumberOfCells() << "\n";

  os << indent << "Cell Data:\n";
  this->CellData->PrintSelf(os,indent.GetNextIndent());

  os << indent << "Point Data:\n";
  this->PointData->PrintSelf(os,indent.GetNextIndent());

  bounds = this->GetBounds();
  os << indent << "Bounds: \n";
  os << indent << "  Xmin,Xmax: (" <<bounds[0] << ", " << bounds[1] << ")\n";
  os << indent << "  Ymin,Ymax: (" <<bounds[2] << ", " << bounds[3] << ")\n";
  os << indent << "  Zmin,Zmax: (" <<bounds[4] << ", " << bounds[5] << ")\n";
  os << indent << "Compute Time: " <<this->ComputeTime.GetMTime() << "\n";
  os << indent << "Release Data: " << (this->ReleaseDataFlag ? "On\n" : "Off\n");
}

<|endoftext|>


<commit_before>#include "ScaleSpriteState.h"

#include "common/Matrix.h"
#include "dataset/ISymbol.h"
#include "dataset/ISprite.h"
#include "history/ArrangeSpriteAtomicOP.h"
#include "history/CombineAOP.h"
#include "history/TranslateSpriteAOP.h"
#include "history/ScaleSpriteAOP.h"

namespace d2d
{

ScaleSpriteState::ScaleSpriteState(ISprite* sprite, const SpriteCtrlNode::Node& ctrl_node)
	: m_ctrl_node(ctrl_node)
{
	m_sprite = sprite;
	m_sprite->retain();

	m_first_pos = m_sprite->getPosition();
	m_first_scale = m_sprite->getScale();
}

ScaleSpriteState::~ScaleSpriteState()
{
	m_sprite->release();
}

AbstractAtomicOP* ScaleSpriteState::OnMouseRelease(const Vector& pos)
{
	CombineAOP* comb = new CombineAOP();

	comb->Insert(new TranslateSpriteAOP(m_sprite, m_sprite->getPosition() - m_first_pos));
	comb->Insert(new ScaleSpriteAOP(m_sprite, m_sprite->getScale(), m_first_scale));

	return comb;
}

bool ScaleSpriteState::OnMouseMove(const Vector& pos)
{
	Scale(pos);
	return true;
}

void ScaleSpriteState::Scale(const Vector& curr)
{
	float hw = m_sprite->getSymbol().getSize().xLength() * 0.5f;
	float hh = m_sprite->getSymbol().getSize().yLength() * 0.5f;
	Matrix t;
	const Vector& center = m_sprite->getCenter();
	t.setTransformation(center.x, center.y, m_sprite->getAngle(),
		m_sprite->getScale().x, m_sprite->getScale().y, 0, 0, m_sprite->getShear().x, m_sprite->getShear().y);

	Vector ori, fix;
	if (m_ctrl_node.type == SpriteCtrlNode::UP)
		ori = Math::transVector(Vector(0.0f, hh), t);
	else if (m_ctrl_node.type == SpriteCtrlNode::DOWN)
		ori = Math::transVector(Vector(0.0f, -hh), t);
	else if (m_ctrl_node.type == SpriteCtrlNode::LEFT)
		ori = Math::transVector(Vector(-hw, 0.0f), t);
	else if (m_ctrl_node.type == SpriteCtrlNode::RIGHT)
		ori = Math::transVector(Vector(hw, 0.0f), t);
	else if (m_ctrl_node.type == SpriteCtrlNode::LEFT_UP)
		ori = Math::transVector(Vector(-hw, hh), t);
	else if (m_ctrl_node.type == SpriteCtrlNode::RIGHT_UP)
		ori = Math::transVector(Vector(hw, hh), t);
	else if (m_ctrl_node.type == SpriteCtrlNode::LEFT_DOWN)
		ori = Math::transVector(Vector(-hw, -hh), t);
	else if (m_ctrl_node.type == SpriteCtrlNode::RIGHT_DOWN)
		ori = Math::transVector(Vector(hw, -hh), t);
	Math::getFootOfPerpendicular(center, ori, curr, &fix);

	float scale = Math::getDistance(center, fix) / Math::getDistance(center, ori);
	scale += (1 - scale) * 0.5f;
	if (m_ctrl_node.type == SpriteCtrlNode::UP || m_ctrl_node.type == SpriteCtrlNode::DOWN)
		m_sprite->setScale(m_sprite->getScale().x, scale * m_sprite->getScale().y);
	else if (m_ctrl_node.type == SpriteCtrlNode::LEFT || m_ctrl_node.type == SpriteCtrlNode::RIGHT)
		m_sprite->setScale(scale * m_sprite->getScale().x, m_sprite->getScale().y);
	else
		m_sprite->setScale(scale * m_sprite->getScale().x, scale * m_sprite->getScale().y);

	Vector offset = (fix - ori) * 0.5f;
	m_sprite->translate(offset);

}

}<commit_msg>[FIXED] scale sprite时控制点计算错误<commit_after>#include "ScaleSpriteState.h"

#include "common/Matrix.h"
#include "dataset/ISymbol.h"
#include "dataset/ISprite.h"
#include "history/ArrangeSpriteAtomicOP.h"
#include "history/CombineAOP.h"
#include "history/TranslateSpriteAOP.h"
#include "history/ScaleSpriteAOP.h"

namespace d2d
{

ScaleSpriteState::ScaleSpriteState(ISprite* sprite, const SpriteCtrlNode::Node& ctrl_node)
	: m_ctrl_node(ctrl_node)
{
	m_sprite = sprite;
	m_sprite->retain();

	m_first_pos = m_sprite->getPosition();
	m_first_scale = m_sprite->getScale();
}

ScaleSpriteState::~ScaleSpriteState()
{
	m_sprite->release();
}

AbstractAtomicOP* ScaleSpriteState::OnMouseRelease(const Vector& pos)
{
	CombineAOP* comb = new CombineAOP();

	comb->Insert(new TranslateSpriteAOP(m_sprite, m_sprite->getPosition() - m_first_pos));
	comb->Insert(new ScaleSpriteAOP(m_sprite, m_sprite->getScale(), m_first_scale));

	return comb;
}

bool ScaleSpriteState::OnMouseMove(const Vector& pos)
{
	Scale(pos);
	return true;
}

void ScaleSpriteState::Scale(const Vector& curr)
{
	Rect r = m_sprite->getSymbol().getSize();
	Matrix t;

//	const Vector& center = m_sprite->getCenter();
	Vector center = m_sprite->getPosition() + m_sprite->getOffset();

	t.setTransformation(m_sprite->getPosition().x, m_sprite->getPosition().y, m_sprite->getAngle(),
		m_sprite->getScale().x, m_sprite->getScale().y, 0, 0, m_sprite->getShear().x, m_sprite->getShear().y);

	d2d::Vector offset = m_sprite->getOffset();
	d2d::Vector fix_node = Math::rotateVector(-offset, m_sprite->getAngle()) + offset;

	Vector ori, fix;
	if (m_ctrl_node.type == SpriteCtrlNode::UP)
		ori = Math::transVector(Vector(r.xCenter(), r.yMax) + fix_node, t);
	else if (m_ctrl_node.type == SpriteCtrlNode::DOWN)
		ori = Math::transVector(Vector(r.xCenter(), r.yMin) + fix_node, t);
	else if (m_ctrl_node.type == SpriteCtrlNode::LEFT)
		ori = Math::transVector(Vector(r.xMin, r.yCenter()) + fix_node, t);
	else if (m_ctrl_node.type == SpriteCtrlNode::RIGHT)
		ori = Math::transVector(Vector(r.xMax, r.yCenter()) + fix_node, t);
	else if (m_ctrl_node.type == SpriteCtrlNode::LEFT_UP)
		ori = Math::transVector(Vector(r.xMin, r.yMax) + fix_node, t);
	else if (m_ctrl_node.type == SpriteCtrlNode::RIGHT_UP)
		ori = Math::transVector(Vector(r.xMax, r.yMax) + fix_node, t);
	else if (m_ctrl_node.type == SpriteCtrlNode::LEFT_DOWN)
		ori = Math::transVector(Vector(r.xMin, r.yMin) + fix_node, t);
	else if (m_ctrl_node.type == SpriteCtrlNode::RIGHT_DOWN)
		ori = Math::transVector(Vector(r.xMax, r.yMin) + fix_node, t);
	Math::getFootOfPerpendicular(center, ori, curr, &fix);

	float scale = Math::getDistance(center, fix) / Math::getDistance(center, ori);
	scale += (1 - scale) * 0.5f;
	if (fabs(scale - 1) < FLT_EPSILON) {
		return;
	}
	if (m_ctrl_node.type == SpriteCtrlNode::UP || m_ctrl_node.type == SpriteCtrlNode::DOWN)
		m_sprite->setScale(m_sprite->getScale().x, scale * m_sprite->getScale().y);
	else if (m_ctrl_node.type == SpriteCtrlNode::LEFT || m_ctrl_node.type == SpriteCtrlNode::RIGHT)
		m_sprite->setScale(scale * m_sprite->getScale().x, m_sprite->getScale().y);
	else
		m_sprite->setScale(scale * m_sprite->getScale().x, scale * m_sprite->getScale().y);

	m_sprite->translate((fix - ori) * 0.5f);
}

}<|endoftext|>


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

#include "ChartTypeTemplate.hxx"

#ifndef _COM_SUN_STAR_CHART2_STACKMODE_HPP_
#include <com/sun/star/chart2/StackMode.hpp>
#endif

namespace chart
{

class NetChartTypeTemplate : public ChartTypeTemplate
{
public:
    explicit NetChartTypeTemplate(
        ::com::sun::star::uno::Reference<
            ::com::sun::star::uno::XComponentContext > const & xContext,
        const ::rtl::OUString & rServiceName,
        ::com::sun::star::chart2::StackMode eStackMode,
        bool bSymbols );
    virtual ~NetChartTypeTemplate();

    APPHELPER_XSERVICEINFO_DECL()

protected:
    // ____ XChartTypeTemplate ____
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDiagram > SAL_CALL
        createDiagram( const ::com::sun::star::uno::Sequence<
                           ::com::sun::star::uno::Reference<
                               ::com::sun::star::chart2::XDataSeries > >& aSeriesSeq )
        throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL matchesTemplate(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XDiagram >& xDiagram )
        throw (::com::sun::star::uno::RuntimeException);

    // ____ ChartTypeTemplate ____
    virtual ::com::sun::star::uno::Reference<
        ::com::sun::star::chart2::XChartType > getDefaultChartType()
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::chart2::StackMode getYStackMode() const;
    virtual ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XBoundedCoordinateSystem >
        createCoordinateSystem(
            const ::com::sun::star::uno::Reference<
                ::com::sun::star::chart2::XBoundedCoordinateSystemContainer > & xCoordSysCnt );

private:
    ::com::sun::star::chart2::StackMode  m_eStackMode;
    bool                                         m_bHasSymbols;
};

} //  namespace chart

// CHART_NETCHARTTYPETEMPLATE_HXX
#endif
<commit_msg>INTEGRATION: CWS chart2mst3 (1.2.4); FILE MERGED 2007/03/26 14:18:33 iha 1.2.4.16: #i75590# copy some aspects from old charttype during creation of new 2005/10/07 12:04:33 bm 1.2.4.15: RESYNC: (1.2-1.3); FILE MERGED 2005/08/05 14:19:58 bm 1.2.4.14: getStackMode: per chart type (open: percent stacking works per coordinate system, how can this be synched) 2004/09/16 12:27:29 bm 1.2.4.13: API simplification 2004/09/15 17:32:06 bm 1.2.4.12: API simplification 2004/06/29 12:26:35 bm 1.2.4.11: XChartTypeTemplate changes 2004/05/27 17:27:12 bm 1.2.4.10: +getChartTypeForNewSeries at XChartTypeTemplate 2004/05/07 15:34:36 bm 1.2.4.9: applyStyle works for single series now 2004/04/21 20:45:54 iha 1.2.4.8: #i20344# net subtypes changed 2004/04/01 10:53:11 bm 1.2.4.7: XChartType: may return a coordinate system now 2004/03/24 19:05:25 bm 1.2.4.6: XChartTypeTemplate changed: matchesTemplate may modify the template s properties if bAdaptProperties is true 2004/03/22 15:23:18 iha 1.2.4.5: added parameter SwapXAndYAxis for horizontal bar chart to method createCoordinateSystems 2004/03/19 14:32:58 bm 1.2.4.4: XDataSource now contains XLabeledDataSources 2004/03/02 16:40:43 bm 1.2.4.3: allow creating more than one coordinate system 2004/02/20 17:43:56 iha 1.2.4.2: integrate categories at ScaleData 2004/02/13 16:51:43 bm 1.2.4.1: join from changes on branch bm_post_chart01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: NetChartTypeTemplate.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 18:50:36 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef CHART_NETCHARTTYPETEMPLATE_HXX
#define CHART_NETCHARTTYPETEMPLATE_HXX

#include "ChartTypeTemplate.hxx"
#include "StackMode.hxx"

namespace chart
{

class NetChartTypeTemplate : public ChartTypeTemplate
{
public:
    explicit NetChartTypeTemplate(
        ::com::sun::star::uno::Reference<
            ::com::sun::star::uno::XComponentContext > const & xContext,
        const ::rtl::OUString & rServiceName,
        StackMode eStackMode,
        bool bSymbols,
        bool bHasLines = true
        );
    virtual ~NetChartTypeTemplate();

    APPHELPER_XSERVICEINFO_DECL()

protected:
    // ____ XChartTypeTemplate ____
    virtual sal_Bool SAL_CALL matchesTemplate(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XDiagram >& xDiagram,
        sal_Bool bAdaptProperties )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XChartType > SAL_CALL
        getChartTypeForNewSeries( const ::com::sun::star::uno::Sequence<
            ::com::sun::star::uno::Reference<
                ::com::sun::star::chart2::XChartType > >& aFormerlyUsedChartTypes )
        throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL applyStyle(
        const ::com::sun::star::uno::Reference< ::com::sun::star::chart2::XDataSeries >& xSeries,
        ::sal_Int32 nChartTypeGroupIndex,
        ::sal_Int32 nSeriesIndex,
        ::sal_Int32 nSeriesCount )
        throw (::com::sun::star::uno::RuntimeException);

    // ____ ChartTypeTemplate ____
    virtual StackMode getStackMode( sal_Int32 nChartTypeIndex ) const;

private:
    StackMode  m_eStackMode;
    bool                                 m_bHasSymbols;
    bool                                 m_bHasLines;
};

} //  namespace chart

// CHART_NETCHARTTYPETEMPLATE_HXX
#endif
<|endoftext|>


<commit_before>//This is the program that is supposed to pull together the resources of the
  //various pluggins and compile them before runtime

#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <vector>
#include <unordered_set>
using namespace std;

//c++17
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;

//Can paint in various colors on linux
/* Short Color Reference:
 * -30 - Normal
 * -25 - Blink
 * 1 - Red
 * 2 - Green
 * 3 - Yellow
 * 4 - Blue
 */
#ifdef _WIN32
  void startPaint(const int color) {}
  void endPaint() {}
#else
  void startPaint(const int color)
  {
    cout << "\033[" << color+30 << "m";
  }
  void endPaint()
  {
    cout << "\033[0m";
  }
#endif

unordered_set<string> load()
{
    string filename = "Compiler/enabledPlugins.conf";
    ifstream file(filename);
    while (!file)
    {
      //Prompt for another file, or not
      char tryAgain;
      startPaint(1);
      cerr << filename << " failed to open. Would you like to try another file? (Y/n) ";
      endPaint();
      cin >> tryAgain;

      //If no, exit program
      if (tryAgain == 'n' || tryAgain == 'N')
      {
        startPaint(1);
        cerr << "No alternate file provided. Cannot continue, closing program.\n";
        endPaint();
        exit(1);
      }

      //Otherwise, get a new file
      cout << "Filename: ";
      cin >> filename;
      file.open(filename);
    }

    //Raed into set and return
    string pluginName;
    unordered_set<string> enabledPlugins;
    while(file >> pluginName)
        enabledPlugins.insert(pluginName);

    file.close();

    return enabledPlugins;
}

void save(const unordered_set<string>& enabledPlugins)
{
    string filename = "Compiler/enabledPlugins.conf";
    ofstream file(filename);
    while (!file)
    {
      //Prompt for another file, or not
      char tryAgain;
      startPaint(1);
      cerr << filename << " failed to open. Would you like to try another file? (Y/n) ";
      endPaint();
      cin >> tryAgain;

      //If no, exit program
      if (tryAgain == 'n' || tryAgain == 'N')
      {
        startPaint(1);
        cerr << "No alternate file provided. Cannot continue, closing program.\n";
        endPaint();
        exit(1);
      }

      //Otherwise, get a new file
      cout << "Filename: ";
      cin >> filename;
      file.open(filename);
    }

    for (const string& pluginName : enabledPlugins)
        file << pluginName << endl;

    file.close();
}

//Make sure that what the calle is looking at is a real plugin
  //does not check if the plugin works, in any fashion
bool verifyPlugin(fs::file_status entry)
{
  //Just a stack of if statements that need to be true
  if(fs::is_directory(entry)) //Makes sure it's actually a folder
    return true;
  return false;
}

//Get a list of all the availible plugins
vector<string> readPlugins()
{
  //Build a vector<string> of all availible plugins
  vector<string> plugins;
  for (auto& entry : fs::directory_iterator("Plugins/"))
  {
    //Verifies that this is a conforming plugin
    if(verifyPlugin(entry.symlink_status()))
    {
      //Gets the string from the directory_entries, removing "Plugins/"
      string sliceString = entry.path();
      plugins.push_back(sliceString.substr(8)); // 8 = len("Plugins/")
    }
  }

  //Return the result back!
  return plugins;
}

//The help commands=
void help()
{
  string helpScript =
  "enable <pluginName>  - enables the plugin with specified name\n"
  "disable <pluginName> - disables the plugin with specified name\n"
  "list \t- lists all plugins\n"
  "listD\t- lists disabled plugins\n"
  "listE\t- lists enabled plugins\n"
  "-compile\t- compiles the program\n"
  "-save \t- saves the list of enabled plugins\n"
  "exit \t- exits the program, discarding unsaved changes\n"
  "help \t- lists this menu\n"
  "\n"
  "";

  cout << helpScript;
}

int main()
{
  //Initialize the list of plugins
  vector<string> plugins = readPlugins();

  //Initialize list of plugins that have already been enabled
  unordered_set<string> enabledPlugins = load();

  //Initialize list of plugins that have yet to be enabled,
    //the difference of the last two lists
  unordered_set<string> disabledPlugins;// = readFile(Plugins/enabledPlugins.txt);
  for (string pluginName : plugins)
    if(enabledPlugins.count(pluginName) == 0)
      disabledPlugins.insert(pluginName);

  //User prompt
  startPaint(3);
  cout << "This is the program that will allow you to choose what plugins to"
          " use, and can compile the program for you.\nFor help, type 'help'\n";
  endPaint();

  //A simple command prompt to interact with the compiler
  string command = "";

  //Write out prompt, in green
  startPaint(2);
  cout << "command: ";
  endPaint();

  //Command prompt, options detailed in the help fuction
  while(cin >> command && command != "exit")
  {
    if (command == "enable")
    {
        //Get name of plugin
        cin >> command;

        //Check if plugin exists
        bool pluginExists = false;
        for (string pluginName : plugins)
          if (pluginName == command)
          {
            pluginExists = true;
            enabledPlugins.insert(command);
            disabledPlugins.erase(command);
            break;
          }
        if (!pluginExists)
          cerr << "The plugin '" << command << "' is not availible.\n";
    }

    else if (command == "disable")
    {
        //Get name of plugin
        cin >> command;

        //Check if plugin exists
        bool pluginExists = false;
        for (string pluginName : plugins)
          if (pluginName == command)
          {
            pluginExists = true;
            disabledPlugins.insert(command);
            enabledPlugins.erase(command);
            break;
          }
        if (!pluginExists)
          cerr << "The plugin '" << command << "' is not availible.\n";
    }

    else if (command == "list")
    {
      for(string& pluginName : plugins)
        cout << pluginName << endl;
    }

    else if (command == "listD")
    {
      for(string pluginName : disabledPlugins)
        cout << pluginName << endl;
    }

    else if (command == "listE")
    {
      for(string pluginName : enabledPlugins)
        cout << pluginName << endl;
    }

    else if (command == "compile")
    {

    }

    else if (command == "save")
    {
        save(enabledPlugins);
    }

    else if(command == "exit")
    {
        break;
    }

    else if(command == "help")
    {
        help();
    }

    else
    {
        cerr << "Unknown command.\n";
    }

    //Write out prompt, in green
    startPaint(2);
    cout << "command: ";
    endPaint();

    //Clear any extra characters in the cin stream
    cin.ignore(1000,'\n');
    cin.clear();
  }
}
<commit_msg>Added Clear Command<commit_after>//This is the program that is supposed to pull together the resources of the
  //various pluggins and compile them before runtime

#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <vector>
#include <unordered_set>
using namespace std;

//c++17
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;

//Can paint in various colors on linux
/* Short Color Reference:
 * -30 - Normal
 * -25 - Blink
 * 1 - Red
 * 2 - Green
 * 3 - Yellow
 * 4 - Blue
 */
#ifdef _WIN32
  void startPaint(const int color) {}
  void endPaint() {}
#else
  void startPaint(const int color)
  {
    cout << "\033[" << color+30 << "m";
  }
  void endPaint()
  {
    cout << "\033[0m";
  }
#endif

unordered_set<string> load()
{
    string filename = "Compiler/enabledPlugins.conf";
    ifstream file(filename);
    while (!file)
    {
      //Prompt for another file, or not
      char tryAgain;
      startPaint(1);
      cerr << filename << " failed to open. Would you like to try another file? (Y/n) ";
      endPaint();
      cin >> tryAgain;

      //If no, exit program
      if (tryAgain == 'n' || tryAgain == 'N')
      {
        startPaint(1);
        cerr << "No alternate file provided. Cannot continue, closing program.\n";
        endPaint();
        exit(1);
      }

      //Otherwise, get a new file
      cout << "Filename: ";
      cin >> filename;
      file.open(filename);
    }

    //Raed into set and return
    string pluginName;
    unordered_set<string> enabledPlugins;
    while(file >> pluginName)
        enabledPlugins.insert(pluginName);

    file.close();

    return enabledPlugins;
}

void save(const unordered_set<string>& enabledPlugins)
{
    string filename = "Compiler/enabledPlugins.conf";
    ofstream file(filename);
    while (!file)
    {
      //Prompt for another file, or not
      char tryAgain;
      startPaint(1);
      cerr << filename << " failed to open. Would you like to try another file? (Y/n) ";
      endPaint();
      cin >> tryAgain;

      //If no, exit program
      if (tryAgain == 'n' || tryAgain == 'N')
      {
        startPaint(1);
        cerr << "No alternate file provided. Cannot continue, closing program.\n";
        endPaint();
        exit(1);
      }

      //Otherwise, get a new file
      cout << "Filename: ";
      cin >> filename;
      file.open(filename);
    }

    for (const string& pluginName : enabledPlugins)
        file << pluginName << endl;

    file.close();
}

//Make sure that what the calle is looking at is a real plugin
  //does not check if the plugin works, in any fashion
bool verifyPlugin(fs::file_status entry)
{
  //Just a stack of if statements that need to be true
  if(fs::is_directory(entry)) //Makes sure it's actually a folder
    return true;
  return false;
}

//Get a list of all the availible plugins
vector<string> readPlugins()
{
  //Build a vector<string> of all availible plugins
  vector<string> plugins;
  for (auto& entry : fs::directory_iterator("Plugins/"))
  {
    //Verifies that this is a conforming plugin
    if(verifyPlugin(entry.symlink_status()))
    {
      //Gets the string from the directory_entries, removing "Plugins/"
      string sliceString = entry.path();
      plugins.push_back(sliceString.substr(8)); // 8 = len("Plugins/")
    }
  }

  //Return the result back!
  return plugins;
}

//The help commands=
void help()
{
  string helpScript =
  "enable <pluginName>  - enables the plugin with specified name\n"
  "disable <pluginName> - disables the plugin with specified name\n"
  "clear\t- disables all plugins\n"
  "list \t- lists all plugins\n"
  "listD\t- lists disabled plugins\n"
  "listE\t- lists enabled plugins\n"
  "-compile\t- compiles the program\n"
  "-save \t- saves the list of enabled plugins\n"
  "exit \t- exits the program, discarding unsaved changes\n"
  "help \t- lists this menu\n"
  "\n"
  "";

  cout << helpScript;
}

int main()
{
  //Initialize the list of plugins
  vector<string> plugins = readPlugins();

  //Initialize list of plugins that have already been enabled
  unordered_set<string> enabledPlugins = load();

  //Initialize list of plugins that have yet to be enabled,
    //the difference of the last two lists
  unordered_set<string> disabledPlugins;// = readFile(Plugins/enabledPlugins.txt);
  for (string pluginName : plugins)
    if(enabledPlugins.count(pluginName) == 0)
      disabledPlugins.insert(pluginName);

  //User prompt
  startPaint(3);
  cout << "This is the program that will allow you to choose what plugins to"
          " use, and can compile the program for you.\nFor help, type 'help'\n";
  endPaint();

  //A simple command prompt to interact with the compiler
  string command = "";

  //Write out prompt, in green
  startPaint(2);
  cout << "command: ";
  endPaint();

  //Command prompt, options detailed in the help fuction
  while(cin >> command && command != "exit")
  {
    if (command == "enable")
    {
        //Get name of plugin
        cin >> command;

        //Check if plugin exists
        bool pluginExists = false;
        for (string pluginName : plugins)
          if (pluginName == command)
          {
            pluginExists = true;
            enabledPlugins.insert(command);
            disabledPlugins.erase(command);
            break;
          }
        if (!pluginExists)
          cerr << "The plugin '" << command << "' is not availible.\n";
    }

    else if (command == "disable")
    {
        //Get name of plugin
        cin >> command;

        //Check if plugin exists
        bool pluginExists = false;
        for (string pluginName : plugins)
          if (pluginName == command)
          {
            pluginExists = true;
            disabledPlugins.insert(command);
            enabledPlugins.erase(command);
            break;
          }
        if (!pluginExists)
          cerr << "The plugin '" << command << "' is not availible.\n";
    }

    else if (command == "list")
    {
      for(string& pluginName : plugins)
        cout << pluginName << endl;
    }

    else if (command == "listD")
    {
      for(string pluginName : disabledPlugins)
        cout << pluginName << endl;
    }

    else if (command == "listE")
    {
      for(string pluginName : enabledPlugins)
        cout << pluginName << endl;
    }

    else if (command == "clear")
    {
      enabledPlugins.clear();

      for (const string& pluginName : plugins)
        disabledPlugins.insert(pluginName);
    }

    else if (command == "compile")
    {

    }

    else if (command == "save")
    {
        save(enabledPlugins);
    }

    else if(command == "exit")
    {
        break;
    }

    else if(command == "help")
    {
        help();
    }

    else
    {
        cerr << "Unknown command.\n";
    }

    //Write out prompt, in green
    startPaint(2);
    cout << "command: ";
    endPaint();

    //Clear any extra characters in the cin stream
    cin.ignore(1000,'\n');
    cin.clear();
  }
}
<|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/extensions/extension_apitest.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"

class DownloadsApiTest : public ExtensionApiTest {
 public:
  void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
  }

  void SetUpTempDownloadsDir() {
    ASSERT_TRUE(tmpdir.CreateUniqueTempDir());
    browser()->profile()->GetPrefs()->SetFilePath(
        prefs::kDownloadDefaultDirectory, tmpdir.path());
  }

 private:
  ScopedTempDir tmpdir;
};

IN_PROC_BROWSER_TEST_F(DownloadsApiTest, Downloads) {
  SetUpTempDownloadsDir();
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("downloads")) << message_;
}
<commit_msg>Disable DownloadsApiTest.Downloads on OSX.<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/extensions/extension_apitest.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"

class DownloadsApiTest : public ExtensionApiTest {
 public:
  void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitch(switches::kEnableExperimentalExtensionApis);
  }

  void SetUpTempDownloadsDir() {
    ASSERT_TRUE(tmpdir.CreateUniqueTempDir());
    browser()->profile()->GetPrefs()->SetFilePath(
        prefs::kDownloadDefaultDirectory, tmpdir.path());
  }

 private:
  ScopedTempDir tmpdir;
};

// Disabled on Mac. http://crbug.com/101170
#if defined(OS_MACOSX)
  #define MAYBE_Downloads DISABLED_Downloads
#else
  #define MAYBE_Downloads Downloads
#endif
IN_PROC_BROWSER_TEST_F(DownloadsApiTest, MAYBE_Downloads) {
  SetUpTempDownloadsDir();
  ASSERT_TRUE(StartTestServer());
  ASSERT_TRUE(RunExtensionTest("downloads")) << message_;
}
<|endoftext|>


<commit_before>// Copyright 2013 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/install_verification/win/module_ids.h"

#include <utility>

#include "base/basictypes.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/string_util.h"
#include "grit/browser_resources.h"
#include "ui/base/resource/resource_bundle.h"

namespace {

struct { size_t id; const char* module_name_digest; }
  kExpectedInstallModules[] = {
    {1u, "c8cc47613e155f2129f480c6ced84549"},  // chrome.dll
    {2u, "49b78a23b0d8d5d8fb60d4e472b22764"},  // chrome_child.dll
  };

// Parses a line consisting of a positive decimal number and a 32-digit
// hexadecimal number, separated by a space. Inserts the output, if valid, into
// |module_ids|. Unexpected leading or trailing characters will cause
// the line to be ignored, as will invalid decimal/hexadecimal characters.
void ParseAdditionalModuleID(
    const base::StringPiece& line,
    ModuleIDs* module_ids) {
  DCHECK(module_ids);

  base::CStringTokenizer line_tokenizer(line.begin(), line.end(), " ");

  if (!line_tokenizer.GetNext())
    return;  // Empty string.
  base::StringPiece id_piece(line_tokenizer.token_piece());

  if (!line_tokenizer.GetNext())
    return;  // No delimiter (' ').
  base::StringPiece digest_piece(line_tokenizer.token_piece());

  if (line_tokenizer.GetNext())
    return;  // Unexpected trailing characters.

  unsigned id = 0;
  if (!StringToUint(id_piece, &id))
    return;  // First token was not decimal.

  if (digest_piece.length() != 32)
    return;  // Second token is not the right length.

  for (base::StringPiece::const_iterator it = digest_piece.begin();
       it != digest_piece.end(); ++it) {
    if (!IsHexDigit(*it))
      return;  // Second token has invalid characters.
  }

  // This is a valid line.
  module_ids->insert(std::make_pair(digest_piece.as_string(), id));
}

}  // namespace

void ParseAdditionalModuleIDs(
    const base::StringPiece& raw_data,
    ModuleIDs* module_ids) {
  DCHECK(module_ids);

  base::CStringTokenizer file_tokenizer(raw_data.begin(),
                                        raw_data.end(),
                                        "\r\n");
  while (file_tokenizer.GetNext()) {
    ParseAdditionalModuleID(base::StringPiece(file_tokenizer.token_piece()),
                            module_ids);
  }
}

void LoadModuleIDs(ModuleIDs* module_ids) {
  for (size_t i = 0; i < arraysize(kExpectedInstallModules); ++i) {
    module_ids->insert(
        std::make_pair(
            kExpectedInstallModules[i].module_name_digest,
            kExpectedInstallModules[i].id));
  }
  ParseAdditionalModuleIDs(
      ResourceBundle::GetSharedInstance().GetRawDataResource(
          IDR_ADDITIONAL_MODULE_IDS),
      module_ids);
}
<commit_msg>Only use IDR_ADDITIONAL_MODULE_IDS in Google Chrome builds.<commit_after>// Copyright 2013 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/install_verification/win/module_ids.h"

#include <utility>

#include "base/basictypes.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/string_util.h"
#include "grit/browser_resources.h"
#include "ui/base/resource/resource_bundle.h"

namespace {

struct { size_t id; const char* module_name_digest; }
  kExpectedInstallModules[] = {
    {1u, "c8cc47613e155f2129f480c6ced84549"},  // chrome.dll
    {2u, "49b78a23b0d8d5d8fb60d4e472b22764"},  // chrome_child.dll
  };

// Parses a line consisting of a positive decimal number and a 32-digit
// hexadecimal number, separated by a space. Inserts the output, if valid, into
// |module_ids|. Unexpected leading or trailing characters will cause
// the line to be ignored, as will invalid decimal/hexadecimal characters.
void ParseAdditionalModuleID(
    const base::StringPiece& line,
    ModuleIDs* module_ids) {
  DCHECK(module_ids);

  base::CStringTokenizer line_tokenizer(line.begin(), line.end(), " ");

  if (!line_tokenizer.GetNext())
    return;  // Empty string.
  base::StringPiece id_piece(line_tokenizer.token_piece());

  if (!line_tokenizer.GetNext())
    return;  // No delimiter (' ').
  base::StringPiece digest_piece(line_tokenizer.token_piece());

  if (line_tokenizer.GetNext())
    return;  // Unexpected trailing characters.

  unsigned id = 0;
  if (!StringToUint(id_piece, &id))
    return;  // First token was not decimal.

  if (digest_piece.length() != 32)
    return;  // Second token is not the right length.

  for (base::StringPiece::const_iterator it = digest_piece.begin();
       it != digest_piece.end(); ++it) {
    if (!IsHexDigit(*it))
      return;  // Second token has invalid characters.
  }

  // This is a valid line.
  module_ids->insert(std::make_pair(digest_piece.as_string(), id));
}

}  // namespace

void ParseAdditionalModuleIDs(
    const base::StringPiece& raw_data,
    ModuleIDs* module_ids) {
  DCHECK(module_ids);

  base::CStringTokenizer file_tokenizer(raw_data.begin(),
                                        raw_data.end(),
                                        "\r\n");
  while (file_tokenizer.GetNext()) {
    ParseAdditionalModuleID(base::StringPiece(file_tokenizer.token_piece()),
                            module_ids);
  }
}

void LoadModuleIDs(ModuleIDs* module_ids) {
  for (size_t i = 0; i < arraysize(kExpectedInstallModules); ++i) {
    module_ids->insert(
        std::make_pair(
            kExpectedInstallModules[i].module_name_digest,
            kExpectedInstallModules[i].id));
  }
  base::StringPiece additional_module_ids;
#if defined(GOOGLE_CHROME_BUILD)
  additional_module_ids =
      ResourceBundle::GetSharedInstance().GetRawDataResource(
          IDR_ADDITIONAL_MODULE_IDS);
#endif
  ParseAdditionalModuleIDs(additional_module_ids, module_ids);
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <fstream>
#include <random>
#include <cstring>
#include "mmap.h"

using namespace naivedb;

TEST(MMapTest, CheckExist) {
    char *filename = std::tmpnam(nullptr);
    std::ofstream os(filename);
    os.close();

    MemoryMappedFile file(filename);
    ASSERT_TRUE(file.isExist());
}

TEST(MMapTest, CheckNotExist) {
    char *filename = std::tmpnam(nullptr);
    MemoryMappedFile file(filename);
    ASSERT_FALSE(file.isExist());
}

TEST(MMapTest, BasicRead) {
    char *filename = std::tmpnam(nullptr);
    std::ofstream os(filename);
    char s[] = "fooFOO";
    os << s;
    os.close();

    MemoryMappedFile file(filename);
    void *view = file.get();
    ASSERT_FALSE(std::memcmp(view, s, sizeof(s)));
}

TEST(MMapTest, BasicWrite) {
    char *filename = std::tmpnam(nullptr);
    MemoryMappedFile file(filename);

    ASSERT_NO_THROW(file.create(1024));
    int buf[] = {0x01452264, 0x01573164};
    std::memcpy(file.get(), buf, sizeof(buf));
    ASSERT_NO_THROW(file.close());

    std::ifstream is(filename);
    for (auto it = std::begin(buf); it != std::end(buf); it++) {
        int i;
        is.read(reinterpret_cast<char *>(&i), sizeof(i));
        ASSERT_EQ(i, *it);
    }
}

TEST(MMapTest, RandomWrite) {
    char *filename = std::tmpnam(nullptr);
    MemoryMappedFile file(filename);
    file.create(1024 * sizeof(int));

    std::uniform_int_distribution<int> dist(0, 1023);
    std::default_random_engine generator;

    int offset = dist(generator) * sizeof(int);
    void *view = file.get(offset);
    int n = dist(generator);
    memcpy(view, &n, sizeof(n));
    file.close();

    std::ifstream is(filename);
    is.seekg(offset);
    int n_read;
    is.read(reinterpret_cast<char *>(&n_read), sizeof(n_read));
    ASSERT_EQ(n, n_read);
}
<commit_msg>Fix tests<commit_after>#include <gtest/gtest.h>
#include <fstream>
#include <random>
#include <cstring>
#include "mmap.h"

using namespace naivedb;

class MMapTest : public ::testing::Test {

protected:
    virtual void SetUp() {
        MemoryMappedFile::setMemoryLimitation(1024*1024*1024);
    }

};

TEST_F(MMapTest, CheckExist) {
    char *filename = std::tmpnam(nullptr);
    std::ofstream os(filename);
    os.close();

    MemoryMappedFile file(filename);
    ASSERT_TRUE(file.isExist());
}

TEST_F(MMapTest, CheckNotExist) {
    char *filename = std::tmpnam(nullptr);
    MemoryMappedFile file(filename);
    ASSERT_FALSE(file.isExist());
}

TEST_F(MMapTest, BasicRead) {
    char *filename = std::tmpnam(nullptr);
    std::ofstream os(filename);
    char s[] = "fooFOO";
    os << s;
    os.close();

    MemoryMappedFile file(filename);
    void *view = file.get();
    ASSERT_FALSE(std::memcmp(view, s, sizeof(s)));
}

TEST_F(MMapTest, BasicWrite) {
    char *filename = std::tmpnam(nullptr);
    MemoryMappedFile file(filename);

    ASSERT_NO_THROW(file.create(1024));
    int buf[] = {0x01452264, 0x01573164};
    std::memcpy(file.get(), buf, sizeof(buf));
    ASSERT_NO_THROW(file.close());

    std::ifstream is(filename);
    for (auto it = std::begin(buf); it != std::end(buf); it++) {
        int i;
        is.read(reinterpret_cast<char *>(&i), sizeof(i));
        ASSERT_EQ(i, *it);
    }
}

TEST_F(MMapTest, RandomWrite) {
    char *filename = std::tmpnam(nullptr);
    MemoryMappedFile file(filename);
    file.create(1024 * sizeof(int));

    std::uniform_int_distribution<int> dist(0, 1023);
    std::default_random_engine generator;

    int offset = dist(generator) * sizeof(int);
    void *view = file.get(offset);
    int n = dist(generator);
    memcpy(view, &n, sizeof(n));
    file.close();

    std::ifstream is(filename);
    is.seekg(offset);
    int n_read;
    is.read(reinterpret_cast<char *>(&n_read), sizeof(n_read));
    ASSERT_EQ(n, n_read);
}
<|endoftext|>