<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 "webkit/support/webkit_support.h"

#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/debug_util.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/i18n/icu_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/sys_string_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/weak_ptr.h"
#include "net/base/net_util.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/WebKit/chromium/public/WebPluginParams.h"
#include "webkit/appcache/web_application_cache_host_impl.h"
#include "webkit/glue/media/buffered_data_source.h"
#include "webkit/glue/media/media_resource_loader_bridge_factory.h"
#include "webkit/glue/media/simple_data_source.h"
#include "webkit/glue/media/video_renderer_impl.h"
#include "webkit/glue/plugins/plugin_list.h"
#include "webkit/glue/plugins/webplugin_impl.h"
#include "webkit/glue/plugins/webplugin_page_delegate.h"
#include "webkit/glue/plugins/webplugininfo.h"
#include "webkit/glue/webkitclient_impl.h"
#include "webkit/glue/webmediaplayer_impl.h"
#include "webkit/support/platform_support.h"
#include "webkit/support/test_webplugin_page_delegate.h"
#include "webkit/support/test_webkit_client.h"
#include "webkit/tools/test_shell/simple_database_system.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"

using WebKit::WebFrame;
using WebKit::WebMediaPlayerClient;
using WebKit::WebPlugin;
using WebKit::WebPluginParams;
using WebKit::WebString;
using WebKit::WebURL;

namespace {

class TestEnvironment {
 public:
  explicit TestEnvironment(bool unit_test_mode) {
    if (!unit_test_mode)
      at_exit_manager_.reset(new base::AtExitManager);
    main_message_loop_.reset(new MessageLoopForUI);
    // TestWebKitClient must be instantiated after the MessageLoopForUI.
    webkit_client_.reset(new TestWebKitClient);
  }

  ~TestEnvironment() {
    SimpleResourceLoaderBridge::Shutdown();
  }

  WebKit::WebKitClient* webkit_client() { return webkit_client_.get(); }

#if defined(OS_WIN)
  void set_theme_engine(WebKit::WebThemeEngine* engine) {
    DCHECK(webkit_client_ != 0);
    webkit_client_->SetThemeEngine(engine);
  }

  WebKit::WebThemeEngine* theme_engine() {
    return webkit_client_->themeEngine();
  }
#endif

 private:
  scoped_ptr<base::AtExitManager> at_exit_manager_;
  scoped_ptr<MessageLoopForUI> main_message_loop_;
  scoped_ptr<TestWebKitClient> webkit_client_;
};

class WebPluginImplWithPageDelegate
    : public webkit_support::TestWebPluginPageDelegate,
      public base::SupportsWeakPtr<WebPluginImplWithPageDelegate>,
      public webkit_glue::WebPluginImpl {
 public:
  WebPluginImplWithPageDelegate(WebFrame* frame,
                                const WebPluginParams& params,
                                const FilePath& path,
                                const std::string& mime_type)
      : webkit_support::TestWebPluginPageDelegate(),
        webkit_glue::WebPluginImpl(
            frame, params, path, mime_type, AsWeakPtr()) {}
  virtual ~WebPluginImplWithPageDelegate() {}
 private:
  DISALLOW_COPY_AND_ASSIGN(WebPluginImplWithPageDelegate);
};

FilePath GetWebKitRootDirFilePath() {
  FilePath basePath;
  PathService::Get(base::DIR_SOURCE_ROOT, &basePath);
  FilePath path = basePath.Append(FILE_PATH_LITERAL("third_party/WebKit"));
  if (!file_util::PathExists(path)) {
    // WebKit/WebKit/chromium/ -> WebKit/
    path = basePath.Append(FILE_PATH_LITERAL("../.."));
  }
  return path;
}

}  // namespace

namespace webkit_support {

static TestEnvironment* test_environment;

void SetUpTestEnvironment() {
  SetUpTestEnvironment(false);
}

void SetUpTestEnvironment(bool unit_test_mode) {
  base::EnableTerminationOnHeapCorruption();

  // Initialize the singleton CommandLine with fixed values.  Some code refer to
  // CommandLine::ForCurrentProcess().  We don't use the actual command-line
  // arguments of DRT to avoid unexpected behavior change.
  //
  // webkit/glue/webmediaplayer_impl.cc checks --enable-openmax.
  // webkit/glue/plugin/plugin_list_posix.cc checks --debug-plugin-loading.
  // webkit/glue/plugin/plugin_list_win.cc checks --old-wmp.
  // If DRT needs these flags, specify them in the following kFixedArguments.
  const char* kFixedArguments[] = {"DumpRenderTree"};
  CommandLine::Init(arraysize(kFixedArguments), kFixedArguments);

  BeforeInitialize();
  test_environment = new TestEnvironment(unit_test_mode);
  AfterInitialize();
  if (!unit_test_mode) {
    // Load ICU data tables.  This has to run after TestEnvironment is created
    // because on Linux, we need base::AtExitManager.
    icu_util::Initialize();
  }
}

void TearDownTestEnvironment() {
  // Flush any remaining messages before we kill ourselves.
  // http://code.google.com/p/chromium/issues/detail?id=9500
  MessageLoop::current()->RunAllPending();

  BeforeShutdown();
  WebKit::shutdown();
  delete test_environment;
  test_environment = NULL;
  AfterShutdown();
}

WebKit::WebKitClient* GetWebKitClient() {
  DCHECK(test_environment);
  return test_environment->webkit_client();
}

WebPlugin* CreateWebPlugin(WebFrame* frame,
                           const WebPluginParams& params) {
  const bool kAllowWildcard = true;
  WebPluginInfo info;
  std::string actual_mime_type;
  if (!NPAPI::PluginList::Singleton()->GetPluginInfo(
          params.url, params.mimeType.utf8(), kAllowWildcard, &info,
          &actual_mime_type)) {
    return NULL;
  }

  if (actual_mime_type.empty())
    actual_mime_type = params.mimeType.utf8();

  return new WebPluginImplWithPageDelegate(
      frame, params, info.path, actual_mime_type);
}

WebKit::WebMediaPlayer* CreateMediaPlayer(WebFrame* frame,
                                          WebMediaPlayerClient* client) {
  scoped_refptr<media::FilterFactoryCollection> factory =
      new media::FilterFactoryCollection();

  appcache::WebApplicationCacheHostImpl* appcache_host =
      appcache::WebApplicationCacheHostImpl::FromFrame(frame);

  // TODO(hclam): this is the same piece of code as in RenderView, maybe they
  // should be grouped together.
  webkit_glue::MediaResourceLoaderBridgeFactory* bridge_factory =
      new webkit_glue::MediaResourceLoaderBridgeFactory(
          GURL(),  // referrer
          "null",  // frame origin
          "null",  // main_frame_origin
          base::GetCurrentProcId(),
          appcache_host ? appcache_host->host_id() : appcache::kNoHostId,
          0);
  // A simple data source that keeps all data in memory.
  media::FilterFactory* simple_data_source_factory =
      webkit_glue::SimpleDataSource::CreateFactory(MessageLoop::current(),
                                                   bridge_factory);
  // A sophisticated data source that does memory caching.
  media::FilterFactory* buffered_data_source_factory =
      webkit_glue::BufferedDataSource::CreateFactory(MessageLoop::current(),
                                                     bridge_factory);
  factory->AddFactory(buffered_data_source_factory);
  factory->AddFactory(simple_data_source_factory);
  return new webkit_glue::WebMediaPlayerImpl(
      client, factory,
      new webkit_glue::VideoRendererImpl::FactoryFactory(false));
}

WebKit::WebApplicationCacheHost* CreateApplicationCacheHost(
    WebFrame*, WebKit::WebApplicationCacheHostClient* client) {
  return SimpleAppCacheSystem::CreateApplicationCacheHost(client);
}

WebKit::WebString GetWebKitRootDir() {
  FilePath path = GetWebKitRootDirFilePath();
  return WebKit::WebString::fromUTF8(WideToUTF8(path.ToWStringHack()).c_str());
}

// Wrapper for debug_util
bool BeingDebugged() {
  return DebugUtil::BeingDebugged();
}

// Wrappers for MessageLoop

void RunMessageLoop() {
  MessageLoop::current()->Run();
}

void QuitMessageLoop() {
  MessageLoop::current()->Quit();
}

void RunAllPendingMessages() {
  MessageLoop::current()->RunAllPending();
}

void DispatchMessageLoop() {
  MessageLoop* current = MessageLoop::current();
  bool old_state = current->NestableTasksAllowed();
  current->SetNestableTasksAllowed(true);
  current->RunAllPending();
  current->SetNestableTasksAllowed(old_state);
}

void PostTaskFromHere(Task* task) {
  MessageLoop::current()->PostTask(FROM_HERE, task);
}

void PostDelayedTaskFromHere(Task* task, int64 delay_ms) {
  MessageLoop::current()->PostDelayedTask(FROM_HERE, task, delay_ms);
}

// Wrappers for FilePath and file_util

WebString GetAbsoluteWebStringFromUTF8Path(const std::string& utf8_path) {
#if defined(OS_WIN)
  FilePath path(UTF8ToWide(utf8_path));
  file_util::AbsolutePath(&path);
  return WebString(path.value());
#else
  FilePath path(base::SysWideToNativeMB(base::SysUTF8ToWide(utf8_path)));
  file_util::AbsolutePath(&path);
  return WideToUTF16(base::SysNativeMBToWide(path.value()));
#endif
}

WebURL CreateURLForPathOrURL(const std::string& path_or_url_in_nativemb) {
  // NativeMB to UTF-8
  std::wstring wide_path_or_url
      = base::SysNativeMBToWide(path_or_url_in_nativemb);
  std::string path_or_url_in_utf8 = WideToUTF8(wide_path_or_url);

  GURL url(path_or_url_in_utf8);
  if (url.is_valid() && url.has_scheme())
    return WebURL(url);
#if defined(OS_WIN)
  return net::FilePathToFileURL(FilePath(wide_path_or_url));
#else
  return net::FilePathToFileURL(FilePath(path_or_url_in_nativemb));
#endif
}

WebURL RewriteLayoutTestsURL(const std::string& utf8_url) {
  const char kPrefix[] = "file:///tmp/LayoutTests/";
  const int kPrefixLen = arraysize(kPrefix) - 1;

  if (utf8_url.compare(0, kPrefixLen, kPrefix, kPrefixLen))
    return WebURL(GURL(utf8_url));

  FilePath replacePath =
      GetWebKitRootDirFilePath().Append(FILE_PATH_LITERAL("LayoutTests/"));
  CHECK(file_util::PathExists(replacePath));
#if defined(OS_WIN)
  std::string utf8_path = WideToUTF8(replacePath.value());
#else
  std::string utf8_path
      = WideToUTF8(base::SysNativeMBToWide(replacePath.value()));
#endif
  std::string newUrl = std::string("file://") + utf8_path
      + utf8_url.substr(kPrefixLen);
  return WebURL(GURL(newUrl));
}

bool SetCurrentDirectoryForFileURL(const WebKit::WebURL& fileUrl) {
  FilePath localPath;
  return net::FileURLToFilePath(fileUrl, &localPath)
      && file_util::SetCurrentDirectory(localPath.DirName());
}

// Bridge for SimpleDatabaseSystem

void SetDatabaseQuota(int quota) {
  SimpleDatabaseSystem::GetInstance()->SetDatabaseQuota(quota);
}

void ClearAllDatabases() {
  SimpleDatabaseSystem::GetInstance()->ClearAllDatabases();
}

// Bridge for SimpleResourceLoaderBridge

void SetAcceptAllCookies(bool accept) {
  SimpleResourceLoaderBridge::SetAcceptAllCookies(accept);
}

// Theme engine
#if defined(OS_WIN)

void SetThemeEngine(WebKit::WebThemeEngine* engine) {
  DCHECK(test_environment);
  test_environment->set_theme_engine(engine);
}

WebKit::WebThemeEngine* GetThemeEngine() {
  DCHECK(test_environment);
  return test_environment->theme_engine();
}

#endif

}  // namespace webkit_support
<commit_msg>Fix detection of WebKit-only checkout or Chromium checkout<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 "webkit/support/webkit_support.h"

