<commit_before>/*
 * Copyright (c) 2007-2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include <iostream>
#include <sstream>

#include "db/rt/Exception.h"
#include "db/test/Test.h"
#include "db/test/Tester.h"
#include "db/test/TestRunner.h"
#include "db/config/ConfigManager.h"
#include "db/data/json/JsonWriter.h"

using namespace std;
using namespace db::rt;
using namespace db::test;
using namespace db::config;

void runConfigManagerTest(TestRunner& tr)
{
   tr.group("ConfigManager");

   tr.test("init");
   {
      DynamicObject expect;
      expect->setType(Map);
      ConfigManager cm;
      Config cfg;
      cfg[ConfigManager::ID] = "config";
      cfg[ConfigManager::MERGE]->setType(Map);
      assert(cm.addConfig(cfg));
      assertDynoCmp(cm.getConfig("config", true), cfg);
      assertDynoCmp(cm.getConfig("config", false), expect);
      assertDynoCmp(cm.getConfig("config"), expect);
   }
   tr.passIfNoException();

   tr.test("init & clear");
   {
      DynamicObject expect;
      expect->setType(Map);
      ConfigManager cm;
      Config cfg;
      cfg[ConfigManager::ID] = "config";
      cfg[ConfigManager::MERGE]->setType(Map);
      assert(cm.addConfig(cfg));
      cm.clear();
      Config cfg2 = cm.getConfig("config");
      assert(cfg2.isNull());
   }
   tr.passIfException();

   tr.test("1 config");
   {
      DynamicObject expect;
      expect->setType(Map);
      expect["a"] = 0;
      ConfigManager cm;
      Config cfg;
      cfg[ConfigManager::ID] = "config";
      cfg[ConfigManager::MERGE]["a"] = 0;
      assert(cm.addConfig(cfg));
      assertNoException();
      assertDynoCmp(cm.getConfig("config"), expect);
   }
   tr.passIfNoException();

   tr.test("config change");
   {
      ConfigManager cm;
      Config cfg;
      cfg[ConfigManager::ID] = "config";
      cfg[ConfigManager::MERGE]["a"] = 0;
      assert(cm.addConfig(cfg));
      DynamicObject a;
      a["a"] = 0;
      assertDynoCmp(cm.getConfig("config"), a);
      Config change = cm.getConfig("config", true);
      change[ConfigManager::MERGE]["a"] = 1;
      assert(cm.setConfig(change));
      DynamicObject expect;
      expect["a"] = 1;
      assert(cm.getConfig("config") != a);
      assertDynoCmp(cm.getConfig("config"), expect);
   }
   tr.passIfNoException();

   tr.test("add");
   {
      DynamicObject expect;
      expect["a"] = 0;
      expect["b"] = 1;
      expect["c"] = 2;
      ConfigManager cm;
      Config a;
      a[ConfigManager::ID] = "config";
      a[ConfigManager::MERGE]["a"] = 0;
      Config b;
      b[ConfigManager::ID] = "config";
      b[ConfigManager::MERGE]["b"] = 1;
      Config c;
      c[ConfigManager::ID] = "config";
      c[ConfigManager::MERGE]["c"] = 2;
      assert(cm.addConfig(a));
      assertNoException();
      assert(cm.addConfig(b));
      assertNoException();
      assert(cm.addConfig(c));
      assertNoException();
      assertDynoCmp(cm.getConfig("config"), expect);
   }
   tr.passIfNoException();

   tr.test("bad remove");
   {
      ConfigManager cm;
      assert(!cm.removeConfig("error"));
      assertException();
      Exception::clearLast();
   }
   tr.passIfNoException();

   tr.test("remove");
   {
      DynamicObject expect;
      expect["a"] = 0;
      expect["b"] = 1;
      expect["c"] = 2;
      ConfigManager cm;
      Config a;
      a[ConfigManager::ID] = "config a";
      a[ConfigManager::GROUP] = "group";
      a[ConfigManager::MERGE]["a"] = 0;
      Config b;
      b[ConfigManager::ID] = "config b";
      b[ConfigManager::GROUP] = "group";
      b[ConfigManager::MERGE]["b"] = 1;
      Config c;
      c[ConfigManager::ID] = "config c";
      c[ConfigManager::GROUP] = "group";
      c[ConfigManager::MERGE]["c"] = 2;
      assert(cm.addConfig(a));
      assertNoException();
      assert(cm.addConfig(b));
      assertNoException();
      assert(cm.addConfig(c));
      assertNoException();
      assertDynoCmp(cm.getConfig("group"), expect);
      DynamicObject expect2;
      expect2["a"] = 0;
      expect2["c"] = 2;
      assert(cm.removeConfig("config b"));
      assertDynoCmp(cm.getConfig("group"), expect2);
   }
   tr.passIfNoException();

   tr.test("default value");
   {
      ConfigManager cm;
      Config a;
      a[ConfigManager::ID] = "config a";
      a[ConfigManager::MERGE] = 1;
      assert(cm.addConfig(a));
      assertNoException();
      Config b;
      b[ConfigManager::ID] = "config b";
      b[ConfigManager::PARENT] = "config a";
      b[ConfigManager::MERGE] = "__default__";
      assert(cm.addConfig(b));
      assertNoException();
      DynamicObject expect;
      expect = 1;
      assertDynoCmp(cm.getConfig("config b"), expect);
   }
   tr.passIfNoException();

   tr.test("default values");
   {
      ConfigManager cm;
      Config cfga;
      cfga[ConfigManager::ID] = "config a";
      Config& a = cfga[ConfigManager::MERGE];
      a[0] = 10;
      a[1] = 11;
      a[2]["0"] = 120;
      a[2]["1"] = 121;
      assert(cm.addConfig(cfga));
      assertNoException();
      Config cfgb;
      cfgb[ConfigManager::ID] = "config b";
      cfgb[ConfigManager::PARENT] = "config a";
      Config& b = cfgb[ConfigManager::MERGE];
      b[0] = "__default__";
      b[1] = 21;
      b[2]["0"] = "__default__";
      b[2]["1"] = 221;
      assert(cm.addConfig(cfgb));
      assertNoException();
      DynamicObject expect;
      expect[0] = 10;
      expect[1] = 21;
      expect[2]["0"] = 120;
      expect[2]["1"] = 221;
      assertDynoCmp(cm.getConfig("config b"), expect);
   }
   tr.passIfNoException();

#if 0
   tr.test("user preferences");
   {
      ConfigManager cm;

      // node
      // built in or loaded defaults
      DynamicObject nodec;
      nodec["node"]["host"] = "localhost";
      nodec["node"]["port"] = 19100;
      nodec["node"]["modulePath"] = "/usr/lib/bitmunk/modules";
      nodec["node"]["userModulePath"] = "~/.bitmunk/modules";
      assert(cm.addConfig(nodec));
      assertNoException();

      // user
      // loaded defaults
      DynamicObject userc;
      userc["node"]["port"] = 19100;
      userc["node"]["comment"] = "My precious...";
      assert(cm.addConfig(userc, ConfigManager::Custom));
      assertNoException();

      // user makes changes during runtime
      DynamicObject c = cm.getConfig();
      c["node"]["port"] = 19200;
      c["node"]["userModulePath"] = "~/.bitmunk/modules:~/.bitmunk/modules-dev";
      c["node"][ConfigManager::TMP]["not in changes"] = true;

      // get the changes from defaults to current config
      // serialize this to disk as needed
      DynamicObject changes;
      cm.getChanges(changes);

      // check it's correct
      DynamicObject expect;
      expect["node"]["port"] = 19200;
      expect["node"]["comment"] = "My precious...";
      expect["node"]["userModulePath"] = "~/.bitmunk/modules:~/.bitmunk/modules-dev";
      // NOTE: will not have TMP var
      assertDynoCmp(changes, expect);
   }
   tr.passIfNoException();
#endif

   tr.test("versioning");
   {
      ConfigManager cm;

      cm.getVersions()->clear();
      Config c;
      c[ConfigManager::ID] = "config";
      assert(cm.addConfig(c));
      assertNoException();

      cm.addVersion("1");
      assert(!cm.addConfig(c));
      assertException();
      Exception::clearLast();

      c[ConfigManager::VERSION] = "2";
      cm.removeConfig("config");
      assert(!cm.addConfig(c));
      assertException();
      Exception::clearLast();

      c[ConfigManager::VERSION] = "1";
      assert(cm.addConfig(c));
      assertNoException();

      c[ConfigManager::VERSION] = "2";
      cm.removeConfig("config");
      cm.addVersion("2");
      assert(cm.addConfig(c));
      assertNoException();
   }
   tr.passIfNoException();

   tr.test("empty array & map");
   {
      ConfigManager cm;
      DynamicObject a;
      a[ConfigManager::ID] = "config";
      a[ConfigManager::MERGE][0]->setType(Array);
      a[ConfigManager::MERGE][1]->setType(Map);
      assert(cm.addConfig(a));
      assertNoException();
      DynamicObject expect;
      expect[0]->setType(Array);
      expect[1]->setType(Map);
      assertDynoCmp(cm.getConfig("config"), expect);
   }
   tr.passIfNoException();

   tr.ungroup();
}

class DbConfigTester : public db::test::Tester
{
public:
   DbConfigTester()
   {
      setName("config");
   }

   /**
    * Run automatic unit tests.
    */
   virtual int runAutomaticTests(TestRunner& tr)
   {
      runConfigManagerTest(tr);
      return 0;
   }

   /**
    * Runs interactive unit tests.
    */
   virtual int runInteractiveTests(TestRunner& tr)
   {
      return 0;
   }
};

#ifndef DB_TEST_NO_MAIN
DB_TEST_MAIN(DbConfigTester)
#endif
<commit_msg>Fixed bugs in config test.<commit_after>/*
 * Copyright (c) 2007-2008 Digital Bazaar, Inc.  All rights reserved.
 */
#include <iostream>
#include <sstream>

#include "db/rt/Exception.h"
#include "db/test/Test.h"
#include "db/test/Tester.h"
#include "db/test/TestRunner.h"
#include "db/config/ConfigManager.h"
#include "db/data/json/JsonWriter.h"

using namespace std;
using namespace db::rt;
using namespace db::test;
using namespace db::config;

