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

#include "chrome/browser/chromeos/drive/sync_client.h"

#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/scoped_ptr.h"
#include "base/prefs/testing_pref_service.h"
#include "base/run_loop.h"
#include "base/test/test_timeouts.h"
#include "chrome/browser/chromeos/drive/change_list_loader.h"
#include "chrome/browser/chromeos/drive/change_list_processor.h"
#include "chrome/browser/chromeos/drive/drive.pb.h"
#include "chrome/browser/chromeos/drive/fake_free_disk_space_getter.h"
#include "chrome/browser/chromeos/drive/file_cache.h"
#include "chrome/browser/chromeos/drive/file_system/operation_observer.h"
#include "chrome/browser/chromeos/drive/job_scheduler.h"
#include "chrome/browser/chromeos/drive/resource_entry_conversion.h"
#include "chrome/browser/chromeos/drive/resource_metadata.h"
#include "chrome/browser/chromeos/drive/test_util.h"
#include "chrome/browser/drive/fake_drive_service.h"
#include "chrome/browser/google_apis/test_util.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace drive {
namespace internal {

namespace {

// The content of files initially stored in the cache.
const char kLocalContent[] = "Hello!";

// The content of files stored in the service.
const char kRemoteContent[] = "World!";

// SyncClientTestDriveService will return GDATA_CANCELLED when a request is
// made with the specified resource ID.
class SyncClientTestDriveService : public ::drive::FakeDriveService {
 public:
  // FakeDriveService override:
  virtual google_apis::CancelCallback DownloadFile(
      const base::FilePath& local_cache_path,
      const std::string& resource_id,
      const google_apis::DownloadActionCallback& download_action_callback,
      const google_apis::GetContentCallback& get_content_callback,
      const google_apis::ProgressCallback& progress_callback) OVERRIDE {
    if (resource_id == resource_id_to_be_cancelled_) {
      base::MessageLoopProxy::current()->PostTask(
          FROM_HERE,
          base::Bind(download_action_callback,
                     google_apis::GDATA_CANCELLED,
                     base::FilePath()));
      return google_apis::CancelCallback();
    }
    return FakeDriveService::DownloadFile(local_cache_path,
                                          resource_id,
                                          download_action_callback,
                                          get_content_callback,
                                          progress_callback);
  }

  void set_resource_id_to_be_cancelled(const std::string& resource_id) {
    resource_id_to_be_cancelled_ = resource_id;
  }

 private:
  std::string resource_id_to_be_cancelled_;
};

class DummyOperationObserver : public file_system::OperationObserver {
  // OperationObserver override:
  virtual void OnDirectoryChangedByOperation(
      const base::FilePath& path) OVERRIDE {}
  virtual void OnCacheFileUploadNeededByOperation(
      const std::string& local_id) OVERRIDE {}
};

}  // namespace

class SyncClientTest : public testing::Test {
 public:
  virtual void SetUp() OVERRIDE {
    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());

    pref_service_.reset(new TestingPrefServiceSimple);
    test_util::RegisterDrivePrefs(pref_service_->registry());

    fake_network_change_notifier_.reset(
        new test_util::FakeNetworkChangeNotifier);

    drive_service_.reset(new SyncClientTestDriveService);
    drive_service_->LoadResourceListForWapi("gdata/empty_feed.json");
    drive_service_->LoadAccountMetadataForWapi(
        "gdata/account_metadata.json");

    scheduler_.reset(new JobScheduler(pref_service_.get(),
                                      drive_service_.get(),
                                      base::MessageLoopProxy::current().get()));

    metadata_storage_.reset(new ResourceMetadataStorage(
        temp_dir_.path(), base::MessageLoopProxy::current().get()));
    ASSERT_TRUE(metadata_storage_->Initialize());

    metadata_.reset(new internal::ResourceMetadata(
        metadata_storage_.get(), base::MessageLoopProxy::current()));
    ASSERT_EQ(FILE_ERROR_OK, metadata_->Initialize());

    cache_.reset(new FileCache(metadata_storage_.get(),
                               temp_dir_.path(),
                               base::MessageLoopProxy::current().get(),
                               NULL /* free_disk_space_getter */));
    ASSERT_TRUE(cache_->Initialize());

    ASSERT_NO_FATAL_FAILURE(SetUpTestData());

    sync_client_.reset(new SyncClient(base::MessageLoopProxy::current().get(),
                                      &observer_,
                                      scheduler_.get(),
                                      metadata_.get(),
                                      cache_.get(),
                                      temp_dir_.path()));

    // Disable delaying so that DoSyncLoop() starts immediately.
    sync_client_->set_delay_for_testing(base::TimeDelta::FromSeconds(0));
  }

  // Adds a file to the service root and |resource_ids_|.
  void AddFileEntry(const std::string& title) {
    google_apis::GDataErrorCode error = google_apis::GDATA_FILE_ERROR;
    scoped_ptr<google_apis::ResourceEntry> entry;
    drive_service_->AddNewFile(
        "text/plain",
        kRemoteContent,
        drive_service_->GetRootResourceId(),
        title,
        false,  // shared_with_me
        google_apis::test_util::CreateCopyResultCallback(&error, &entry));
    base::RunLoop().RunUntilIdle();
    ASSERT_EQ(google_apis::HTTP_CREATED, error);
    ASSERT_TRUE(entry);
    resource_ids_[title] = entry->resource_id();
  }

  // Sets up data for tests.
  void SetUpTestData() {
    // Prepare a temp file.
    base::FilePath temp_file;
    EXPECT_TRUE(file_util::CreateTemporaryFileInDir(temp_dir_.path(),
                                                    &temp_file));
    ASSERT_TRUE(google_apis::test_util::WriteStringToFile(temp_file,
                                                          kLocalContent));

    // Prepare 3 pinned-but-not-present files.
    ASSERT_NO_FATAL_FAILURE(AddFileEntry("foo"));
    EXPECT_EQ(FILE_ERROR_OK, cache_->Pin(resource_ids_["foo"]));

    ASSERT_NO_FATAL_FAILURE(AddFileEntry("bar"));
    EXPECT_EQ(FILE_ERROR_OK, cache_->Pin(resource_ids_["bar"]));

    ASSERT_NO_FATAL_FAILURE(AddFileEntry("baz"));
    EXPECT_EQ(FILE_ERROR_OK, cache_->Pin(resource_ids_["baz"]));

    // Prepare a pinned-and-fetched file.
    const std::string md5_fetched = "md5";
    ASSERT_NO_FATAL_FAILURE(AddFileEntry("fetched"));
    EXPECT_EQ(FILE_ERROR_OK,
              cache_->Store(resource_ids_["fetched"], md5_fetched,
                            temp_file, FileCache::FILE_OPERATION_COPY));
    EXPECT_EQ(FILE_ERROR_OK, cache_->Pin(resource_ids_["fetched"]));

    // Prepare a pinned-and-fetched-and-dirty file.
    const std::string md5_dirty = "";  // Don't care.
    ASSERT_NO_FATAL_FAILURE(AddFileEntry("dirty"));
    EXPECT_EQ(FILE_ERROR_OK,
              cache_->Store(resource_ids_["dirty"], md5_dirty,
                            temp_file, FileCache::FILE_OPERATION_COPY));
    EXPECT_EQ(FILE_ERROR_OK, cache_->Pin(resource_ids_["dirty"]));
    EXPECT_EQ(FILE_ERROR_OK, cache_->MarkDirty(resource_ids_["dirty"]));

    // Load data from the service to the metadata.
    FileError error = FILE_ERROR_FAILED;
    internal::ChangeListLoader change_list_loader(
        base::MessageLoopProxy::current().get(),
        metadata_.get(),
        scheduler_.get(),
        drive_service_.get());
    change_list_loader.LoadIfNeeded(
        DirectoryFetchInfo(),
        google_apis::test_util::CreateCopyResultCallback(&error));
    base::RunLoop().RunUntilIdle();
    EXPECT_EQ(FILE_ERROR_OK, error);
  }

 protected:
  content::TestBrowserThreadBundle thread_bundle_;
  base::ScopedTempDir temp_dir_;
  scoped_ptr<TestingPrefServiceSimple> pref_service_;
  scoped_ptr<test_util::FakeNetworkChangeNotifier>
      fake_network_change_notifier_;
  scoped_ptr<SyncClientTestDriveService> drive_service_;
  DummyOperationObserver observer_;
  scoped_ptr<JobScheduler> scheduler_;
  scoped_ptr<ResourceMetadataStorage,
             test_util::DestroyHelperForTests> metadata_storage_;
  scoped_ptr<ResourceMetadata, test_util::DestroyHelperForTests> metadata_;
  scoped_ptr<FileCache, test_util::DestroyHelperForTests> cache_;
  scoped_ptr<SyncClient> sync_client_;

  std::map<std::string, std::string> resource_ids_;  // Name-to-id map.
};

TEST_F(SyncClientTest, StartProcessingBacklog) {
  sync_client_->StartProcessingBacklog();
  base::RunLoop().RunUntilIdle();

  FileCacheEntry cache_entry;
  // Pinned files get downloaded.
  EXPECT_TRUE(cache_->GetCacheEntry(resource_ids_["foo"], &cache_entry));
  EXPECT_TRUE(cache_entry.is_present());

  EXPECT_TRUE(cache_->GetCacheEntry(resource_ids_["bar"], &cache_entry));
  EXPECT_TRUE(cache_entry.is_present());

  EXPECT_TRUE(cache_->GetCacheEntry(resource_ids_["baz"], &cache_entry));
  EXPECT_TRUE(cache_entry.is_present());

  // Dirty file gets uploaded.
  EXPECT_TRUE(cache_->GetCacheEntry(resource_ids_["dirty"], &cache_entry));
  EXPECT_FALSE(cache_entry.is_dirty());
}

TEST_F(SyncClientTest, AddFetchTask) {
  sync_client_->AddFetchTask(resource_ids_["foo"]);
  base::RunLoop().RunUntilIdle();

  FileCacheEntry cache_entry;
  EXPECT_TRUE(cache_->GetCacheEntry(resource_ids_["foo"], &cache_entry));
  EXPECT_TRUE(cache_entry.is_present());
}

TEST_F(SyncClientTest, AddFetchTaskAndCancelled) {
  // Trigger fetching of a file which results in cancellation.
  drive_service_->set_resource_id_to_be_cancelled(resource_ids_["foo"]);
  sync_client_->AddFetchTask(resource_ids_["foo"]);
  base::RunLoop().RunUntilIdle();

  // The file should be unpinned if the user wants the download to be cancelled.
  FileCacheEntry cache_entry;
  EXPECT_FALSE(cache_->GetCacheEntry(resource_ids_["foo"], &cache_entry));
}

TEST_F(SyncClientTest, RemoveFetchTask) {
  sync_client_->AddFetchTask(resource_ids_["foo"]);
  sync_client_->AddFetchTask(resource_ids_["bar"]);
  sync_client_->AddFetchTask(resource_ids_["baz"]);

  sync_client_->RemoveFetchTask(resource_ids_["foo"]);
  sync_client_->RemoveFetchTask(resource_ids_["baz"]);
  base::RunLoop().RunUntilIdle();

  // Only "bar" should be fetched.
  FileCacheEntry cache_entry;
  EXPECT_TRUE(cache_->GetCacheEntry(resource_ids_["foo"], &cache_entry));
  EXPECT_FALSE(cache_entry.is_present());

  EXPECT_TRUE(cache_->GetCacheEntry(resource_ids_["bar"], &cache_entry));
  EXPECT_TRUE(cache_entry.is_present());

  EXPECT_TRUE(cache_->GetCacheEntry(resource_ids_["baz"], &cache_entry));
  EXPECT_FALSE(cache_entry.is_present());

}