#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/debug_util.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/i18n/icu_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/sys_string_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/weak_ptr.h"
#include "net/base/net_util.h"
#include "third_party/WebKit/WebKit/chromium/public/WebKit.h"
#include "third_party/WebKit/WebKit/chromium/public/WebPluginParams.h"
#include "webkit/appcache/web_application_cache_host_impl.h"
#include "webkit/glue/media/buffered_data_source.h"
#include "webkit/glue/media/media_resource_loader_bridge_factory.h"
#include "webkit/glue/media/simple_data_source.h"
#include "webkit/glue/media/video_renderer_impl.h"
#include "webkit/glue/plugins/plugin_list.h"
#include "webkit/glue/plugins/webplugin_impl.h"
#include "webkit/glue/plugins/webplugin_page_delegate.h"
#include "webkit/glue/plugins/webplugininfo.h"
#include "webkit/glue/webkitclient_impl.h"
#include "webkit/glue/webmediaplayer_impl.h"
#include "webkit/support/platform_support.h"
#include "webkit/support/test_webplugin_page_delegate.h"
#include "webkit/support/test_webkit_client.h"
#include "webkit/tools/test_shell/simple_database_system.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"

using WebKit::WebFrame;
using WebKit::WebMediaPlayerClient;
using WebKit::WebPlugin;
using WebKit::WebPluginParams;
using WebKit::WebString;
using WebKit::WebURL;

namespace {

class TestEnvironment {
 public:
  explicit TestEnvironment(bool unit_test_mode) {
    if (!unit_test_mode)
      at_exit_manager_.reset(new base::AtExitManager);
    main_message_loop_.reset(new MessageLoopForUI);
    // TestWebKitClient must be instantiated after the MessageLoopForUI.
    webkit_client_.reset(new TestWebKitClient);
  }

  ~TestEnvironment() {
    SimpleResourceLoaderBridge::Shutdown();
  }

  WebKit::WebKitClient* webkit_client() { return webkit_client_.get(); }

#if defined(OS_WIN)
  void set_theme_engine(WebKit::WebThemeEngine* engine) {
    DCHECK(webkit_client_ != 0);
    webkit_client_->SetThemeEngine(engine);
  }

  WebKit::WebThemeEngine* theme_engine() {
    return webkit_client_->themeEngine();
  }
#endif

 private:
  scoped_ptr<base::AtExitManager> at_exit_manager_;
  scoped_ptr<MessageLoopForUI> main_message_loop_;
  scoped_ptr<TestWebKitClient> webkit_client_;
};

class WebPluginImplWithPageDelegate
    : public webkit_support::TestWebPluginPageDelegate,
      public base::SupportsWeakPtr<WebPluginImplWithPageDelegate>,
      public webkit_glue::WebPluginImpl {
 public:
  WebPluginImplWithPageDelegate(WebFrame* frame,
                                const WebPluginParams& params,
                                const FilePath& path,
                                const std::string& mime_type)
      : webkit_support::TestWebPluginPageDelegate(),
        webkit_glue::WebPluginImpl(
            frame, params, path, mime_type, AsWeakPtr()) {}
  virtual ~WebPluginImplWithPageDelegate() {}
 private:
  DISALLOW_COPY_AND_ASSIGN(WebPluginImplWithPageDelegate);
};

FilePath GetWebKitRootDirFilePath() {
  FilePath basePath;
  PathService::Get(base::DIR_SOURCE_ROOT, &basePath);
  if (file_util::PathExists(basePath.Append(FILE_PATH_LITERAL("chrome")))) {
    return basePath.Append(FILE_PATH_LITERAL("third_party/WebKit"));
  } else {
    // WebKit/WebKit/chromium/ -> WebKit/
    return basePath.Append(FILE_PATH_LITERAL("../.."));
  }
}

}  // namespace

namespace webkit_support {

static TestEnvironment* test_environment;

void SetUpTestEnvironment() {
  SetUpTestEnvironment(false);
}

void SetUpTestEnvironment(bool unit_test_mode) {
  base::EnableTerminationOnHeapCorruption();

  // Initialize the singleton CommandLine with fixed values.  Some code refer to
  // CommandLine::ForCurrentProcess().  We don't use the actual command-line
  // arguments of DRT to avoid unexpected behavior change.
  //
  // webkit/glue/webmediaplayer_impl.cc checks --enable-openmax.
  // webkit/glue/plugin/plugin_list_posix.cc checks --debug-plugin-loading.
  // webkit/glue/plugin/plugin_list_win.cc checks --old-wmp.
  // If DRT needs these flags, specify them in the following kFixedArguments.
  const char* kFixedArguments[] = {"DumpRenderTree"};
  CommandLine::Init(arraysize(kFixedArguments), kFixedArguments);

  BeforeInitialize();
  test_environment = new TestEnvironment(unit_test_mode);
  AfterInitialize();
  if (!unit_test_mode) {
    // Load ICU data tables.  This has to run after TestEnvironment is created
    // because on Linux, we need base::AtExitManager.
    icu_util::Initialize();
  }
}

void TearDownTestEnvironment() {
  // Flush any remaining messages before we kill ourselves.
  // http://code.google.com/p/chromium/issues/detail?id=9500
  MessageLoop::current()->RunAllPending();

  BeforeShutdown();
  WebKit::shutdown();
  delete test_environment;
  test_environment = NULL;
  AfterShutdown();
}

WebKit::WebKitClient* GetWebKitClient() {
  DCHECK(test_environment);
  return test_environment->webkit_client();
}

WebPlugin* CreateWebPlugin(WebFrame* frame,
                           const WebPluginParams& params) {
  const bool kAllowWildcard = true;
  WebPluginInfo info;
  std::string actual_mime_type;
  if (!NPAPI::PluginList::Singleton()->GetPluginInfo(
          params.url, params.mimeType.utf8(), kAllowWildcard, &info,
          &actual_mime_type)) {
    return NULL;
  }

  if (actual_mime_type.empty())
    actual_mime_type = params.mimeType.utf8();

  return new WebPluginImplWithPageDelegate(
      frame, params, info.path, actual_mime_type);
}

WebKit::WebMediaPlayer* CreateMediaPlayer(WebFrame* frame,
                                          WebMediaPlayerClient* client) {
  scoped_refptr<media::FilterFactoryCollection> factory =
      new media::FilterFactoryCollection();

  appcache::WebApplicationCacheHostImpl* appcache_host =
      appcache::WebApplicationCacheHostImpl::FromFrame(frame);

  // TODO(hclam): this is the same piece of code as in RenderView, maybe they
  // should be grouped together.
  webkit_glue::MediaResourceLoaderBridgeFactory* bridge_factory =
      new webkit_glue::MediaResourceLoaderBridgeFactory(
          GURL(),  // referrer
          "null",  // frame origin
          "null",  // main_frame_origin
          base::GetCurrentProcId(),
          appcache_host ? appcache_host->host_id() : appcache::kNoHostId,
          0);
  // A simple data source that keeps all data in memory.
  media::FilterFactory* simple_data_source_factory =
      webkit_glue::SimpleDataSource::CreateFactory(MessageLoop::current(),
                                                   bridge_factory);
  // A sophisticated data source that does memory caching.
  media::FilterFactory* buffered_data_source_factory =
      webkit_glue::BufferedDataSource::CreateFactory(MessageLoop::current(),
                                                     bridge_factory);
  factory->AddFactory(buffered_data_source_factory);
  factory->AddFactory(simple_data_source_factory);
  return new webkit_glue::WebMediaPlayerImpl(
      client, factory,
      new webkit_glue::VideoRendererImpl::FactoryFactory(false));
}

WebKit::WebApplicationCacheHost* CreateApplicationCacheHost(
    WebFrame*, WebKit::WebApplicationCacheHostClient* client) {
  return SimpleAppCacheSystem::CreateApplicationCacheHost(client);
}

WebKit::WebString GetWebKitRootDir() {
  FilePath path = GetWebKitRootDirFilePath();
  return WebKit::WebString::fromUTF8(WideToUTF8(path.ToWStringHack()).c_str());
}

// Wrapper for debug_util
bool BeingDebugged() {
  return DebugUtil::BeingDebugged();
}

// Wrappers for MessageLoop

void RunMessageLoop() {
  MessageLoop::current()->Run();
}

void QuitMessageLoop() {
  MessageLoop::current()->Quit();
}

void RunAllPendingMessages() {
  MessageLoop::current()->RunAllPending();
}

void DispatchMessageLoop() {
  MessageLoop* current = MessageLoop::current();
  bool old_state = current->NestableTasksAllowed();
  current->SetNestableTasksAllowed(true);
  current->RunAllPending();
  current->SetNestableTasksAllowed(old_state);
}

void PostTaskFromHere(Task* task) {
  MessageLoop::current()->PostTask(FROM_HERE, task);
}

void PostDelayedTaskFromHere(Task* task, int64 delay_ms) {
  MessageLoop::current()->PostDelayedTask(FROM_HERE, task, delay_ms);
}

// Wrappers for FilePath and file_util

WebString GetAbsoluteWebStringFromUTF8Path(const std::string& utf8_path) {
#if defined(OS_WIN)
  FilePath path(UTF8ToWide(utf8_path));
  file_util::AbsolutePath(&path);
  return WebString(path.value());
#else
  FilePath path(base::SysWideToNativeMB(base::SysUTF8ToWide(utf8_path)));
  file_util::AbsolutePath(&path);
  return WideToUTF16(base::SysNativeMBToWide(path.value()));
#endif
}

WebURL CreateURLForPathOrURL(const std::string& path_or_url_in_nativemb) {
  // NativeMB to UTF-8
  std::wstring wide_path_or_url
      = base::SysNativeMBToWide(path_or_url_in_nativemb);
  std::string path_or_url_in_utf8 = WideToUTF8(wide_path_or_url);

  GURL url(path_or_url_in_utf8);
  if (url.is_valid() && url.has_scheme())
    return WebURL(url);
#if defined(OS_WIN)
  return net::FilePathToFileURL(FilePath(wide_path_or_url));
#else
  return net::FilePathToFileURL(FilePath(path_or_url_in_nativemb));
#endif
}

WebURL RewriteLayoutTestsURL(const std::string& utf8_url) {
  const char kPrefix[] = "file:///tmp/LayoutTests/";
  const int kPrefixLen = arraysize(kPrefix) - 1;

  if (utf8_url.compare(0, kPrefixLen, kPrefix, kPrefixLen))
    return WebURL(GURL(utf8_url));

  FilePath replacePath =
      GetWebKitRootDirFilePath().Append(FILE_PATH_LITERAL("LayoutTests/"));
  CHECK(file_util::PathExists(replacePath));
#if defined(OS_WIN)
  std::string utf8_path = WideToUTF8(replacePath.value());
#else
  std::string utf8_path
      = WideToUTF8(base::SysNativeMBToWide(replacePath.value()));
#endif
  std::string newUrl = std::string("file://") + utf8_path
      + utf8_url.substr(kPrefixLen);
  return WebURL(GURL(newUrl));
}

bool SetCurrentDirectoryForFileURL(const WebKit::WebURL& fileUrl) {
  FilePath localPath;
  return net::FileURLToFilePath(fileUrl, &localPath)
      && file_util::SetCurrentDirectory(localPath.DirName());
}

// Bridge for SimpleDatabaseSystem

void SetDatabaseQuota(int quota) {
  SimpleDatabaseSystem::GetInstance()->SetDatabaseQuota(quota);
}

void ClearAllDatabases() {
  SimpleDatabaseSystem::GetInstance()->ClearAllDatabases();
}

// Bridge for SimpleResourceLoaderBridge

void SetAcceptAllCookies(bool accept) {
  SimpleResourceLoaderBridge::SetAcceptAllCookies(accept);
}

// Theme engine
#if defined(OS_WIN)

void SetThemeEngine(WebKit::WebThemeEngine* engine) {
  DCHECK(test_environment);
  test_environment->set_theme_engine(engine);
}

WebKit::WebThemeEngine* GetThemeEngine() {
  DCHECK(test_environment);
  return test_environment->theme_engine();
}

#endif

}  // namespace webkit_support
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
//  animMgrTest.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "UnitTest++/src/UnitTest++.h"
#include "Anim/AnimTypes.h"
#include "Anim/private/animMgr.h"