void runConfigManagerTest(TestRunner& tr)
{
   tr.group("ConfigManager");

   tr.test("init");
   {
      DynamicObject expect;
      expect->setType(Map);
      ConfigManager cm;
      Config cfg;
      cfg[ConfigManager::ID] = "config";
      cfg[ConfigManager::MERGE]->setType(Map);
      assert(cm.addConfig(cfg));
      assertDynoCmp(cm.getConfig("config", true), cfg);
      assertDynoCmp(cm.getConfig("config", false), expect);
      assertDynoCmp(cm.getConfig("config"), expect);
   }
   tr.passIfNoException();

   tr.test("init & clear");
   {
      DynamicObject expect;
      expect->setType(Map);
      ConfigManager cm;
      Config cfg;
      cfg[ConfigManager::ID] = "config";
      cfg[ConfigManager::MERGE]->setType(Map);
      assert(cm.addConfig(cfg));
      cm.clear();
      Config cfg2 = cm.getConfig("config");
      assert(cfg2.isNull());
   }
   tr.passIfException();

   tr.test("1 config");
   {
      DynamicObject expect;
      expect->setType(Map);
      expect["a"] = 0;
      ConfigManager cm;
      Config cfg;
      cfg[ConfigManager::ID] = "config";
      cfg[ConfigManager::MERGE]["a"] = 0;
      assert(cm.addConfig(cfg));
      assertNoException();
      assertDynoCmp(cm.getConfig("config"), expect);
   }
   tr.passIfNoException();

   tr.test("config change");
   {
      ConfigManager cm;
      Config cfg;
      cfg[ConfigManager::ID] = "config";
      cfg[ConfigManager::MERGE]["a"] = 0;
      assert(cm.addConfig(cfg));
      DynamicObject a;
      a["a"] = 0;
      assertDynoCmp(cm.getConfig("config"), a);
      Config change = cm.getConfig("config", true);
      change[ConfigManager::MERGE]["a"] = 1;
      assert(cm.setConfig(change));
      DynamicObject expect;
      expect["a"] = 1;
      assert(cm.getConfig("config") != a);
      assertDynoCmp(cm.getConfig("config"), expect);
   }
   tr.passIfNoException();

   tr.test("add");
   {
      DynamicObject expect;
      expect["a"] = 0;
      expect["b"] = 1;
      expect["c"] = 2;
      ConfigManager cm;
      Config a;
      a[ConfigManager::ID] = "config";
      a[ConfigManager::MERGE]["a"] = 0;
      Config b;
      b[ConfigManager::ID] = "config";
      b[ConfigManager::MERGE]["b"] = 1;
      Config c;
      c[ConfigManager::ID] = "config";
      c[ConfigManager::MERGE]["c"] = 2;
      assert(cm.addConfig(a));
      assertNoException();
      assert(cm.addConfig(b));
      assertNoException();
      assert(cm.addConfig(c));
      assertNoException();
      assertDynoCmp(cm.getConfig("config"), expect);
   }
   tr.passIfNoException();

   tr.test("bad remove");
   {
      ConfigManager cm;
      assert(!cm.removeConfig("error"));
      assertException();
      Exception::clearLast();
   }
   tr.passIfNoException();

   tr.test("remove");
   {
      DynamicObject expect;
      expect["a"] = 0;
      expect["b"] = 1;
      expect["c"] = 2;
      ConfigManager cm;
      Config a;
      a[ConfigManager::ID] = "config a";
      a[ConfigManager::GROUP] = "group";
      a[ConfigManager::MERGE]["a"] = 0;
      Config b;
      b[ConfigManager::ID] = "config b";
      b[ConfigManager::GROUP] = "group";
      b[ConfigManager::MERGE]["b"] = 1;
      Config c;
      c[ConfigManager::ID] = "config c";
      c[ConfigManager::GROUP] = "group";
      c[ConfigManager::MERGE]["c"] = 2;
      assert(cm.addConfig(a));
      assertNoException();
      assert(cm.addConfig(b));
      assertNoException();
      assert(cm.addConfig(c));
      assertNoException();
      assertDynoCmp(cm.getConfig("group"), expect);
      DynamicObject expect2;
      expect2["a"] = 0;
      expect2["c"] = 2;
      assert(cm.removeConfig("config b"));
      assertDynoCmp(cm.getConfig("group"), expect2);
   }
   tr.passIfNoException();

   tr.test("default value");
   {
      ConfigManager cm;
      Config a;
      a[ConfigManager::ID] = "config a";
      a[ConfigManager::MERGE] = 1;
      assert(cm.addConfig(a));
      assertNoException();
      Config b;
      b[ConfigManager::ID] = "config b";
      b[ConfigManager::PARENT] = "config a";
      b[ConfigManager::MERGE] = ConfigManager::DEFAULT_VALUE;
      assert(cm.addConfig(b));
      assertNoException();
      DynamicObject expect;
      expect = 1;
      assertDynoCmp(cm.getConfig("config b"), expect);
   }
   tr.passIfNoException();

   tr.test("default values");
   {
      ConfigManager cm;
      Config cfga;
      cfga[ConfigManager::ID] = "config a";
      Config& a = cfga[ConfigManager::MERGE];
      a[0] = 10;
      a[1] = 11;
      a[2]["0"] = 120;
      a[2]["1"] = 121;
      assert(cm.addConfig(cfga));
      assertNoException();
      Config cfgb;
      cfgb[ConfigManager::ID] = "config b";
      cfgb[ConfigManager::PARENT] = "config a";
      Config& b = cfgb[ConfigManager::MERGE];
      b[0] = ConfigManager::DEFAULT_VALUE;
      b[1] = 21;
      b[2]["0"] = ConfigManager::DEFAULT_VALUE;
      b[2]["1"] = 221;
      assert(cm.addConfig(cfgb));
      assertNoException();
      DynamicObject expect;
      expect[0] = 10;
      expect[1] = 21;
      expect[2]["0"] = 120;
      expect[2]["1"] = 221;
      assertDynoCmp(cm.getConfig("config b"), expect);
   }
   tr.passIfNoException();

#if 0
   tr.test("user preferences");
   {
      ConfigManager cm;

      // node
      // built in or loaded defaults
      DynamicObject nodec;
      nodec["node"]["host"] = "localhost";
      nodec["node"]["port"] = 19100;
      nodec["node"]["modulePath"] = "/usr/lib/bitmunk/modules";
      nodec["node"]["userModulePath"] = "~/.bitmunk/modules";
      assert(cm.addConfig(nodec));
      assertNoException();

      // user
      // loaded defaults
      DynamicObject userc;
      userc["node"]["port"] = 19100;
      userc["node"]["comment"] = "My precious...";
      assert(cm.addConfig(userc, ConfigManager::Custom));
      assertNoException();

      // user makes changes during runtime
      DynamicObject c = cm.getConfig();
      c["node"]["port"] = 19200;
      c["node"]["userModulePath"] = "~/.bitmunk/modules:~/.bitmunk/modules-dev";
      c["node"][ConfigManager::TMP]["not in changes"] = true;

      // get the changes from defaults to current config
      // serialize this to disk as needed
      DynamicObject changes;
      cm.getChanges(changes);

      // check it's correct
      DynamicObject expect;
      expect["node"]["port"] = 19200;
      expect["node"]["comment"] = "My precious...";
      expect["node"]["userModulePath"] = "~/.bitmunk/modules:~/.bitmunk/modules-dev";
      // NOTE: will not have TMP var
      assertDynoCmp(changes, expect);
   }
   tr.passIfNoException();
#endif

   tr.test("versioning");
   {
      ConfigManager cm;

      cm.getVersions()->clear();
      Config c;
      c[ConfigManager::ID] = "config";
      assert(cm.addConfig(c));
      assertNoException();

      cm.addVersion("1");
      assert(!cm.addConfig(c));
      assertException();
      Exception::clearLast();

      c[ConfigManager::VERSION] = "2";
      cm.removeConfig("config");
      assert(!cm.addConfig(c));
      assertException();
      Exception::clearLast();

      c[ConfigManager::VERSION] = "1";
      assert(cm.addConfig(c));
      assertNoException();

      c[ConfigManager::VERSION] = "2";
      cm.removeConfig("config");
      cm.addVersion("2");
      assert(cm.addConfig(c));
      assertNoException();
   }
   tr.passIfNoException();

   tr.test("empty array & map");
   {
      ConfigManager cm;
      DynamicObject a;
      a[ConfigManager::ID] = "config";
      a[ConfigManager::MERGE][0]->setType(Array);
      a[ConfigManager::MERGE][1]->setType(Map);
      assert(cm.addConfig(a));
      assertNoException();
      DynamicObject expect;
      expect[0]->setType(Array);
      expect[1]->setType(Map);
      assertDynoCmp(cm.getConfig("config"), expect);
   }
   tr.passIfNoException();

   tr.ungroup();
}

class DbConfigTester : public db::test::Tester
{
public:
   DbConfigTester()
   {
      setName("config");
   }

   /**
    * Run automatic unit tests.
    */
   virtual int runAutomaticTests(TestRunner& tr)
   {
      runConfigManagerTest(tr);
      return 0;
   }

   /**
    * Runs interactive unit tests.
    */
   virtual int runInteractiveTests(TestRunner& tr)
   {
      return 0;
   }
};

#ifndef DB_TEST_NO_MAIN
DB_TEST_MAIN(DbConfigTester)
#endif
<|endoftext|>


<commit_before>//////////////////////////////////////////////////
//
//   ChCCollisionSystemBullet.cpp
//
// ------------------------------------------------
// 	 Copyright:Alessandro Tasora / DeltaKnowledge
//             www.deltaknowledge.com
// ------------------------------------------------
///////////////////////////////////////////////////

#include "ChCCollisionSystemBulletParallel.h"

#include "collision/ChCModelBullet.h"
#include "collision/ChCCollisionSystem.h"
#include "physics/ChBody.h"
#include "physics/ChProximityContainerBase.h"

#include "chrono_parallel/ChParallelDefines.h"
#include "chrono_parallel/ChLcpSystemDescriptorParallel.h"

namespace chrono {
namespace collision {

/*
 void defaultChronoNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, btDispatcherInfo& dispatchInfo)
 {
 btCollisionDispatcher::defaultNearCallback(collisionPair, dispatcher, dispatchInfo);
 if (broad_callback)
 broad_callback(collisionPair, dispatcher, dispatchInfo);
 }
 */

ChCollisionSystemBulletParallel::ChCollisionSystemBulletParallel(unsigned int max_objects, double scene_size) {
	// btDefaultCollisionConstructionInfo conf_info(...); ***TODO***
	bt_collision_configuration = new btDefaultCollisionConfiguration();
	bt_dispatcher = new btCollisionDispatcher(bt_collision_configuration);

	//***OLD***

	btScalar sscene_size = (btScalar) scene_size;
	btVector3 worldAabbMin(-sscene_size, -sscene_size, -sscene_size);
	btVector3 worldAabbMax(sscene_size, sscene_size, sscene_size);
	bt_broadphase = new bt32BitAxisSweep3(worldAabbMin, worldAabbMax, max_objects, 0, true); // true for disabling raycast accelerator

	//***NEW***
	//bt_broadphase = new btDbvtBroadphase();

	bt_collision_world = new btCollisionWorld(bt_dispatcher, bt_broadphase, bt_collision_configuration);

	// custom collision for sphere-sphere case ***OBSOLETE***
	//bt_dispatcher->registerCollisionCreateFunc(SPHERE_SHAPE_PROXYTYPE,SPHERE_SHAPE_PROXYTYPE,new btSphereSphereCollisionAlgorithm::CreateFunc);

	// register custom collision for GIMPACT mesh case too
	btGImpactCollisionAlgorithm::registerAlgorithm(bt_dispatcher);

	counter = 0;

}

ChCollisionSystemBulletParallel::~ChCollisionSystemBulletParallel() {
	if (bt_collision_world)
		delete bt_collision_world;
	if (bt_broadphase)
		delete bt_broadphase;
	if (bt_dispatcher)
		delete bt_dispatcher;
	if (bt_collision_configuration)
		delete bt_collision_configuration;
}

void ChCollisionSystemBulletParallel::Clear(void) {
	int numManifolds = bt_collision_world->getDispatcher()->getNumManifolds();
	for (int i = 0; i < numManifolds; i++) {
		btPersistentManifold* contactManifold = bt_collision_world->getDispatcher()->getManifoldByIndexInternal(i);
		contactManifold->clearManifold();
	}
}

void ChCollisionSystemBulletParallel::Add(ChCollisionModel* model) {
	if (((ChModelBullet*) model)->GetBulletModel()->getCollisionShape()) {
		model->SyncPosition();
		btCollisionObject* collision_object = ((ChModelBullet*) model)->GetBulletModel();
		collision_object->setCompanionId(counter);
		int family_group =  ((ChModelBullet*) model)->GetFamilyGroup();
		int family_mask = ((ChModelBullet*) model)->GetFamilyMask();
		bt_collision_world->addCollisionObject(collision_object,family_group, family_mask);
		counter++;
		data_container->num_models++;
	}
}

void ChCollisionSystemBulletParallel::Remove(ChCollisionModel* model) {
	if (((ChModelBullet*) model)->GetBulletModel()->getCollisionShape()) {
		bt_collision_world->removeCollisionObject(((ChModelBullet*) model)->GetBulletModel());
	}
}

void ChCollisionSystemBulletParallel::Run() {
   data_container->system_timer.start("collision_broad");
	if (bt_collision_world) {
		bt_collision_world->performDiscreteCollisionDetection();
	}
	data_container->system_timer.stop("collision_broad");

}
void ChCollisionSystemBulletParallel::ReportContacts(ChContactContainerBase* mcontactcontainer) {
   data_container->system_timer.start("collision_narrow");
	data_container->host_data.norm_rigid_rigid.clear();
	data_container->host_data.cpta_rigid_rigid.clear();
	data_container->host_data.cptb_rigid_rigid.clear();
	data_container->host_data.dpth_rigid_rigid.clear();
	data_container->host_data.bids_rigid_rigid.clear();
	data_container->num_contacts = 0;
	mcontactcontainer->BeginAddContact();
	ChCollisionInfo icontact;

	int numManifolds = bt_collision_world->getDispatcher()->getNumManifolds();
	for (int i = 0; i < numManifolds; i++) {
		btPersistentManifold* contactManifold = bt_collision_world->getDispatcher()->getManifoldByIndexInternal(i);
		btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0());
		btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1());
		contactManifold->refreshContactPoints(obA->getWorldTransform(), obB->getWorldTransform());