TEST_F(SyncClientTest, ExistingPinnedFiles) {
  // Start checking the existing pinned files. This will collect the resource
  // IDs of pinned files, with stale local cache files.
  sync_client_->StartCheckingExistingPinnedFiles();
  base::RunLoop().RunUntilIdle();

  // "fetched" and "dirty" are the existing pinned files.
  // The non-dirty one should be synced, but the dirty one should not.
  base::FilePath cache_file;
  std::string content;
  EXPECT_EQ(FILE_ERROR_OK, cache_->GetFile(resource_ids_["fetched"],
                                           &cache_file));
  EXPECT_TRUE(base::ReadFileToString(cache_file, &content));
  EXPECT_EQ(kRemoteContent, content);
  content.clear();

  EXPECT_EQ(FILE_ERROR_OK, cache_->GetFile(resource_ids_["dirty"],
                                           &cache_file));
  EXPECT_TRUE(base::ReadFileToString(cache_file, &content));
  EXPECT_EQ(kLocalContent, content);
}

TEST_F(SyncClientTest, RetryOnDisconnection) {
  // Let the service go down.
  drive_service_->set_offline(true);
  // Change the network connection state after some delay, to test that
  // FILE_ERROR_NO_CONNECTION is handled by SyncClient correctly.
  // Without this delay, JobScheduler will keep the jobs unrun and SyncClient
  // will receive no error.
  base::MessageLoopProxy::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&test_util::FakeNetworkChangeNotifier::SetConnectionType,
                 base::Unretained(fake_network_change_notifier_.get()),
                 net::NetworkChangeNotifier::CONNECTION_NONE),
      TestTimeouts::tiny_timeout());

  // Try fetch and upload.
  sync_client_->AddFetchTask(resource_ids_["foo"]);
  sync_client_->AddUploadTask(resource_ids_["dirty"]);
  base::RunLoop().RunUntilIdle();

  // Not yet fetched nor uploaded.
  FileCacheEntry cache_entry;
  EXPECT_TRUE(cache_->GetCacheEntry(resource_ids_["foo"], &cache_entry));
  EXPECT_FALSE(cache_entry.is_present());
  EXPECT_TRUE(cache_->GetCacheEntry(resource_ids_["dirty"], &cache_entry));
  EXPECT_TRUE(cache_entry.is_dirty());

  // Switch to online.
  fake_network_change_notifier_->SetConnectionType(
      net::NetworkChangeNotifier::CONNECTION_WIFI);
  drive_service_->set_offline(false);
  base::RunLoop().RunUntilIdle();

  // Fetched and uploaded.
  EXPECT_TRUE(cache_->GetCacheEntry(resource_ids_["foo"], &cache_entry));
  EXPECT_TRUE(cache_entry.is_present());
  EXPECT_TRUE(cache_->GetCacheEntry(resource_ids_["dirty"], &cache_entry));
  EXPECT_FALSE(cache_entry.is_dirty());
}

}  // namespace internal
}  // namespace drive
<commit_msg>drive: Rewrite SyncClientTest to deal with local IDs properly<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/drive/sync_client.h"

#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/memory/scoped_ptr.h"
#include "base/prefs/testing_pref_service.h"
#include "base/run_loop.h"
#include "base/test/test_timeouts.h"
#include "chrome/browser/chromeos/drive/change_list_loader.h"
#include "chrome/browser/chromeos/drive/change_list_processor.h"
#include "chrome/browser/chromeos/drive/drive.pb.h"
#include "chrome/browser/chromeos/drive/fake_free_disk_space_getter.h"
#include "chrome/browser/chromeos/drive/file_cache.h"
#include "chrome/browser/chromeos/drive/file_system/operation_observer.h"
#include "chrome/browser/chromeos/drive/job_scheduler.h"
#include "chrome/browser/chromeos/drive/resource_entry_conversion.h"
#include "chrome/browser/chromeos/drive/resource_metadata.h"
#include "chrome/browser/chromeos/drive/test_util.h"
#include "chrome/browser/drive/fake_drive_service.h"
#include "chrome/browser/google_apis/test_util.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace drive {
namespace internal {

namespace {

// The content of files initially stored in the cache.
const char kLocalContent[] = "Hello!";

// The content of files stored in the service.
const char kRemoteContent[] = "World!";

// SyncClientTestDriveService will return GDATA_CANCELLED when a request is
// made with the specified resource ID.
class SyncClientTestDriveService : public ::drive::FakeDriveService {
 public:
  // FakeDriveService override:
  virtual google_apis::CancelCallback DownloadFile(
      const base::FilePath& local_cache_path,
      const std::string& resource_id,
      const google_apis::DownloadActionCallback& download_action_callback,
      const google_apis::GetContentCallback& get_content_callback,
      const google_apis::ProgressCallback& progress_callback) OVERRIDE {
    if (resource_id == resource_id_to_be_cancelled_) {
      base::MessageLoopProxy::current()->PostTask(
          FROM_HERE,
          base::Bind(download_action_callback,
                     google_apis::GDATA_CANCELLED,
                     base::FilePath()));
      return google_apis::CancelCallback();
    }
    return FakeDriveService::DownloadFile(local_cache_path,
                                          resource_id,
                                          download_action_callback,
                                          get_content_callback,
                                          progress_callback);
  }

  void set_resource_id_to_be_cancelled(const std::string& resource_id) {
    resource_id_to_be_cancelled_ = resource_id;
  }

 private:
  std::string resource_id_to_be_cancelled_;
};

class DummyOperationObserver : public file_system::OperationObserver {
  // OperationObserver override:
  virtual void OnDirectoryChangedByOperation(
      const base::FilePath& path) OVERRIDE {}
  virtual void OnCacheFileUploadNeededByOperation(
      const std::string& local_id) OVERRIDE {}
};

}  // namespace

class SyncClientTest : public testing::Test {
 public:
  virtual void SetUp() OVERRIDE {
    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());

    pref_service_.reset(new TestingPrefServiceSimple);
    test_util::RegisterDrivePrefs(pref_service_->registry());

    fake_network_change_notifier_.reset(
        new test_util::FakeNetworkChangeNotifier);

    drive_service_.reset(new SyncClientTestDriveService);
    drive_service_->LoadResourceListForWapi("gdata/empty_feed.json");
    drive_service_->LoadAccountMetadataForWapi(
        "gdata/account_metadata.json");

    scheduler_.reset(new JobScheduler(pref_service_.get(),
                                      drive_service_.get(),
                                      base::MessageLoopProxy::current().get()));

    metadata_storage_.reset(new ResourceMetadataStorage(
        temp_dir_.path(), base::MessageLoopProxy::current().get()));
    ASSERT_TRUE(metadata_storage_->Initialize());

    metadata_.reset(new internal::ResourceMetadata(
        metadata_storage_.get(), base::MessageLoopProxy::current()));
    ASSERT_EQ(FILE_ERROR_OK, metadata_->Initialize());

    cache_.reset(new FileCache(metadata_storage_.get(),
                               temp_dir_.path(),
                               base::MessageLoopProxy::current().get(),
                               NULL /* free_disk_space_getter */));
    ASSERT_TRUE(cache_->Initialize());

    ASSERT_NO_FATAL_FAILURE(SetUpTestData());

    sync_client_.reset(new SyncClient(base::MessageLoopProxy::current().get(),
                                      &observer_,
                                      scheduler_.get(),
                                      metadata_.get(),
                                      cache_.get(),
                                      temp_dir_.path()));

    // Disable delaying so that DoSyncLoop() starts immediately.
    sync_client_->set_delay_for_testing(base::TimeDelta::FromSeconds(0));
  }

  // Adds a file to the service root and |resource_ids_|.
  void AddFileEntry(const std::string& title) {
    google_apis::GDataErrorCode error = google_apis::GDATA_FILE_ERROR;
    scoped_ptr<google_apis::ResourceEntry> entry;
    drive_service_->AddNewFile(
        "text/plain",
        kRemoteContent,
        drive_service_->GetRootResourceId(),
        title,
        false,  // shared_with_me
        google_apis::test_util::CreateCopyResultCallback(&error, &entry));
    base::RunLoop().RunUntilIdle();
    ASSERT_EQ(google_apis::HTTP_CREATED, error);
    ASSERT_TRUE(entry);
    resource_ids_[title] = entry->resource_id();
  }

  // Sets up data for tests.
  void SetUpTestData() {
    // Prepare a temp file.
    base::FilePath temp_file;
    EXPECT_TRUE(file_util::CreateTemporaryFileInDir(temp_dir_.path(),
                                                    &temp_file));
    ASSERT_TRUE(google_apis::test_util::WriteStringToFile(temp_file,
                                                          kLocalContent));

    // Add file entries to the service.
    ASSERT_NO_FATAL_FAILURE(AddFileEntry("foo"));
    ASSERT_NO_FATAL_FAILURE(AddFileEntry("bar"));
    ASSERT_NO_FATAL_FAILURE(AddFileEntry("baz"));
    ASSERT_NO_FATAL_FAILURE(AddFileEntry("fetched"));
    ASSERT_NO_FATAL_FAILURE(AddFileEntry("dirty"));

    // Load data from the service to the metadata.
    FileError error = FILE_ERROR_FAILED;
    internal::ChangeListLoader change_list_loader(
        base::MessageLoopProxy::current().get(),
        metadata_.get(),
        scheduler_.get(),
        drive_service_.get());
    change_list_loader.LoadIfNeeded(
        DirectoryFetchInfo(),
        google_apis::test_util::CreateCopyResultCallback(&error));
    base::RunLoop().RunUntilIdle();
    EXPECT_EQ(FILE_ERROR_OK, error);

    // Prepare 3 pinned-but-not-present files.
    EXPECT_EQ(FILE_ERROR_OK, cache_->Pin(GetLocalId("foo")));
    EXPECT_EQ(FILE_ERROR_OK, cache_->Pin(GetLocalId("bar")));
    EXPECT_EQ(FILE_ERROR_OK, cache_->Pin(GetLocalId("baz")));

    // Prepare a pinned-and-fetched file.
    const std::string md5_fetched = "md5";
    EXPECT_EQ(FILE_ERROR_OK,
              cache_->Store(GetLocalId("fetched"), md5_fetched,
                            temp_file, FileCache::FILE_OPERATION_COPY));
    EXPECT_EQ(FILE_ERROR_OK, cache_->Pin(GetLocalId("fetched")));

    // Prepare a pinned-and-fetched-and-dirty file.
    const std::string md5_dirty = "";  // Don't care.
    EXPECT_EQ(FILE_ERROR_OK,
              cache_->Store(GetLocalId("dirty"), md5_dirty,
                            temp_file, FileCache::FILE_OPERATION_COPY));
    EXPECT_EQ(FILE_ERROR_OK, cache_->Pin(GetLocalId("dirty")));
    EXPECT_EQ(FILE_ERROR_OK, cache_->MarkDirty(GetLocalId("dirty")));

  }

 protected:
  std::string GetLocalId(const std::string& title) {
    EXPECT_EQ(1U, resource_ids_.count(title));
    std::string local_id;
    EXPECT_EQ(FILE_ERROR_OK,
              metadata_->GetIdByResourceId(resource_ids_[title], &local_id));
    return local_id;
  }

  content::TestBrowserThreadBundle thread_bundle_;
  base::ScopedTempDir temp_dir_;
  scoped_ptr<TestingPrefServiceSimple> pref_service_;
  scoped_ptr<test_util::FakeNetworkChangeNotifier>
      fake_network_change_notifier_;
  scoped_ptr<SyncClientTestDriveService> drive_service_;
  DummyOperationObserver observer_;
  scoped_ptr<JobScheduler> scheduler_;
  scoped_ptr<ResourceMetadataStorage,
             test_util::DestroyHelperForTests> metadata_storage_;
  scoped_ptr<ResourceMetadata, test_util::DestroyHelperForTests> metadata_;
  scoped_ptr<FileCache, test_util::DestroyHelperForTests> cache_;
  scoped_ptr<SyncClient> sync_client_;