using namespace Oryol;
using namespace Oryol::_priv;

TEST(animMgr) {

    // setup
    AnimSetup setup;
    setup.MaxNumLibs = 4;
    setup.MaxNumClips = 16;
    setup.MaxNumCurves = 128;
    setup.MaxNumKeys = 1024;
    setup.ResourceLabelStackCapacity = 16;
    setup.ResourceRegistryCapacity = 24;
    animMgr mgr;
    mgr.setup(setup);
    CHECK(mgr.isValid);
    CHECK(mgr.resContainer.IsValid());
    CHECK(mgr.resContainer.registry.IsValid());
    CHECK(mgr.libPool.IsValid());
    CHECK(mgr.clipPool.Capacity() == 16);
    CHECK(mgr.curvePool.Capacity() == 128);
    CHECK(mgr.keys.Size() == 1024);
    CHECK(mgr.keys.Offset() == 0);
    CHECK(mgr.numKeys == 0);
    CHECK(mgr.valuePool != nullptr);

    // create a library with two clips
    Array<AnimCurveFormat::Enum> curveLayout({
        AnimCurveFormat::Float2,
        AnimCurveFormat::Float3,
        AnimCurveFormat::Float4,
    });
    Array<AnimCurveSetup> clip1Curves({
        { false, 1.0f, 2.0f, 3.0f, 4.0f },
        { false, 5.0f, 6.0f, 7.0f, 8.0f },
        { true,  9.0f, 10.0f, 11.0f, 12.0f }
    });
    Array<AnimCurveSetup> clip2Curves({
        { true, 4.0f, 3.0f, 2.0f, 1.0f },
        { false, 8.0f, 7.0f, 6.0f, 5.0f },
        { true,  12.0f, 11.0f, 10.0f, 9.0f }
    });
    Array<AnimClipSetup> clips({
        { "clip1", 10, 0.04f, clip1Curves.MakeSlice() },
        { "clip2", 20, 0.04f, clip2Curves.MakeSlice() },
    });
    AnimLibrarySetup libSetup;
    libSetup.Name = "human";
    libSetup.CurveLayout = curveLayout.MakeSlice();
    libSetup.Clips = clips.MakeSlice();

    ResourceLabel l1 = mgr.resContainer.PushLabel();
    Id lib1 = mgr.createLibrary(libSetup);
    mgr.resContainer.PopLabel();
    CHECK(lib1.IsValid());
    CHECK(mgr.lookupLibrary(lib1) != nullptr);
    CHECK(mgr.libPool.QueryPoolInfo().NumUsedSlots == 1);
    CHECK(mgr.clipPool.Size() == 2);
    CHECK(mgr.curvePool.Size() == 6);
    CHECK(mgr.numKeys == 110);
    const AnimLibrary* lib1Ptr = mgr.lookupLibrary(lib1);
    CHECK(lib1Ptr->Name == "human");
    CHECK(lib1Ptr->SampleStride == 9);
    CHECK(lib1Ptr->Clips.Size() == 2);
    CHECK(lib1Ptr->Clips[0].Name == "clip1");
    CHECK(lib1Ptr->Clips[0].Length == 10);
    CHECK(lib1Ptr->Clips[0].KeyStride == 5);
    CHECK(lib1Ptr->Clips[0].Keys.Size() == 50);
    CHECK(lib1Ptr->Clips[0].Keys.Offset() == 0);
    CHECK(lib1Ptr->Clips[0].Curves.Size() == 3);
    CHECK(lib1Ptr->Clips[0].Curves.Offset() == 0);
    CHECK(lib1Ptr->Clips[0].Curves[0].Format == AnimCurveFormat::Float2);
    CHECK(lib1Ptr->Clips[0].Curves[0].Stride == 2);
    CHECK(!lib1Ptr->Clips[0].Curves[0].Static);
    CHECK(lib1Ptr->Clips[0].Curves[0].KeyIndex == 0);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[0].StaticValue[0], 1.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[0].StaticValue[1], 2.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[0].StaticValue[2], 3.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[0].StaticValue[3], 4.0f, 0.001f);
    CHECK(lib1Ptr->Clips[0].Curves[1].Format == AnimCurveFormat::Float3);
    CHECK(lib1Ptr->Clips[0].Curves[1].Stride == 3);
    CHECK(!lib1Ptr->Clips[0].Curves[1].Static);
    CHECK(lib1Ptr->Clips[0].Curves[1].KeyIndex == 2);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[1].StaticValue[0], 5.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[1].StaticValue[1], 6.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[1].StaticValue[2], 7.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[1].StaticValue[3], 8.0f, 0.001f);
    CHECK(lib1Ptr->Clips[0].Curves[2].Format == AnimCurveFormat::Float4);
    CHECK(lib1Ptr->Clips[0].Curves[2].Stride == 0);
    CHECK(lib1Ptr->Clips[0].Curves[2].Static);
    CHECK(lib1Ptr->Clips[0].Curves[2].KeyIndex == InvalidIndex);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[2].StaticValue[0], 9.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[2].StaticValue[1], 10.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[2].StaticValue[2], 11.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[2].StaticValue[3], 12.0f, 0.001f);
    CHECK(lib1Ptr->Clips[1].Name == "clip2");
    CHECK(lib1Ptr->Clips[1].Length == 20);
    CHECK(lib1Ptr->Clips[1].KeyStride == 3);
    CHECK(lib1Ptr->Clips[1].Keys.Size() == 60);
    CHECK(lib1Ptr->Clips[1].Keys.Offset() == 50);
    CHECK(lib1Ptr->Clips[1].Curves.Size() == 3);
    CHECK(lib1Ptr->Clips[1].Curves.Offset() == 3);
    CHECK(lib1Ptr->Clips[1].Curves[0].Format == AnimCurveFormat::Float2);
    CHECK(lib1Ptr->Clips[1].Curves[0].Stride == 0);
    CHECK(lib1Ptr->Clips[1].Curves[0].Static);
    CHECK(lib1Ptr->Clips[1].Curves[0].KeyIndex == InvalidIndex);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[0].StaticValue[0], 4.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[0].StaticValue[1], 3.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[0].StaticValue[2], 2.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[0].StaticValue[3], 1.0f, 0.001f);
    CHECK(lib1Ptr->Clips[1].Curves[1].Format == AnimCurveFormat::Float3);
    CHECK(lib1Ptr->Clips[1].Curves[1].Stride == 3);
    CHECK(!lib1Ptr->Clips[1].Curves[1].Static);
    CHECK(lib1Ptr->Clips[1].Curves[1].KeyIndex == 0);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[1].StaticValue[0], 8.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[1].StaticValue[1], 7.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[1].StaticValue[2], 6.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[1].StaticValue[3], 5.0f, 0.001f);
    CHECK(lib1Ptr->Clips[1].Curves[2].Format == AnimCurveFormat::Float4);
    CHECK(lib1Ptr->Clips[1].Curves[2].Stride == 0);
    CHECK(lib1Ptr->Clips[1].Curves[2].Static);
    CHECK(lib1Ptr->Clips[1].Curves[2].KeyIndex == InvalidIndex);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[2].StaticValue[0], 12.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[2].StaticValue[1], 11.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[2].StaticValue[2], 10.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[2].StaticValue[3], 9.0f, 0.001f);

    libSetup.Name = "Bla";
    Id lib2 = mgr.createLibrary(libSetup);
    CHECK(lib2.IsValid());
    CHECK(mgr.lookupLibrary(lib2) != nullptr);
    CHECK(mgr.libPool.QueryPoolInfo().NumUsedSlots == 2);
    CHECK(mgr.clipPool.Size() == 4);
    CHECK(mgr.curvePool.Size() == 12);
    CHECK(mgr.numKeys == 220);
    mgr.destroy(l1);
    CHECK(mgr.libPool.QueryPoolInfo().NumUsedSlots == 1);
    CHECK(mgr.clipPool.Size() == 2);
    CHECK(mgr.curvePool.Size() == 6);
    CHECK(mgr.numKeys == 110);

    mgr.discard();
    CHECK(!mgr.isValid);
    CHECK(mgr.clipPool.Size() == 0);
    CHECK(mgr.curvePool.Size() == 0);
    CHECK(mgr.numKeys == 0);
}<commit_msg>More testing code<commit_after>//------------------------------------------------------------------------------
//  animMgrTest.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "UnitTest++/src/UnitTest++.h"
#include "Anim/AnimTypes.h"
#include "Anim/private/animMgr.h"

using namespace Oryol;
using namespace Oryol::_priv;