		icontact.modelA = (ChCollisionModel*) obA->getUserPointer();
		icontact.modelB = (ChCollisionModel*) obB->getUserPointer();

		double envelopeA = icontact.modelA->GetEnvelope();
		double envelopeB = icontact.modelB->GetEnvelope();

		double marginA = icontact.modelA->GetSafeMargin();
		double marginB = icontact.modelB->GetSafeMargin();

		bool activeA = ((ChBody*) (icontact.modelA->GetPhysicsItem()))->IsActive();
		bool activeB = ((ChBody*) (icontact.modelB->GetPhysicsItem()))->IsActive();

		if (activeA == 0 && activeB == 0) {
			continue;
		}

		// Execute custom broadphase callback, if any
		bool do_narrow_contactgeneration = true;
		if (this->broad_callback)
			do_narrow_contactgeneration = this->broad_callback->BroadCallback(icontact.modelA, icontact.modelB);

		if (do_narrow_contactgeneration) {
			int numContacts = contactManifold->getNumContacts();

			for (int j = 0; j < numContacts; j++) {
				btManifoldPoint& pt = contactManifold->getContactPoint(j);

				if (pt.getDistance() < marginA + marginB) // to discard "too far" constraints (the Bullet engine also has its threshold)
						{

					btVector3 ptA = pt.getPositionWorldOnA();
					btVector3 ptB = pt.getPositionWorldOnB();

					icontact.vpA.Set(ptA.getX(), ptA.getY(), ptA.getZ());
					icontact.vpB.Set(ptB.getX(), ptB.getY(), ptB.getZ());

					icontact.vN.Set(-pt.m_normalWorldOnB.getX(), -pt.m_normalWorldOnB.getY(), -pt.m_normalWorldOnB.getZ());
					icontact.vN.Normalize();

					double ptdist = pt.getDistance();

					icontact.vpA = icontact.vpA - icontact.vN * envelopeA;
					icontact.vpB = icontact.vpB + icontact.vN * envelopeB;

					//Required because parallel code expects the offset to be done before hand, this is for performance reasons later on.
					icontact.vpA = icontact.vpA - ((ChBody*) (icontact.modelA->GetPhysicsItem()))->GetPos();
					icontact.vpB = icontact.vpB - ((ChBody*) (icontact.modelB->GetPhysicsItem()))->GetPos();

					icontact.distance = ptdist + envelopeA + envelopeB;

					icontact.reaction_cache = pt.reactions_cache;

					// Execute some user custom callback, if any
					if (this->narrow_callback)
						this->narrow_callback->NarrowCallback(icontact);

					// Add to contact container
					mcontactcontainer->AddContact(icontact);

					data_container->host_data.norm_rigid_rigid.push_back(R3(icontact.vN.x, icontact.vN.y, icontact.vN.z));
					data_container->host_data.cpta_rigid_rigid.push_back(R3(icontact.vpA.x, icontact.vpA.y, icontact.vpA.z));
					data_container->host_data.cptb_rigid_rigid.push_back(R3(icontact.vpB.x, icontact.vpB.y, icontact.vpB.z));
					data_container->host_data.dpth_rigid_rigid.push_back(icontact.distance);
					data_container->host_data.bids_rigid_rigid.push_back(I2(obA->getCompanionId(), obB->getCompanionId()));
					data_container->num_contacts++;

				}

			}
		}
		//you can un-comment out this line, and then all points are removed
		//contactManifold->clearManifold();
	}

	mcontactcontainer->EndAddContact();
	data_container->system_timer.stop("collision_narrow");
}
} // END_OF_NAMESPACE____
} // END_OF_NAMESPACE____

<commit_msg>contact container does not need to be filled<commit_after>//////////////////////////////////////////////////
//
//   ChCCollisionSystemBullet.cpp
//
// ------------------------------------------------
// 	 Copyright:Alessandro Tasora / DeltaKnowledge
//             www.deltaknowledge.com
// ------------------------------------------------
///////////////////////////////////////////////////

#include "ChCCollisionSystemBulletParallel.h"

#include "collision/ChCModelBullet.h"
#include "collision/ChCCollisionSystem.h"
#include "physics/ChBody.h"
#include "physics/ChProximityContainerBase.h"

#include "chrono_parallel/ChParallelDefines.h"
#include "chrono_parallel/ChLcpSystemDescriptorParallel.h"

namespace chrono {
namespace collision {

/*
 void defaultChronoNearCallback(btBroadphasePair& collisionPair, btCollisionDispatcher& dispatcher, btDispatcherInfo& dispatchInfo)
 {
 btCollisionDispatcher::defaultNearCallback(collisionPair, dispatcher, dispatchInfo);
 if (broad_callback)
 broad_callback(collisionPair, dispatcher, dispatchInfo);
 }
 */

ChCollisionSystemBulletParallel::ChCollisionSystemBulletParallel(unsigned int max_objects,
                                                                 double scene_size) {
   // btDefaultCollisionConstructionInfo conf_info(...); ***TODO***
   bt_collision_configuration = new btDefaultCollisionConfiguration();
   bt_dispatcher = new btCollisionDispatcher(bt_collision_configuration);

   //***OLD***

   btScalar sscene_size = (btScalar) scene_size;
   btVector3 worldAabbMin(-sscene_size, -sscene_size, -sscene_size);
   btVector3 worldAabbMax(sscene_size, sscene_size, sscene_size);
   bt_broadphase = new bt32BitAxisSweep3(worldAabbMin, worldAabbMax, max_objects, 0, true);  // true for disabling raycast accelerator

   //***NEW***
   //bt_broadphase = new btDbvtBroadphase();

   bt_collision_world = new btCollisionWorld(bt_dispatcher, bt_broadphase, bt_collision_configuration);

   // custom collision for sphere-sphere case ***OBSOLETE***
   //bt_dispatcher->registerCollisionCreateFunc(SPHERE_SHAPE_PROXYTYPE,SPHERE_SHAPE_PROXYTYPE,new btSphereSphereCollisionAlgorithm::CreateFunc);

   // register custom collision for GIMPACT mesh case too
   btGImpactCollisionAlgorithm::registerAlgorithm(bt_dispatcher);

   counter = 0;

}

ChCollisionSystemBulletParallel::~ChCollisionSystemBulletParallel() {
   if (bt_collision_world)
      delete bt_collision_world;
   if (bt_broadphase)
      delete bt_broadphase;
   if (bt_dispatcher)
      delete bt_dispatcher;
   if (bt_collision_configuration)
      delete bt_collision_configuration;
}

void ChCollisionSystemBulletParallel::Clear(void) {
   int numManifolds = bt_collision_world->getDispatcher()->getNumManifolds();
   for (int i = 0; i < numManifolds; i++) {
      btPersistentManifold* contactManifold = bt_collision_world->getDispatcher()->getManifoldByIndexInternal(i);
      contactManifold->clearManifold();
   }
}

void ChCollisionSystemBulletParallel::Add(ChCollisionModel* model) {
   if (((ChModelBullet*) model)->GetBulletModel()->getCollisionShape()) {
      model->SyncPosition();
      btCollisionObject* collision_object = ((ChModelBullet*) model)->GetBulletModel();
      collision_object->setCompanionId(counter);
      int family_group = ((ChModelBullet*) model)->GetFamilyGroup();
      int family_mask = ((ChModelBullet*) model)->GetFamilyMask();
      bt_collision_world->addCollisionObject(collision_object, family_group, family_mask);
      counter++;
      data_container->num_models++;
   }
}

void ChCollisionSystemBulletParallel::Remove(ChCollisionModel* model) {
   if (((ChModelBullet*) model)->GetBulletModel()->getCollisionShape()) {
      bt_collision_world->removeCollisionObject(((ChModelBullet*) model)->GetBulletModel());
   }
}

void ChCollisionSystemBulletParallel::Run() {
   data_container->system_timer.start("collision_broad");
   if (bt_collision_world) {
      bt_collision_world->performDiscreteCollisionDetection();
   }
   data_container->system_timer.stop("collision_broad");

}
void ChCollisionSystemBulletParallel::ReportContacts(ChContactContainerBase* mcontactcontainer) {
   data_container->system_timer.start("collision_narrow");
   data_container->host_data.norm_rigid_rigid.clear();
   data_container->host_data.cpta_rigid_rigid.clear();
   data_container->host_data.cptb_rigid_rigid.clear();
   data_container->host_data.dpth_rigid_rigid.clear();
   data_container->host_data.bids_rigid_rigid.clear();
   data_container->num_contacts = 0;
   //mcontactcontainer->BeginAddContact();
   ChCollisionInfo icontact;

   int numManifolds = bt_collision_world->getDispatcher()->getNumManifolds();
   for (int i = 0; i < numManifolds; i++) {
      btPersistentManifold* contactManifold = bt_collision_world->getDispatcher()->getManifoldByIndexInternal(i);
      btCollisionObject* obA = static_cast<btCollisionObject*>(contactManifold->getBody0());
      btCollisionObject* obB = static_cast<btCollisionObject*>(contactManifold->getBody1());
      contactManifold->refreshContactPoints(obA->getWorldTransform(), obB->getWorldTransform());

      icontact.modelA = (ChCollisionModel*) obA->getUserPointer();
      icontact.modelB = (ChCollisionModel*) obB->getUserPointer();

      double envelopeA = icontact.modelA->GetEnvelope();
      double envelopeB = icontact.modelB->GetEnvelope();

      double marginA = icontact.modelA->GetSafeMargin();
      double marginB = icontact.modelB->GetSafeMargin();

      bool activeA = ((ChBody*) (icontact.modelA->GetPhysicsItem()))->IsActive();
      bool activeB = ((ChBody*) (icontact.modelB->GetPhysicsItem()))->IsActive();

      if (activeA == 0 && activeB == 0) {
         continue;
      }

      // Execute custom broadphase callback, if any
      bool do_narrow_contactgeneration = true;
      if (this->broad_callback)
         do_narrow_contactgeneration = this->broad_callback->BroadCallback(icontact.modelA, icontact.modelB);

      if (do_narrow_contactgeneration) {
         int numContacts = contactManifold->getNumContacts();

         for (int j = 0; j < numContacts; j++) {
            btManifoldPoint& pt = contactManifold->getContactPoint(j);

            if (pt.getDistance() < marginA + marginB)  // to discard "too far" constraints (the Bullet engine also has its threshold)
                  {

               btVector3 ptA = pt.getPositionWorldOnA();
               btVector3 ptB = pt.getPositionWorldOnB();

               icontact.vpA.Set(ptA.getX(), ptA.getY(), ptA.getZ());
               icontact.vpB.Set(ptB.getX(), ptB.getY(), ptB.getZ());

               icontact.vN.Set(-pt.m_normalWorldOnB.getX(), -pt.m_normalWorldOnB.getY(), -pt.m_normalWorldOnB.getZ());
               icontact.vN.Normalize();

               double ptdist = pt.getDistance();

               icontact.vpA = icontact.vpA - icontact.vN * envelopeA;
               icontact.vpB = icontact.vpB + icontact.vN * envelopeB;

               //Required because parallel code expects the offset to be done before hand, this is for performance reasons later on.
               icontact.vpA = icontact.vpA - ((ChBody*) (icontact.modelA->GetPhysicsItem()))->GetPos();
               icontact.vpB = icontact.vpB - ((ChBody*) (icontact.modelB->GetPhysicsItem()))->GetPos();

               icontact.distance = ptdist + envelopeA + envelopeB;

               icontact.reaction_cache = pt.reactions_cache;

               // Execute some user custom callback, if any
               if (this->narrow_callback)
                  this->narrow_callback->NarrowCallback(icontact);

               // Add to contact container
               //mcontactcontainer->AddContact(icontact);

               data_container->host_data.norm_rigid_rigid.push_back(R3(icontact.vN.x, icontact.vN.y, icontact.vN.z));
               data_container->host_data.cpta_rigid_rigid.push_back(R3(icontact.vpA.x, icontact.vpA.y, icontact.vpA.z));
               data_container->host_data.cptb_rigid_rigid.push_back(R3(icontact.vpB.x, icontact.vpB.y, icontact.vpB.z));
               data_container->host_data.dpth_rigid_rigid.push_back(icontact.distance);
               data_container->host_data.bids_rigid_rigid.push_back(I2(obA->getCompanionId(), obB->getCompanionId()));
               data_container->num_contacts++;

            }

         }
      }
      //you can un-comment out this line, and then all points are removed
      //contactManifold->clearManifold();
   }

   //mcontactcontainer->EndAddContact();
   data_container->system_timer.stop("collision_narrow");
}
}  // END_OF_NAMESPACE____
}  // END_OF_NAMESPACE____