  std::map<std::string, std::string> resource_ids_;  // Name-to-id map.
};

TEST_F(SyncClientTest, StartProcessingBacklog) {
  sync_client_->StartProcessingBacklog();
  base::RunLoop().RunUntilIdle();

  FileCacheEntry cache_entry;
  // Pinned files get downloaded.
  EXPECT_TRUE(cache_->GetCacheEntry(GetLocalId("foo"), &cache_entry));
  EXPECT_TRUE(cache_entry.is_present());

  EXPECT_TRUE(cache_->GetCacheEntry(GetLocalId("bar"), &cache_entry));
  EXPECT_TRUE(cache_entry.is_present());

  EXPECT_TRUE(cache_->GetCacheEntry(GetLocalId("baz"), &cache_entry));
  EXPECT_TRUE(cache_entry.is_present());

  // Dirty file gets uploaded.
  EXPECT_TRUE(cache_->GetCacheEntry(GetLocalId("dirty"), &cache_entry));
  EXPECT_FALSE(cache_entry.is_dirty());
}

TEST_F(SyncClientTest, AddFetchTask) {
  sync_client_->AddFetchTask(GetLocalId("foo"));
  base::RunLoop().RunUntilIdle();

  FileCacheEntry cache_entry;
  EXPECT_TRUE(cache_->GetCacheEntry(GetLocalId("foo"), &cache_entry));
  EXPECT_TRUE(cache_entry.is_present());
}

TEST_F(SyncClientTest, AddFetchTaskAndCancelled) {
  // Trigger fetching of a file which results in cancellation.
  drive_service_->set_resource_id_to_be_cancelled(resource_ids_["foo"]);
  sync_client_->AddFetchTask(GetLocalId("foo"));
  base::RunLoop().RunUntilIdle();

  // The file should be unpinned if the user wants the download to be cancelled.
  FileCacheEntry cache_entry;
  EXPECT_FALSE(cache_->GetCacheEntry(GetLocalId("foo"), &cache_entry));
}

TEST_F(SyncClientTest, RemoveFetchTask) {
  sync_client_->AddFetchTask(GetLocalId("foo"));
  sync_client_->AddFetchTask(GetLocalId("bar"));
  sync_client_->AddFetchTask(GetLocalId("baz"));

  sync_client_->RemoveFetchTask(GetLocalId("foo"));
  sync_client_->RemoveFetchTask(GetLocalId("baz"));
  base::RunLoop().RunUntilIdle();

  // Only "bar" should be fetched.
  FileCacheEntry cache_entry;
  EXPECT_TRUE(cache_->GetCacheEntry(GetLocalId("foo"), &cache_entry));
  EXPECT_FALSE(cache_entry.is_present());

  EXPECT_TRUE(cache_->GetCacheEntry(GetLocalId("bar"), &cache_entry));
  EXPECT_TRUE(cache_entry.is_present());

  EXPECT_TRUE(cache_->GetCacheEntry(GetLocalId("baz"), &cache_entry));
  EXPECT_FALSE(cache_entry.is_present());

}

TEST_F(SyncClientTest, ExistingPinnedFiles) {
  // Start checking the existing pinned files. This will collect the resource
  // IDs of pinned files, with stale local cache files.
  sync_client_->StartCheckingExistingPinnedFiles();
  base::RunLoop().RunUntilIdle();

  // "fetched" and "dirty" are the existing pinned files.
  // The non-dirty one should be synced, but the dirty one should not.
  base::FilePath cache_file;
  std::string content;
  EXPECT_EQ(FILE_ERROR_OK, cache_->GetFile(GetLocalId("fetched"), &cache_file));
  EXPECT_TRUE(base::ReadFileToString(cache_file, &content));
  EXPECT_EQ(kRemoteContent, content);
  content.clear();

  EXPECT_EQ(FILE_ERROR_OK, cache_->GetFile(GetLocalId("dirty"), &cache_file));
  EXPECT_TRUE(base::ReadFileToString(cache_file, &content));
  EXPECT_EQ(kLocalContent, content);
}

TEST_F(SyncClientTest, RetryOnDisconnection) {
  // Let the service go down.
  drive_service_->set_offline(true);
  // Change the network connection state after some delay, to test that
  // FILE_ERROR_NO_CONNECTION is handled by SyncClient correctly.
  // Without this delay, JobScheduler will keep the jobs unrun and SyncClient
  // will receive no error.
  base::MessageLoopProxy::current()->PostDelayedTask(
      FROM_HERE,
      base::Bind(&test_util::FakeNetworkChangeNotifier::SetConnectionType,
                 base::Unretained(fake_network_change_notifier_.get()),
                 net::NetworkChangeNotifier::CONNECTION_NONE),
      TestTimeouts::tiny_timeout());

  // Try fetch and upload.
  sync_client_->AddFetchTask(GetLocalId("foo"));
  sync_client_->AddUploadTask(GetLocalId("dirty"));
  base::RunLoop().RunUntilIdle();

  // Not yet fetched nor uploaded.
  FileCacheEntry cache_entry;
  EXPECT_TRUE(cache_->GetCacheEntry(GetLocalId("foo"), &cache_entry));
  EXPECT_FALSE(cache_entry.is_present());
  EXPECT_TRUE(cache_->GetCacheEntry(GetLocalId("dirty"), &cache_entry));
  EXPECT_TRUE(cache_entry.is_dirty());

  // Switch to online.
  fake_network_change_notifier_->SetConnectionType(
      net::NetworkChangeNotifier::CONNECTION_WIFI);
  drive_service_->set_offline(false);
  base::RunLoop().RunUntilIdle();

  // Fetched and uploaded.
  EXPECT_TRUE(cache_->GetCacheEntry(GetLocalId("foo"), &cache_entry));
  EXPECT_TRUE(cache_entry.is_present());
  EXPECT_TRUE(cache_->GetCacheEntry(GetLocalId("dirty"), &cache_entry));
  EXPECT_FALSE(cache_entry.is_dirty());
}

}  // namespace internal
}  // namespace drive
<|endoftext|>


<commit_before>#include"HybridApplication.h"
namespace HybridRenderer
{
	Application::Application()
		: mRoot(0)
	{
	}

	Application::~Application()
	{
		//Delete the Ogre root.
		delete mRoot;
	}

	void Application::initialiseOgre()
	{
		mRoot = new Ogre::Root();
	}

	bool Application::go()
	{
		//1. Create Ogre root. Rely on the default plugin loading mechanism.
		initialiseOgre();
		//2.Initialise resources from resources.cfg - For now!
		initialiseResourcePaths();
		//3.Try to initialise a render system.
		//Uses the config dialog and ogre.cfg restoration for now.
		if(!setupRenderSystem())
			return false;
		//4.Create the render window using mRoot->initialise
		createRenderWindow();
		//5.Create a scene.
		createScene();
		//6.Set the default no. of mipmaps and initialise resources as needed.
		initialiseResources();
		//7.Keep looping until exit.
		startRenderLoop();
		return true;
	}

	bool Application::setupRenderSystem()
	{
		if (!mRoot->restoreConfig() && !mRoot->showConfigDialog())
			return false;
		//This else is for intent more than anything else.
		else
			return true;
	}

	void Application::chooseSceneManager()
	{
        	sceneManager = mRoot->createSceneManager(Ogre::ST_GENERIC, "HybridSceneManager");
	}

	void Application::createScene()
	{
		chooseSceneManager();
		Ogre::Camera *cam = sceneManager->createCamera("Camera");
		Ogre::Viewport *vp = mRoot->getAutoCreatedWindow()->addViewport(cam);
		vp->setBackgroundColour(Ogre::ColourValue(0.0f,0.0f,0.0f));
		cam->setAspectRatio(Ogre::Real(vp->getActualWidth()) /
				Ogre::Real(vp->getActualHeight()));
	}

	void Application::createRayTraceScene()
	{
	}

	void Application::createRenderWindow()
	{
		mRoot->initialise(true, "Tutorial Render Window");
	}

	void Application::initialiseResourcePaths()
	{
		//Define Resources

		//Handle with more care later.
		Ogre::String secName, typeName, archName;
		Ogre::ConfigFile cf;
		cf.load("resources.cfg");
		Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
        	while (seci.hasMoreElements())
        	{
	        	secName = seci.peekNextKey();
			Ogre::ConfigFile::SettingsMultiMap *settings = seci.\
								      getNext();
			Ogre::ConfigFile::SettingsMultiMap::iterator i;
		        for (i = settings->begin(); i != settings->end(); ++i)
		        {
		        	typeName = i->first;
				archName = i->second;
				Ogre::ResourceGroupManager::getSingleton().\
					addResourceLocation(archName, typeName, secName);
			}
   		}

	}

	void Application::initialiseResources()
	{
		//Set the default number of mipmaps.
		Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
		//Resource loading -- Change this to initialise only the resources
		//needed later.
		Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
	}

	void Application::setupInputSystem()
	{
		// set up the input handlers
		inputListener = new InputHandler(stateManager, hWnd);
	}

	void Application::startRenderLoop()
	{

		while (stateManager->getCurrentState() != SHUTDOWN)
		{
			inputListener->capture();
			// run the message pump (Eihort)
			Ogre::WindowEventUtilities::messagePump();
			ogre->renderOneFrame();
		}

	}
}
<commit_msg>Removed errors - integration is still gtoing on.<commit_after>#include"HybridApplication.h"

namespace HybridRenderer
{
	Application::Application()
		: mRoot(0)
	{
	}

	Application::~Application()
	{
		//Delete the Ogre root.
		delete mRoot;
	}

	void Application::initialiseOgre()
	{
		mRoot = new Ogre::Root();
	}

	bool Application::go()
	{
		//1. Create Ogre root. Rely on the default plugin loading mechanism.
		initialiseOgre();
		//2.Initialise resources from resources.cfg - For now!
		initialiseResourcePaths();
		//3.Try to initialise a render system.
		//Uses the config dialog and ogre.cfg restoration for now.
		if(!setupRenderSystem())
			return false;
		//4.Create the render window using mRoot->initialise
		createRenderWindow();
		//5.Create a scene.
		createScene();
		//6.Set the default no. of mipmaps and initialise resources as needed.
		initialiseResources();
		//7.Keep looping until exit.
		startRenderLoop();
		return true;
	}

	bool Application::setupRenderSystem()
	{
		if (!mRoot->restoreConfig() && !mRoot->showConfigDialog())
			return false;
		//This else is for intent more than anything else.
		else
			return true;
	}

	void Application::chooseSceneManager()
	{
        	sceneManager = mRoot->createSceneManager(Ogre::ST_GENERIC, "HybridSceneManager");
	}

	void Application::createScene()
	{
		chooseSceneManager();
		Ogre::Camera *cam = sceneManager->createCamera("Camera");
		Ogre::Viewport *vp = mRoot->getAutoCreatedWindow()->addViewport(cam);
		vp->setBackgroundColour(Ogre::ColourValue(0.0f,0.0f,0.0f));
		cam->setAspectRatio(Ogre::Real(vp->getActualWidth()) /
				Ogre::Real(vp->getActualHeight()));
	}

	void Application::createRayTraceScene()
	{
	}

	void Application::createRenderWindow()
	{
		mRoot->initialise(true, "Tutorial Render Window");
	}