TEST(animMgr) {

    // setup
    AnimSetup setup;
    setup.MaxNumLibs = 4;
    setup.MaxNumClips = 16;
    setup.MaxNumCurves = 128;
    setup.MaxNumKeys = 1024;
    setup.ResourceLabelStackCapacity = 16;
    setup.ResourceRegistryCapacity = 24;
    animMgr mgr;
    mgr.setup(setup);
    CHECK(mgr.isValid);
    CHECK(mgr.resContainer.IsValid());
    CHECK(mgr.resContainer.registry.IsValid());
    CHECK(mgr.libPool.IsValid());
    CHECK(mgr.clipPool.Capacity() == 16);
    CHECK(mgr.curvePool.Capacity() == 128);
    CHECK(mgr.keys.Size() == 1024);
    CHECK(mgr.keys.Offset() == 0);
    CHECK(mgr.numKeys == 0);
    CHECK(mgr.valuePool != nullptr);

    // create a library with two clips
    Array<AnimCurveFormat::Enum> curveLayout({
        AnimCurveFormat::Float2,
        AnimCurveFormat::Float3,
        AnimCurveFormat::Float4,
    });
    Array<AnimCurveSetup> clip1Curves({
        { false, 1.0f, 2.0f, 3.0f, 4.0f },
        { false, 5.0f, 6.0f, 7.0f, 8.0f },
        { true,  9.0f, 10.0f, 11.0f, 12.0f }
    });
    Array<AnimCurveSetup> clip2Curves({
        { true, 4.0f, 3.0f, 2.0f, 1.0f },
        { false, 8.0f, 7.0f, 6.0f, 5.0f },
        { true,  12.0f, 11.0f, 10.0f, 9.0f }
    });
    Array<AnimClipSetup> clips({
        { "clip1", 10, 0.04f, clip1Curves.MakeSlice() },
        { "clip2", 20, 0.04f, clip2Curves.MakeSlice() },
    });
    AnimLibrarySetup libSetup;
    libSetup.Name = "human";
    libSetup.CurveLayout = curveLayout.MakeSlice();
    libSetup.Clips = clips.MakeSlice();

    ResourceLabel l1 = mgr.resContainer.PushLabel();
    Id lib1 = mgr.createLibrary(libSetup);
    mgr.resContainer.PopLabel();
    CHECK(lib1.IsValid());
    CHECK(mgr.lookupLibrary(lib1) != nullptr);
    CHECK(mgr.libPool.QueryPoolInfo().NumUsedSlots == 1);
    CHECK(mgr.clipPool.Size() == 2);
    CHECK(mgr.curvePool.Size() == 6);
    CHECK(mgr.numKeys == 110);
    const AnimLibrary* lib1Ptr = mgr.lookupLibrary(lib1);
    CHECK(lib1Ptr->Name == "human");
    CHECK(lib1Ptr->SampleStride == 9);
    CHECK(lib1Ptr->Clips.Size() == 2);
    CHECK(lib1Ptr->Clips[0].Name == "clip1");
    CHECK(lib1Ptr->Clips[0].Length == 10);
    CHECK(lib1Ptr->Clips[0].KeyStride == 5);
    CHECK(lib1Ptr->Clips[0].Keys.Size() == 50);
    CHECK(lib1Ptr->Clips[0].Keys.Offset() == 0);
    CHECK(lib1Ptr->Clips[0].Curves.Size() == 3);
    CHECK(lib1Ptr->Clips[0].Curves.Offset() == 0);
    CHECK(lib1Ptr->Clips[0].Curves[0].Format == AnimCurveFormat::Float2);
    CHECK(lib1Ptr->Clips[0].Curves[0].Stride == 2);
    CHECK(!lib1Ptr->Clips[0].Curves[0].Static);
    CHECK(lib1Ptr->Clips[0].Curves[0].KeyIndex == 0);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[0].StaticValue[0], 1.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[0].StaticValue[1], 2.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[0].StaticValue[2], 3.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[0].StaticValue[3], 4.0f, 0.001f);
    CHECK(lib1Ptr->Clips[0].Curves[1].Format == AnimCurveFormat::Float3);
    CHECK(lib1Ptr->Clips[0].Curves[1].Stride == 3);
    CHECK(!lib1Ptr->Clips[0].Curves[1].Static);
    CHECK(lib1Ptr->Clips[0].Curves[1].KeyIndex == 2);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[1].StaticValue[0], 5.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[1].StaticValue[1], 6.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[1].StaticValue[2], 7.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[1].StaticValue[3], 8.0f, 0.001f);
    CHECK(lib1Ptr->Clips[0].Curves[2].Format == AnimCurveFormat::Float4);
    CHECK(lib1Ptr->Clips[0].Curves[2].Stride == 0);
    CHECK(lib1Ptr->Clips[0].Curves[2].Static);
    CHECK(lib1Ptr->Clips[0].Curves[2].KeyIndex == InvalidIndex);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[2].StaticValue[0], 9.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[2].StaticValue[1], 10.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[2].StaticValue[2], 11.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[0].Curves[2].StaticValue[3], 12.0f, 0.001f);
    CHECK(lib1Ptr->Clips[1].Name == "clip2");
    CHECK(lib1Ptr->Clips[1].Length == 20);
    CHECK(lib1Ptr->Clips[1].KeyStride == 3);
    CHECK(lib1Ptr->Clips[1].Keys.Size() == 60);
    CHECK(lib1Ptr->Clips[1].Keys.Offset() == 50);
    CHECK(lib1Ptr->Clips[1].Curves.Size() == 3);
    CHECK(lib1Ptr->Clips[1].Curves.Offset() == 3);
    CHECK(lib1Ptr->Clips[1].Curves[0].Format == AnimCurveFormat::Float2);
    CHECK(lib1Ptr->Clips[1].Curves[0].Stride == 0);
    CHECK(lib1Ptr->Clips[1].Curves[0].Static);
    CHECK(lib1Ptr->Clips[1].Curves[0].KeyIndex == InvalidIndex);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[0].StaticValue[0], 4.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[0].StaticValue[1], 3.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[0].StaticValue[2], 2.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[0].StaticValue[3], 1.0f, 0.001f);
    CHECK(lib1Ptr->Clips[1].Curves[1].Format == AnimCurveFormat::Float3);
    CHECK(lib1Ptr->Clips[1].Curves[1].Stride == 3);
    CHECK(!lib1Ptr->Clips[1].Curves[1].Static);
    CHECK(lib1Ptr->Clips[1].Curves[1].KeyIndex == 0);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[1].StaticValue[0], 8.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[1].StaticValue[1], 7.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[1].StaticValue[2], 6.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[1].StaticValue[3], 5.0f, 0.001f);
    CHECK(lib1Ptr->Clips[1].Curves[2].Format == AnimCurveFormat::Float4);
    CHECK(lib1Ptr->Clips[1].Curves[2].Stride == 0);
    CHECK(lib1Ptr->Clips[1].Curves[2].Static);
    CHECK(lib1Ptr->Clips[1].Curves[2].KeyIndex == InvalidIndex);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[2].StaticValue[0], 12.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[2].StaticValue[1], 11.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[2].StaticValue[2], 10.0f, 0.001f);
    CHECK_CLOSE(lib1Ptr->Clips[1].Curves[2].StaticValue[3], 9.0f, 0.001f);

    libSetup.Name = "Bla";
    Id lib2 = mgr.createLibrary(libSetup);
    CHECK(lib2.IsValid());
    CHECK(mgr.lookupLibrary(lib2) != nullptr);
    CHECK(mgr.libPool.QueryPoolInfo().NumUsedSlots == 2);
    CHECK(mgr.clipPool.Size() == 4);
    CHECK(mgr.curvePool.Size() == 12);
    CHECK(mgr.numKeys == 220);
    const AnimLibrary* lib2Ptr = mgr.lookupLibrary(lib2);
    CHECK(lib2Ptr->Name == "Bla");
    CHECK(lib2Ptr->SampleStride == 9);
    CHECK(lib2Ptr->Clips.Size() == 2);
    CHECK(lib2Ptr->Clips[0].Name == "clip1");
    CHECK(lib2Ptr->Clips[0].Length == 10);
    CHECK(lib2Ptr->Clips[0].KeyStride == 5);
    CHECK(lib2Ptr->Clips[0].Keys.Size() == 50);
    CHECK(lib2Ptr->Clips[0].Keys.Offset() == 110);
    CHECK(lib2Ptr->Clips[0].Curves.Size() == 3);
    CHECK(lib2Ptr->Clips[0].Curves.Offset() == 6);
    CHECK(lib2Ptr->Clips[0].Curves[0].Format == AnimCurveFormat::Float2);
    CHECK(lib2Ptr->Clips[0].Curves[0].Stride == 2);
    CHECK(!lib2Ptr->Clips[0].Curves[0].Static);
    CHECK(lib2Ptr->Clips[0].Curves[0].KeyIndex == 0);
    CHECK_CLOSE(lib2Ptr->Clips[0].Curves[0].StaticValue[0], 1.0f, 0.001f);
    CHECK_CLOSE(lib2Ptr->Clips[0].Curves[0].StaticValue[1], 2.0f, 0.001f);
    CHECK_CLOSE(lib2Ptr->Clips[0].Curves[0].StaticValue[2], 3.0f, 0.001f);
    CHECK_CLOSE(lib2Ptr->Clips[0].Curves[0].StaticValue[3], 4.0f, 0.001f);
    CHECK(lib2Ptr->Clips[0].Curves[1].Format == AnimCurveFormat::Float3);
    CHECK(lib2Ptr->Clips[0].Curves[1].Stride == 3);
    CHECK(!lib2Ptr->Clips[0].Curves[1].Static);
    CHECK(lib2Ptr->Clips[0].Curves[1].KeyIndex == 2);
    CHECK_CLOSE(lib2Ptr->Clips[0].Curves[1].StaticValue[0], 5.0f, 0.001f);
    CHECK_CLOSE(lib2Ptr->Clips[0].Curves[1].StaticValue[1], 6.0f, 0.001f);
    CHECK_CLOSE(lib2Ptr->Clips[0].Curves[1].StaticValue[2], 7.0f, 0.001f);
    CHECK_CLOSE(lib2Ptr->Clips[0].Curves[1].StaticValue[3], 8.0f, 0.001f);
    CHECK(lib2Ptr->Clips[0].Curves[2].Format == AnimCurveFormat::Float4);
    CHECK(lib2Ptr->Clips[0].Curves[2].Stride == 0);
    CHECK(lib2Ptr->Clips[0].Curves[2].Static);
    CHECK(lib2Ptr->Clips[0].Curves[2].KeyIndex == InvalidIndex);
    CHECK_CLOSE(lib2Ptr->Clips[0].Curves[2].StaticValue[0], 9.0f, 0.001f);
    CHECK_CLOSE(lib2Ptr->Clips[0].Curves[2].StaticValue[1], 10.0f, 0.001f);
    CHECK_CLOSE(lib2Ptr->Clips[0].Curves[2].StaticValue[2], 11.0f, 0.001f);
    CHECK_CLOSE(lib2Ptr->Clips[0].Curves[2].StaticValue[3], 12.0f, 0.001f);
    CHECK(lib2Ptr->Clips[1].Name == "clip2");
    CHECK(lib2Ptr->Clips[1].Length == 20);
    CHECK(lib2Ptr->Clips[1].KeyStride == 3);
    CHECK(lib2Ptr->Clips[1].Keys.Size() == 60);
    CHECK(lib2Ptr->Clips[1].Keys.Offset() == 160);
    CHECK(lib2Ptr->Clips[1].Curves.Size() == 3);
    CHECK(lib2Ptr->Clips[1].Curves.Offset() == 9);
    CHECK(lib2Ptr->Clips[1].Curves[0].Format == AnimCurveFormat::Float2);
    CHECK(lib2Ptr->Clips[1].Curves[0].Stride == 0);
    CHECK(lib2Ptr->Clips[1].Curves[0].Static);
    CHECK(lib2Ptr->Clips[1].Curves[0].KeyIndex == InvalidIndex);
    CHECK_CLOSE(lib2Ptr->Clips[1].Curves[0].StaticValue[0], 4.0f, 0.001f);
    CHECK_CLOSE(lib2Ptr->Clips[1].Curves[0].StaticValue[1], 3.0f, 0.001f);
    CHECK_CLOSE(lib2Ptr->Clips[1].Curves[0].StaticValue[2], 2.0f, 0.001f);
    CHECK_CLOSE(lib2Ptr->Clips[1].Curves[0].StaticValue[3], 1.0f, 0.001f);
    CHECK(lib2Ptr->Clips[1].Curves[1].Format == AnimCurveFormat::Float3);
    CHECK(lib2Ptr->Clips[1].Curves[1].Stride == 3);
    CHECK(!lib2Ptr->Clips[1].Curves[1].Static);
    CHECK(lib2Ptr->Clips[1].Curves[1].KeyIndex == 0);
    CHECK_CLOSE(lib2Ptr->Clips[1].Curves[1].StaticValue[0], 8.0f, 0.001f);
    CHECK_CLOSE(lib2Ptr->Clips[1].Curves[1].StaticValue[1], 7.0f, 0.001f);
    CHECK_CLOSE(lib2Ptr->Clips[1].Curves[1].StaticValue[2], 6.0f, 0.001f);
    CHECK_CLOSE(lib2Ptr->Clips[1].Curves[1].StaticValue[3], 5.0f, 0.001f);
    CHECK(lib2Ptr->Clips[1].Curves[2].Format == AnimCurveFormat::Float4);
    CHECK(lib2Ptr->Clips[1].Curves[2].Stride == 0);
    CHECK(lib2Ptr->Clips[1].Curves[2].Static);
    CHECK(lib2Ptr->Clips[1].Curves[2].KeyIndex == InvalidIndex);
    CHECK_CLOSE(lib2Ptr->Clips[1].Curves[2].StaticValue[0], 12.0f, 0.001f);
    CHECK_CLOSE(lib2Ptr->Clips[1].Curves[2].StaticValue[1], 11.0f, 0.001f);
    CHECK_CLOSE(lib2Ptr->Clips[1].Curves[2].StaticValue[2], 10.0f, 0.001f);
    CHECK_CLOSE(lib2Ptr->Clips[1].Curves[2].StaticValue[3], 9.0f, 0.001f);
    mgr.destroy(l1);
    CHECK(mgr.libPool.QueryPoolInfo().NumUsedSlots == 1);
    CHECK(mgr.clipPool.Size() == 2);
    CHECK(mgr.curvePool.Size() == 6);
    CHECK(mgr.numKeys == 110);

    mgr.discard();
    CHECK(!mgr.isValid);
    CHECK(mgr.clipPool.Size() == 0);
    CHECK(mgr.curvePool.Size() == 0);
    CHECK(mgr.numKeys == 0);
}<|endoftext|>