<|endoftext|>


<commit_before>#include <archie/utils/fused/find.h>
#include <archie/utils/test.h>
#include <type_traits>

namespace fused = archie::utils::fused;

void canUseFusedFind() {
  unsigned a = 0u;
  int b = 1;
  char c = '2';
  double d = 3.0;
  unsigned e = 4u;

  auto x = fused::find<unsigned&>(a, b, c, d, e);
  auto y = fused::find<double&>(a, b, c, d, e);
  EXPECT_EQ(a, x);
  EXPECT_EQ(d, y);
}

template <typename Tp>
using is_u = std::is_unsigned<std::decay_t<Tp>>;

template <typename Tp>
using is_s = std::is_signed<std::decay_t<Tp>>;

void canUseFusedFindIf() {
  unsigned a = 0u;
  int b = 1;
  char c = '2';
  double d = 3.0;
  unsigned e = 4u;

  auto x = fused::find_if<is_u>(a, b, c, d, e);
  auto y = fused::find_if<is_s>(a, b, c, d, e);
  EXPECT_EQ(a, x);
  EXPECT_EQ(b, y);
}

int main() {
  canUseFusedFind();
  canUseFusedFindIf();
  return 0;
}
<commit_msg>fused::find with rvalue<commit_after>#include <archie/utils/fused/find.h>
#include <archie/utils/test.h>
#include <type_traits>

namespace fused = archie::utils::fused;

void canUseFusedFind() {
  unsigned a = 0u;
  int b = 1;
  char c = '2';
  double d = 3.0;
  unsigned e = 4u;

  auto x = fused::find<unsigned&>(a, b, c, d, e);
  auto y = fused::find<double&>(a, b, c, d, e);
  EXPECT_EQ(a, x);
  EXPECT_EQ(d, y);

  EXPECT_EQ(1, fused::find<int>(1, 2u, 3.0, '4'));
  EXPECT_EQ(2u, fused::find<unsigned>(1, 2u, 3.0, '4'));
  EXPECT_EQ(3.0, fused::find<double>(1, 2u, 3.0, '4'));
  EXPECT_EQ('4', fused::find<char>(1, 2u, 3.0, '4'));
}

template <typename Tp>
using is_u = std::is_unsigned<std::decay_t<Tp>>;

template <typename Tp>
using is_s = std::is_signed<std::decay_t<Tp>>;

void canUseFusedFindIf() {
  unsigned a = 0u;
  int b = 1;
  char c = '2';
  double d = 3.0;
  unsigned e = 4u;

  auto x = fused::find_if<is_u>(a, b, c, d, e);
  auto y = fused::find_if<is_s>(a, b, c, d, e);
  EXPECT_EQ(a, x);
  EXPECT_EQ(b, y);
}

int main() {
  canUseFusedFind();
  canUseFusedFindIf();
  return 0;
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Mathematics (glm.g-truc.net)
///
/// Copyright (c) 2005 - 2015 G-Truc Creation (www.g-truc.net)
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Restrictions:
///		By making use of the Software for military purposes, you choose to make
///		a Bunny unhappy.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
///
/// @file test/gtx/gtx_integer.cpp
/// @date 2011-10-11 / 2014-11-25
/// @author Christophe Riccio
///////////////////////////////////////////////////////////////////////////////////

#include <glm/exponential.hpp>
#include <glm/gtc/epsilon.hpp>
#include <glm/gtx/integer.hpp>
#include <cstdio>
/*
int test_floor_log2()
{
	int Error = 0;

	for(std::size_t i = 1; i < 1000000; ++i)
	{
		glm::uint A = glm::floor_log2(glm::uint(i));
		glm::uint B = glm::uint(glm::floor(glm::log2(double(i)))); // Will fail with float, lack of accuracy

		Error += A == B ? 0 : 1;
		assert(!Error);
	}

	return Error;
}
*/
int test_log2()
{
	int Error = 0;

	for(std::size_t i = 1; i < 24; ++i)
	{
		glm::uint A = glm::log2(glm::uint(1 << i));
		glm::uint B = glm::uint(glm::log2(double(1 << i)));

		//Error += glm::equalEpsilon(double(A), B, 1.0) ? 0 : 1;
		Error += glm::abs(double(A) - B) <= 24 ? 0 : 1;
		assert(!Error);

		printf("Log2(%d) Error: %d, %d\n", 1 << i, A, B);
	}

	printf("log2 error: %d\n", Error);

	return Error;
}

int test_nlz()
{
	int Error = 0;

	for(glm::uint i = 1; i < glm::uint(33); ++i)
		Error += glm::nlz(i) == glm::uint(31u) - glm::findMSB(i) ? 0 : 1;
		//printf("%d, %d\n", glm::nlz(i), 31u - glm::findMSB(i));

	return Error;
}

int main()
{
	int Error = 0;

	Error += test_nlz();
//	Error += test_floor_log2();
	Error += test_log2();

	return Error;
}

<commit_msg>test: Don't use 'Error:' or 'error:' in test output<commit_after>///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Mathematics (glm.g-truc.net)
///
/// Copyright (c) 2005 - 2015 G-Truc Creation (www.g-truc.net)
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Restrictions:
///		By making use of the Software for military purposes, you choose to make
///		a Bunny unhappy.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
///
/// @file test/gtx/gtx_integer.cpp
/// @date 2011-10-11 / 2014-11-25
/// @author Christophe Riccio
///////////////////////////////////////////////////////////////////////////////////

#include <glm/exponential.hpp>
#include <glm/gtc/epsilon.hpp>
#include <glm/gtx/integer.hpp>
#include <cstdio>
/*
int test_floor_log2()
{
	int Error = 0;

	for(std::size_t i = 1; i < 1000000; ++i)
	{
		glm::uint A = glm::floor_log2(glm::uint(i));
		glm::uint B = glm::uint(glm::floor(glm::log2(double(i)))); // Will fail with float, lack of accuracy

		Error += A == B ? 0 : 1;
		assert(!Error);
	}

	return Error;
}
*/
int test_log2()
{
	int Error = 0;

	for(std::size_t i = 1; i < 24; ++i)
	{
		glm::uint A = glm::log2(glm::uint(1 << i));
		glm::uint B = glm::uint(glm::log2(double(1 << i)));

		//Error += glm::equalEpsilon(double(A), B, 1.0) ? 0 : 1;
		Error += glm::abs(double(A) - B) <= 24 ? 0 : 1;
		assert(!Error);

		printf("Log2(%d) error A=%d, B=%d\n", 1 << i, A, B);
	}

	printf("log2 error=%d\n", Error);

	return Error;
}

int test_nlz()
{
	int Error = 0;

	for(glm::uint i = 1; i < glm::uint(33); ++i)
		Error += glm::nlz(i) == glm::uint(31u) - glm::findMSB(i) ? 0 : 1;
		//printf("%d, %d\n", glm::nlz(i), 31u - glm::findMSB(i));

	return Error;
}

int main()
{
	int Error = 0;

	Error += test_nlz();
//	Error += test_floor_log2();
	Error += test_log2();

	return Error;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: LogarithmicRegressionCurveCalculator.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 13:26:01 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "LogarithmicRegressionCurveCalculator.hxx"
#include "macros.hxx"
#include "RegressionCalculationHelper.hxx"

#ifndef INCLUDED_RTL_MATH_HXX
#include <rtl/math.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

using namespace ::com::sun::star;

using ::rtl::OUString;
using ::rtl::OUStringBuffer;

namespace chart
{

LogarithmicRegressionCurveCalculator::LogarithmicRegressionCurveCalculator() :
        m_fSlope( 0.0 ),
        m_fIntercept( 0.0 ),
        m_fCorrelationCoeffitient( 0.0 )
{
    ::rtl::math::setNan( & m_fSlope );
    ::rtl::math::setNan( & m_fIntercept );
    ::rtl::math::setNan( & m_fCorrelationCoeffitient );
}

LogarithmicRegressionCurveCalculator::~LogarithmicRegressionCurveCalculator()
{}

// ____ XRegressionCurve ____
void SAL_CALL LogarithmicRegressionCurveCalculator::recalculateRegression(
    const uno::Sequence< double >& aXValues,
    const uno::Sequence< double >& aYValues )
    throw (uno::RuntimeException)
{
    RegressionCalculationHelper::tDoubleVectorPair aValues(
        RegressionCalculationHelper::cleanup(
            aXValues, aYValues,
            RegressionCalculationHelper::isValidAndXPositive()));

    const size_t nMax = aValues.first.size();
    if( nMax == 0 )
    {
        ::rtl::math::setNan( & m_fSlope );
        ::rtl::math::setNan( & m_fIntercept );
        ::rtl::math::setNan( & m_fCorrelationCoeffitient );
        return;
    }

    double fAverageX = 0.0, fAverageY = 0.0;
    size_t i = 0;
    for( i = 0; i < nMax; ++i )
    {
        fAverageX += log( aValues.first[i] );
        fAverageY += aValues.second[i];
    }

    const double fN = static_cast< double >( nMax );
    fAverageX /= fN;
    fAverageY /= fN;

    double fQx = 0.0, fQy = 0.0, fQxy = 0.0;
    for( i = 0; i < nMax; ++i )
    {
        double fDeltaX = log( aValues.first[i] ) - fAverageX;
        double fDeltaY = aValues.second[i] - fAverageY;

        fQx  += fDeltaX * fDeltaX;
        fQy  += fDeltaY * fDeltaY;
        fQxy += fDeltaX * fDeltaY;
    }

    m_fSlope = fQxy / fQx;
    m_fIntercept = fAverageY - m_fSlope * fAverageX;
    m_fCorrelationCoeffitient = fQxy / sqrt( fQx * fQy );
}

double SAL_CALL LogarithmicRegressionCurveCalculator::getCurveValue( double x )
    throw (lang::IllegalArgumentException,
           uno::RuntimeException)
{
    double fResult;
    ::rtl::math::setNan( & fResult );

    if( ! ( ::rtl::math::isNan( m_fSlope ) ||
            ::rtl::math::isNan( m_fIntercept )))
    {
        fResult = m_fSlope * log( x ) + m_fIntercept;
    }

    return fResult;
}

double SAL_CALL LogarithmicRegressionCurveCalculator::getCorrelationCoefficient()
    throw (uno::RuntimeException)
{
    return m_fCorrelationCoeffitient;
}

OUString SAL_CALL LogarithmicRegressionCurveCalculator::getRepresentation()
    throw (uno::RuntimeException)
{
    OUStringBuffer aBuf( C2U( "f(x) = " ));

    bool bHaveSlope = false;

    if( m_fSlope != 0.0 )
    {
        if( ! ::rtl::math::approxEqual( m_fSlope, 1.0 ))
        {
            aBuf.append( NUMBER_TO_STR( m_fSlope ));
            aBuf.append( sal_Unicode( ' ' ));
            aBuf.append( sal_Unicode( 0x00b7 ));
            aBuf.append( sal_Unicode( ' ' ));
        }
        aBuf.appendAscii( RTL_CONSTASCII_STRINGPARAM( "log(x)" ));
        bHaveSlope = true;
    }

    if( m_fIntercept != 0.0 )
    {
        if( ! bHaveSlope )
        {
            aBuf.append( NUMBER_TO_STR( m_fIntercept ));
        }
        else
        {
            if( m_fIntercept < 0.0 )
            {
                aBuf.appendAscii( RTL_CONSTASCII_STRINGPARAM( " - " ));
                aBuf.append( NUMBER_TO_STR( fabs( m_fIntercept )));
            }
            else
            {
                aBuf.appendAscii( RTL_CONSTASCII_STRINGPARAM( " + " ));
                aBuf.append( NUMBER_TO_STR( m_fIntercept ));
            }
        }
    }

    return aBuf.makeStringAndClear();
}

} //  namespace chart
<commit_msg>INTEGRATION: CWS chart17 (1.6.110); FILE MERGED 2007/10/23 15:02:36 bm 1.6.110.2: #i82891# improve rendering of regression curves using XRegressionCurveCalculator::getCurveValues() 2007/10/12 12:35:09 bm 1.6.110.1: #i7998# equations for regression curves<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: LogarithmicRegressionCurveCalculator.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-23 12:05:55 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "LogarithmicRegressionCurveCalculator.hxx"
#include "macros.hxx"
#include "RegressionCalculationHelper.hxx"

#include <rtl/math.hxx>
#include <rtl/ustrbuf.hxx>

using namespace ::com::sun::star;

using ::rtl::OUString;
using ::rtl::OUStringBuffer;

namespace chart
{

LogarithmicRegressionCurveCalculator::LogarithmicRegressionCurveCalculator() :
        m_fSlope( 0.0 ),
        m_fIntercept( 0.0 )
{
    ::rtl::math::setNan( & m_fSlope );
    ::rtl::math::setNan( & m_fIntercept );
}

LogarithmicRegressionCurveCalculator::~LogarithmicRegressionCurveCalculator()
{}

// ____ XRegressionCurve ____
void SAL_CALL LogarithmicRegressionCurveCalculator::recalculateRegression(
    const uno::Sequence< double >& aXValues,
    const uno::Sequence< double >& aYValues )
    throw (uno::RuntimeException)
{
    RegressionCalculationHelper::tDoubleVectorPair aValues(
        RegressionCalculationHelper::cleanup(
            aXValues, aYValues,
            RegressionCalculationHelper::isValidAndXPositive()));

    const size_t nMax = aValues.first.size();
    if( nMax == 0 )
    {
        ::rtl::math::setNan( & m_fSlope );
        ::rtl::math::setNan( & m_fIntercept );
        ::rtl::math::setNan( & m_fCorrelationCoeffitient );
        return;
    }

    double fAverageX = 0.0, fAverageY = 0.0;
    size_t i = 0;
    for( i = 0; i < nMax; ++i )
    {
        fAverageX += log( aValues.first[i] );
        fAverageY += aValues.second[i];
    }

    const double fN = static_cast< double >( nMax );
    fAverageX /= fN;
    fAverageY /= fN;

    double fQx = 0.0, fQy = 0.0, fQxy = 0.0;
    for( i = 0; i < nMax; ++i )
    {
        double fDeltaX = log( aValues.first[i] ) - fAverageX;
        double fDeltaY = aValues.second[i] - fAverageY;

        fQx  += fDeltaX * fDeltaX;
        fQy  += fDeltaY * fDeltaY;
        fQxy += fDeltaX * fDeltaY;
    }

    m_fSlope = fQxy / fQx;
    m_fIntercept = fAverageY - m_fSlope * fAverageX;
    m_fCorrelationCoeffitient = fQxy / sqrt( fQx * fQy );
}

double SAL_CALL LogarithmicRegressionCurveCalculator::getCurveValue( double x )
    throw (lang::IllegalArgumentException,
           uno::RuntimeException)
{
    double fResult;
    ::rtl::math::setNan( & fResult );

    if( ! ( ::rtl::math::isNan( m_fSlope ) ||
            ::rtl::math::isNan( m_fIntercept )))
    {
        fResult = m_fSlope * log( x ) + m_fIntercept;
    }

    return fResult;
}

uno::Sequence< geometry::RealPoint2D > SAL_CALL LogarithmicRegressionCurveCalculator::getCurveValues(
    double min, double max, ::sal_Int32 nPointCount,
    const uno::Reference< chart2::XScaling >& xScalingX,
    const uno::Reference< chart2::XScaling >& xScalingY,
    ::sal_Bool bMaySkipPointsInCalculation )
    throw (lang::IllegalArgumentException,
           uno::RuntimeException)
{
    if( bMaySkipPointsInCalculation &&
        isLogarithmicScaling( xScalingX ) &&
        isLinearScaling( xScalingY ))
    {
        // optimize result
        uno::Sequence< geometry::RealPoint2D > aResult( 2 );
        aResult[0].X = min;
        aResult[0].Y = this->getCurveValue( min );
        aResult[1].X = max;
        aResult[1].Y = this->getCurveValue( max );

        return aResult;
    }
    return RegressionCurveCalculator::getCurveValues( min, max, nPointCount, xScalingX, xScalingY, bMaySkipPointsInCalculation );
}

OUString LogarithmicRegressionCurveCalculator::ImplGetRepresentation(
    const uno::Reference< util::XNumberFormatter >& xNumFormatter,
    ::sal_Int32 nNumberFormatKey ) const
{
    OUStringBuffer aBuf( C2U( "f(x) = " ));

    bool bHaveSlope = false;

    if( m_fSlope != 0.0 )
    {
        if( ::rtl::math::approxEqual( fabs( m_fSlope ), 1.0 ))
        {
            if( m_fSlope < 0 )
                aBuf.append( UC_MINUS_SIGN );
        }
        else
        {
            aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, m_fSlope ));
            aBuf.append( UC_SPACE );
        }
        aBuf.appendAscii( RTL_CONSTASCII_STRINGPARAM( "log(x)" ));
        bHaveSlope = true;
    }

    if( bHaveSlope )
    {
        if( m_fIntercept < 0.0 )
        {
            aBuf.append( UC_SPACE );
            aBuf.append( UC_MINUS_SIGN );
            aBuf.append( UC_SPACE );
            aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, fabs( m_fIntercept )));
        }
        else if( m_fIntercept > 0.0 )
        {
            aBuf.appendAscii( RTL_CONSTASCII_STRINGPARAM( " + " ));
            aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, m_fIntercept ));
        }
    }
    else
    {
        aBuf.append( getFormattedString( xNumFormatter, nNumberFormatKey, m_fIntercept ));
    }

    return aBuf.makeStringAndClear();
}

} //  namespace chart
<|endoftext|>


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