	void Application::initialiseResourcePaths()
	{
		//Define Resources

		//Handle with more care later.
		Ogre::String secName, typeName, archName;
		Ogre::ConfigFile cf;
		cf.load("resources.cfg");
		Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator();
        	while (seci.hasMoreElements())
        	{
	        	secName = seci.peekNextKey();
			Ogre::ConfigFile::SettingsMultiMap *settings = seci.\
								      getNext();
			Ogre::ConfigFile::SettingsMultiMap::iterator i;
		        for (i = settings->begin(); i != settings->end(); ++i)
		        {
		        	typeName = i->first;
				archName = i->second;
				Ogre::ResourceGroupManager::getSingleton().\
					addResourceLocation(archName, typeName, secName);
			}
   		}

	}

	void Application::initialiseResources()
	{
		//Set the default number of mipmaps.
		Ogre::TextureManager::getSingleton().setDefaultNumMipmaps(5);
		//Resource loading -- Change this to initialise only the resources
		//needed later.
		Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
	}

	void Application::setupInputSystem()
	{
		// set up the input handlers
		inputListener = new InputListener(stateManager, hWnd);
	}

	void Application::startRenderLoop()
	{

		while (stateManager->getCurrentState() != SHUTDOWN)
		{
			inputListener->capture();
			// run the message pump (Eihort)
			Ogre::WindowEventUtilities::messagePump();
			mRoot->renderOneFrame();
		}

	}
}
<|endoftext|>


<commit_before>// @(#)root/rint:$Name:  $:$Id: TRint.cxx,v 1.28 2004/03/15 15:01:41 rdm Exp $
// Author: Rene Brun   17/02/95

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// Rint                                                                 //
//                                                                      //
// Rint is the ROOT Interactive Interface. It allows interactive access //
// to the ROOT system via the CINT C/C++ interpreter.                   //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TROOT.h"
#include "TClass.h"
#include "TVirtualX.h"
#include "Getline.h"
#include "TStyle.h"
#include "TObjectTable.h"
#include "TClassTable.h"
#include "TStopwatch.h"
#include "TBenchmark.h"
#include "TRint.h"
#include "TSystem.h"
#include "TEnv.h"
#include "TSysEvtHandler.h"
#include "TError.h"
#include "TException.h"
#include "TInterpreter.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TFile.h"
#include "TMapFile.h"
#include "TTabCom.h"
#include "TError.h"

#ifdef R__UNIX
#include <signal.h>

extern "C" {
   extern int G__get_security_error();
   extern int G__genericerror(const char* msg);
}
#endif

static Int_t key_pressed(Int_t key) { gApplication->KeyPressed(key); return 0; }

//----- Interrupt signal handler -----------------------------------------------
//______________________________________________________________________________
class TInterruptHandler : public TSignalHandler {
public:
   TInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { }
   Bool_t  Notify();
};

//______________________________________________________________________________
Bool_t TInterruptHandler::Notify()
{
   // TRint interrupt handler.

   if (fDelay) {
      fDelay++;
      return kTRUE;
   }

   // make sure we use the sbrk heap (in case of mapped files)
   gMmallocDesc = 0;

   if (!G__get_security_error())
      G__genericerror("\n *** Break *** keyboard interrupt");
   else {
      Break("TInterruptHandler::Notify", "keyboard interrupt");
      if (TROOT::Initialized()) {
         Getlinem(kInit, "Root > ");
         gInterpreter->RewindDictionary();
         Throw(GetSignal());
      }
   }
   return kTRUE;
}

//----- Terminal Input file handler --------------------------------------------
//______________________________________________________________________________
class TTermInputHandler : public TFileHandler {
public:
   TTermInputHandler(Int_t fd) : TFileHandler(fd, 1) { }
   Bool_t Notify();
   Bool_t ReadNotify() { return Notify(); }
};

//______________________________________________________________________________
Bool_t TTermInputHandler::Notify()
{
   return gApplication->HandleTermInput();
}

ClassImp(TRint)

//______________________________________________________________________________
TRint::TRint(const char *appClassName, Int_t *argc, char **argv, void *options,
             Int_t numOptions, Bool_t noLogo)
       : TApplication(appClassName, argc, argv, options, numOptions)
{
   // Create an application environment. The TRint environment provides an
   // interface to the WM manager functionality and eventloop via inheritance
   // of TApplication and in addition provides interactive access to
   // the CINT C++ interpreter via the command line.

   fNcmd          = 0;
   fDefaultPrompt = "root [%d] ";
   fInterrupt     = kFALSE;

   gBenchmark = new TBenchmark();

   if (!noLogo && !NoLogoOpt())
      PrintLogo();

   // Everybody expects iostream to be available, so load it...
   ProcessLine("#include <iostream>", kTRUE);
   ProcessLine("#include <_string>",kTRUE); // for std::string iostream.

   // Allow the usage of ClassDef and ClassImp in interpreted macros
   ProcessLine("#include <RtypesCint.h>", kTRUE);

   // The following libs are also useful to have, make sure they are loaded...
   gROOT->LoadClass("TGeometry",   "Graf3d");
   gROOT->LoadClass("TTree",       "Tree");
   gROOT->LoadClass("TMatrix",     "Matrix");
   gROOT->LoadClass("TMinuit",     "Minuit");
   gROOT->LoadClass("TPostScript", "Postscript");
   gROOT->LoadClass("TCanvas",     "Gpad");
   gROOT->LoadClass("THtml",       "Html");

   // Load user functions
   const char *logon;
   logon = gEnv->GetValue("Rint.Load", (char*)0);
   if (logon) {
      char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
      if (mac)
         ProcessLine(Form(".L %s",logon),kTRUE);
      delete [] mac;
   }

   // Execute logon macro
   logon = gEnv->GetValue("Rint.Logon", (char*)0);
   if (logon && !NoLogOpt()) {
      char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
      if (mac)
         ProcessFile(logon);
      delete [] mac;
   }

   gInterpreter->SaveContext();
   gInterpreter->SaveGlobalsContext();

   // Install interrupt and terminal input handlers
   TInterruptHandler *ih = new TInterruptHandler();
   ih->Add();
   SetSignalHandler(ih);

   // Handle stdin events
   fInputHandler = new TTermInputHandler(0);
   fInputHandler->Add();

   // Goto into raw terminal input mode
   char defhist[128];
#ifndef R__VMS
   sprintf(defhist, "%s/.root_hist", gSystem->Getenv("HOME"));
#else
   sprintf(defhist, "%s.root_hist", gSystem->Getenv("HOME"));
#endif
   logon = gEnv->GetValue("Rint.History", defhist);
   Gl_histinit((char *)logon);
   Gl_windowchanged();

   // Setup for tab completion
   gTabCom = new TTabCom;
   Gl_in_key = &key_pressed;
}

//______________________________________________________________________________
TRint::~TRint()
{

}

//______________________________________________________________________________
void TRint::Run(Bool_t retrn)
{
   // Main application eventloop. First process files given on the command
   // line and then go into the main application event loop, unless the -q
   // command line option was specfied in which case the program terminates.
   // When retrun is true this method returns even when -q was specified.
   //
   // When QuitOpt is true and retrn is false, terminate the application with
   // an error code equal to either the ProcessLine error (if any) or the
   // return value of the command casted to a long.

   Getlinem(kInit, GetPrompt());

   Long_t retval = 0;
   Int_t  error = 0;

   // Process shell command line input files
   if (InputFiles()) {
      Int_t nfile = 0;
      TObjString *file;
      TIter next(InputFiles());
      RETRY {
         while ((file = (TObjString *)next())) {
            char cmd[256];
            if (!fNcmd)
               printf("\n");
            if (file->String().EndsWith(".root")) {
               const char *rfile = (const char*)file->String();
               Printf("Attaching file %s as _file%d...", rfile, nfile);
               sprintf(cmd, "TFile *_file%d = TFile::Open(\"%s\")", nfile++, rfile);
            } else {
               Printf("Processing %s...", (const char*)file->String());
               sprintf(cmd, ".x %s", (const char*)file->String());
            }
            Getlinem(kCleanUp, 0);
            Gl_histadd(cmd);
            fNcmd++;
            retval = ProcessLine(cmd,kFALSE,&error);
            if (error!=0) break;
         }
      } ENDTRY;

      if (QuitOpt()) {
         if (retrn) return;
         Terminate(error==0 ? retval : error);
      }

      ClearInputFiles();

      Getlinem(kInit, GetPrompt());
   }

   if (QuitOpt()) {
      printf("\n");
      if (retrn) return;
      Terminate(0);
   }

   TApplication::Run(retrn);

   Getlinem(kCleanUp, 0);
}

//______________________________________________________________________________
void TRint::PrintLogo()
{
   // Print the ROOT logo on standard output.

   Int_t iday,imonth,iyear;
   static const char *months[] = {"January","February","March","April","May",
                                  "June","July","August","September","October",
                                  "November","December"};
   const char *root_version = gROOT->GetVersion();
   Int_t idatqq = gROOT->GetVersionDate();
   iday   = idatqq%100;
   imonth = (idatqq/100)%100;
   iyear  = (idatqq/10000);
   char *root_date = Form("%d %s %4d",iday,months[imonth-1],iyear);

   Printf("  *******************************************");
   Printf("  *                                         *");
   Printf("  *        W E L C O M E  to  R O O T       *");
   Printf("  *                                         *");
   Printf("  *   Version%10s %17s   *", root_version, root_date);
// Printf("  *            Development version          *");
   Printf("  *                                         *");
   Printf("  *  You are welcome to visit our Web site  *");
   Printf("  *          http://root.cern.ch            *");
   Printf("  *                                         *");
   Printf("  *******************************************");

   if (strstr(gVirtualX->GetName(), "TTF")) {
      Int_t major, minor, patch;
      //TTF::Version(major, minor, patch);
      // avoid dependency on libGraf and hard code, will not change too often
      major = 2; minor = 1; patch = 3;
      Printf("\nFreeType Engine v%d.%d.%d used to render TrueType fonts.",
             major, minor, patch);
   }
#ifdef _REENTRANT
   else
      printf("\n");
   Printf("Compiled for %s with thread support.", gSystem->GetBuildArch());
#else
   else
      printf("\n");
   Printf("Compiled for %s.", gSystem->GetBuildArch());
#endif

   gInterpreter->PrintIntro();

#ifdef R__UNIX
   // Popdown X logo, only if started with -splash option
   for (int i = 0; i < Argc(); i++)
      if (!strcmp(Argv(i), "-splash"))
         kill(getppid(), SIGUSR1);
#endif
}

//______________________________________________________________________________
char *TRint::GetPrompt()
{
   // Get prompt from interpreter. Either "root [n]" or "end with '}'".

   char *s = gInterpreter->GetPrompt();
   if (s[0])
      strcpy(fPrompt, s);
   else
      sprintf(fPrompt, fDefaultPrompt.Data(), fNcmd);

   return fPrompt;
}

//______________________________________________________________________________
const char *TRint::SetPrompt(const char *newPrompt)
{
   // Set a new default prompt. It returns the previous prompt.
   // The prompt may contain a %d which will be replaced by the commend
   // number. The default prompt is "root [%d] ". The maximum length of
   // the prompt is 55 characters. To set the prompt in an interactive
   // session do:
   // root [0] ((TRint*)gROOT->GetApplication())->SetPrompt("aap> ")
   // aap>

   static TString op = fDefaultPrompt;

   if (newPrompt && strlen(newPrompt) <= 55)
      fDefaultPrompt = newPrompt;
   else
      Error("SetPrompt", "newPrompt too long (> 55 characters)");

   return op.Data();
}