<commit_before><commit_msg>Handled failures of Spool correctly.<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed crashes due to uninitialized undo stack<commit_after><|endoftext|>


<commit_before>/*
 * fMBT, free Model Based Testing tool
 * Copyright (c) 2011, Intel Corporation.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU Lesser General Public License,
 * version 2.1, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */
#ifndef __adapter_h__
#define __adapter_h__

#include <vector>
#include <string>
#include <map>
#include "writable.hh"
#include "alphabet.hh"
#include "factory.hh"
#include "log.hh"
#include <sys/time.h>

/* Creating and initialising an adapter is a call sequence

   1. constructor(log, params) where params contain configuration
   arguments

   2. set_actions(actions), by default just stored to the "actions"
   member.

   3. init()

   If is ready for responding to execute() and observe(), init()
   returns true. If init() returns false, stringify() may return
   reason for failure.
*/

class Adapter: public Writable {
public:
  static struct timeval current_time;
  Adapter(Log& l, std::string params = "");
  virtual ~Adapter();
  virtual void set_actions(std::vector<std::string>* _actions);
  virtual bool init();

  /** \brief execute an action and report results
   * \param action input/output parameter for suggesting and reporting
   *               executed action
   *
   * When called, action table contains exactly one action: executing
   * action[0] is suggested by the test generator. At exit it contains
   * the action whose execution is reported. Reporting more unusual
   * cases:
   *
   * 1. Result of the execution does not match any of the known
   *    actions: action table contains only integer 0.
   *
   * 2. Execution result corresponds to more than one actions:
   *    action table contains all alternative actions.
   *
   * 3. Execution of the suggested action is blocked:
   *    action table is empty.
   */
  virtual void execute(std::vector<int> &action) = 0;

  /** \brief report observed events
   * \param action (output) corresponds to observed event
   * \param block should adapter wait for events
   * \return true if events have been observed
   *
   * observe reports one event at a time. If an event matches to
   * multiple actions, all alternative actions are returned in the
   * action parameter.
   *
   * If block is false, observe should report events occured so
   * far. Otherwise it should wait for events and return either when
   * there is something to report or when there will not be anything
   * to report.
   */
  virtual int observe(std::vector<int> &action, bool block = false) = 0;

  /* Adapter stack / tree setup and browsing API */
  void setparent(Adapter* a);
  virtual Adapter* up();
  virtual Adapter* down(unsigned int a);
  virtual std::vector<std::string>& getAdapterNames();

  /* Methods for reading action names */
  virtual std::vector<std::string>& getAllActions();

  /// Returns action name for string comparisons
  std::string& getActionName(int action);

  /// Returns number corresponding to actionName or -1 if not found
  int getActionNumber(std::string& name);
  int getActionNumber(const char* name);

  /// Returns escaped action name (can be logged to XML)
  const char* getUActionName(int action);

protected:
  Log& log;
  std::vector<std::string>* actions;

  std::vector<const char*> unames;
  Adapter* parent;
  std::vector<std::string> adapter_names;
};

FACTORY_DECLARATION(Adapter);

#define CHECK_TIMEOUT {                      \
  gettimeofday(&Adapter::current_time,NULL); \
  struct timeval tv { Test_engine::end_time,0  }; \
  if (!timercmp(&current_time,&tv,<)) {       \
    return TIMEOUT;                          \
  }                                          \
}

#endif
<commit_msg>fixed stopping test too early on timeout<commit_after>/*
 * fMBT, free Model Based Testing tool
 * Copyright (c) 2011, Intel Corporation.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms and conditions of the GNU Lesser General Public License,
 * version 2.1, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope 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 program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
 *
 */
#ifndef __adapter_h__
#define __adapter_h__

#include <vector>
#include <string>
#include <map>
#include "writable.hh"
#include "alphabet.hh"
#include "factory.hh"
#include "log.hh"
#include <sys/time.h>

/* Creating and initialising an adapter is a call sequence

   1. constructor(log, params) where params contain configuration
   arguments

   2. set_actions(actions), by default just stored to the "actions"
   member.

   3. init()

   If is ready for responding to execute() and observe(), init()
   returns true. If init() returns false, stringify() may return
   reason for failure.
*/

class Adapter: public Writable {
public:
  static struct timeval current_time;
  Adapter(Log& l, std::string params = "");
  virtual ~Adapter();
  virtual void set_actions(std::vector<std::string>* _actions);
  virtual bool init();

  /** \brief execute an action and report results
   * \param action input/output parameter for suggesting and reporting
   *               executed action
   *
   * When called, action table contains exactly one action: executing
   * action[0] is suggested by the test generator. At exit it contains
   * the action whose execution is reported. Reporting more unusual
   * cases:
   *
   * 1. Result of the execution does not match any of the known
   *    actions: action table contains only integer 0.
   *
   * 2. Execution result corresponds to more than one actions:
   *    action table contains all alternative actions.
   *
   * 3. Execution of the suggested action is blocked:
   *    action table is empty.
   */
  virtual void execute(std::vector<int> &action) = 0;

  /** \brief report observed events
   * \param action (output) corresponds to observed event
   * \param block should adapter wait for events
   * \return true if events have been observed
   *
   * observe reports one event at a time. If an event matches to
   * multiple actions, all alternative actions are returned in the
   * action parameter.
   *
   * If block is false, observe should report events occured so
   * far. Otherwise it should wait for events and return either when
   * there is something to report or when there will not be anything
   * to report.
   */
  virtual int observe(std::vector<int> &action, bool block = false) = 0;

  /* Adapter stack / tree setup and browsing API */
  void setparent(Adapter* a);
  virtual Adapter* up();
  virtual Adapter* down(unsigned int a);
  virtual std::vector<std::string>& getAdapterNames();

  /* Methods for reading action names */
  virtual std::vector<std::string>& getAllActions();

  /// Returns action name for string comparisons
  std::string& getActionName(int action);

  /// Returns number corresponding to actionName or -1 if not found
  int getActionNumber(std::string& name);
  int getActionNumber(const char* name);

  /// Returns escaped action name (can be logged to XML)
  const char* getUActionName(int action);

protected:
  Log& log;
  std::vector<std::string>* actions;

  std::vector<const char*> unames;
  Adapter* parent;
  std::vector<std::string> adapter_names;
};

FACTORY_DECLARATION(Adapter);

#define CHECK_TIMEOUT {                             \
  gettimeofday(&Adapter::current_time,NULL);        \
  if (Test_engine::end_time != -1) {                \
    struct timeval tv { Test_engine::end_time,0  }; \
    if (!timercmp(&current_time,&tv,<)) {           \
      return TIMEOUT;                               \
    }                                               \
  }                                                 \
}

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;

bool isDirectory(char* directoryName) {

	struct stat directoryInCurrent;

	if (-1 == (stat(directoryName, &directoryInCurrent))) {

		perror("stat failed");
		return false;
	}

	if (directoryInCurrent.st_mode & S_IFDIR) {
		return true;
	}
	else {
		return false;
	}
}

int ls(char* directoryName) {

		char const *dirName = ".";
		DIR *dirp;
		if (!(dirp = opendir(dirName))) {
			cerr << "Error(" << errno << ") opening " << dirName << endl;
		}

		dirent *direntp;
		while ((direntp = readdir(dirp))) {
			if (direntp->d_name[0] != '.') {

				//cout << direntp->d_name << endl; // use stat here to find attributes of a file
				printf(direntp->d_name, 8);
				cout << " ";
			}
		}
		cout << endl;
		closedir(dirp);
		return 0;
}

int lsWithFlags(char* directoryName, vector<string> flags) {

	bool isA = false;
	bool isL = false;
	bool isR = false;
	for (unsigned i = 0; i < flags.size(); ++i) {
		for (unsigned k = 0; k < flags.at(i).size(); ++k) {
			if (flags.at(i).at(k) == 'a')
				isA = true;
			else if (flags.at(i).at(k) == 'l')
				isL = true;
			else if (flags.at(i).at(k) == 'R')
				isR = true;
		}

	}
	char const *dirName = directoryName;
	DIR *dirp;
	if (!(dirp = opendir(dirName))) {
		cerr << "Error(" << errno << ") opening " << dirName << endl;
		return errno;
	}

	dirent *direntp;
	if (isA) {
		while ((direntp = readdir(dirp))) {

			//cout << direntp->d_name << endl; // use stat here to find attributes of a file
			printf(direntp->d_name, 8);
			cout << " ";

		}
	}
	cout << endl;
	closedir(dirp);
	return 0;
}

int main(int argc, char* argv[]) {

	if (argc == 1) {

		if (errno == ls(".")) {

			return errno;
		}
	}

	else {

		vector<string> directories;
		vector<string> flags;
		vector<int> directoryIndex;
		bool directoryInArgv = false;
		for (int i = 1; i < argc; ++i) {

			if (isDirectory(argv[i])) {
				directoryInArgv = true;
				break;
			}
			else {

				if (argv[i][0] == '-') {

					flags.push_back(argv[i]);
				}
			}
		}
		if (!directoryInArgv) {

			if (errno == lsWithFlags(".", flags)) {

				return errno;
			}
		}
		else {
			for (int i = 0; i < argc; ++i) {

				if (isDirectory(argv[i])) {
					directories.push_back(argv[i]);
					directoryIndex.push_back(i);
				}
			}

			cout << "directories size: " << directories.size() << endl;
			for (unsigned int i = 0; i < directories.size(); ++i) {
				flags.clear();
				for (unsigned int k = static_cast<unsigned>(directoryIndex.at(i));
					 (i + 1) < directoryIndex.size() &&
					 k != (unsigned)directoryIndex.at(i + 1);
					  ++k) {
					if (argv[k][0] == '-') {

						flags.push_back(argv[k]);
					}
				}

				char* directoryName = new char[directories.at(i).size() + 1];
				strcpy(directoryName, directories.at(i).c_str());
				if (errno == lsWithFlags(directoryName, flags)) {

					return errno;
				}
			}
		}
	}

}

<commit_msg>changed conditions for boolean variables in lswithflags function<commit_after>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;

bool isDirectory(char* directoryName) {

	struct stat directoryInCurrent;

	if (-1 == (stat(directoryName, &directoryInCurrent))) {

		perror("stat failed");
		return false;
	}

	if (directoryInCurrent.st_mode & S_IFDIR) {
		return true;
	}
	else {
		return false;
	}
}

int ls(char* directoryName) {

		char const *dirName = ".";
		DIR *dirp;
		if (!(dirp = opendir(dirName))) {
			cerr << "Error(" << errno << ") opening " << dirName << endl;
		}

		dirent *direntp;
		while ((direntp = readdir(dirp))) {
			if (direntp->d_name[0] != '.') {

				//cout << direntp->d_name << endl; // use stat here to find attributes of a file
				printf(direntp->d_name, 8);
				cout << " ";
			}
		}
		cout << endl;
		closedir(dirp);
		return 0;
}