#include <string>

#include "app/l10n_util.h"
#include "base/file_path.h"
#include "base/gfx/rect.h"
#include "chrome/browser/view_ids.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/test/automation/automation_constants.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "grit/generated_resources.h"
#include "net/base/net_util.h"
#include "views/event.h"

class BlockedPopupContainerInteractiveTest : public UITest {
 protected:
  BlockedPopupContainerInteractiveTest() {
    show_window_ = true;
  }

  virtual void SetUp() {
    UITest::SetUp();

    browser_ = automation()->GetBrowserWindow(0);
    ASSERT_TRUE(browser_.get());

    window_ = browser_->GetWindow();
    ASSERT_TRUE(window_.get());

    tab_ = browser_->GetTab(0);
    ASSERT_TRUE(tab_.get());
  }

  void NavigateMainTabTo(const std::wstring& file_name) {
    FilePath filename(test_data_directory_);
    filename = filename.AppendASCII("constrained_files");
    filename = filename.Append(FilePath::FromWStringHack(file_name));
    ASSERT_TRUE(tab_->NavigateToURL(net::FilePathToFileURL(filename)));
  }

  void SimulateClickInCenterOf(const scoped_refptr<WindowProxy>& window) {
    gfx::Rect tab_view_bounds;
    ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER,
                                      &tab_view_bounds, true));

    // Simulate a click of the actual link to force user_gesture to be
    // true; if we don't, the resulting popup will be constrained, which
    // isn't what we want to test.
    ASSERT_TRUE(window->SimulateOSClick(tab_view_bounds.CenterPoint(),
                                        views::Event::EF_LEFT_BUTTON_DOWN));
  }

  scoped_refptr<BrowserProxy> browser_;
  scoped_refptr<WindowProxy> window_;
  scoped_refptr<TabProxy> tab_;
};

TEST_F(BlockedPopupContainerInteractiveTest, TestOpenAndResizeTo) {
  NavigateMainTabTo(L"constrained_window_onload_resizeto.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser != NULL);
  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());
  ASSERT_TRUE(popup_window != NULL);

  // Make sure we were created with the correct width and height.
  gfx::Rect rect;
  bool is_timeout = false;
  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(
                  VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));
  ASSERT_FALSE(is_timeout);

#if !defined(OS_LINUX)
  // TODO(estade): This is a real failure; we create popups with the wrong size.
  // Fix it. Note: it appears that we are setting the window's bounds to 300,320
  // instead of setting the content's bounds to 300,320.
  EXPECT_EQ(300, rect.width());
  EXPECT_EQ(320, rect.height());
#endif

  SimulateClickInCenterOf(popup_window);

  // No idea how to wait here other then sleeping. This timeout used to be
  // lower, then we started hitting it before it was done. :(
  PlatformThread::Sleep(5000);

  // The actual content will be LESS than (200, 200) because resizeTo
  // deals with a window's outer{Width,Height} instead of its
  // inner{Width,Height}.
  is_timeout = false;
  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(
                 VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));
  ASSERT_FALSE(is_timeout);
  EXPECT_LT(rect.height(), 200);
#if defined(OS_LINUX)
  // On Linux we may run in an environment where there is no window frame. In
  // this case our width might be exactly 200. The height will still be less
  // because we have to show the location bar.
  EXPECT_LE(rect.width(), 200);
#else
  EXPECT_LT(rect.width(), 200);
#endif
}

// Helper function used to get the number of blocked popups out of the window
// title.
bool ParseCountOutOfTitle(const std::wstring& title, int* output) {
  // Since we will be reading the number of popup windows open by grabbing the
  // number out of the window title, and that format string is localized, we
  // need to find out the offset into that string.
  const wchar_t* placeholder = L"XXXX";
  size_t offset =
      l10n_util::GetStringF(IDS_POPUPS_BLOCKED_COUNT, placeholder).
      find(placeholder);

  std::wstring number;
  while (offset < title.size() && iswdigit(title[offset])) {
    number += title[offset];
    offset++;
  }

  return StringToInt(WideToUTF16(number), output);
}

// Tests that in the window.open() equivalent of a fork bomb, we stop building
// windows.
TEST_F(BlockedPopupContainerInteractiveTest, DontSpawnEndlessPopups) {
  NavigateMainTabTo(L"infinite_popups.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser.get());
  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));
  ASSERT_TRUE(popup_tab.get());

  // And now we spin, waiting to make sure that we don't spawn popup
  // windows endlessly. The current limit is 25, so allowing for possible race
  // conditions and one off errors, don't break out until we go over 30 popup
  // windows (in which case we are bork bork bork).
  const int kMaxPopupWindows = 30;

  int popup_window_count = 0;
  int new_popup_window_count = 0;
  int times_slept = 0;
  bool continuing = true;
  while (continuing && popup_window_count < kMaxPopupWindows) {
    ASSERT_TRUE(popup_tab->GetBlockedPopupCount(&new_popup_window_count));
    if (new_popup_window_count == popup_window_count) {
      if (times_slept == 10) {
        continuing = false;
      } else {
        // Nothing intereseting is going on wait it out.
        PlatformThread::Sleep(automation::kSleepTime);
        times_slept++;
      }
    } else {
      times_slept = 0;
    }

    EXPECT_GE(new_popup_window_count, popup_window_count);
    EXPECT_LE(new_popup_window_count, kMaxPopupWindows);
    popup_window_count = new_popup_window_count;
  }
}