//______________________________________________________________________________
Bool_t TRint::HandleTermInput()
{
   // Handle input coming from terminal.

   static TStopwatch timer;
   char *line;

   if ((line = Getlinem(kOneChar, 0))) {
      if (line[0] == 0 && Gl_eof())
         Terminate(0);

      gVirtualX->SetKeyAutoRepeat(kTRUE);

      Gl_histadd(line);

      TString sline = line;
      line[0] = 0;

      // strip off '\n' and leading and trailing blanks
      sline = sline.Chop();
      sline = sline.Strip(TString::kBoth);
      ReturnPressed((char*)sline.Data());

      fInterrupt = kFALSE;

      if (!gInterpreter->GetMore() && !sline.IsNull()) fNcmd++;

      // prevent recursive calling of this input handler
      fInputHandler->DeActivate();

      if (gROOT->Timer()) timer.Start();

      Bool_t added = kFALSE;
#ifdef R__EH
      try {
#endif
         TRY {
            ProcessLine(sline);
         } CATCH(excode) {
            // enable again input handler
            fInputHandler->Add();
            added = kTRUE;
            Throw(excode);
         } ENDTRY;
#ifdef R__EH
      }
      // handle every exception
      catch (...) {
         // enable again intput handler
         if (!added) fInputHandler->Add();
         throw;
      }
#endif

      if (gROOT->Timer()) timer.Print();

      // enable again intput handler
      fInputHandler->Activate();

      if (!sline.BeginsWith(".reset"))
         gInterpreter->EndOfLineAction();

      gTabCom->ClearAll();
      Getlinem(kInit, GetPrompt());
   }
   return kTRUE;
}

//______________________________________________________________________________
void TRint::Terminate(Int_t status)
{
   // Terminate the application. Reset the terminal to sane mode and call
   // the logoff macro defined via Rint.Logoff environment variable.

   Getlinem(kCleanUp, 0);

   if (ReturnFromRun()) {
      gSystem->ExitLoop();
   } else {
      //Execute logoff macro
      const char *logoff;
      logoff = gEnv->GetValue("Rint.Logoff", (char*)0);
      if (logoff && !NoLogOpt()) {
         char *mac = gSystem->Which(TROOT::GetMacroPath(), logoff, kReadPermission);
         if (mac)
            ProcessFile(logoff);
         delete [] mac;
      }

      gSystem->Exit(status);
   }
}
<commit_msg>fix warning on MacOS X: rint/src/TRint.cxx:210: warning: variable `Long_t retval' might be clobbered by    `longjmp' or `vfork' rint/src/TRint.cxx:215: warning: variable `Int_t nfile' might be clobbered by    `longjmp' or `vfork'<commit_after>// @(#)root/rint:$Name:  $:$Id: TRint.cxx,v 1.29 2004/04/20 09:27:03 rdm Exp $
// Author: Rene Brun   17/02/95

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// Rint                                                                 //
//                                                                      //
// Rint is the ROOT Interactive Interface. It allows interactive access //
// to the ROOT system via the CINT C/C++ interpreter.                   //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TROOT.h"
#include "TClass.h"
#include "TVirtualX.h"
#include "Getline.h"
#include "TStyle.h"
#include "TObjectTable.h"
#include "TClassTable.h"
#include "TStopwatch.h"
#include "TBenchmark.h"
#include "TRint.h"
#include "TSystem.h"
#include "TEnv.h"
#include "TSysEvtHandler.h"
#include "TError.h"
#include "TException.h"
#include "TInterpreter.h"
#include "TObjArray.h"
#include "TObjString.h"
#include "TFile.h"
#include "TMapFile.h"
#include "TTabCom.h"
#include "TError.h"

#ifdef R__UNIX
#include <signal.h>

extern "C" {
   extern int G__get_security_error();
   extern int G__genericerror(const char* msg);
}
#endif

static Int_t key_pressed(Int_t key) { gApplication->KeyPressed(key); return 0; }

//----- Interrupt signal handler -----------------------------------------------
//______________________________________________________________________________
class TInterruptHandler : public TSignalHandler {
public:
   TInterruptHandler() : TSignalHandler(kSigInterrupt, kFALSE) { }
   Bool_t  Notify();
};

//______________________________________________________________________________
Bool_t TInterruptHandler::Notify()
{
   // TRint interrupt handler.

   if (fDelay) {
      fDelay++;
      return kTRUE;
   }

   // make sure we use the sbrk heap (in case of mapped files)
   gMmallocDesc = 0;

   if (!G__get_security_error())
      G__genericerror("\n *** Break *** keyboard interrupt");
   else {
      Break("TInterruptHandler::Notify", "keyboard interrupt");
      if (TROOT::Initialized()) {
         Getlinem(kInit, "Root > ");
         gInterpreter->RewindDictionary();
         Throw(GetSignal());
      }
   }
   return kTRUE;
}

//----- Terminal Input file handler --------------------------------------------
//______________________________________________________________________________
class TTermInputHandler : public TFileHandler {
public:
   TTermInputHandler(Int_t fd) : TFileHandler(fd, 1) { }
   Bool_t Notify();
   Bool_t ReadNotify() { return Notify(); }
};

//______________________________________________________________________________
Bool_t TTermInputHandler::Notify()
{
   return gApplication->HandleTermInput();
}

ClassImp(TRint)

//______________________________________________________________________________
TRint::TRint(const char *appClassName, Int_t *argc, char **argv, void *options,
             Int_t numOptions, Bool_t noLogo)
       : TApplication(appClassName, argc, argv, options, numOptions)
{
   // Create an application environment. The TRint environment provides an
   // interface to the WM manager functionality and eventloop via inheritance
   // of TApplication and in addition provides interactive access to
   // the CINT C++ interpreter via the command line.

   fNcmd          = 0;
   fDefaultPrompt = "root [%d] ";
   fInterrupt     = kFALSE;

   gBenchmark = new TBenchmark();

   if (!noLogo && !NoLogoOpt())
      PrintLogo();

   // Everybody expects iostream to be available, so load it...
   ProcessLine("#include <iostream>", kTRUE);
   ProcessLine("#include <_string>",kTRUE); // for std::string iostream.

   // Allow the usage of ClassDef and ClassImp in interpreted macros
   ProcessLine("#include <RtypesCint.h>", kTRUE);

   // The following libs are also useful to have, make sure they are loaded...
   gROOT->LoadClass("TGeometry",   "Graf3d");
   gROOT->LoadClass("TTree",       "Tree");
   gROOT->LoadClass("TMatrix",     "Matrix");
   gROOT->LoadClass("TMinuit",     "Minuit");
   gROOT->LoadClass("TPostScript", "Postscript");
   gROOT->LoadClass("TCanvas",     "Gpad");
   gROOT->LoadClass("THtml",       "Html");

   // Load user functions
   const char *logon;
   logon = gEnv->GetValue("Rint.Load", (char*)0);
   if (logon) {
      char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
      if (mac)
         ProcessLine(Form(".L %s",logon),kTRUE);
      delete [] mac;
   }

   // Execute logon macro
   logon = gEnv->GetValue("Rint.Logon", (char*)0);
   if (logon && !NoLogOpt()) {
      char *mac = gSystem->Which(TROOT::GetMacroPath(), logon, kReadPermission);
      if (mac)
         ProcessFile(logon);
      delete [] mac;
   }

   gInterpreter->SaveContext();
   gInterpreter->SaveGlobalsContext();

   // Install interrupt and terminal input handlers
   TInterruptHandler *ih = new TInterruptHandler();
   ih->Add();
   SetSignalHandler(ih);

   // Handle stdin events
   fInputHandler = new TTermInputHandler(0);
   fInputHandler->Add();

   // Goto into raw terminal input mode
   char defhist[128];
#ifndef R__VMS
   sprintf(defhist, "%s/.root_hist", gSystem->Getenv("HOME"));
#else
   sprintf(defhist, "%s.root_hist", gSystem->Getenv("HOME"));
#endif
   logon = gEnv->GetValue("Rint.History", defhist);
   Gl_histinit((char *)logon);
   Gl_windowchanged();

   // Setup for tab completion
   gTabCom = new TTabCom;
   Gl_in_key = &key_pressed;
}

//______________________________________________________________________________
TRint::~TRint()
{

}

//______________________________________________________________________________
void TRint::Run(Bool_t retrn)
{
   // Main application eventloop. First process files given on the command
   // line and then go into the main application event loop, unless the -q
   // command line option was specfied in which case the program terminates.
   // When retrun is true this method returns even when -q was specified.
   //
   // When QuitOpt is true and retrn is false, terminate the application with
   // an error code equal to either the ProcessLine error (if any) or the
   // return value of the command casted to a long.

   Getlinem(kInit, GetPrompt());

   Long_t retval = 0;
   Int_t  error = 0;

   // Process shell command line input files
   if (InputFiles()) {
      TIter next(InputFiles());
      RETRY {
         retval = 0; error = 0;
         Int_t nfile = 0;
         TObjString *file;
         while ((file = (TObjString *)next())) {
            char cmd[256];
            if (!fNcmd)
               printf("\n");
            if (file->String().EndsWith(".root")) {
               const char *rfile = (const char*)file->String();
               Printf("Attaching file %s as _file%d...", rfile, nfile);
               sprintf(cmd, "TFile *_file%d = TFile::Open(\"%s\")", nfile++, rfile);
            } else {
               Printf("Processing %s...", (const char*)file->String());
               sprintf(cmd, ".x %s", (const char*)file->String());
            }
            Getlinem(kCleanUp, 0);
            Gl_histadd(cmd);
            fNcmd++;
            retval = ProcessLine(cmd, kFALSE, &error);
            if (error != 0) break;
         }
      } ENDTRY;

      if (QuitOpt()) {
         if (retrn) return;
         Terminate(error == 0 ? retval : error);
      }

      ClearInputFiles();

      Getlinem(kInit, GetPrompt());
   }

   if (QuitOpt()) {
      printf("\n");
      if (retrn) return;
      Terminate(0);
   }

   TApplication::Run(retrn);

   Getlinem(kCleanUp, 0);
}

//______________________________________________________________________________
void TRint::PrintLogo()
{
   // Print the ROOT logo on standard output.

   Int_t iday,imonth,iyear;
   static const char *months[] = {"January","February","March","April","May",
                                  "June","July","August","September","October",
                                  "November","December"};
   const char *root_version = gROOT->GetVersion();
   Int_t idatqq = gROOT->GetVersionDate();
   iday   = idatqq%100;
   imonth = (idatqq/100)%100;
   iyear  = (idatqq/10000);
   char *root_date = Form("%d %s %4d",iday,months[imonth-1],iyear);

   Printf("  *******************************************");
   Printf("  *                                         *");
   Printf("  *        W E L C O M E  to  R O O T       *");
   Printf("  *                                         *");
   Printf("  *   Version%10s %17s   *", root_version, root_date);
// Printf("  *            Development version          *");
   Printf("  *                                         *");
   Printf("  *  You are welcome to visit our Web site  *");
   Printf("  *          http://root.cern.ch            *");
   Printf("  *                                         *");
   Printf("  *******************************************");

   if (strstr(gVirtualX->GetName(), "TTF")) {
      Int_t major, minor, patch;
      //TTF::Version(major, minor, patch);
      // avoid dependency on libGraf and hard code, will not change too often
      major = 2; minor = 1; patch = 3;
      Printf("\nFreeType Engine v%d.%d.%d used to render TrueType fonts.",
             major, minor, patch);
   }
#ifdef _REENTRANT
   else
      printf("\n");
   Printf("Compiled for %s with thread support.", gSystem->GetBuildArch());
#else
   else
      printf("\n");
   Printf("Compiled for %s.", gSystem->GetBuildArch());
#endif

   gInterpreter->PrintIntro();

#ifdef R__UNIX
   // Popdown X logo, only if started with -splash option
   for (int i = 0; i < Argc(); i++)
      if (!strcmp(Argv(i), "-splash"))
         kill(getppid(), SIGUSR1);
#endif
}