int lsWithFlags(char* directoryName, vector<string> flags) {

	bool isA = false;
	bool isL = false;
	bool isR = false;
	for (unsigned i = 0; i < flags.size(); ++i) {
		for (unsigned k = 0; k < flags.at(i).size(); ++k) {
			if (flags.at(i).at(k) == 'a')
				isA = true;
			else if (flags.at(i).at(k) == 'l')
				isL = true;
			else if (flags.at(i).at(k) == 'R')
				isR = true;
		}

	}
	char const *dirName = directoryName;
	DIR *dirp;
	if (!(dirp = opendir(dirName))) {
		cerr << "Error(" << errno << ") opening " << dirName << endl;
		return errno;
	}

	dirent *direntp;
	if (isA) {
		while ((direntp = readdir(dirp))) {

			//cout << direntp->d_name << endl; // use stat here to find attributes of a file
			printf(direntp->d_name, 8);
			cout << " ";

		}
	}
	cout << endl;
	closedir(dirp);
	return 0;
}

int main(int argc, char* argv[]) {

	if (argc == 1) {

		if (errno == ls(".")) {

			return errno;
		}
	}

	else {

		vector<string> directories;
		vector<string> flags;
		vector<int> directoryIndex;
		bool directoryInArgv = false;
		for (int i = 1; i < argc; ++i) {

			if (isDirectory(argv[i])) {
				directoryInArgv = true;
				break;
			}
			else {

				if (argv[i][0] == '-') {

					flags.push_back(argv[i]);
				}
			}
		}
		if (!directoryInArgv) {

			if (errno == lsWithFlags(".", flags)) {

				return errno;
			}
		}
		else {
			for (int i = 0; i < argc; ++i) {

				if (isDirectory(argv[i])) {
					directories.push_back(argv[i]);
					directoryIndex.push_back(i);
				}
			}

			for (unsigned int i = 0; i < directories.size(); ++i) {
				flags.clear();
				for (unsigned int k = static_cast<unsigned>(directoryIndex.at(i));
					 (i + 1) < directoryIndex.size() &&
					 k != (unsigned)directoryIndex.at(i + 1);
					  ++k) {
					if (argv[k][0] == '-') {

						flags.push_back(argv[k]);
					}
				}

				cout << "flags: ";
				for (unsigned i = 0; i < flags.size(); ++i) {

					cout << flags.at(i) << " ";
				}
				cout << endl;

				char* directoryName = new char[directories.at(i).size() + 1];
				strcpy(directoryName, directories.at(i).c_str());

				if (errno == lsWithFlags(directoryName, flags)) {

					return errno;
				}
			}
		}
	}

}

<|endoftext|>


<commit_before>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <cstring>

using namespace std;

#define printVec(x) for(unsigned int i = 0; i < x.size(); i++) \
                        cout << x.at(i) << " "; \
                    cout << endl;

//function to print out the contents of argv
void printARGV(char **argv){
    int i = 0;
    while(argv[i] != NULL){
        cout << "Pos " << i << ": " << argv[i] << endl;
        i++;
    }
    cout << endl;
}

/*this function will get all the file descriptors or directors and put
 them into a vector of strings called file_O_dir*/

/*vector<string> getFiles_Dir (char **argv, pos_){
    string targets; //this is the rest of the targest after the flags
    vector<string> importantStuff;

    unsigned int pos = pos_;
    while(argv[pos] != '\0'){
        cout << " << argv[pos]; " << argv[pos] << endl;
        cout << endl;
        pos++;
    }
    cout << endl;

    return importantStuff;
}*/

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

    //test and case variables
    string flags_;
    string ls = "ls";
    char dash = '-';
//  --------------------------------------------------------------------

    //vectors of flags -a, -l, -R
    vector<char> flags;
    flags.push_back('a');
    flags.push_back('l');
    flags.push_back('R');

    //vector of files & directories
    vector<string> files_dirs;
//  --------------------------------------------------------------------

    bool isFlag_a = false; //bool to determine if the flag is -a
    bool isFlag_l = false; //bool to determine if the flag is -l
    bool isFlag_R = false; //bool to determine if the flag is -R
    bool is_ls = false;    //bool to determine if the input ONLY ls
//  --------------------------------------------------------------------

    if(argc <= 1){ //assumes the user didn't type anything
        return 0;
    }
//  --------------------------------------------------------------------

    //What's in char **argv?
    printARGV(argv);
//  --------------------------------------------------------------------

    /*if you type anything other than ls or ls with flags,
      output an error and quit the program*/
    if(argc > 1 && argc <= 2 && argv[1] != ls){
        cout << "Error: no form of ls" << endl;
        exit(1);
    }
    /*did the user type is ls only?*/
    else if(argc > 1 && argc <= 2 && argv[1] == ls){
        is_ls = true;
        if(is_ls) cout << "Only run ls on current directory" << endl;
        return 0;
    }

    if(argc > 1 && argv[1] == ls){ //if there is ls followed by a dir or file
        ;
    }
    else{
        for(int x = 0; x < argc; ++x){
            if(*(argv[x]) == dash){ //grabs flags
                flags_ = argv[x]; //put the cstring in a string
                flags_.erase(flags_.begin()); //erase the '-' at the beginning

                //go through each flag_ and compare with the vector of flags
                for(unsigned int i = 0 ; i < flags_.size(); ++i){
                    for(unsigned int j = 0; j < flags.size(); ++j){
                        if(flags_.at(i) == flags.at(j)){
                            if(flags.at(j) == 'a'){
                                isFlag_a = true;
                                if(isFlag_a) cout << "We have a!" << endl;
                            }
                            else if(flags.at(j) == 'l'){
                                isFlag_l = true;
                                if(isFlag_l) cout << "We have l!" << endl;
                            }
                            else if(flags.at(j) == 'R'){
                                isFlag_R = true;
                                if(isFlag_R) cout << "We have R!" << endl;
                            }
                        }
                    }
                }
            }
        }
    }

    //files_dirs = getFiles_Dir(argv, );
//  --------------------------------------------------------------------

    return 0;
}
<commit_msg>have flags and directory/file extraction working<commit_after>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <cstring>
#include <cstddef>
using namespace std;

#define printVec(x) for(unsigned int i = 0; i < x.size(); i++) \
                        cout << x.at(i) << " "; \
                    cout << endl;

//function to print out the contents of argv
void printARGV(char **argv){
    int i = 0;
    while(argv[i] != NULL){
        cout << "Pos " << i << ": " << argv[i] << endl;
        i++;
    }
    cout << endl;
}

/*this function will get all the file descriptors or directories and put
 them into a vector of strings called file_O_dir*/

//anything that is not 'ls' or '-<flags>' is considered a file or dir

vector<string> getFiles_Dirs (char **argv){
    string targets; //this is the rest of the targest after the flags

    string ls = "ls";
    char dash = '-';

    vector<string> importantStuff;

    unsigned int pos = 1;
    while(argv[pos] != '\0'){
        string temp = argv[pos]; //keep the current argv part in a string

        if(argv[pos] == ls){
            pos++; //increment position to get next arg
            continue; //continue to next iteration
        }

        if(argv[pos][0] == dash){
            pos++; //increment position to get next arg
            continue; //continue to next iteration
        }

        importantStuff.push_back(temp); //if both cases fail, you add it!

        pos++; //increment to get next arg
    }

    return importantStuff;
}

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

    //test and case variables
    string flags_;
    string ls = "ls";
    char dash = '-';
//  --------------------------------------------------------------------

    //vectors of flags -a, -l, -R
    vector<char> flags;
    flags.push_back('a');
    flags.push_back('l');
    flags.push_back('R');

    //vector of files & directories
    vector<string> files_dirs;
//  --------------------------------------------------------------------

    bool isFlag_a = false; //bool to determine if the flag is -a
    bool isFlag_l = false; //bool to determine if the flag is -l
    bool isFlag_R = false; //bool to determine if the flag is -R
    bool is_ls = false;    //bool to determine if the input ONLY ls
//  --------------------------------------------------------------------

    if(argc <= 1){ //assumes the user didn't type anything
        return 0;
    }
//  --------------------------------------------------------------------

    //What's in char **argv?
    printARGV(argv);
//  --------------------------------------------------------------------

    /*if you type anything other than ls or ls with flags,
      output an error and quit the program*/
    if(argc > 1 && argc <= 2 && argv[1] != ls){
        cout << "Error: no form of ls" << endl;
        exit(1);
    }
    /*below are some cases for ls*/
    else if(argc > 1  && argv[1] == ls){ //is there a ls?
        is_ls = true;
        if(is_ls) cout << "run ls depending on the size of dir vector" << endl;

        files_dirs = getFiles_Dirs(argv); //get directories or files

        //where there any directories or files that were called?
        if( !(files_dirs.size() > 0) ){
            //call ls on the current working directory
        }
    }
    else{ //is there a ls with flags and maybe files or dir
        for(int x = 0; x < argc; ++x){
            if(*(argv[x]) == dash){ //grabs flags
                flags_ = argv[x]; //put the cstring in a string
                flags_.erase(flags_.begin()); //erase the '-' at the beginning

                //go through each flag_ and compare with the vector of flags
                for(unsigned int i = 0 ; i < flags_.size(); ++i){
                    for(unsigned int j = 0; j < flags.size(); ++j){
                        if(flags_.at(i) == flags.at(j)){
                            if(flags.at(j) == 'a'){
                                isFlag_a = true;
                                if(isFlag_a) cout << "We have a!" << endl;
                            }
                            else if(flags.at(j) == 'l'){
                                isFlag_l = true;
                                if(isFlag_l) cout << "We have l!" << endl;
                            }
                            else if(flags.at(j) == 'R'){
                                isFlag_R = true;
                                if(isFlag_R) cout << "We have R!" << endl;
                            }
                        }
                    }
                }
            }
        }
    }

    //files_dirs = getFiles_Dir(argv, );
//  --------------------------------------------------------------------

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;

bool isDirectory(char* directoryName) {

	struct stat directoryInCurrent;

	if (-1 == (stat(directoryName, &directoryInCurrent))) {

		return false;
	}

	if (directoryInCurrent.st_mode & S_IFDIR) {
		return true;
	}
	else {
		return false;
	}
}

int ls(char* directoryName) {

		char const *dirName = ".";
		DIR *dirp;
		if (!(dirp = opendir(dirName))) {
			cerr << "Error(" << errno << ") opening " << dirName << endl;
		}

		dirent *direntp;
		while ((direntp = readdir(dirp))) {
			if (direntp->d_name[0] != '.') {

				//cout << direntp->d_name << endl; // use stat here to find attributes of a file
				printf(direntp->d_name, 8);
				cout << " ";
			}
		}
		cout << endl;
		closedir(dirp);
		return 0;
}

int lsWithFlags(char* directoryName, vector<string> flags) {

	bool isA = false;
	bool isL = false;
	bool isR = false;
	for (unsigned i = 0; i < flags.size(); ++i) {
		for (unsigned k = 0; k < flags.at(i).size(); ++k) {
			if (flags.at(i).at(k) == 'a')
				isA = true;
			else if (flags.at(i).at(k) == 'l')
				isL = true;
			else if (flags.at(i).at(k) == 'R')
				isR = true;
		}

	}
	char const *dirName = directoryName;
	DIR *dirp;
	if (!(dirp = opendir(dirName))) {
		cerr << "Error(" << errno << ") opening " << dirName << endl;
		return errno;
	}

	dirent *direntp;
	if (isA) {
		while ((direntp = readdir(dirp))) {

			//cout << direntp->d_name << endl; // use stat here to find attributes of a file
			printf(direntp->d_name, 8);
			cout << " ";

		}
	}
	cout << endl;
	closedir(dirp);
	return 0;
}