// Make sure that we refuse to close windows when a constrained popup is
// displayed.
TEST_F(BlockedPopupContainerInteractiveTest, WindowOpenWindowClosePopup) {
  NavigateMainTabTo(L"openclose_main.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));

  // Make sure we have a blocked popup notification
  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser.get());
  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());
  ASSERT_TRUE(popup_window.get());
  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));
  ASSERT_TRUE(popup_tab.get());
  ASSERT_TRUE(popup_tab->WaitForBlockedPopupCountToChangeTo(1, 1000));

  // Ensure we didn't close the first popup window.
  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 3000));
}

TEST_F(BlockedPopupContainerInteractiveTest, BlockAlertFromBlockedPopup) {
  NavigateMainTabTo(L"block_alert.html");

  // Wait for there to be an app modal dialog (and fail if it's shown).
  ASSERT_FALSE(automation()->WaitForAppModalDialog(4000));

  // Ensure one browser window.
  int browser_window_count;
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&browser_window_count));
  ASSERT_EQ(1, browser_window_count);

  // Ensure one blocked popup window: the popup didn't escape.
  int popup_count = 0;
  ASSERT_TRUE(tab_->GetBlockedPopupCount(&popup_count));
  ASSERT_EQ(1, popup_count);
}

TEST_F(BlockedPopupContainerInteractiveTest, ShowAlertFromNormalPopup) {
  NavigateMainTabTo(L"show_alert.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));

  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser.get());
  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());
  ASSERT_TRUE(popup_window.get());
  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));
  ASSERT_TRUE(popup_tab.get());

  SimulateClickInCenterOf(popup_window);

  // Wait for there to be an app modal dialog.
  ASSERT_TRUE(automation()->WaitForAppModalDialog(5000));
}

// Make sure that window focus works while creating a popup window so that we
// don't
TEST_F(BlockedPopupContainerInteractiveTest, DontBreakOnBlur) {
  NavigateMainTabTo(L"window_blur_test.html");
  SimulateClickInCenterOf(window_);

  // Wait for the popup window to open.
  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  // We popup shouldn't be closed by the onblur handler.
  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 1500));
}
<commit_msg>Fix 2 failing BlockedPopupContainerInteractiveTests on Linux.<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>

#include "app/l10n_util.h"
#include "base/file_path.h"
#include "base/gfx/rect.h"
#include "chrome/browser/view_ids.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/test/automation/automation_constants.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "grit/generated_resources.h"
#include "net/base/net_util.h"
#include "views/event.h"

class BlockedPopupContainerInteractiveTest : public UITest {
 protected:
  BlockedPopupContainerInteractiveTest() {
    show_window_ = true;
  }

  virtual void SetUp() {
    UITest::SetUp();

    browser_ = automation()->GetBrowserWindow(0);
    ASSERT_TRUE(browser_.get());

    window_ = browser_->GetWindow();
    ASSERT_TRUE(window_.get());

    tab_ = browser_->GetTab(0);
    ASSERT_TRUE(tab_.get());
  }

  void NavigateMainTabTo(const std::wstring& file_name) {
    FilePath filename(test_data_directory_);
    filename = filename.AppendASCII("constrained_files");
    filename = filename.Append(FilePath::FromWStringHack(file_name));
    ASSERT_TRUE(tab_->NavigateToURL(net::FilePathToFileURL(filename)));
  }

  void SimulateClickInCenterOf(const scoped_refptr<WindowProxy>& window) {
    gfx::Rect tab_view_bounds;
    ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER,
                                      &tab_view_bounds, true));

    // Simulate a click of the actual link to force user_gesture to be
    // true; if we don't, the resulting popup will be constrained, which
    // isn't what we want to test.
    ASSERT_TRUE(window->SimulateOSClick(tab_view_bounds.CenterPoint(),
                                        views::Event::EF_LEFT_BUTTON_DOWN));
  }

  scoped_refptr<BrowserProxy> browser_;
  scoped_refptr<WindowProxy> window_;
  scoped_refptr<TabProxy> tab_;
};

TEST_F(BlockedPopupContainerInteractiveTest, TestOpenAndResizeTo) {
  NavigateMainTabTo(L"constrained_window_onload_resizeto.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser != NULL);
  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());
  ASSERT_TRUE(popup_window != NULL);

  // Make sure we were created with the correct width and height.
  gfx::Rect rect;
  bool is_timeout = false;
  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(
                  VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));
  ASSERT_FALSE(is_timeout);

#if !defined(OS_LINUX)
  // TODO(estade): This is a real failure; we create popups with the wrong size.
  // Fix it. Note: it appears that we are setting the window's bounds to 300,320
  // instead of setting the content's bounds to 300,320.
  EXPECT_EQ(300, rect.width());
  EXPECT_EQ(320, rect.height());
#endif

#if defined(OS_LINUX)
  // It seems we have to wait a little bit for the widgets to spin up before
  // we can start clicking on them.
  PlatformThread::Sleep(500);
#endif

  SimulateClickInCenterOf(popup_window);

  // No idea how to wait here other then sleeping. This timeout used to be
  // lower, then we started hitting it before it was done. :(
  PlatformThread::Sleep(5000);

  // The actual content will be LESS than (200, 200) because resizeTo
  // deals with a window's outer{Width,Height} instead of its
  // inner{Width,Height}.
  is_timeout = false;
  ASSERT_TRUE(popup_window->GetViewBoundsWithTimeout(
                 VIEW_ID_TAB_CONTAINER, &rect, false, 1000, &is_timeout));
  ASSERT_FALSE(is_timeout);
  EXPECT_LT(rect.height(), 200);
#if defined(OS_LINUX)
  // On Linux we may run in an environment where there is no window frame. In
  // this case our width might be exactly 200. The height will still be less
  // because we have to show the location bar.
  EXPECT_LE(rect.width(), 200);
#else
  EXPECT_LT(rect.width(), 200);
#endif
}

// Helper function used to get the number of blocked popups out of the window
// title.
bool ParseCountOutOfTitle(const std::wstring& title, int* output) {
  // Since we will be reading the number of popup windows open by grabbing the
  // number out of the window title, and that format string is localized, we
  // need to find out the offset into that string.
  const wchar_t* placeholder = L"XXXX";
  size_t offset =
      l10n_util::GetStringF(IDS_POPUPS_BLOCKED_COUNT, placeholder).
      find(placeholder);

  std::wstring number;
  while (offset < title.size() && iswdigit(title[offset])) {
    number += title[offset];
    offset++;
  }

  return StringToInt(WideToUTF16(number), output);
}

// Tests that in the window.open() equivalent of a fork bomb, we stop building
// windows.
TEST_F(BlockedPopupContainerInteractiveTest, DontSpawnEndlessPopups) {
  NavigateMainTabTo(L"infinite_popups.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser.get());
  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));
  ASSERT_TRUE(popup_tab.get());

  // And now we spin, waiting to make sure that we don't spawn popup
  // windows endlessly. The current limit is 25, so allowing for possible race
  // conditions and one off errors, don't break out until we go over 30 popup
  // windows (in which case we are bork bork bork).
  const int kMaxPopupWindows = 30;

  int popup_window_count = 0;
  int new_popup_window_count = 0;
  int times_slept = 0;
  bool continuing = true;
  while (continuing && popup_window_count < kMaxPopupWindows) {
    ASSERT_TRUE(popup_tab->GetBlockedPopupCount(&new_popup_window_count));
    if (new_popup_window_count == popup_window_count) {
      if (times_slept == 10) {
        continuing = false;
      } else {
        // Nothing intereseting is going on wait it out.
        PlatformThread::Sleep(automation::kSleepTime);
        times_slept++;
      }
    } else {
      times_slept = 0;
    }

    EXPECT_GE(new_popup_window_count, popup_window_count);
    EXPECT_LE(new_popup_window_count, kMaxPopupWindows);
    popup_window_count = new_popup_window_count;
  }
}

// Make sure that we refuse to close windows when a constrained popup is
// displayed.
TEST_F(BlockedPopupContainerInteractiveTest, WindowOpenWindowClosePopup) {
  NavigateMainTabTo(L"openclose_main.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));

  // Make sure we have a blocked popup notification
  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser.get());
  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());
  ASSERT_TRUE(popup_window.get());
  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));
  ASSERT_TRUE(popup_tab.get());
  ASSERT_TRUE(popup_tab->WaitForBlockedPopupCountToChangeTo(1, 1000));

  // Ensure we didn't close the first popup window.
  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 3000));
}

TEST_F(BlockedPopupContainerInteractiveTest, BlockAlertFromBlockedPopup) {
  NavigateMainTabTo(L"block_alert.html");

  // Wait for there to be an app modal dialog (and fail if it's shown).
  ASSERT_FALSE(automation()->WaitForAppModalDialog(4000));

  // Ensure one browser window.
  int browser_window_count;
  ASSERT_TRUE(automation()->GetBrowserWindowCount(&browser_window_count));
  ASSERT_EQ(1, browser_window_count);

  // Ensure one blocked popup window: the popup didn't escape.
  int popup_count = 0;
  ASSERT_TRUE(tab_->GetBlockedPopupCount(&popup_count));
  ASSERT_EQ(1, popup_count);
}

TEST_F(BlockedPopupContainerInteractiveTest, ShowAlertFromNormalPopup) {
  NavigateMainTabTo(L"show_alert.html");
  SimulateClickInCenterOf(window_);

  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 5000));

  scoped_refptr<BrowserProxy> popup_browser(automation()->GetBrowserWindow(1));
  ASSERT_TRUE(popup_browser.get());
  scoped_refptr<WindowProxy> popup_window(popup_browser->GetWindow());
  ASSERT_TRUE(popup_window.get());
  scoped_refptr<TabProxy> popup_tab(popup_browser->GetTab(0));
  ASSERT_TRUE(popup_tab.get());

#if defined(OS_LINUX)
  // It seems we have to wait a little bit for the widgets to spin up before
  // we can start clicking on them.
  PlatformThread::Sleep(500);
#endif

  SimulateClickInCenterOf(popup_window);

  // Wait for there to be an app modal dialog.
  ASSERT_TRUE(automation()->WaitForAppModalDialog(5000));
}

// Make sure that window focus works while creating a popup window so that we
// don't
TEST_F(BlockedPopupContainerInteractiveTest, DontBreakOnBlur) {
  NavigateMainTabTo(L"window_blur_test.html");
  SimulateClickInCenterOf(window_);

  // Wait for the popup window to open.
  ASSERT_TRUE(automation()->WaitForWindowCountToBecome(2, 1000));

  // We popup shouldn't be closed by the onblur handler.
  ASSERT_FALSE(automation()->WaitForWindowCountToBecome(1, 1500));
}
<|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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/task_manager/task_manager.h"
#include "chrome/browser/task_manager/task_manager_browsertest_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/browser_window.h"
#include "extensions/common/switches.h"

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, Processes) {
  ASSERT_TRUE(RunExtensionTest("processes/api")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ProcessesVsTaskManager) {
  // Ensure task manager is not yet updating
  TaskManagerModel* model = TaskManager::GetInstance()->model();
  EXPECT_EQ(0, model->update_requests_);
  EXPECT_EQ(TaskManagerModel::IDLE, model->update_state_);

  // Load extension that adds listener in background page
  ExtensionTestMessageListener listener("ready", false);
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("processes").AppendASCII("onupdated")));
  ASSERT_TRUE(listener.WaitUntilSatisfied());

  // Ensure the task manager has started updating
  EXPECT_EQ(1, model->update_requests_);
  EXPECT_EQ(TaskManagerModel::TASK_PENDING, model->update_state_);

  // Now show the task manager and wait for it to be ready
  chrome::ShowTaskManager(browser());

  EXPECT_EQ(2, model->update_requests_);
  EXPECT_EQ(TaskManagerModel::TASK_PENDING, model->update_state_);

  // Unload the extension and check that listener count decreases
  UnloadExtension(last_loaded_extension_id());
  EXPECT_EQ(1, model->update_requests_);
}
<commit_msg>Disable flaky test: ExtensionApiTest.Processes<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 "base/command_line.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/task_manager/task_manager.h"
#include "chrome/browser/task_manager/task_manager_browsertest_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/browser_window.h"
#include "extensions/common/switches.h"