//______________________________________________________________________________
char *TRint::GetPrompt()
{
   // Get prompt from interpreter. Either "root [n]" or "end with '}'".

   char *s = gInterpreter->GetPrompt();
   if (s[0])
      strcpy(fPrompt, s);
   else
      sprintf(fPrompt, fDefaultPrompt.Data(), fNcmd);

   return fPrompt;
}

//______________________________________________________________________________
const char *TRint::SetPrompt(const char *newPrompt)
{
   // Set a new default prompt. It returns the previous prompt.
   // The prompt may contain a %d which will be replaced by the commend
   // number. The default prompt is "root [%d] ". The maximum length of
   // the prompt is 55 characters. To set the prompt in an interactive
   // session do:
   // root [0] ((TRint*)gROOT->GetApplication())->SetPrompt("aap> ")
   // aap>

   static TString op = fDefaultPrompt;

   if (newPrompt && strlen(newPrompt) <= 55)
      fDefaultPrompt = newPrompt;
   else
      Error("SetPrompt", "newPrompt too long (> 55 characters)");

   return op.Data();
}

//______________________________________________________________________________
Bool_t TRint::HandleTermInput()
{
   // Handle input coming from terminal.

   static TStopwatch timer;
   char *line;

   if ((line = Getlinem(kOneChar, 0))) {
      if (line[0] == 0 && Gl_eof())
         Terminate(0);

      gVirtualX->SetKeyAutoRepeat(kTRUE);

      Gl_histadd(line);

      TString sline = line;
      line[0] = 0;

      // strip off '\n' and leading and trailing blanks
      sline = sline.Chop();
      sline = sline.Strip(TString::kBoth);
      ReturnPressed((char*)sline.Data());

      fInterrupt = kFALSE;

      if (!gInterpreter->GetMore() && !sline.IsNull()) fNcmd++;

      // prevent recursive calling of this input handler
      fInputHandler->DeActivate();

      if (gROOT->Timer()) timer.Start();

      Bool_t added = kFALSE;
#ifdef R__EH
      try {
#endif
         TRY {
            ProcessLine(sline);
         } CATCH(excode) {
            // enable again input handler
            fInputHandler->Add();
            added = kTRUE;
            Throw(excode);
         } ENDTRY;
#ifdef R__EH
      }
      // handle every exception
      catch (...) {
         // enable again intput handler
         if (!added) fInputHandler->Add();
         throw;
      }
#endif

      if (gROOT->Timer()) timer.Print();

      // enable again intput handler
      fInputHandler->Activate();

      if (!sline.BeginsWith(".reset"))
         gInterpreter->EndOfLineAction();

      gTabCom->ClearAll();
      Getlinem(kInit, GetPrompt());
   }
   return kTRUE;
}

//______________________________________________________________________________
void TRint::Terminate(Int_t status)
{
   // Terminate the application. Reset the terminal to sane mode and call
   // the logoff macro defined via Rint.Logoff environment variable.

   Getlinem(kCleanUp, 0);

   if (ReturnFromRun()) {
      gSystem->ExitLoop();
   } else {
      //Execute logoff macro
      const char *logoff;
      logoff = gEnv->GetValue("Rint.Logoff", (char*)0);
      if (logoff && !NoLogOpt()) {
         char *mac = gSystem->Which(TROOT::GetMacroPath(), logoff, kReadPermission);
         if (mac)
            ProcessFile(logoff);
         delete [] mac;
      }

      gSystem->Exit(status);
   }
}
<|endoftext|>


<commit_before>// tests the inclusion algorithm for all 2D and 3D elements

#include "FemusInit.hpp"
#include "Marker.hpp"
#include "MultiLevelMesh.hpp"
#include "VTKWriter.hpp"
#include "NonLinearImplicitSystem.hpp"
#include "MyVector.hpp"

using namespace femus;

void PrintStreamline(const std::string output_path, const std::vector< std::vector<double> > &xn);

// double InitalValueU(const std::vector < double >& x) {
//   return 0.5;
// }
//
// double InitalValueV(const std::vector < double >& x) {
//   return 0.5;
// }
//
// double InitalValueW(const std::vector < double >& x) {
//   return 0.5;
// }

double InitalValueU(const std::vector < double >& x) {
  return -x[1];
}

double InitalValueV(const std::vector < double >& x) {
  return x[0];
}

double InitalValueW(const std::vector < double >& x) {
  return 0.;
}

double InitalValueU(const std::vector < double >& x) {
  return (-x[1]+x[2])/sqrt(3);
}

double InitalValueV(const std::vector < double >& x) {
  return (x[0]-x[2])/sqrt(3);
}

double InitalValueW(const std::vector < double >& x) {
  return (x[1]-x[0])/sqrt(3);
}

bool SetRefinementFlag(const std::vector < double >& x, const int& elemgroupnumber, const int& level) {

  bool refine = 0;

  if(elemgroupnumber == 6 && level < 4) refine = 1;
  if(elemgroupnumber == 7 && level < 5) refine = 1;
  if(elemgroupnumber == 8 && level < 6) refine = 1;

  return refine;

}

int main(int argc, char** args) {

  // init Petsc-MPI communicator
  FemusInit mpinit(argc, args, MPI_COMM_WORLD);

  std::vector < double > x(3, 0); // marker
  MultiLevelMesh mlMsh;
  double scalingFactor = 1.;
  unsigned numberOfUniformLevels = 1;
  unsigned numberOfSelectiveLevels = 0;
  std::vector < std::string > variablesToBePrinted;

  /* element types
  0 = HEX
  1 = TET
  2 = WEDGE
  3 = QUAD
  4 = TRI
   */

  unsigned solType = 2;

  std::cout << " --------------------------------------------------     TEST     --------------------------------------------------" << std::endl;

  //mlMsh.ReadCoarseMesh("./input/prism3D.neu", "seventh", scalingFactor);
  //mlMsh.ReadCoarseMesh("./input/square.neu", "seventh", scalingFactor);
  //mlMsh.ReadCoarseMesh("./input/tri2.neu", "seventh", scalingFactor);
  //mlMsh.ReadCoarseMesh("./input/cubeHex.neu", "seventh", scalingFactor);
  mlMsh.ReadCoarseMesh("./input/cubeTet.neu", "seventh", scalingFactor);
  mlMsh.RefineMesh(numberOfUniformLevels + numberOfSelectiveLevels, numberOfUniformLevels , SetRefinementFlag);

  unsigned dim = mlMsh.GetDimension();

  MultiLevelSolution mlSol(&mlMsh);
  // add variables to mlSol
  mlSol.AddSolution("U", LAGRANGE, SECOND, 2);
  mlSol.AddSolution("V", LAGRANGE, SECOND, 2);
  if(dim == 3) mlSol.AddSolution("W", LAGRANGE, SECOND, 2);
  mlSol.Initialize("U" , InitalValueU);
  mlSol.Initialize("V" , InitalValueV);
  if(dim == 3) mlSol.Initialize("W", InitalValueW);

//   //Test 1 (QUAD):
//
  //NOTE tests ran with 4 procs
//   x[0] = -0.46875; //the marker is in element 191 (proc 3 of 4)
//   x[1] = -0.5;
//   x[2] = 0.;

    x[0] = 0.125;
    x[1] = 0.125;
    x[2] = -0.25;

// //Test 1 (TET):  element 20
//     //NOTE Tests ran with 2 procs
//       x[0] = -0.5;
//       x[1] = 0.;
//       x[2] = 0.;

  std::cout << " --------------------------------------------------------------------------------------------- " << std::endl;
  Marker a1Quad(x, VOLUME, mlMsh.GetLevel(0), solType, true);
  //Marker a( x, VOLUME, mlMsh.GetLevel(numberOfUniformLevels + numberOfSelectiveLevels -1) );
  std::cout << " The coordinates of the marker are " << x[0] << " ," << x[1] << " ," << x[2] << std::endl;
  std::cout << " The marker type is " <<  a1Quad.GetMarkerType() << std::endl;

  double T = 2 * acos(-1.);
  unsigned n  = 100;

  std::vector < std::vector < double > > xn(n + 1);
  for(unsigned k = 0; k < n; k++) {
    a1Quad.GetMarkerCoordinates(xn[k]);
    a1Quad.Advection(mlSol.GetLevel(0), 2, T / n);
  }
  a1Quad.GetMarkerCoordinates(xn[n]);
  for(unsigned i = 0;  i < xn.size(); i++) {
    for(unsigned d = 0; d < xn[i].size(); d++) {
      std::cout << xn[i][d] << " ";
    }
    std::cout << std::endl;
  }

//   std::vector < MyVector < double > > xn(dim);
//   for(unsigned k = 0; k < n; k++) {
//     a1Quad.GetMarkerCoordinates(xn);
//     a1Quad.Advection(mlSol.GetLevel(0), 2, T / n);
//   }
//   a1Quad.GetMarkerCoordinates(xn);
//   for(unsigned d = 0; d < dim; d++) {
//     xn[d].stack();
//     std::cout << xn[d] << std::endl;
//   }

  variablesToBePrinted.push_back("All");

  VTKWriter vtkIO(&mlSol);
  vtkIO.SetDebugOutput(true);
  vtkIO.Write(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);

  PrintStreamline(DEFAULT_OUTPUTDIR, xn);

  return 0;
}

#include "Files.hpp"
#include <b64/b64.h>