int main(int argc, char* argv[]) {

	if (argc == 1) {

		if (errno == ls(".")) {

			return errno;
		}
	}

	else {

		vector<string> directories;
		vector<string> flags;
		vector<int> directoryIndex;
		bool directoryInArgv = false;
		for (int i = 1; i < argc; ++i) {

			if (isDirectory(argv[i])) {
				directoryInArgv = true;

			}
			else {

				if (argv[i][0] == '-') {

					flags.push_back(argv[i]);
				}
			}
		}
		if (!directoryInArgv) {

			if (errno == lsWithFlags(".", flags)) {

				return errno;
			}
		}
		else {

			cout << 131 << endl;
			for (int i = 1; i < argc; ++i) {

				if (isDirectory(argv[i])) {
					directories.push_back(argv[i]);
					directoryIndex.push_back(i);
				}
			}

			cout << "directories size: " << directories.size() << endl;
			cout << "directories indeces are: ";
			for (unsigned i = 0; i < directoryIndex.size(); ++i) {

				cout << directoryIndex.at(i) << " ";
			}
			cout << endl;

			for (unsigned int i = 0; i < directories.size(); ++i) {
				flags.clear();

				for (int k = directoryIndex.at(i); k < argc && !isDirectory(argv[k]); ++k) {

					if (argv[k][0] == '-')
						flags.push_back(argv[k]);
				}

				char* directoryName = new char[directories.at(i).size() + 1];
				strcpy(directoryName, directories.at(i).c_str());

				if (flags.size() == 0) {

					if (errno == ls(directoryName)) {

						return errno;
					}
				}
				else {
			   	(errno == lsWithFlags(directoryName, flags)) {

						return errno;
					}
				}

				delete [] directoryName;
			}
		}
	}

}

<commit_msg>changed conditions for boolean variables in lswithflags function<commit_after>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;

bool isDirectory(char* directoryName) {

	struct stat directoryInCurrent;

	if (-1 == (stat(directoryName, &directoryInCurrent))) {

		return false;
	}

	if (directoryInCurrent.st_mode & S_IFDIR) {
		return true;
	}
	else {
		return false;
	}
}

int ls(char* directoryName) {

		char const *dirName = ".";
		DIR *dirp;
		if (!(dirp = opendir(dirName))) {
			cerr << "Error(" << errno << ") opening " << dirName << endl;
		}

		dirent *direntp;
		while ((direntp = readdir(dirp))) {
			if (direntp->d_name[0] != '.') {

				//cout << direntp->d_name << endl; // use stat here to find attributes of a file
				printf(direntp->d_name, 8);
				cout << " ";
			}
		}
		cout << endl;
		closedir(dirp);
		return 0;
}

int lsWithFlags(char* directoryName, vector<string> flags) {

	bool isA = false;
	bool isL = false;
	bool isR = false;
	for (unsigned i = 0; i < flags.size(); ++i) {
		for (unsigned k = 0; k < flags.at(i).size(); ++k) {
			if (flags.at(i).at(k) == 'a')
				isA = true;
			else if (flags.at(i).at(k) == 'l')
				isL = true;
			else if (flags.at(i).at(k) == 'R')
				isR = true;
		}

	}
	char const *dirName = directoryName;
	DIR *dirp;
	if (!(dirp = opendir(dirName))) {
		cerr << "Error(" << errno << ") opening " << dirName << endl;
		return errno;
	}

	dirent *direntp;
	if (isA) {
		while ((direntp = readdir(dirp))) {

			//cout << direntp->d_name << endl; // use stat here to find attributes of a file
			printf(direntp->d_name, 8);
			cout << " ";

		}
	}
	cout << endl;
	closedir(dirp);
	return 0;
}

int main(int argc, char* argv[]) {

	if (argc == 1) {

		if (errno == ls(".")) {

			return errno;
		}
	}

	else {

		vector<string> directories;
		vector<string> flags;
		vector<int> directoryIndex;
		bool directoryInArgv = false;
		for (int i = 1; i < argc; ++i) {

			if (isDirectory(argv[i])) {
				directoryInArgv = true;

			}
			else {

				if (argv[i][0] == '-') {

					flags.push_back(argv[i]);
				}
			}
		}
		if (!directoryInArgv) {

			if (errno == lsWithFlags(".", flags)) {

				return errno;
			}
		}
		else {

			cout << 131 << endl;
			for (int i = 1; i < argc; ++i) {

				if (isDirectory(argv[i])) {
					directories.push_back(argv[i]);
					directoryIndex.push_back(i);
				}
			}

			cout << "directories size: " << directories.size() << endl;
			cout << "directories indeces are: ";
			for (unsigned i = 0; i < directoryIndex.size(); ++i) {

				cout << directoryIndex.at(i) << " ";
			}
			cout << endl;

			for (unsigned int i = 0; i < directories.size(); ++i) {
				flags.clear();

				for (int k = directoryIndex.at(i); k < argc && !isDirectory(argv[k]); ++k) {

					if (argv[k][0] == '-')
						flags.push_back(argv[k]);
				}

				char* directoryName = new char[directories.at(i).size() + 1];
				strcpy(directoryName, directories.at(i).c_str());

				if (flags.size() == 0) {

					if (errno == ls(directoryName)) {

						return errno;
					}
				}
				else {
			   	if	(errno == lsWithFlags(directoryName, flags)) {

						return errno;
					}
				}

				delete [] directoryName;
			}
		}
	}

}

<|endoftext|>


<commit_before>//@"fn": "entry.cpp"
//@"author": "yash101 (Dev)"
//@"description": "This file serves as the entry point for the program. Once the program is launched, the function, main() is called."

//This is the header for entry.cpp. It contains the variable extern definitions so that
//The main variables in this file can be accessed elsewhere.
#include "entry.h"
#include "server/tcp_socket.h"
#include "server/httpserver.h"

class H : public dev::HttpServer
{
private:
  void on_request(dev::HttpServerSession& session)
  {
    session.response = "
Hi!
";
  }
};

int main(int argc, char** argv)
{
  //Assign the incoming arguments to our arguments' structure
  Arguments::argc = argc;
  Arguments::argv = argv;
//  H().start(1234);
  try
  {
    dev::HttpServer().start(1235);
  }
  catch(std::exception& e)
  {}
}

int Arguments::argc;
char** Arguments::argv;
<commit_msg>Changed the port to 1234.<commit_after>//@"fn": "entry.cpp"
//@"author": "yash101 (Dev)"
//@"description": "This file serves as the entry point for the program. Once the program is launched, the function, main() is called."

//This is the header for entry.cpp. It contains the variable extern definitions so that
//The main variables in this file can be accessed elsewhere.
#include "entry.h"
#include "server/tcp_socket.h"
#include "server/httpserver.h"

class H : public dev::HttpServer
{
private:
  void on_request(dev::HttpServerSession& session)
  {
    session.response = "
Hi!
";
  }
};

int main(int argc, char** argv)
{
  //Assign the incoming arguments to our arguments' structure
  Arguments::argc = argc;
  Arguments::argv = argv;
//  H().start(1234);
  try
  {
    dev::HttpServer().start(1234);
  }
  catch(std::exception& e)
  {}
}

int Arguments::argc;
char** Arguments::argv;
<|endoftext|>


<commit_before>/*

Copyright (c) 2010, Arvid Norberg
All rights reserved.

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

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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

*/

#include "test.hpp"
#include "setup_transfer.hpp"
#include "udp_tracker.hpp"
#include "libtorrent/alert.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/error_code.hpp"

#include <fstream>

using namespace libtorrent;

int test_main()
{
	int http_port = start_web_server();
	int udp_port = start_udp_tracker();

	int prev_udp_announces = num_udp_announces();

	int const alert_mask = alert::all_categories
		& ~alert::progress_notification
		& ~alert::stats_notification;

	session* s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48875, 49800), "0.0.0.0", 0, alert_mask);

	session_settings sett;
	sett.half_open_limit = 1;
	sett.announce_to_all_trackers = true;
	sett.announce_to_all_tiers = true;
	s->set_settings(sett);

	error_code ec;
	remove_all("tmp1_tracker", ec);
	create_directory("tmp1_tracker", ec);
	std::ofstream file(combine_path("tmp1_tracker", "temporary").c_str());
	boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 13, false);
	file.close();

	char tracker_url[200];
	snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port);
	t->add_tracker(tracker_url, 0);

	snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port);
	t->add_tracker(tracker_url, 1);

	add_torrent_params addp;
	addp.flags &= ~add_torrent_params::flag_paused;
	addp.flags &= ~add_torrent_params::flag_auto_managed;
	addp.flags |= add_torrent_params::flag_seed_mode;
	addp.ti = t;
	addp.save_path = "tmp1_tracker";
	torrent_handle h = s->add_torrent(addp);

	for (int i = 0; i < 50; ++i)
	{
		print_alerts(*s, "s");
		test_sleep(100);
		if (num_udp_announces() == prev_udp_announces + 1)
			break;
	}

	// we should have announced to the tracker by now
	TEST_EQUAL(num_udp_announces(), prev_udp_announces + 1);

	fprintf(stderr, "destructing session\n");
	delete s;
	fprintf(stderr, "done\n");

	// we should have announced the stopped event now
	TEST_EQUAL(num_udp_announces(), prev_udp_announces + 2);

	// ========================================
	// test that we move on to try the next tier if the first one fails
	// ========================================

	s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(39775, 39800), "0.0.0.0", 0, alert_mask);

	sett.half_open_limit = 1;
	sett.announce_to_all_trackers = true;
	sett.announce_to_all_tiers = false;
	sett.tracker_completion_timeout = 2;
	sett.tracker_receive_timeout = 1;
	s->set_settings(sett);

	remove_all("tmp2_tracker", ec);
	create_directory("tmp2_tracker", ec);
	file.open(combine_path("tmp2_tracker", "temporary").c_str());
	t = ::create_torrent(&file, 16 * 1024, 13, false);
	file.close();

	// this should fail
	snprintf(tracker_url, sizeof(tracker_url), "udp://www1.non-existent.com:80/announce");
	t->add_tracker(tracker_url, 0);

	// and this should fail
	snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.2:3/announce");
	t->add_tracker(tracker_url, 1);

	// this should be announced to
	// udp trackers are prioritized if they're on the same host as an http one
	// so this must be before the http one on 127.0.0.1
	snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port);
	t->add_tracker(tracker_url, 2);

	// and this should not be announced to (since the one before it succeeded)
	snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port);
	t->add_tracker(tracker_url, 3);

	prev_udp_announces = num_udp_announces();

	addp.flags &= ~add_torrent_params::flag_paused;
	addp.flags &= ~add_torrent_params::flag_auto_managed;
	addp.flags |= add_torrent_params::flag_seed_mode;
	addp.ti = t;
	addp.save_path = "tmp2_tracker";
	h = s->add_torrent(addp);

	for (int i = 0; i < 50; ++i)
	{
		print_alerts(*s, "s");
		test_sleep(100);
		if (num_udp_announces() == prev_udp_announces + 1) break;
	}

	test_sleep(1000);

	TEST_EQUAL(num_udp_announces(), prev_udp_announces + 1);

	fprintf(stderr, "destructing session\n");
	delete s;
	fprintf(stderr, "done\n");

	stop_udp_tracker();
	stop_web_server();

	return 0;
}

<commit_msg>improve debug output from test_tracker<commit_after>/*

Copyright (c) 2010, Arvid Norberg
All rights reserved.

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

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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

*/

#include "test.hpp"
#include "setup_transfer.hpp"
#include "udp_tracker.hpp"
#include "libtorrent/alert.hpp"
#include "libtorrent/session.hpp"
#include "libtorrent/error_code.hpp"

#include <fstream>

using namespace libtorrent;