// Test is flaky: http://crbug.com/346990
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_Processes) {
  ASSERT_TRUE(RunExtensionTest("processes/api")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ProcessesVsTaskManager) {
  // Ensure task manager is not yet updating
  TaskManagerModel* model = TaskManager::GetInstance()->model();
  EXPECT_EQ(0, model->update_requests_);
  EXPECT_EQ(TaskManagerModel::IDLE, model->update_state_);

  // Load extension that adds listener in background page
  ExtensionTestMessageListener listener("ready", false);
  ASSERT_TRUE(LoadExtension(
      test_data_dir_.AppendASCII("processes").AppendASCII("onupdated")));
  ASSERT_TRUE(listener.WaitUntilSatisfied());

  // Ensure the task manager has started updating
  EXPECT_EQ(1, model->update_requests_);
  EXPECT_EQ(TaskManagerModel::TASK_PENDING, model->update_state_);

  // Now show the task manager and wait for it to be ready
  chrome::ShowTaskManager(browser());

  EXPECT_EQ(2, model->update_requests_);
  EXPECT_EQ(TaskManagerModel::TASK_PENDING, model->update_state_);

  // Unload the extension and check that listener count decreases
  UnloadExtension(last_loaded_extension_id());
  EXPECT_EQ(1, model->update_requests_);
}
<|endoftext|>


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

#include "base/message_loop.h"
#include "base/process.h"
#include "base/scoped_ptr.h"
#include "chrome/browser/renderer_host/audio_renderer_host.h"
#include "testing/gtest/include/gtest/gtest.h"

class AudioRendererHostTest : public testing::Test {
 protected:
  virtual void SetUp() {
    // Create a message loop so AudioRendererHost can use it.
    message_loop_.reset(new MessageLoop(MessageLoop::TYPE_IO));
    host_ = new AudioRendererHost(message_loop_.get());
  }

  virtual void TearDown() {
    // This task post a task to message_loop_ to do internal destruction on
    // message_loop_.
    host_->Destroy();
    // We need to continue running message_loop_ to complete all destructions.
    message_loop_->RunAllPending();
  }

  scoped_refptr<AudioRendererHost> host_;
  scoped_ptr<MessageLoop> message_loop_;
};

TEST_F(AudioRendererHostTest, NoTest) {
  // TODO(hclam): come up with useful tests.
}
<commit_msg>Unit tests for AudioRendererHost TEST=AudioRendererHostTest.CreateStream      AudioRendererHostTest.MockStreamDataConversation BUG=16035<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/message_loop.h"
#include "base/process.h"
#include "base/process_util.h"
#include "base/scoped_ptr.h"
#include "chrome/browser/renderer_host/audio_renderer_host.h"
#include "chrome/common/render_messages.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

using ::testing::_;
using ::testing::DoAll;
using ::testing::InSequence;
using ::testing::Return;
using ::testing::SetArgumentPointee;

namespace {

const int kInvalidId = -1;
const int kProcessId = 100;
const int kRouteId = 200;
const int kBufferCapacity = 65536;
const int kPacketSize = 16384;

}  // namespace

class MockAudioRendererHost : public AudioRendererHost {
 public:
  MockAudioRendererHost(MessageLoop* loop)
      : AudioRendererHost(loop) {
  }

  // A list of mock methods.
  MOCK_METHOD4(OnRequestPacket,
               void(int routing_id, int stream_id,
                    size_t bytes_in_buffer, int64 message_timestamp));

  MOCK_METHOD3(OnStreamCreated,
               void(int routing_id, int stream_id, int length));

  MOCK_METHOD4(OnStreamStateChanged,
               void(int routing_id, int stream_id,
                    AudioOutputStream::State state, int info));

  MOCK_METHOD4(OnStreamVolume,
               void(int routing_id, int stream_id, double left, double right));

  base::SharedMemory* shared_memory() { return shared_memory_.get(); }

 protected:
  // This method is used to dispatch IPC messages to the renderer. We intercept
  // these messages here and dispatch to our mock methods to verify the
  // conversation between this object and the renderer.
  virtual void Send(IPC::Message* message) {
    CHECK(message);

    // In this method we dispatch the messages to the according handlers as if
    // we are the renderer.
    bool handled = true;
    IPC_BEGIN_MESSAGE_MAP(MockAudioRendererHost, *message)
      IPC_MESSAGE_HANDLER(ViewMsg_RequestAudioPacket, OnRequestPacket)
      IPC_MESSAGE_HANDLER(ViewMsg_NotifyAudioStreamCreated, OnStreamCreated)
      IPC_MESSAGE_HANDLER(ViewMsg_NotifyAudioStreamStateChanged,
                          OnStreamStateChanged)
      IPC_MESSAGE_HANDLER(ViewMsg_NotifyAudioStreamVolume, OnStreamVolume)
      IPC_MESSAGE_UNHANDLED(handled = false)
    IPC_END_MESSAGE_MAP()
    EXPECT_TRUE(handled);

    delete message;
  }

 private:
  // These handler methods do minimal things and delegate to the mock methods.
  void OnRequestPacket(const IPC::Message& msg, int stream_id,
                       size_t bytes_in_buffer, int64 message_timestamp) {
    OnRequestPacket(msg.routing_id(), stream_id, bytes_in_buffer,
                    message_timestamp);
  }

  void OnStreamCreated(const IPC::Message& msg, int stream_id,
                       base::SharedMemoryHandle handle, int length) {
    // Maps the shared memory.
    shared_memory_.reset(new base::SharedMemory(handle, true));
    CHECK(shared_memory_->Map(length));
    CHECK(shared_memory_->memory());

    // And then delegate the call to the mock method.
    OnStreamCreated(msg.routing_id(), stream_id, length);
  }

  void OnStreamStateChanged(const IPC::Message& msg, int stream_id,
                            AudioOutputStream::State state, int info) {
    OnStreamStateChanged(msg.routing_id(), stream_id, state, info);
  }

  void OnStreamVolume(const IPC::Message& msg, int stream_id,
                      double left, double right) {
    OnStreamVolume(msg.routing_id(), stream_id, left, right);
  }

  scoped_ptr<base::SharedMemory> shared_memory_;

  DISALLOW_COPY_AND_ASSIGN(MockAudioRendererHost);
};

class AudioRendererHostTest : public testing::Test {
 public:
  AudioRendererHostTest()
      : current_stream_id_(0) {
  }

 protected:
  virtual void SetUp() {
    // Create a message loop so AudioRendererHost can use it.
    message_loop_.reset(new MessageLoop(MessageLoop::TYPE_IO));
    host_ = new MockAudioRendererHost(message_loop_.get());
    CHECK(host_);
  }

  virtual void TearDown() {
    // This task post a task to message_loop_ to do internal destruction on
    // message_loop_.
    host_->Destroy();
    // We need to continue running message_loop_ to complete all destructions.
    message_loop_->RunAllPending();
  }

  AudioRendererHost::IPCAudioSource* CreateAudioStream(
      AudioManager::Format format) {
    InSequence s;

    // 1. We will first receive a OnStreamCreated() signal.
    EXPECT_CALL(*host_,
                OnStreamCreated(kRouteId, current_stream_id_, kPacketSize));

    // 2. First packet request will arrive. This request is sent by
    //    IPCAudioSource::CreateIPCAudioSource to start buffering.
    EXPECT_CALL(*host_, OnRequestPacket(kRouteId, current_stream_id_, 0, _));

    AudioRendererHost::IPCAudioSource* source =
        AudioRendererHost::IPCAudioSource::CreateIPCAudioSource(
            host_,
            kProcessId,
            kRouteId,
            current_stream_id_,
            base::GetCurrentProcessHandle(),
            format,
            2,
            AudioManager::kAudioCDSampleRate,
            16,
            kPacketSize,
            kBufferCapacity);
    EXPECT_TRUE(source);
    EXPECT_EQ(kProcessId, source->process_id());
    EXPECT_EQ(kRouteId, source->route_id());
    EXPECT_EQ(current_stream_id_, source->stream_id());
    return source;
  }

  AudioRendererHost::IPCAudioSource* CreateRealStream() {
    return CreateAudioStream(AudioManager::AUDIO_PCM_LINEAR);
  }

  AudioRendererHost::IPCAudioSource* CreateMockStream() {
    return CreateAudioStream(AudioManager::AUDIO_MOCK);
  }

  int current_stream_id_;
  scoped_refptr<MockAudioRendererHost> host_;
  scoped_ptr<MessageLoop> message_loop_;

 private:
  DISALLOW_COPY_AND_ASSIGN(AudioRendererHostTest);
};

// Audio output stream only works stably on windows. Also there's no mock
// audio output streams for mac and linux.
// TODO(hclam): make these tests work on mac and linux.
#if defined(OS_WIN)

TEST_F(AudioRendererHostTest, CreateMockStream) {
  scoped_ptr<AudioRendererHost::IPCAudioSource> source(CreateMockStream());
}

TEST_F(AudioRendererHostTest, MockStreamDataConversation) {
  scoped_ptr<AudioRendererHost::IPCAudioSource> source(CreateMockStream());

  // We will receive packet requests until the buffer is full. We first send
  // three packets of 16KB, then we send packets of 1KB until the buffer is
  // full. Then there will no more packet requests.
  EXPECT_CALL(*host_,
      OnRequestPacket(kRouteId, current_stream_id_, kPacketSize, _));
  EXPECT_CALL(*host_,
      OnRequestPacket(kRouteId, current_stream_id_, 2 * kPacketSize, _));
  for (int size = 3 * kPacketSize; size < kBufferCapacity; size += 1024) {
    EXPECT_CALL(*host_, OnRequestPacket(kRouteId, current_stream_id_, size, _));
  }

  source->NotifyPacketReady(kPacketSize);
  source->NotifyPacketReady(kPacketSize);
  source->NotifyPacketReady(kPacketSize);
  for (int size = 0; size < kPacketSize; size += 1024) {
    source->NotifyPacketReady(1024);
  }
}

#endif
<|endoftext|>


<commit_before>// Copyright 2014 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/search_engines/ui_thread_search_terms_data.h"

#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/google/google_brand.h"
#include "chrome/browser/google/google_profile_helper.h"
#include "chrome/browser/omnibox/omnibox_field_trial.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search/instant_service.h"
#include "chrome/browser/search/instant_service_factory.h"
#include "chrome/browser/search/search.h"
#include "chrome/browser/sync/glue/device_info.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/pref_names.h"
#include "components/google/core/browser/google_util.h"
#include "components/search/search.h"
#include "content/public/browser/browser_thread.h"
#include "sync/protocol/sync.pb.h"
#include "url/gurl.h"

#if defined(ENABLE_RLZ)
#include "chrome/browser/rlz/rlz.h"
#endif

using content::BrowserThread;

// static
std::string* UIThreadSearchTermsData::google_base_url_ = NULL;

UIThreadSearchTermsData::UIThreadSearchTermsData(Profile* profile)
    : profile_(profile) {
  DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
      BrowserThread::CurrentlyOn(BrowserThread::UI));
}

std::string UIThreadSearchTermsData::GoogleBaseURLValue() const {
  DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
      BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (google_base_url_)
    return *google_base_url_;
  GURL base_url(google_util::CommandLineGoogleBaseURL());
  if (base_url.is_valid())
    return base_url.spec();
  return profile_ ?
      google_profile_helper::GetGoogleHomePageURL(profile_).spec() :
      SearchTermsData::GoogleBaseURLValue();
}

std::string UIThreadSearchTermsData::GetApplicationLocale() const {
  DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
      BrowserThread::CurrentlyOn(BrowserThread::UI));
  return g_browser_process->GetApplicationLocale();
}

// Android implementations are in ui_thread_search_terms_data_android.cc.
#if !defined(OS_ANDROID)
base::string16 UIThreadSearchTermsData::GetRlzParameterValue(
    bool from_app_list) const {
  DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
      BrowserThread::CurrentlyOn(BrowserThread::UI));
  base::string16 rlz_string;