void PrintStreamline(const std::string output_path, const std::vector< std::vector<double> > &xn) {

  // *********** open vtu files *************
  std::ofstream fout;

  std::string dirnamePVTK = "./";
  Files files;
  files.CheckDir(output_path, dirnamePVTK);

  std::string filename_prefix = "streamline";

  std::ostringstream filename;
  filename << output_path << "./" << filename_prefix << ".vtu";

  fout.open(filename.str().c_str());
  if(!fout.is_open()) {
    std::cout << std::endl << " The output file " << filename.str() << " cannot be opened.\n";
    abort();
  }

  unsigned nvt = xn.size();
  unsigned nel = nvt - 1;

  const unsigned dim_array_coord [] = { nvt * 3 * sizeof(float) };
  const unsigned dim_array_conn[]   = { nel * 2 * sizeof( int ) };
  const unsigned dim_array_off []   = { nel * sizeof( int ) };
  const unsigned dim_array_type []  = { nel * sizeof( short unsigned ) };

  unsigned buffer_size = ( dim_array_coord[0] > dim_array_conn[0] ) ? dim_array_coord[0] : dim_array_conn[0];
  void* buffer_void = new char [buffer_size];
  char* buffer_char = static_cast <char*>(buffer_void);

  size_t cch;
  cch = b64::b64_encode(&buffer_char[0], buffer_size , NULL, 0);
  vector <char> enc;
  enc.resize(cch);
  char* pt_char;

  // *********** write vtu header ************
  fout << "<?xml version=\"1.0\"?>" << std::endl;
  fout << "<VTKFile type = \"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">" << std::endl;
  fout << "  <UnstructuredGrid>" << std::endl;

  fout  << "    <Piece NumberOfPoints= \"" << nvt
 	<< "\" NumberOfCells= \"" << nel
	<< "\" >" << std::endl;

  //-----------------------------------------------------------------------------------------------
  // print coordinates *********************************************Solu*******************************************
  fout  << "      <Points>" << std::endl;
  fout  << "        <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"binary\">" << std::endl;

  // point pointer to common mamory area buffer of void type;
  float* var_coord = static_cast< float* >(buffer_void);

  for(unsigned i = 0; i < nvt; i++) {
    for(unsigned d = 0; d < 3; d++) {
      var_coord[i * 3 + d] = (xn[i].size() > d) ? xn[i][d] : 0.;
    }
  }

  cch = b64::b64_encode(&dim_array_coord[0], sizeof(dim_array_coord), NULL, 0);
  b64::b64_encode(&dim_array_coord[0], sizeof(dim_array_coord), &enc[0], cch);
  pt_char = &enc[0];
  for(unsigned i = 0; i < cch; i++, pt_char++) fout << *pt_char;

  //print coordinates array
  cch = b64::b64_encode(&var_coord[0], dim_array_coord[0] , NULL, 0);
  b64::b64_encode(&var_coord[0], dim_array_coord[0], &enc[0], cch);
  pt_char = &enc[0];
  for(unsigned i = 0; i < cch; i++, pt_char++) fout << *pt_char;
  fout << std::endl;

  fout  << "        </DataArray>" << std::endl;
  fout  << "      </Points>" << std::endl;
  //-----------------------------------------------------------------------------------------------

    // Printing of element connectivity - offset - format type  *
    fout  << "      <Cells>" << std::endl;
    //-----------------------------------------------------------------------------------------------
    //print connectivity
    fout  << "        <DataArray type=\"Int32\" Name=\"connectivity\" format=\"binary\">" << std::endl;

    // point pointer to common mamory area buffer of void type;
    int* var_conn = static_cast <int*>( buffer_void );
    unsigned icount = 0;
    for(unsigned iel = 0; iel < nel; iel++ ) {
      for( unsigned j = 0; j < 2; j++ ) {
        var_conn[icount] = iel + j;;
        icount++;
      }
    }

    //print connectivity dimension
    cch = b64::b64_encode( &dim_array_conn[0], sizeof( dim_array_conn ), NULL, 0 );
    b64::b64_encode( &dim_array_conn[0], sizeof( dim_array_conn ), &enc[0], cch );
    pt_char = &enc[0];
    for( unsigned i = 0; i < cch; i++, pt_char++ ) fout << *pt_char;

    //print connectivity array
    cch = b64::b64_encode( &var_conn[0], dim_array_conn[0] , NULL, 0 );
    b64::b64_encode( &var_conn[0], dim_array_conn[0], &enc[0], cch );
    pt_char = &enc[0];
    for( unsigned i = 0; i < cch; i++, pt_char++ ) fout << *pt_char;
    fout << std::endl;
    fout << "        </DataArray>" << std::endl;
    //------------------------------------------------------------------------------------------------
    fout  << "        <DataArray type=\"Int32\" Name=\"offsets\" format=\"binary\">" << std::endl;
     // point pointer to common memory area buffer of void type;
    int* var_off = static_cast <int*>( buffer_void );
    // print offset array
    for( int iel = 0; iel < nel; iel++ ) {
      var_off[iel] = (iel+1) * 2;
    }

    //print offset dimension
    cch = b64::b64_encode( &dim_array_off[0], sizeof( dim_array_off ), NULL, 0 );
    b64::b64_encode( &dim_array_off[0], sizeof( dim_array_off ), &enc[0], cch );
    pt_char = &enc[0];
    for( unsigned i = 0; i < cch; i++, pt_char++ ) fout << *pt_char;

    //print offset array
    cch = b64::b64_encode( &var_off[0], dim_array_off[0] , NULL, 0 );
    b64::b64_encode( &var_off[0], dim_array_off[0], &enc[0], cch );
    pt_char = &enc[0];
    for( unsigned i = 0; i < cch; i++, pt_char++ ) fout << *pt_char;

    fout  << std::endl;

    fout  << "        </DataArray>" << std::endl;

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

    //Element format type : 23:Serendipity(8-nodes)  28:Quad9-Biquadratic
    fout  << "        <DataArray type=\"UInt16\" Name=\"types\" format=\"binary\">" << std::endl;

    // point pointer to common mamory area buffer of void type;
    unsigned short* var_type = static_cast <unsigned short*>( buffer_void );

    for( unsigned iel = 0; iel < nel; iel++ ) {
      var_type[iel] = 3;
    }

    //print element format dimension
    cch = b64::b64_encode( &dim_array_type[0], sizeof( dim_array_type ), NULL, 0 );
    b64::b64_encode( &dim_array_type[0], sizeof( dim_array_type ), &enc[0], cch );
    pt_char = &enc[0];
    for( unsigned i = 0; i < cch; i++, pt_char++ ) fout << *pt_char;

    //print element format array
    cch = b64::b64_encode( &var_type[0], dim_array_type[0] , NULL, 0 );
    b64::b64_encode( &var_type[0], dim_array_type[0], &enc[0], cch );
    pt_char = &enc[0];
    for( unsigned i = 0; i < cch; i++, pt_char++ ) fout << *pt_char;

    fout  << std::endl;
    fout  << "        </DataArray>" << std::endl;

    //----------------------------------------------------------------------------------------------------
//
    fout  << "      </Cells>" << std::endl;

  //-----------------------------------------------------------------------------------------------
  // Printing of element connectivity - offset - format type  *
//   fout  << "      <Cells>" << std::endl;
//   fout  << "      </Cells>" << std::endl;

  fout << "    </Piece>" << std::endl;
  fout << "  </UnstructuredGrid>" << std::endl;
  fout << "</VTKFile>" << std::endl;
  fout.close();

  delete [] var_coord;
  //--------------------------------------------------------------------------------------------------------
  return;
}

<commit_msg>run test 3D<commit_after>// tests the inclusion algorithm for all 2D and 3D elements

#include "FemusInit.hpp"
#include "Marker.hpp"
#include "MultiLevelMesh.hpp"
#include "VTKWriter.hpp"
#include "NonLinearImplicitSystem.hpp"
#include "MyVector.hpp"

using namespace femus;

void PrintStreamline(const std::string output_path, const std::vector< std::vector<double> > &xn);

// double InitalValueU(const std::vector < double >& x) {
//   return 0.5;
// }
//
// double InitalValueV(const std::vector < double >& x) {
//   return 0.5;
// }
//
// double InitalValueW(const std::vector < double >& x) {
//   return 0.5;
// }

double InitalValueU(const std::vector < double >& x) {
  return -x[1];
}

double InitalValueV(const std::vector < double >& x) {
  return x[0];
}

double InitalValueW(const std::vector < double >& x) {
  return 0.;
}

// double InitalValueU(const std::vector < double >& x) {
//   return (-x[1]+x[2])/sqrt(3);
// }
//
// double InitalValueV(const std::vector < double >& x) {
//   return (x[0]-x[2])/sqrt(3);
// }
//
// double InitalValueW(const std::vector < double >& x) {
//   return (x[1]-x[0])/sqrt(3);
// }

bool SetRefinementFlag(const std::vector < double >& x, const int& elemgroupnumber, const int& level) {

  bool refine = 0;

  if(elemgroupnumber == 6 && level < 4) refine = 1;
  if(elemgroupnumber == 7 && level < 5) refine = 1;
  if(elemgroupnumber == 8 && level < 6) refine = 1;

  return refine;

}

int main(int argc, char** args) {

  // init Petsc-MPI communicator
  FemusInit mpinit(argc, args, MPI_COMM_WORLD);

  std::vector < double > x(3, 0); // marker
  MultiLevelMesh mlMsh;
  double scalingFactor = 1.;
  unsigned numberOfUniformLevels = 1;
  unsigned numberOfSelectiveLevels = 0;
  std::vector < std::string > variablesToBePrinted;

  /* element types
  0 = HEX
  1 = TET
  2 = WEDGE
  3 = QUAD
  4 = TRI
   */

  unsigned solType = 2;

  std::cout << " --------------------------------------------------     TEST     --------------------------------------------------" << std::endl;

  //mlMsh.ReadCoarseMesh("./input/prism3D.neu", "seventh", scalingFactor);
  //mlMsh.ReadCoarseMesh("./input/square.neu", "seventh", scalingFactor);
  //mlMsh.ReadCoarseMesh("./input/tri2.neu", "seventh", scalingFactor);
  //mlMsh.ReadCoarseMesh("./input/cubeHex.neu", "seventh", scalingFactor);
  mlMsh.ReadCoarseMesh("./input/cubeTet.neu", "seventh", scalingFactor);
  mlMsh.RefineMesh(numberOfUniformLevels + numberOfSelectiveLevels, numberOfUniformLevels , SetRefinementFlag);

  unsigned dim = mlMsh.GetDimension();

  MultiLevelSolution mlSol(&mlMsh);
  // add variables to mlSol
  mlSol.AddSolution("U", LAGRANGE, SECOND, 2);
  mlSol.AddSolution("V", LAGRANGE, SECOND, 2);
  if(dim == 3) mlSol.AddSolution("W", LAGRANGE, SECOND, 2);
  mlSol.Initialize("U" , InitalValueU);
  mlSol.Initialize("V" , InitalValueV);
  if(dim == 3) mlSol.Initialize("W", InitalValueW);

//   //Test 1 (QUAD):
//
  //NOTE tests ran with 4 procs
//   x[0] = -0.46875; //the marker is in element 191 (proc 3 of 4)
//   x[1] = -0.5;
//   x[2] = 0.;

    x[0] = 0.125;
    x[1] = 0.125;
    x[2] = -0.25;

// //Test 1 (TET):  element 20
//     //NOTE Tests ran with 2 procs
//       x[0] = -0.5;
//       x[1] = 0.;
//       x[2] = 0.;

  std::cout << " --------------------------------------------------------------------------------------------- " << std::endl;
  Marker a1Quad(x, VOLUME, mlMsh.GetLevel(0), solType, true);
  //Marker a( x, VOLUME, mlMsh.GetLevel(numberOfUniformLevels + numberOfSelectiveLevels -1) );
  std::cout << " The coordinates of the marker are " << x[0] << " ," << x[1] << " ," << x[2] << std::endl;
  std::cout << " The marker type is " <<  a1Quad.GetMarkerType() << std::endl;

  double T = 2 * acos(-1.);
  unsigned n  = 100;

  std::vector < std::vector < double > > xn(n + 1);
  for(unsigned k = 0; k < n; k++) {
    a1Quad.GetMarkerCoordinates(xn[k]);
    a1Quad.Advection(mlSol.GetLevel(0), 2, T / n);
  }
  a1Quad.GetMarkerCoordinates(xn[n]);
  for(unsigned i = 0;  i < xn.size(); i++) {
    for(unsigned d = 0; d < xn[i].size(); d++) {
      std::cout << xn[i][d] << " ";
    }
    std::cout << std::endl;
  }

//   std::vector < MyVector < double > > xn(dim);
//   for(unsigned k = 0; k < n; k++) {
//     a1Quad.GetMarkerCoordinates(xn);
//     a1Quad.Advection(mlSol.GetLevel(0), 2, T / n);
//   }
//   a1Quad.GetMarkerCoordinates(xn);
//   for(unsigned d = 0; d < dim; d++) {
//     xn[d].stack();
//     std::cout << xn[d] << std::endl;
//   }

  variablesToBePrinted.push_back("All");

  VTKWriter vtkIO(&mlSol);
  vtkIO.SetDebugOutput(true);
  vtkIO.Write(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted);

  PrintStreamline(DEFAULT_OUTPUTDIR, xn);

  return 0;
}

#include "Files.hpp"
#include <b64/b64.h>