int test_main()
{
	int http_port = start_web_server();
	int udp_port = start_udp_tracker();

	int prev_udp_announces = num_udp_announces();

	int const alert_mask = alert::all_categories
		& ~alert::progress_notification
		& ~alert::stats_notification;

	session* s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48875, 49800), "0.0.0.0", 0, alert_mask);

	session_settings sett;
	sett.half_open_limit = 1;
	sett.announce_to_all_trackers = true;
	sett.announce_to_all_tiers = true;
	s->set_settings(sett);

	error_code ec;
	remove_all("tmp1_tracker", ec);
	create_directory("tmp1_tracker", ec);
	std::ofstream file(combine_path("tmp1_tracker", "temporary").c_str());
	boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024, 13, false);
	file.close();

	char tracker_url[200];
	snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port);
	t->add_tracker(tracker_url, 0);

	snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port);
	t->add_tracker(tracker_url, 1);

	add_torrent_params addp;
	addp.flags &= ~add_torrent_params::flag_paused;
	addp.flags &= ~add_torrent_params::flag_auto_managed;
	addp.flags |= add_torrent_params::flag_seed_mode;
	addp.ti = t;
	addp.save_path = "tmp1_tracker";
	torrent_handle h = s->add_torrent(addp);

	for (int i = 0; i < 50; ++i)
	{
		print_alerts(*s, "s");
		if (num_udp_announces() == prev_udp_announces + 1)
			break;

		fprintf(stderr, "UDP: %d / %d\n", int(num_udp_announces())
			, int(prev_udp_announces) + 1);
		test_sleep(100);
	}

	// we should have announced to the tracker by now
	TEST_EQUAL(num_udp_announces(), prev_udp_announces + 1);

	fprintf(stderr, "destructing session\n");
	delete s;
	fprintf(stderr, "done\n");

	// we should have announced the stopped event now
	TEST_EQUAL(num_udp_announces(), prev_udp_announces + 2);

	// ========================================
	// test that we move on to try the next tier if the first one fails
	// ========================================

	s = new libtorrent::session(fingerprint("LT", 0, 1, 0, 0), std::make_pair(39775, 39800), "0.0.0.0", 0, alert_mask);

	sett.half_open_limit = 1;
	sett.announce_to_all_trackers = true;
	sett.announce_to_all_tiers = false;
	sett.tracker_completion_timeout = 2;
	sett.tracker_receive_timeout = 1;
	s->set_settings(sett);

	remove_all("tmp2_tracker", ec);
	create_directory("tmp2_tracker", ec);
	file.open(combine_path("tmp2_tracker", "temporary").c_str());
	t = ::create_torrent(&file, 16 * 1024, 13, false);
	file.close();

	// this should fail
	snprintf(tracker_url, sizeof(tracker_url), "udp://www1.non-existent.com:80/announce");
	t->add_tracker(tracker_url, 0);

	// and this should fail
	snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.2:3/announce");
	t->add_tracker(tracker_url, 1);

	// this should be announced to
	// udp trackers are prioritized if they're on the same host as an http one
	// so this must be before the http one on 127.0.0.1
	snprintf(tracker_url, sizeof(tracker_url), "udp://127.0.0.1:%d/announce", udp_port);
	t->add_tracker(tracker_url, 2);

	// and this should not be announced to (since the one before it succeeded)
	snprintf(tracker_url, sizeof(tracker_url), "http://127.0.0.1:%d/announce", http_port);
	t->add_tracker(tracker_url, 3);

	prev_udp_announces = num_udp_announces();

	addp.flags &= ~add_torrent_params::flag_paused;
	addp.flags &= ~add_torrent_params::flag_auto_managed;
	addp.flags |= add_torrent_params::flag_seed_mode;
	addp.ti = t;
	addp.save_path = "tmp2_tracker";
	h = s->add_torrent(addp);

	for (int i = 0; i < 50; ++i)
	{
		print_alerts(*s, "s");
		if (num_udp_announces() == prev_udp_announces + 1) break;

		fprintf(stderr, "UDP: %d / %d\n", int(num_udp_announces())
			, int(prev_udp_announces) + 1);
		test_sleep(100);
	}

	test_sleep(1000);

	TEST_EQUAL(num_udp_announces(), prev_udp_announces + 1);

	fprintf(stderr, "destructing session\n");
	delete s;
	fprintf(stderr, "done\n");

	stop_udp_tracker();
	stop_web_server();

	return 0;
}

<|endoftext|>


<commit_before><commit_msg>Correct compilation warnings<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;

bool isDirectory(char* directoryName) {

	struct stat directoryInCurrent;

	if (-1 == (stat(directoryName, &directoryInCurrent))) {

		return false;
	}

	if (directoryInCurrent.st_mode & S_IFDIR) {
		return true;
	}
	else {
		return false;
	}
}

int ls(char* directoryName) {

		char const *dirName = ".";
		DIR *dirp;
		if (!(dirp = opendir(dirName))) {
			cerr << "Error(" << errno << ") opening " << dirName << endl;
		}

		dirent *direntp;
		while ((direntp = readdir(dirp))) {
			if (direntp->d_name[0] != '.') {

				//cout << direntp->d_name << endl; // use stat here to find attributes of a file
				printf(direntp->d_name, 8);
				cout << " ";
			}
		}
		cout << endl;
		closedir(dirp);
		return 0;
}

int lsWithFlags(char* directoryName, vector<string> flags) {

	bool isA = false;
	bool isL = false;
	bool isR = false;
	for (unsigned i = 0; i < flags.size(); ++i) {
		for (unsigned k = 0; k < flags.at(i).size(); ++k) {
			if (flags.at(i).at(k) == 'a')
				isA = true;
			else if (flags.at(i).at(k) == 'l')
				isL = true;
			else if (flags.at(i).at(k) == 'R')
				isR = true;
		}

	}
	char const *dirName = directoryName;
	DIR *dirp;
	if (!(dirp = opendir(dirName))) {
		cerr << "Error(" << errno << ") opening " << dirName << endl;
		return errno;
	}

	dirent *direntp;
	if (isA) {
		while ((direntp = readdir(dirp))) {

			//cout << direntp->d_name << endl; // use stat here to find attributes of a file
			printf(direntp->d_name, 8);
			cout << " ";

		}
	}
	cout << endl;
	closedir(dirp);
	return 0;
}

int main(int argc, char* argv[]) {

	if (argc == 1) {

		if (errno == ls(".")) {

			return errno;
		}
	}

	else {

		vector<string> directories;
		vector<string> flags;
		vector<int> directoryIndex;
		bool directoryInArgv = false;
		for (int i = 1; i < argc; ++i) {

			if (isDirectory(argv[i])) {
				directoryInArgv = true;

			}
			else {

				if (argv[i][0] == '-') {

					flags.push_back(argv[i]);
				}
			}
		}
		if (!directoryInArgv) {

			if (errno == lsWithFlags(".", flags)) {

				return errno;
			}
		}
		else {

			for (int i = 1; i < argc; ++i) {

				if (isDirectory(argv[i])) {
					directories.push_back(argv[i]);
					directoryIndex.push_back(i);
				}
			}

			cout << "directories: ";
			for (unsigned i = 0; i < directories.size(); ++i)
				cout << directories.at(i) << " ";
			cout << endl;

			for (unsigned int i = 0; i < directories.size(); ++i) {
				cout << 145 << endl;
				flags.clear();

				for (int k = directoryIndex.at(i) + 1; k < argc && !isDirectory(argv[k]); ++k) {
					if (argv[k][0] == '-')
						flags.push_back(argv[k]);
				}

				char* directoryName = new char[directories.at(i).size() + 1];
				strcpy(directoryName, directories.at(i).c_str());

				if (flags.size() == 0) {
					cout << 152 << endl;
					cout << directories.at(i) << ":" << endl;
					if (errno == ls(directoryName)) {
						cout << 161 << endl;
						return errno;
					}
				}
				else {
					cout << directories.at(i) << ":" << endl;
			   	if	(errno == lsWithFlags(directoryName, flags)) {

						return errno;
					}
				}

				delete [] directoryName;
			}
		}
	}

}

<commit_msg>changed conditions for boolean variables in lswithflags function<commit_after>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;

bool isDirectory(char* directoryName) {

	struct stat directoryInCurrent;

	if (-1 == (stat(directoryName, &directoryInCurrent))) {

		return false;
	}

	if (directoryInCurrent.st_mode & S_IFDIR) {
		return true;
	}
	else {
		return false;
	}
}

int ls(char* directoryName) {

		char const *dirName = ".";
		DIR *dirp;
		if (!(dirp = opendir(dirName))) {
			cerr << "Error(" << errno << ") opening " << dirName << endl;
		}

		dirent *direntp;
		while ((direntp = readdir(dirp))) {
			if (direntp->d_name[0] != '.') {

				//cout << direntp->d_name << endl; // use stat here to find attributes of a file
				printf(direntp->d_name, 8);
				cout << " ";
			}
		}
		cout << endl;
		closedir(dirp);
		return 0;
}

int lsWithFlags(char* directoryName, vector<string> flags) {

	bool isA = false;
	bool isL = false;
	bool isR = false;
	for (unsigned i = 0; i < flags.size(); ++i) {
		for (unsigned k = 0; k < flags.at(i).size(); ++k) {
			if (flags.at(i).at(k) == 'a')
				isA = true;
			else if (flags.at(i).at(k) == 'l')
				isL = true;
			else if (flags.at(i).at(k) == 'R')
				isR = true;
		}

	}
	char const *dirName = directoryName;
	DIR *dirp;
	if (!(dirp = opendir(dirName))) {
		cerr << "Error(" << errno << ") opening " << dirName << endl;
		return errno;
	}

	dirent *direntp;
	if (isA) {
		while ((direntp = readdir(dirp))) {

			//cout << direntp->d_name << endl; // use stat here to find attributes of a file
			printf(direntp->d_name, 8);
			cout << " ";

		}
	}
	cout << endl;
	closedir(dirp);
	return 0;
}

int main(int argc, char* argv[]) {

	if (argc == 1) {

		if (errno == ls(".")) {

			return errno;
		}
	}

	else {

		vector<string> directories;
		vector<string> flags;
		vector<int> directoryIndex;
		bool directoryInArgv = false;
		for (int i = 1; i < argc; ++i) {

			if (isDirectory(argv[i])) {
				directoryInArgv = true;

			}
			else {

				if (argv[i][0] == '-') {

					flags.push_back(argv[i]);
				}
			}
		}
		if (!directoryInArgv) {

			if (errno == lsWithFlags(".", flags)) {

				return errno;
			}
		}
		else {

			for (int i = 1; i < argc; ++i) {

				if (isDirectory(argv[i])) {
					directories.push_back(argv[i]);
					directoryIndex.push_back(i);
				}
			}

			cout << "directories: ";
			for (unsigned i = 0; i < directories.size(); ++i)
				cout << directories.at(i) << " ";
			cout << endl;

			for (unsigned int i = 0; i < directories.size(); ++i) {
				cout << 145 << endl;
				flags.clear();

				for (int k = directoryIndex.at(i) + 1; k < argc && !isDirectory(argv[k]); ++k) {
					if (argv[k][0] == '-')
						flags.push_back(argv[k]);
				}

				char* directoryName = new char[directories.at(i).size() + 1];
				strcpy(directoryName, directories.at(i).c_str());

				if (flags.size() == 0) {
					cout << 152 << endl;
					cout << directories.at(i) << ":" << endl;
					ls(directoryName);
				}
				else {
					cout << directories.at(i) << ":" << endl;
			   	if	(errno == lsWithFlags(directoryName, flags)) {

						return errno;
					}
				}

				delete [] directoryName;
			}
		}
	}

}

<|endoftext|>