#if defined(ENABLE_RLZ)
  // For organic brandcodes do not use rlz at all. Empty brandcode usually
  // means a chromium install. This is ok.
  std::string brand;
  if (google_brand::GetBrand(&brand) && !brand.empty() &&
      !google_brand::IsOrganic(brand)) {
    // This call will return false the first time(s) it is called until the
    // value has been cached. This normally would mean that at most one omnibox
    // search might not send the RLZ data but this is not really a problem.
    rlz_lib::AccessPoint access_point = RLZTracker::ChromeOmnibox();
#if !defined(OS_IOS)
    if (from_app_list)
      access_point = RLZTracker::ChromeAppList();
#endif
    RLZTracker::GetAccessPointRlz(access_point, &rlz_string);
  }
#endif
  return rlz_string;
}

// We can enable this on non-Android if other platforms ever want a non-empty
// search client string.  There is already a unit test in place for Android
// called TemplateURLTest::SearchClient.
std::string UIThreadSearchTermsData::GetSearchClient() const {
  DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
      BrowserThread::CurrentlyOn(BrowserThread::UI));
  return std::string();
}
#endif

std::string UIThreadSearchTermsData::GetSuggestClient() const {
  DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
      BrowserThread::CurrentlyOn(BrowserThread::UI));
#if defined(OS_ANDROID)
  sync_pb::SyncEnums::DeviceType device_type =
      browser_sync::DeviceInfo::GetLocalDeviceType();
  return device_type == sync_pb::SyncEnums_DeviceType_TYPE_PHONE ?
    "chrome" : "chrome-omni";
#else
  return chrome::IsInstantExtendedAPIEnabled() ? "chrome-omni" : "chrome";
#endif
}

std::string UIThreadSearchTermsData::GetSuggestRequestIdentifier() const {
  DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
      BrowserThread::CurrentlyOn(BrowserThread::UI));
#if defined(OS_ANDROID)
  sync_pb::SyncEnums::DeviceType device_type =
      browser_sync::DeviceInfo::GetLocalDeviceType();
  if (device_type == sync_pb::SyncEnums_DeviceType_TYPE_PHONE) {
    return OmniboxFieldTrial::EnableAnswersInSuggest() ?
        "chrome-mobile-ext-ansg" : "chrome-mobile-ext";
  }
  return OmniboxFieldTrial::EnableAnswersInSuggest() ?
      "chrome-ext-ansg" : "chrome-ext";
#else
  return "chrome-ext";
#endif
}

bool UIThreadSearchTermsData::EnableAnswersInSuggest() const {
  return OmniboxFieldTrial::EnableAnswersInSuggest();
}

bool UIThreadSearchTermsData::IsShowingSearchTermsOnSearchResultsPages() const {
  return chrome::IsInstantExtendedAPIEnabled() &&
      chrome::IsQueryExtractionEnabled();
}

std::string UIThreadSearchTermsData::InstantExtendedEnabledParam(
    bool for_search) const {
  return chrome::InstantExtendedEnabledParam(for_search);
}

std::string UIThreadSearchTermsData::ForceInstantResultsParam(
    bool for_prerender) const {
  return chrome::ForceInstantResultsParam(for_prerender);
}

int UIThreadSearchTermsData::OmniboxStartMargin() const {
  InstantService* instant_service =
      InstantServiceFactory::GetForProfile(profile_);
  // Android and iOS have no InstantService.
  return instant_service ?
      instant_service->omnibox_start_margin() : chrome::kDisableStartMargin;
}

std::string UIThreadSearchTermsData::NTPIsThemedParam() const {
  DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
         BrowserThread::CurrentlyOn(BrowserThread::UI));
#if defined(ENABLE_THEMES)
  if (!chrome::IsInstantExtendedAPIEnabled())
    return std::string();

  // TODO(dhollowa): Determine fraction of custom themes that don't affect the
  // NTP background and/or color.
  ThemeService* theme_service = ThemeServiceFactory::GetForProfile(profile_);
  // NTP is considered themed if the theme is not default and not native (GTK+).
  if (theme_service && !theme_service->UsingDefaultTheme() &&
      !theme_service->UsingSystemTheme())
    return "es_th=1&";
#endif  // defined(ENABLE_THEMES)

  return std::string();
}

// It's acutally OK to call this method on any thread, but it's currently placed
// in UIThreadSearchTermsData since SearchTermsData cannot depend on
// VersionInfo.
std::string UIThreadSearchTermsData::GoogleImageSearchSource() const {
  chrome::VersionInfo version_info;
  if (version_info.is_valid()) {
    std::string version(version_info.Name() + " " + version_info.Version());
    if (version_info.IsOfficialBuild())
      version += " (Official)";
    version += " " + version_info.OSType();
    std::string modifier(version_info.GetVersionStringModifier());
    if (!modifier.empty())
      version += " " + modifier;
    return version;
  }
  return "unknown";
}

// static
void UIThreadSearchTermsData::SetGoogleBaseURL(const std::string& base_url) {
  delete google_base_url_;
  google_base_url_ = base_url.empty() ? NULL : new std::string(base_url);
}
<commit_msg>[AiS] widen AiS to iOS.<commit_after>// Copyright 2014 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/search_engines/ui_thread_search_terms_data.h"

#include "base/command_line.h"
#include "base/logging.h"
#include "base/metrics/field_trial.h"
#include "base/prefs/pref_service.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/google/google_brand.h"
#include "chrome/browser/google/google_profile_helper.h"
#include "chrome/browser/omnibox/omnibox_field_trial.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/search/instant_service.h"
#include "chrome/browser/search/instant_service_factory.h"
#include "chrome/browser/search/search.h"
#include "chrome/browser/sync/glue/device_info.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/pref_names.h"
#include "components/google/core/browser/google_util.h"
#include "components/search/search.h"
#include "content/public/browser/browser_thread.h"
#include "sync/protocol/sync.pb.h"
#include "url/gurl.h"

#if defined(ENABLE_RLZ)
#include "chrome/browser/rlz/rlz.h"
#endif

using content::BrowserThread;

// static
std::string* UIThreadSearchTermsData::google_base_url_ = NULL;

UIThreadSearchTermsData::UIThreadSearchTermsData(Profile* profile)
    : profile_(profile) {
  DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
      BrowserThread::CurrentlyOn(BrowserThread::UI));
}

std::string UIThreadSearchTermsData::GoogleBaseURLValue() const {
  DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
      BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (google_base_url_)
    return *google_base_url_;
  GURL base_url(google_util::CommandLineGoogleBaseURL());
  if (base_url.is_valid())
    return base_url.spec();
  return profile_ ?
      google_profile_helper::GetGoogleHomePageURL(profile_).spec() :
      SearchTermsData::GoogleBaseURLValue();
}

std::string UIThreadSearchTermsData::GetApplicationLocale() const {
  DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
      BrowserThread::CurrentlyOn(BrowserThread::UI));
  return g_browser_process->GetApplicationLocale();
}

// Android implementations are in ui_thread_search_terms_data_android.cc.
#if !defined(OS_ANDROID)
base::string16 UIThreadSearchTermsData::GetRlzParameterValue(
    bool from_app_list) const {
  DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
      BrowserThread::CurrentlyOn(BrowserThread::UI));
  base::string16 rlz_string;
#if defined(ENABLE_RLZ)
  // For organic brandcodes do not use rlz at all. Empty brandcode usually
  // means a chromium install. This is ok.
  std::string brand;
  if (google_brand::GetBrand(&brand) && !brand.empty() &&
      !google_brand::IsOrganic(brand)) {
    // This call will return false the first time(s) it is called until the
    // value has been cached. This normally would mean that at most one omnibox
    // search might not send the RLZ data but this is not really a problem.
    rlz_lib::AccessPoint access_point = RLZTracker::ChromeOmnibox();
#if !defined(OS_IOS)
    if (from_app_list)
      access_point = RLZTracker::ChromeAppList();
#endif
    RLZTracker::GetAccessPointRlz(access_point, &rlz_string);
  }
#endif
  return rlz_string;
}

// We can enable this on non-Android if other platforms ever want a non-empty
// search client string.  There is already a unit test in place for Android
// called TemplateURLTest::SearchClient.
std::string UIThreadSearchTermsData::GetSearchClient() const {
  DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
      BrowserThread::CurrentlyOn(BrowserThread::UI));
  return std::string();
}
#endif

std::string UIThreadSearchTermsData::GetSuggestClient() const {
  DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
      BrowserThread::CurrentlyOn(BrowserThread::UI));
#if defined(OS_ANDROID)
  sync_pb::SyncEnums::DeviceType device_type =
      browser_sync::DeviceInfo::GetLocalDeviceType();
  return device_type == sync_pb::SyncEnums_DeviceType_TYPE_PHONE ?
    "chrome" : "chrome-omni";
#else
  return chrome::IsInstantExtendedAPIEnabled() ? "chrome-omni" : "chrome";
#endif
}

std::string UIThreadSearchTermsData::GetSuggestRequestIdentifier() const {
  DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
      BrowserThread::CurrentlyOn(BrowserThread::UI));
#if defined(OS_ANDROID)
  sync_pb::SyncEnums::DeviceType device_type =
      browser_sync::DeviceInfo::GetLocalDeviceType();
  if (device_type == sync_pb::SyncEnums_DeviceType_TYPE_PHONE) {
    return OmniboxFieldTrial::EnableAnswersInSuggest() ?
        "chrome-mobile-ext-ansg" : "chrome-mobile-ext";
  }
  return OmniboxFieldTrial::EnableAnswersInSuggest() ?
      "chrome-ext-ansg" : "chrome-ext";
#elif defined(OS_IOS)
  return OmniboxFieldTrial::EnableAnswersInSuggest() ?
      "chrome-ext-ansg" : "chrome-ext";
#else
  return "chrome-ext";
#endif
}

bool UIThreadSearchTermsData::EnableAnswersInSuggest() const {
  return OmniboxFieldTrial::EnableAnswersInSuggest();
}

bool UIThreadSearchTermsData::IsShowingSearchTermsOnSearchResultsPages() const {
  return chrome::IsInstantExtendedAPIEnabled() &&
      chrome::IsQueryExtractionEnabled();
}

std::string UIThreadSearchTermsData::InstantExtendedEnabledParam(
    bool for_search) const {
  return chrome::InstantExtendedEnabledParam(for_search);
}

std::string UIThreadSearchTermsData::ForceInstantResultsParam(
    bool for_prerender) const {
  return chrome::ForceInstantResultsParam(for_prerender);
}

int UIThreadSearchTermsData::OmniboxStartMargin() const {
  InstantService* instant_service =
      InstantServiceFactory::GetForProfile(profile_);
  // Android and iOS have no InstantService.
  return instant_service ?
      instant_service->omnibox_start_margin() : chrome::kDisableStartMargin;
}

std::string UIThreadSearchTermsData::NTPIsThemedParam() const {
  DCHECK(!BrowserThread::IsThreadInitialized(BrowserThread::UI) ||
         BrowserThread::CurrentlyOn(BrowserThread::UI));
#if defined(ENABLE_THEMES)
  if (!chrome::IsInstantExtendedAPIEnabled())
    return std::string();

  // TODO(dhollowa): Determine fraction of custom themes that don't affect the
  // NTP background and/or color.
  ThemeService* theme_service = ThemeServiceFactory::GetForProfile(profile_);
  // NTP is considered themed if the theme is not default and not native (GTK+).
  if (theme_service && !theme_service->UsingDefaultTheme() &&
      !theme_service->UsingSystemTheme())
    return "es_th=1&";
#endif  // defined(ENABLE_THEMES)

  return std::string();
}

// It's acutally OK to call this method on any thread, but it's currently placed
// in UIThreadSearchTermsData since SearchTermsData cannot depend on
// VersionInfo.
std::string UIThreadSearchTermsData::GoogleImageSearchSource() const {
  chrome::VersionInfo version_info;
  if (version_info.is_valid()) {
    std::string version(version_info.Name() + " " + version_info.Version());
    if (version_info.IsOfficialBuild())
      version += " (Official)";
    version += " " + version_info.OSType();
    std::string modifier(version_info.GetVersionStringModifier());
    if (!modifier.empty())
      version += " " + modifier;
    return version;
  }
  return "unknown";
}

// static
void UIThreadSearchTermsData::SetGoogleBaseURL(const std::string& base_url) {
  delete google_base_url_;
  google_base_url_ = base_url.empty() ? NULL : new std::string(base_url);
}
<|endoftext|>