void PrintStreamline(const std::string output_path, const std::vector< std::vector<double> > &xn) {

  // *********** open vtu files *************
  std::ofstream fout;

  std::string dirnamePVTK = "./";
  Files files;
  files.CheckDir(output_path, dirnamePVTK);

  std::string filename_prefix = "streamline";

  std::ostringstream filename;
  filename << output_path << "./" << filename_prefix << ".vtu";

  fout.open(filename.str().c_str());
  if(!fout.is_open()) {
    std::cout << std::endl << " The output file " << filename.str() << " cannot be opened.\n";
    abort();
  }

  unsigned nvt = xn.size();
  unsigned nel = nvt - 1;

  const unsigned dim_array_coord [] = { nvt * 3 * sizeof(float) };
  const unsigned dim_array_conn[]   = { nel * 2 * sizeof( int ) };
  const unsigned dim_array_off []   = { nel * sizeof( int ) };
  const unsigned dim_array_type []  = { nel * sizeof( short unsigned ) };

  unsigned buffer_size = ( dim_array_coord[0] > dim_array_conn[0] ) ? dim_array_coord[0] : dim_array_conn[0];
  void* buffer_void = new char [buffer_size];
  char* buffer_char = static_cast <char*>(buffer_void);

  size_t cch;
  cch = b64::b64_encode(&buffer_char[0], buffer_size , NULL, 0);
  vector <char> enc;
  enc.resize(cch);
  char* pt_char;

  // *********** write vtu header ************
  fout << "<?xml version=\"1.0\"?>" << std::endl;
  fout << "<VTKFile type = \"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">" << std::endl;
  fout << "  <UnstructuredGrid>" << std::endl;

  fout  << "    <Piece NumberOfPoints= \"" << nvt
 	<< "\" NumberOfCells= \"" << nel
	<< "\" >" << std::endl;

  //-----------------------------------------------------------------------------------------------
  // print coordinates *********************************************Solu*******************************************
  fout  << "      <Points>" << std::endl;
  fout  << "        <DataArray type=\"Float32\" NumberOfComponents=\"3\" format=\"binary\">" << std::endl;

  // point pointer to common mamory area buffer of void type;
  float* var_coord = static_cast< float* >(buffer_void);

  for(unsigned i = 0; i < nvt; i++) {
    for(unsigned d = 0; d < 3; d++) {
      var_coord[i * 3 + d] = (xn[i].size() > d) ? xn[i][d] : 0.;
    }
  }

  cch = b64::b64_encode(&dim_array_coord[0], sizeof(dim_array_coord), NULL, 0);
  b64::b64_encode(&dim_array_coord[0], sizeof(dim_array_coord), &enc[0], cch);
  pt_char = &enc[0];
  for(unsigned i = 0; i < cch; i++, pt_char++) fout << *pt_char;

  //print coordinates array
  cch = b64::b64_encode(&var_coord[0], dim_array_coord[0] , NULL, 0);
  b64::b64_encode(&var_coord[0], dim_array_coord[0], &enc[0], cch);
  pt_char = &enc[0];
  for(unsigned i = 0; i < cch; i++, pt_char++) fout << *pt_char;
  fout << std::endl;

  fout  << "        </DataArray>" << std::endl;
  fout  << "      </Points>" << std::endl;
  //-----------------------------------------------------------------------------------------------

    // Printing of element connectivity - offset - format type  *
    fout  << "      <Cells>" << std::endl;
    //-----------------------------------------------------------------------------------------------
    //print connectivity
    fout  << "        <DataArray type=\"Int32\" Name=\"connectivity\" format=\"binary\">" << std::endl;

    // point pointer to common mamory area buffer of void type;
    int* var_conn = static_cast <int*>( buffer_void );
    unsigned icount = 0;
    for(unsigned iel = 0; iel < nel; iel++ ) {
      for( unsigned j = 0; j < 2; j++ ) {
        var_conn[icount] = iel + j;;
        icount++;
      }
    }

    //print connectivity dimension
    cch = b64::b64_encode( &dim_array_conn[0], sizeof( dim_array_conn ), NULL, 0 );
    b64::b64_encode( &dim_array_conn[0], sizeof( dim_array_conn ), &enc[0], cch );
    pt_char = &enc[0];
    for( unsigned i = 0; i < cch; i++, pt_char++ ) fout << *pt_char;

    //print connectivity array
    cch = b64::b64_encode( &var_conn[0], dim_array_conn[0] , NULL, 0 );
    b64::b64_encode( &var_conn[0], dim_array_conn[0], &enc[0], cch );
    pt_char = &enc[0];
    for( unsigned i = 0; i < cch; i++, pt_char++ ) fout << *pt_char;
    fout << std::endl;
    fout << "        </DataArray>" << std::endl;
    //------------------------------------------------------------------------------------------------
    fout  << "        <DataArray type=\"Int32\" Name=\"offsets\" format=\"binary\">" << std::endl;
     // point pointer to common memory area buffer of void type;
    int* var_off = static_cast <int*>( buffer_void );
    // print offset array
    for( int iel = 0; iel < nel; iel++ ) {
      var_off[iel] = (iel+1) * 2;
    }

    //print offset dimension
    cch = b64::b64_encode( &dim_array_off[0], sizeof( dim_array_off ), NULL, 0 );
    b64::b64_encode( &dim_array_off[0], sizeof( dim_array_off ), &enc[0], cch );
    pt_char = &enc[0];
    for( unsigned i = 0; i < cch; i++, pt_char++ ) fout << *pt_char;

    //print offset array
    cch = b64::b64_encode( &var_off[0], dim_array_off[0] , NULL, 0 );
    b64::b64_encode( &var_off[0], dim_array_off[0], &enc[0], cch );
    pt_char = &enc[0];
    for( unsigned i = 0; i < cch; i++, pt_char++ ) fout << *pt_char;

    fout  << std::endl;

    fout  << "        </DataArray>" << std::endl;

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

    //Element format type : 23:Serendipity(8-nodes)  28:Quad9-Biquadratic
    fout  << "        <DataArray type=\"UInt16\" Name=\"types\" format=\"binary\">" << std::endl;

    // point pointer to common mamory area buffer of void type;
    unsigned short* var_type = static_cast <unsigned short*>( buffer_void );

    for( unsigned iel = 0; iel < nel; iel++ ) {
      var_type[iel] = 3;
    }

    //print element format dimension
    cch = b64::b64_encode( &dim_array_type[0], sizeof( dim_array_type ), NULL, 0 );
    b64::b64_encode( &dim_array_type[0], sizeof( dim_array_type ), &enc[0], cch );
    pt_char = &enc[0];
    for( unsigned i = 0; i < cch; i++, pt_char++ ) fout << *pt_char;

    //print element format array
    cch = b64::b64_encode( &var_type[0], dim_array_type[0] , NULL, 0 );
    b64::b64_encode( &var_type[0], dim_array_type[0], &enc[0], cch );
    pt_char = &enc[0];
    for( unsigned i = 0; i < cch; i++, pt_char++ ) fout << *pt_char;

    fout  << std::endl;
    fout  << "        </DataArray>" << std::endl;

    //----------------------------------------------------------------------------------------------------
//
    fout  << "      </Cells>" << std::endl;

  //-----------------------------------------------------------------------------------------------
  // Printing of element connectivity - offset - format type  *
//   fout  << "      <Cells>" << std::endl;
//   fout  << "      </Cells>" << std::endl;

  fout << "    </Piece>" << std::endl;
  fout << "  </UnstructuredGrid>" << std::endl;
  fout << "</VTKFile>" << std::endl;
  fout.close();

  delete [] var_coord;
  //--------------------------------------------------------------------------------------------------------
  return;
}

<|endoftext|>


<commit_before>// Copyright (c) 2010 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/chromeos/login/screen_locker_tester.h"

#include <gdk/gdkkeysyms.h>

#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/login/mock_authenticator.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/screen_lock_view.h"
#include "views/controls/button/button.h"
#include "views/controls/label.h"
#include "views/controls/textfield/textfield.h"
#include "views/widget/widget_gtk.h"
#include "views/widget/root_view.h"

namespace chromeos {

test::ScreenLockerTester* ScreenLocker::GetTester() {
  return new test::ScreenLockerTester();
}

namespace test {

bool ScreenLockerTester::IsLocked() {
  return ScreenLocker::screen_locker_ != NULL &&
      ScreenLocker::screen_locker_->lock_widget_->GetRootView()->IsVisible();
}

void ScreenLockerTester::InjectMockAuthenticator(
    const char* user, const char* password) {
  DCHECK(ScreenLocker::screen_locker_);
  ScreenLocker::screen_locker_->SetAuthenticator(
      new MockAuthenticator(ScreenLocker::screen_locker_, user, password));
}

void ScreenLockerTester::EnterPassword(const char* password) {
  DCHECK(ScreenLocker::screen_locker_);
  views::Textfield* pass = GetPasswordField();
  pass->SetText(ASCIIToUTF16(password));
  GdkEvent* event = gdk_event_new(GDK_KEY_PRESS);

  event->key.keyval = GDK_Return;
  views::Textfield::Keystroke ret(&event->key);
  ScreenLocker::screen_locker_->screen_lock_view_->HandleKeystroke(pass, ret);

  gdk_event_free(event);
}

void ScreenLockerTester::EmulateWindowManagerReady() {
  DCHECK(ScreenLocker::screen_locker_);
  ScreenLocker::screen_locker_->OnWindowManagerReady();
}

views::Textfield* ScreenLockerTester::GetPasswordField() {
  DCHECK(ScreenLocker::screen_locker_);
  return ScreenLocker::screen_locker_->screen_lock_view_->password_field_;
}

views::Widget* ScreenLockerTester::GetWidget() {
  DCHECK(ScreenLocker::screen_locker_);
  return ScreenLocker::screen_locker_->lock_window_;
}

}  // namespace test

}  // namespace chromeos
<commit_msg>Another quick CrOS fix.<commit_after>// Copyright (c) 2010 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/chromeos/login/screen_locker_tester.h"

#include <gdk/gdkkeysyms.h>

#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/login/mock_authenticator.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/screen_lock_view.h"
#include "views/controls/button/button.h"
#include "views/controls/label.h"
#include "views/controls/textfield/textfield.h"
#include "views/widget/widget_gtk.h"
#include "views/widget/root_view.h"

namespace chromeos {

test::ScreenLockerTester* ScreenLocker::GetTester() {
  return new test::ScreenLockerTester();
}

namespace test {

bool ScreenLockerTester::IsLocked() {
  return ScreenLocker::screen_locker_ != NULL &&
      ScreenLocker::screen_locker_->lock_widget_->GetRootView()->IsVisible();
}

void ScreenLockerTester::InjectMockAuthenticator(
    const char* user, const char* password) {
  DCHECK(ScreenLocker::screen_locker_);
  ScreenLocker::screen_locker_->SetAuthenticator(
      new MockAuthenticator(ScreenLocker::screen_locker_, user, password));
}

void ScreenLockerTester::EnterPassword(const char* password) {
  DCHECK(ScreenLocker::screen_locker_);
  views::Textfield* pass = GetPasswordField();
  pass->SetText(ASCIIToUTF16(password));
  GdkEvent* event = gdk_event_new(GDK_KEY_PRESS);

  event->key.keyval = GDK_Return;
  views::Textfield::Keystroke ret(&event->key);
  ScreenLocker::screen_locker_->screen_lock_view_->HandleKeystroke(pass, ret);

  gdk_event_free(event);
}

void ScreenLockerTester::EmulateWindowManagerReady() {
  DCHECK(ScreenLocker::screen_locker_);
  ScreenLocker::screen_locker_->OnWindowManagerReady();
}

views::Textfield* ScreenLockerTester::GetPasswordField() {
  DCHECK(ScreenLocker::screen_locker_);
  return ScreenLocker::screen_locker_->screen_lock_view_->password_field_;
}

views::Widget* ScreenLockerTester::GetWidget() {
  DCHECK(ScreenLocker::screen_locker_);
  return ScreenLocker::screen_locker_->lock_window_;
}

}  // namespace test

}  // namespace chromeos
<|endoftext|>