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

#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

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

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PermissionsFail) {
  ASSERT_TRUE(RunExtensionTest("permissions/disabled")) << message_;

  // Since the experimental APIs require a flag, this will fail even though
  // It's enabled.
  // TODO(erikkay) This test is currently broken because LoadExtension in
  // ExtensionBrowserTest doesn't actually fail, it just times out.  To fix this
  // I'll need to add an EXTENSION_LOAD_ERROR notification, which is probably
  // too much for the branch.  I'll enable this on trunk later.
  //ASSERT_FALSE(RunExtensionTest("permissions/enabled"))) << message_;
}

IN_PROC_BROWSER_TEST_F(ExperimentalApiTest, PermissionsSucceed) {
  ASSERT_TRUE(RunExtensionTest("permissions/enabled")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ExperimentalPermissionsFail) {
  // At the time this test is being created, there is no experimental
  // function that will not be graduating soon, and does not require a
  // tab id as an argument.  So, we need the tab permission to get
  // a tab id.
  ASSERT_TRUE(RunExtensionTest("permissions/experimental_disabled"))
      << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FavIconPermission) {
  ASSERT_TRUE(RunExtensionTest("permissions/favicon")) << message_;
}
<commit_msg>Disable ExtensionApiTest.FavIconPermission on Linux<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/common/chrome_switches.h"

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

// All kinds of crashes on Linux http://crbug.com/41027
#if defined(OS_LINUX)
#define FavIconPermission DISABLED_FavIconPermission
#endif

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, PermissionsFail) {
  ASSERT_TRUE(RunExtensionTest("permissions/disabled")) << message_;

  // Since the experimental APIs require a flag, this will fail even though
  // It's enabled.
  // TODO(erikkay) This test is currently broken because LoadExtension in
  // ExtensionBrowserTest doesn't actually fail, it just times out.  To fix this
  // I'll need to add an EXTENSION_LOAD_ERROR notification, which is probably
  // too much for the branch.  I'll enable this on trunk later.
  //ASSERT_FALSE(RunExtensionTest("permissions/enabled"))) << message_;
}

IN_PROC_BROWSER_TEST_F(ExperimentalApiTest, PermissionsSucceed) {
  ASSERT_TRUE(RunExtensionTest("permissions/enabled")) << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, ExperimentalPermissionsFail) {
  // At the time this test is being created, there is no experimental
  // function that will not be graduating soon, and does not require a
  // tab id as an argument.  So, we need the tab permission to get
  // a tab id.
  ASSERT_TRUE(RunExtensionTest("permissions/experimental_disabled"))
      << message_;
}

IN_PROC_BROWSER_TEST_F(ExtensionApiTest, FavIconPermission) {
  ASSERT_TRUE(RunExtensionTest("permissions/favicon")) << message_;
}
<|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/process_singleton.h"

#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <unistd.h>
#include <vector>
#include <string>

#include "base/eintr_wrapper.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/chrome_process_util.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

typedef UITest ProcessSingletonLinuxTest;

// A helper method to call ProcessSingleton::NotifyOtherProcess().
// |url| will be added to CommandLine for current process, so that it can be
// sent to browser process by ProcessSingleton::NotifyOtherProcess().
ProcessSingleton::NotifyResult NotifyOtherProcess(const std::string& url,
                                                  int timeout_ms) {
  FilePath user_data_dir;
  PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);

  // Hack: mutate the current process's command line so we don't show a dialog.
  // Note that this only works if we have no loose values on the command line,
  // but that's fine for unit tests.  In a UI test we disable error dialogs
  // when spawning Chrome, but this test hits the ProcessSingleton directly.
  CommandLine* cmd_line = CommandLine::ForCurrentProcess();
  if (!cmd_line->HasSwitch(switches::kNoProcessSingletonDialog))
    cmd_line->AppendSwitch(switches::kNoProcessSingletonDialog);

  CommandLine new_cmd_line(*cmd_line);
  new_cmd_line.AppendLooseValue(ASCIIToWide(url));

  ProcessSingleton process_singleton(user_data_dir);

  return process_singleton.NotifyOtherProcessWithTimeout(
      new_cmd_line, timeout_ms / 1000);
}

}  // namespace

// Test if the socket file and symbol link created by ProcessSingletonLinux
// are valid. When running this test, the ProcessSingleton object is already
// initiated by UITest. So we just test against this existing object.
TEST_F(ProcessSingletonLinuxTest, CheckSocketFile) {
  FilePath user_data_dir;
  FilePath socket_path;
  FilePath lock_path;
  PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);

  socket_path = user_data_dir.Append(chrome::kSingletonSocketFilename);
  lock_path = user_data_dir.Append(chrome::kSingletonLockFilename);

  struct stat statbuf;
  ASSERT_EQ(0, lstat(lock_path.value().c_str(), &statbuf));
  ASSERT_TRUE(S_ISLNK(statbuf.st_mode));
  char buf[PATH_MAX + 1];
  ssize_t len = readlink(lock_path.value().c_str(), buf, PATH_MAX);
  ASSERT_GT(len, 0);
  buf[len] = '\0';

  ASSERT_EQ(0, lstat(socket_path.value().c_str(), &statbuf));
  ASSERT_TRUE(S_ISSOCK(statbuf.st_mode));
}

#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
// The following tests in linux/view does not pass without a window manager,
// which is true in build/try bots.
// See http://crbug.com/30953.
#define NotifyOtherProcessSuccess FLAKY_NotifyOtherProcessSuccess
#define NotifyOtherProcessHostChanged FLAKY_NotifyOtherProcessHostChanged
#endif

// TODO(james.su@gmail.com): port following tests to Windows.
// Test success case of NotifyOtherProcess().
TEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessSuccess) {
  std::string url("about:blank");
  int original_tab_count = GetTabCount();

  EXPECT_EQ(ProcessSingleton::PROCESS_NOTIFIED,
            NotifyOtherProcess(url, action_timeout_ms()));
  EXPECT_EQ(original_tab_count + 1, GetTabCount());
  EXPECT_EQ(url, GetActiveTabURL().spec());
}

// Test failure case of NotifyOtherProcess().
TEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessFailure) {
  base::ProcessId pid = browser_process_id();

  ASSERT_GE(pid, 1);

  // Block the browser process, then it'll be killed by
  // ProcessSingleton::NotifyOtherProcess().
  kill(pid, SIGSTOP);

  // Wait to make sure the browser process is actually stopped.
  // It's necessary when running with valgrind.
  HANDLE_EINTR(waitpid(pid, 0, WUNTRACED));

  std::string url("about:blank");
  EXPECT_EQ(ProcessSingleton::PROCESS_NONE,
            NotifyOtherProcess(url, action_timeout_ms()));

  // Wait for a while to make sure the browser process is actually killed.
  EXPECT_FALSE(CrashAwareSleep(sleep_timeout_ms()));
}

// Test that we don't kill ourselves by accident if a lockfile with the same pid
// happens to exist.
// TODO(mattm): This doesn't really need to be a uitest.  (We don't use the
// uitest created browser process, but we do use some uitest provided stuff like
// the user_data_dir and the NotifyOtherProcess function in this file, which
// would have to be duplicated or shared if this test was moved into a
// unittest.)
TEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessNoSuicide) {
  FilePath lock_path = user_data_dir().Append(chrome::kSingletonLockFilename);
  EXPECT_EQ(0, unlink(lock_path.value().c_str()));
  std::string symlink_content = StringPrintf(
      "%s%c%u",
      net::GetHostName().c_str(),
      '-',
      base::GetCurrentProcId());
  EXPECT_EQ(0, symlink(symlink_content.c_str(), lock_path.value().c_str()));

  base::ProcessId pid = browser_process_id();

  ASSERT_GE(pid, 1);

  // Block the browser process, so that ProcessSingleton::NotifyOtherProcess()
  // will want to kill something.
  kill(pid, SIGSTOP);

  // Wait to make sure the browser process is actually stopped.
  // It's necessary when running with valgrind.
  HANDLE_EINTR(waitpid(pid, 0, WUNTRACED));

  std::string url("about:blank");
  EXPECT_EQ(ProcessSingleton::PROCESS_NONE,
            NotifyOtherProcess(url, action_timeout_ms()));
  // If we've gotten to this point without killing ourself, the test succeeded.

  // Unblock the browser process so the test actually finishes.
  kill(pid, SIGCONT);
}

// Test that we can still notify a process on the same host even after the
// hostname changed.
TEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessHostChanged) {
  FilePath lock_path = user_data_dir().Append(chrome::kSingletonLockFilename);
  EXPECT_EQ(0, unlink(lock_path.value().c_str()));
  EXPECT_EQ(0, symlink("FAKEFOOHOST-1234", lock_path.value().c_str()));

  int original_tab_count = GetTabCount();

  std::string url("about:blank");
  EXPECT_EQ(ProcessSingleton::PROCESS_NOTIFIED,
            NotifyOtherProcess(url, action_timeout_ms()));
  EXPECT_EQ(original_tab_count + 1, GetTabCount());
  EXPECT_EQ(url, GetActiveTabURL().spec());
}

// Test that we fail when lock says process is on another host and we can't
// notify it over the socket.
TEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessDifferingHost) {
  base::ProcessId pid = browser_process_id();

  ASSERT_GE(pid, 1);

  // Kill the browser process, so that it does not respond on the socket.
  kill(pid, SIGKILL);
  // Wait for a while to make sure the browser process is actually killed.
  EXPECT_FALSE(CrashAwareSleep(sleep_timeout_ms()));

  FilePath lock_path = user_data_dir().Append(chrome::kSingletonLockFilename);
  EXPECT_EQ(0, unlink(lock_path.value().c_str()));
  EXPECT_EQ(0, symlink("FAKEFOOHOST-1234", lock_path.value().c_str()));

  std::string url("about:blank");
  EXPECT_EQ(ProcessSingleton::PROFILE_IN_USE,
            NotifyOtherProcess(url, action_timeout_ms()));
}
<commit_msg>ProcessSingletonLinux.NotifyOtherProcessNoSuicide removes socket instead of sending SIGSTOP.<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/process_singleton.h"

#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <unistd.h>
#include <vector>
#include <string>

#include "base/eintr_wrapper.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_process.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/test/chrome_process_util.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

typedef UITest ProcessSingletonLinuxTest;

// A helper method to call ProcessSingleton::NotifyOtherProcess().
// |url| will be added to CommandLine for current process, so that it can be
// sent to browser process by ProcessSingleton::NotifyOtherProcess().
ProcessSingleton::NotifyResult NotifyOtherProcess(const std::string& url,
                                                  int timeout_ms) {
  FilePath user_data_dir;
  PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);

  // Hack: mutate the current process's command line so we don't show a dialog.
  // Note that this only works if we have no loose values on the command line,
  // but that's fine for unit tests.  In a UI test we disable error dialogs
  // when spawning Chrome, but this test hits the ProcessSingleton directly.
  CommandLine* cmd_line = CommandLine::ForCurrentProcess();
  if (!cmd_line->HasSwitch(switches::kNoProcessSingletonDialog))
    cmd_line->AppendSwitch(switches::kNoProcessSingletonDialog);

  CommandLine new_cmd_line(*cmd_line);
  new_cmd_line.AppendLooseValue(ASCIIToWide(url));

  ProcessSingleton process_singleton(user_data_dir);

  return process_singleton.NotifyOtherProcessWithTimeout(
      new_cmd_line, timeout_ms / 1000);
}

}  // namespace

// Test if the socket file and symbol link created by ProcessSingletonLinux
// are valid. When running this test, the ProcessSingleton object is already
// initiated by UITest. So we just test against this existing object.
TEST_F(ProcessSingletonLinuxTest, CheckSocketFile) {
  FilePath user_data_dir;
  FilePath socket_path;
  FilePath lock_path;
  PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);

  socket_path = user_data_dir.Append(chrome::kSingletonSocketFilename);
  lock_path = user_data_dir.Append(chrome::kSingletonLockFilename);

  struct stat statbuf;
  ASSERT_EQ(0, lstat(lock_path.value().c_str(), &statbuf));
  ASSERT_TRUE(S_ISLNK(statbuf.st_mode));
  char buf[PATH_MAX + 1];
  ssize_t len = readlink(lock_path.value().c_str(), buf, PATH_MAX);
  ASSERT_GT(len, 0);
  buf[len] = '\0';

  ASSERT_EQ(0, lstat(socket_path.value().c_str(), &statbuf));
  ASSERT_TRUE(S_ISSOCK(statbuf.st_mode));
}

#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
// The following tests in linux/view does not pass without a window manager,
// which is true in build/try bots.
// See http://crbug.com/30953.
#define NotifyOtherProcessSuccess FLAKY_NotifyOtherProcessSuccess
#define NotifyOtherProcessHostChanged FLAKY_NotifyOtherProcessHostChanged
#endif

// TODO(james.su@gmail.com): port following tests to Windows.
// Test success case of NotifyOtherProcess().
TEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessSuccess) {
  std::string url("about:blank");
  int original_tab_count = GetTabCount();

  EXPECT_EQ(ProcessSingleton::PROCESS_NOTIFIED,
            NotifyOtherProcess(url, action_timeout_ms()));
  EXPECT_EQ(original_tab_count + 1, GetTabCount());
  EXPECT_EQ(url, GetActiveTabURL().spec());
}

// Test failure case of NotifyOtherProcess().
TEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessFailure) {
  base::ProcessId pid = browser_process_id();

  ASSERT_GE(pid, 1);

  // Block the browser process, then it'll be killed by
  // ProcessSingleton::NotifyOtherProcess().
  kill(pid, SIGSTOP);

  // Wait to make sure the browser process is actually stopped.
  // It's necessary when running with valgrind.
  HANDLE_EINTR(waitpid(pid, 0, WUNTRACED));

  std::string url("about:blank");
  EXPECT_EQ(ProcessSingleton::PROCESS_NONE,
            NotifyOtherProcess(url, action_timeout_ms()));

  // Wait for a while to make sure the browser process is actually killed.
  EXPECT_FALSE(CrashAwareSleep(sleep_timeout_ms()));
}

// Test that we don't kill ourselves by accident if a lockfile with the same pid
// happens to exist.
// TODO(mattm): This doesn't really need to be a uitest.  (We don't use the
// uitest created browser process, but we do use some uitest provided stuff like
// the user_data_dir and the NotifyOtherProcess function in this file, which
// would have to be duplicated or shared if this test was moved into a
// unittest.)
TEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessNoSuicide) {
  FilePath lock_path = user_data_dir().Append(chrome::kSingletonLockFilename);
  FilePath socket_path = user_data_dir().Append(chrome::kSingletonSocketFilename);

  // Replace lockfile with one containing our own pid.
  EXPECT_EQ(0, unlink(lock_path.value().c_str()));
  std::string symlink_content = StringPrintf(
      "%s%c%u",
      net::GetHostName().c_str(),
      '-',
      base::GetCurrentProcId());
  EXPECT_EQ(0, symlink(symlink_content.c_str(), lock_path.value().c_str()));

  // Remove socket so that we will not be able to notify the existing browser.
  EXPECT_EQ(0, unlink(socket_path.value().c_str()));

  std::string url("about:blank");
  EXPECT_EQ(ProcessSingleton::PROCESS_NONE,
            NotifyOtherProcess(url, action_timeout_ms()));
  // If we've gotten to this point without killing ourself, the test succeeded.
}

// Test that we can still notify a process on the same host even after the
// hostname changed.
TEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessHostChanged) {
  FilePath lock_path = user_data_dir().Append(chrome::kSingletonLockFilename);
  EXPECT_EQ(0, unlink(lock_path.value().c_str()));
  EXPECT_EQ(0, symlink("FAKEFOOHOST-1234", lock_path.value().c_str()));

  int original_tab_count = GetTabCount();

  std::string url("about:blank");
  EXPECT_EQ(ProcessSingleton::PROCESS_NOTIFIED,
            NotifyOtherProcess(url, action_timeout_ms()));
  EXPECT_EQ(original_tab_count + 1, GetTabCount());
  EXPECT_EQ(url, GetActiveTabURL().spec());
}

// Test that we fail when lock says process is on another host and we can't
// notify it over the socket.
TEST_F(ProcessSingletonLinuxTest, NotifyOtherProcessDifferingHost) {
  base::ProcessId pid = browser_process_id();

  ASSERT_GE(pid, 1);

  // Kill the browser process, so that it does not respond on the socket.
  kill(pid, SIGKILL);
  // Wait for a while to make sure the browser process is actually killed.
  EXPECT_FALSE(CrashAwareSleep(sleep_timeout_ms()));

  FilePath lock_path = user_data_dir().Append(chrome::kSingletonLockFilename);
  EXPECT_EQ(0, unlink(lock_path.value().c_str()));
  EXPECT_EQ(0, symlink("FAKEFOOHOST-1234", lock_path.value().c_str()));

  std::string url("about:blank");
  EXPECT_EQ(ProcessSingleton::PROFILE_IN_USE,
            NotifyOtherProcess(url, action_timeout_ms()));
}
<|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/default_plugin/plugin_database_handler.h"

#include "libxml/parser.h"
#include "libxml/xpath.h"

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/string_split.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/default_plugin/plugin_impl.h"
#include "chrome/default_plugin/plugin_main.h"

using base::Time;
using base::TimeDelta;

PluginDatabaseHandler::PluginDatabaseHandler(
    PluginInstallerImpl& plugin_installer_instance)
    : plugin_downloads_file_(INVALID_HANDLE_VALUE),
      plugin_installer_instance_(plugin_installer_instance),
      ignore_plugin_db_data_(false) {
}

PluginDatabaseHandler::~PluginDatabaseHandler() {
  if (plugin_downloads_file_ != INVALID_HANDLE_VALUE) {
    ::CloseHandle(plugin_downloads_file_);
    plugin_downloads_file_ = INVALID_HANDLE_VALUE;
  }
}

bool PluginDatabaseHandler::DownloadPluginsFileIfNeeded(
    const std::string& plugin_finder_url) {
  DCHECK(!plugin_finder_url.empty());
  // The time in days for which the plugins list is cached.
  // TODO(iyengar) Make this configurable.
  const int kPluginsListCacheTimeInDays = 3;

  plugin_finder_url_ = plugin_finder_url;

  PathService::Get(base::DIR_MODULE, &plugins_file_);
  plugins_file_ += L"\\chrome_plugins_file.xml";

  bool initiate_download = false;
  if (!file_util::PathExists(FilePath::FromWStringHack(plugins_file_))) {
    initiate_download = true;
  } else {
    SYSTEMTIME creation_system_time = {0};
    if (!file_util::GetFileCreationLocalTime(plugins_file_,
                                             &creation_system_time)) {
      NOTREACHED();
      return false;
    }

    FILETIME creation_file_time = {0};
    ::SystemTimeToFileTime(&creation_system_time, &creation_file_time);

    FILETIME current_time = {0};
    ::GetSystemTimeAsFileTime(&current_time);

    Time file_time = Time::FromFileTime(creation_file_time);
    Time current_system_time = Time::FromFileTime(current_time);

    TimeDelta time_diff = file_time - current_system_time;
    if (time_diff.InDays() > kPluginsListCacheTimeInDays) {
      initiate_download = true;
    }
  }

  if (initiate_download) {
    DVLOG(1) << "Initiating GetURLNotify on the plugin finder URL "
             << plugin_finder_url.c_str();

    plugin_installer_instance_.set_plugin_installer_state(
        PluginListDownloadInitiated);

    DCHECK(default_plugin::g_browser->geturlnotify);
    default_plugin::g_browser->geturlnotify(
        plugin_installer_instance_.instance(), plugin_finder_url.c_str(),
        NULL, NULL);
  } else {
    DVLOG(1) << "Plugins file " << plugins_file_ << " already exists";
    plugin_downloads_file_ = ::CreateFile(plugins_file_.c_str(), GENERIC_READ,
                                          FILE_SHARE_READ, NULL, OPEN_EXISTING,
                                          FILE_ATTRIBUTE_NORMAL, NULL);
    if (plugin_downloads_file_ == INVALID_HANDLE_VALUE) {
      DVLOG(1) << "Failed to open plugins file " << plugins_file_
               << " Error " << ::GetLastError();
      NOTREACHED();
      return false;
    }
    // The URLNotify function contains all handling needed to parse the plugins
    // file and display the UI accordingly.
    plugin_installer_instance_.set_plugin_installer_state(
        PluginListDownloadInitiated);
    plugin_installer_instance_.URLNotify(plugin_finder_url.c_str(),
                                         NPRES_DONE);
  }
  return true;
}

int32 PluginDatabaseHandler::Write(NPStream* stream, int32 offset,
                                   int32 buffer_length, void* buffer) {
  if (ignore_plugin_db_data_) {
    return buffer_length;
  }

  if (plugin_downloads_file_ == INVALID_HANDLE_VALUE) {
    DVLOG(1) << "About to create plugins file " << plugins_file_;
    plugin_downloads_file_ = CreateFile(plugins_file_.c_str(),
                                        GENERIC_READ | GENERIC_WRITE,
                                        FILE_SHARE_READ, NULL, CREATE_ALWAYS,
                                        FILE_ATTRIBUTE_NORMAL, NULL);
    if (plugin_downloads_file_ == INVALID_HANDLE_VALUE) {
      unsigned long error = ::GetLastError();
      if (error == ERROR_SHARING_VIOLATION) {
        // File may have been downloaded by another plugin instance on this
        // page.
        plugin_downloads_file_ = ::CreateFile(
            plugins_file_.c_str(), GENERIC_READ,
            FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL, NULL);
        if (plugin_downloads_file_ != INVALID_HANDLE_VALUE) {
          ignore_plugin_db_data_ = true;
          return buffer_length;
        }
      }

      DVLOG(1) << "Failed to create plugins file " << plugins_file_
               << " Error " << ::GetLastError();
      NOTREACHED();
      return 0;
    }
  }

  DWORD bytes_written = 0;
  if (0 == lstrcmpiA(stream->url, plugin_finder_url_.c_str())) {
    DCHECK(plugin_downloads_file_ != INVALID_HANDLE_VALUE);

    WriteFile(plugin_downloads_file_, buffer, buffer_length, &bytes_written,
              NULL);
    DCHECK_EQ(buffer_length, static_cast<int32>(bytes_written));
  }
  return bytes_written;
}

bool PluginDatabaseHandler::ParsePluginList() {
  if (plugin_downloads_file_ == INVALID_HANDLE_VALUE) {
    DLOG(WARNING) << "Invalid plugins file";
    NOTREACHED();
    return false;
  }

  bool parse_result = false;

  std::string plugins_file = WideToUTF8(plugins_file_.c_str());
  xmlDocPtr plugin_downloads_doc = xmlParseFile(plugins_file.c_str());
  if (plugin_downloads_doc == NULL) {
    DLOG(WARNING) << "Failed to parse plugins file " << plugins_file.c_str();
    return parse_result;
  }

  xmlXPathContextPtr context = NULL;
  xmlXPathObjectPtr plugins_result = NULL;

  do {
    context = xmlXPathNewContext(plugin_downloads_doc);
    if (context == NULL) {
      DLOG(WARNING) << "Failed to retrieve XPath context";
      NOTREACHED();
      parse_result = false;
      break;
    }

    plugins_result =
        xmlXPathEvalExpression(reinterpret_cast<const xmlChar*>("//plugin"),
                               context);
    if ((plugins_result == NULL) ||
         xmlXPathNodeSetIsEmpty(plugins_result->nodesetval)) {
      DLOG(WARNING) << "Failed to find XPath //plugin";
      NOTREACHED();
      parse_result = false;
      break;
    }

    xmlNodeSetPtr plugin_list = plugins_result->nodesetval;
    for (int plugin_index = 0; plugin_index < plugin_list->nodeNr;
         ++plugin_index) {
      PluginDetail plugin_detail;
      if (!ReadPluginInfo(plugin_list->nodeTab[plugin_index]->children,
                          &plugin_detail)) {
        DLOG(ERROR) << "Failed to read plugin details at index "
                    << plugin_index;
        break;
      }
      downloaded_plugins_list_.push_back(plugin_detail);
    }
    if (downloaded_plugins_list_.size())
      parse_result = true;
  } while (0);

  xmlXPathFreeContext(context);
  xmlXPathFreeObject(plugins_result);
  xmlFreeDoc(plugin_downloads_doc);
  xmlCleanupParser();
  DVLOG(1) << "Parse plugins file result " << parse_result;
  return parse_result;
}

bool PluginDatabaseHandler::GetPluginDetailsForMimeType(
    const char* mime_type, const char* language,
    std::string* download_url, std::wstring* plugin_name,
    bool* download_url_for_display) {
  if (!mime_type || !language || !download_url || !plugin_name ||
      !download_url_for_display) {
    NOTREACHED();
    return false;
  }

  PluginList::iterator plugin_index;
  for (plugin_index = downloaded_plugins_list_.begin();
       plugin_index != downloaded_plugins_list_.end();
       ++plugin_index) {
    PluginDetail& current_plugin = *plugin_index;

    std::vector<std::string>::iterator mime_type_index;
    for (mime_type_index = current_plugin.mime_types.begin();
         mime_type_index != current_plugin.mime_types.end();
         ++mime_type_index) {
      if ((0 == lstrcmpiA(mime_type, (*mime_type_index).c_str())) &&
          (0 == lstrcmpiA(language, current_plugin.language.c_str()))) {
        *download_url = current_plugin.download_url;
        *plugin_name = current_plugin.display_name;
        *download_url_for_display = current_plugin.download_url_for_display;
        return true;
      }
    }
  }
  return false;
}

void PluginDatabaseHandler::Close(bool delete_file) {
  if (plugin_downloads_file_ != INVALID_HANDLE_VALUE) {
    ::CloseHandle(plugin_downloads_file_);
    plugin_downloads_file_ = INVALID_HANDLE_VALUE;
    if (delete_file) {
      ::DeleteFile(plugins_file_.c_str());
      plugins_file_.clear();
    }
  }
}

bool PluginDatabaseHandler::ReadPluginInfo(_xmlNode* plugin_node,
                                           PluginDetail* plugin_detail) {
  static const char kMimeTypeSeparator = ';';

  if (!plugin_node) {
    NOTREACHED();
    return false;
  }

  _xmlNode* plugin_mime_type = plugin_node->next;
  if ((plugin_mime_type == NULL) ||
      (plugin_mime_type->next == NULL)) {
    DLOG(WARNING) << "Failed to find mime type node in file";
    NOTREACHED();
    return false;
  }
  _xmlNode* plugin_mime_type_vals = plugin_mime_type->children;
  if (plugin_mime_type_vals == NULL) {
    DLOG(WARNING) << "Invalid mime type";
    NOTREACHED();
    return false;
  }
  // Skip the first child of each node as it is the text element
  // for that node.
  _xmlNode* plugin_lang_node = plugin_mime_type->next->next;
  if ((plugin_lang_node == NULL) ||
      (plugin_lang_node->next == NULL)) {
    DLOG(WARNING) << "Failed to find plugin language node";
    NOTREACHED();
    return false;
  }
  _xmlNode* plugin_lang_val = plugin_lang_node->children;
  if (plugin_lang_val == NULL) {
    DLOG(WARNING) << "Invalid plugin language";
    NOTREACHED();
    return false;
  }
  _xmlNode* plugin_name_node = plugin_lang_node->next->next;
  if ((plugin_name_node == NULL) ||
      (plugin_name_node->next == NULL)) {
    DLOG(WARNING) << "Failed to find plugin name node";
    NOTREACHED();
    return false;
  }
  _xmlNode* plugin_name_val = plugin_name_node->children;
  if (plugin_name_val == NULL) {
    DLOG(WARNING) << "Invalid plugin name";
    NOTREACHED();
    return false;
  }
  _xmlNode* plugin_download_url_node = plugin_name_node->next->next;
  if (plugin_download_url_node == NULL) {
    DLOG(WARNING) << "Failed to find plugin URL node";
    NOTREACHED();
    return false;
  }
  _xmlNode* plugin_download_url_val = plugin_download_url_node->children;
  if (plugin_download_url_val == NULL) {
    DLOG(WARNING) << "Invalid plugin URL";
    NOTREACHED();
    return false;
  }

  // Look for the DisplayUrl node. By default every URL is treated as an
  // executable URL.
  plugin_detail->download_url_for_display = false;

  _xmlNode* plugin_download_url_for_display_node =
      plugin_download_url_node->next->next;
  if (plugin_download_url_for_display_node) {
    _xmlNode* url_for_display_val =
        plugin_download_url_for_display_node->children;
    if (url_for_display_val) {
      int url_for_display = 0;
      base::StringToInt(
          reinterpret_cast<const char*>(url_for_display_val->content),
          &url_for_display);
      if (url_for_display != 0)
        plugin_detail->download_url_for_display = true;
    }
  }

  plugin_detail->display_name =
      UTF8ToWide(reinterpret_cast<const char*>(plugin_name_val->content));
  plugin_detail->download_url =
      reinterpret_cast<const char*>(plugin_download_url_val->content);

  base::SplitString(
      reinterpret_cast<const char*>(plugin_mime_type_vals->content),
      kMimeTypeSeparator, &plugin_detail->mime_types);

  plugin_detail->language =
      reinterpret_cast<const char*>(plugin_lang_val->content);

  return true;
}
<commit_msg>default plugin: Remove dcheck when unable to open the database file.<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/default_plugin/plugin_database_handler.h"

#include "libxml/parser.h"
#include "libxml/xpath.h"

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/string_number_conversions.h"
#include "base/string_split.h"
#include "base/string_util.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/default_plugin/plugin_impl.h"
#include "chrome/default_plugin/plugin_main.h"

using base::Time;
using base::TimeDelta;

PluginDatabaseHandler::PluginDatabaseHandler(
    PluginInstallerImpl& plugin_installer_instance)
    : plugin_downloads_file_(INVALID_HANDLE_VALUE),
      plugin_installer_instance_(plugin_installer_instance),
      ignore_plugin_db_data_(false) {
}

PluginDatabaseHandler::~PluginDatabaseHandler() {
  if (plugin_downloads_file_ != INVALID_HANDLE_VALUE) {
    ::CloseHandle(plugin_downloads_file_);
    plugin_downloads_file_ = INVALID_HANDLE_VALUE;
  }
}

bool PluginDatabaseHandler::DownloadPluginsFileIfNeeded(
    const std::string& plugin_finder_url) {
  DCHECK(!plugin_finder_url.empty());
  // The time in days for which the plugins list is cached.
  // TODO(iyengar) Make this configurable.
  const int kPluginsListCacheTimeInDays = 3;

  plugin_finder_url_ = plugin_finder_url;

  PathService::Get(base::DIR_MODULE, &plugins_file_);
  plugins_file_ += L"\\chrome_plugins_file.xml";

  bool initiate_download = false;
  if (!file_util::PathExists(FilePath::FromWStringHack(plugins_file_))) {
    initiate_download = true;
  } else {
    SYSTEMTIME creation_system_time = {0};
    if (!file_util::GetFileCreationLocalTime(plugins_file_,
                                             &creation_system_time)) {
      NOTREACHED();
      return false;
    }

    FILETIME creation_file_time = {0};
    ::SystemTimeToFileTime(&creation_system_time, &creation_file_time);

    FILETIME current_time = {0};
    ::GetSystemTimeAsFileTime(&current_time);

    Time file_time = Time::FromFileTime(creation_file_time);
    Time current_system_time = Time::FromFileTime(current_time);

    TimeDelta time_diff = file_time - current_system_time;
    if (time_diff.InDays() > kPluginsListCacheTimeInDays) {
      initiate_download = true;
    }
  }

  if (initiate_download) {
    DVLOG(1) << "Initiating GetURLNotify on the plugin finder URL "
             << plugin_finder_url.c_str();

    plugin_installer_instance_.set_plugin_installer_state(
        PluginListDownloadInitiated);

    DCHECK(default_plugin::g_browser->geturlnotify);
    default_plugin::g_browser->geturlnotify(
        plugin_installer_instance_.instance(), plugin_finder_url.c_str(),
        NULL, NULL);
  } else {
    DVLOG(1) << "Plugins file " << plugins_file_ << " already exists";
    plugin_downloads_file_ = ::CreateFile(plugins_file_.c_str(), GENERIC_READ,
                                          FILE_SHARE_READ, NULL, OPEN_EXISTING,
                                          FILE_ATTRIBUTE_NORMAL, NULL);
    if (plugin_downloads_file_ == INVALID_HANDLE_VALUE) {
      DVLOG(1) << "Failed to open plugins file " << plugins_file_
               << " Error " << ::GetLastError();
      NOTREACHED();
      return false;
    }
    // The URLNotify function contains all handling needed to parse the plugins
    // file and display the UI accordingly.
    plugin_installer_instance_.set_plugin_installer_state(
        PluginListDownloadInitiated);
    plugin_installer_instance_.URLNotify(plugin_finder_url.c_str(),
                                         NPRES_DONE);
  }
  return true;
}

int32 PluginDatabaseHandler::Write(NPStream* stream, int32 offset,
                                   int32 buffer_length, void* buffer) {
  if (ignore_plugin_db_data_) {
    return buffer_length;
  }

  if (plugin_downloads_file_ == INVALID_HANDLE_VALUE) {
    DVLOG(1) << "About to create plugins file " << plugins_file_;
    plugin_downloads_file_ = CreateFile(plugins_file_.c_str(),
                                        GENERIC_READ | GENERIC_WRITE,
                                        FILE_SHARE_READ, NULL, CREATE_ALWAYS,
                                        FILE_ATTRIBUTE_NORMAL, NULL);
    if (plugin_downloads_file_ == INVALID_HANDLE_VALUE) {
      unsigned long error = ::GetLastError();
      if (error == ERROR_SHARING_VIOLATION) {
        // File may have been downloaded by another plugin instance on this
        // page.
        plugin_downloads_file_ = ::CreateFile(
            plugins_file_.c_str(), GENERIC_READ,
            FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL, NULL);
        if (plugin_downloads_file_ != INVALID_HANDLE_VALUE) {
          ignore_plugin_db_data_ = true;
          return buffer_length;
        }
      }

      DLOG(ERROR) << "Failed to create plugins file " << plugins_file_
                  << " Error " << ::GetLastError();
      return 0;
    }
  }

  DWORD bytes_written = 0;
  if (0 == lstrcmpiA(stream->url, plugin_finder_url_.c_str())) {
    DCHECK(plugin_downloads_file_ != INVALID_HANDLE_VALUE);

    WriteFile(plugin_downloads_file_, buffer, buffer_length, &bytes_written,
              NULL);
    DCHECK_EQ(buffer_length, static_cast<int32>(bytes_written));
  }
  return bytes_written;
}

bool PluginDatabaseHandler::ParsePluginList() {
  if (plugin_downloads_file_ == INVALID_HANDLE_VALUE) {
    DLOG(WARNING) << "Invalid plugins file";
    NOTREACHED();
    return false;
  }

  bool parse_result = false;

  std::string plugins_file = WideToUTF8(plugins_file_.c_str());
  xmlDocPtr plugin_downloads_doc = xmlParseFile(plugins_file.c_str());
  if (plugin_downloads_doc == NULL) {
    DLOG(WARNING) << "Failed to parse plugins file " << plugins_file.c_str();
    return parse_result;
  }

  xmlXPathContextPtr context = NULL;
  xmlXPathObjectPtr plugins_result = NULL;

  do {
    context = xmlXPathNewContext(plugin_downloads_doc);
    if (context == NULL) {
      DLOG(WARNING) << "Failed to retrieve XPath context";
      NOTREACHED();
      parse_result = false;
      break;
    }

    plugins_result =
        xmlXPathEvalExpression(reinterpret_cast<const xmlChar*>("//plugin"),
                               context);
    if ((plugins_result == NULL) ||
         xmlXPathNodeSetIsEmpty(plugins_result->nodesetval)) {
      DLOG(WARNING) << "Failed to find XPath //plugin";
      NOTREACHED();
      parse_result = false;
      break;
    }

    xmlNodeSetPtr plugin_list = plugins_result->nodesetval;
    for (int plugin_index = 0; plugin_index < plugin_list->nodeNr;
         ++plugin_index) {
      PluginDetail plugin_detail;
      if (!ReadPluginInfo(plugin_list->nodeTab[plugin_index]->children,
                          &plugin_detail)) {
        DLOG(ERROR) << "Failed to read plugin details at index "
                    << plugin_index;
        break;
      }
      downloaded_plugins_list_.push_back(plugin_detail);
    }
    if (downloaded_plugins_list_.size())
      parse_result = true;
  } while (0);

  xmlXPathFreeContext(context);
  xmlXPathFreeObject(plugins_result);
  xmlFreeDoc(plugin_downloads_doc);
  xmlCleanupParser();
  DVLOG(1) << "Parse plugins file result " << parse_result;
  return parse_result;
}

bool PluginDatabaseHandler::GetPluginDetailsForMimeType(
    const char* mime_type, const char* language,
    std::string* download_url, std::wstring* plugin_name,
    bool* download_url_for_display) {
  if (!mime_type || !language || !download_url || !plugin_name ||
      !download_url_for_display) {
    NOTREACHED();
    return false;
  }

  PluginList::iterator plugin_index;
  for (plugin_index = downloaded_plugins_list_.begin();
       plugin_index != downloaded_plugins_list_.end();
       ++plugin_index) {
    PluginDetail& current_plugin = *plugin_index;

    std::vector<std::string>::iterator mime_type_index;
    for (mime_type_index = current_plugin.mime_types.begin();
         mime_type_index != current_plugin.mime_types.end();
         ++mime_type_index) {
      if ((0 == lstrcmpiA(mime_type, (*mime_type_index).c_str())) &&
          (0 == lstrcmpiA(language, current_plugin.language.c_str()))) {
        *download_url = current_plugin.download_url;
        *plugin_name = current_plugin.display_name;
        *download_url_for_display = current_plugin.download_url_for_display;
        return true;
      }
    }
  }
  return false;
}

void PluginDatabaseHandler::Close(bool delete_file) {
  if (plugin_downloads_file_ != INVALID_HANDLE_VALUE) {
    ::CloseHandle(plugin_downloads_file_);
    plugin_downloads_file_ = INVALID_HANDLE_VALUE;
    if (delete_file) {
      ::DeleteFile(plugins_file_.c_str());
      plugins_file_.clear();
    }
  }
}

bool PluginDatabaseHandler::ReadPluginInfo(_xmlNode* plugin_node,
                                           PluginDetail* plugin_detail) {
  static const char kMimeTypeSeparator = ';';

  if (!plugin_node) {
    NOTREACHED();
    return false;
  }

  _xmlNode* plugin_mime_type = plugin_node->next;
  if ((plugin_mime_type == NULL) ||
      (plugin_mime_type->next == NULL)) {
    DLOG(WARNING) << "Failed to find mime type node in file";
    NOTREACHED();
    return false;
  }
  _xmlNode* plugin_mime_type_vals = plugin_mime_type->children;
  if (plugin_mime_type_vals == NULL) {
    DLOG(WARNING) << "Invalid mime type";
    NOTREACHED();
    return false;
  }
  // Skip the first child of each node as it is the text element
  // for that node.
  _xmlNode* plugin_lang_node = plugin_mime_type->next->next;
  if ((plugin_lang_node == NULL) ||
      (plugin_lang_node->next == NULL)) {
    DLOG(WARNING) << "Failed to find plugin language node";
    NOTREACHED();
    return false;
  }
  _xmlNode* plugin_lang_val = plugin_lang_node->children;
  if (plugin_lang_val == NULL) {
    DLOG(WARNING) << "Invalid plugin language";
    NOTREACHED();
    return false;
  }
  _xmlNode* plugin_name_node = plugin_lang_node->next->next;
  if ((plugin_name_node == NULL) ||
      (plugin_name_node->next == NULL)) {
    DLOG(WARNING) << "Failed to find plugin name node";
    NOTREACHED();
    return false;
  }
  _xmlNode* plugin_name_val = plugin_name_node->children;
  if (plugin_name_val == NULL) {
    DLOG(WARNING) << "Invalid plugin name";
    NOTREACHED();
    return false;
  }
  _xmlNode* plugin_download_url_node = plugin_name_node->next->next;
  if (plugin_download_url_node == NULL) {
    DLOG(WARNING) << "Failed to find plugin URL node";
    NOTREACHED();
    return false;
  }
  _xmlNode* plugin_download_url_val = plugin_download_url_node->children;
  if (plugin_download_url_val == NULL) {
    DLOG(WARNING) << "Invalid plugin URL";
    NOTREACHED();
    return false;
  }

  // Look for the DisplayUrl node. By default every URL is treated as an
  // executable URL.
  plugin_detail->download_url_for_display = false;

  _xmlNode* plugin_download_url_for_display_node =
      plugin_download_url_node->next->next;
  if (plugin_download_url_for_display_node) {
    _xmlNode* url_for_display_val =
        plugin_download_url_for_display_node->children;
    if (url_for_display_val) {
      int url_for_display = 0;
      base::StringToInt(
          reinterpret_cast<const char*>(url_for_display_val->content),
          &url_for_display);
      if (url_for_display != 0)
        plugin_detail->download_url_for_display = true;
    }
  }

  plugin_detail->display_name =
      UTF8ToWide(reinterpret_cast<const char*>(plugin_name_val->content));
  plugin_detail->download_url =
      reinterpret_cast<const char*>(plugin_download_url_val->content);

  base::SplitString(
      reinterpret_cast<const char*>(plugin_mime_type_vals->content),
      kMimeTypeSeparator, &plugin_detail->mime_types);

  plugin_detail->language =
      reinterpret_cast<const char*>(plugin_lang_val->content);

  return true;
}
<|endoftext|>


<commit_before>// @(#)root/eve7:$Id$
// Authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007

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

//______________________________________________________________________________
// TTreeTools
//
// Collection of classes for TTree interaction.

#include <ROOT/REveTreeTools.hxx>

#include "TTree.h"
#include "TTreeFormula.h"

using namespace ROOT::Experimental;

/** \class REveSelectorToEventList
\ingroup REve
TSelector that stores entry numbers of matching TTree entries into
an event-list.
*/

////////////////////////////////////////////////////////////////////////////////
/// Constructor.

REveSelectorToEventList::REveSelectorToEventList(TEventList* evl, const char* sel) :
   TSelectorDraw(), fEvList(evl)
{
   fInputList.Add(new TNamed("varexp", ""));
   fInputList.Add(new TNamed("selection", sel));
   SetInputList(&fInputList);
}

////////////////////////////////////////////////////////////////////////////////
/// Process entry.

Bool_t REveSelectorToEventList::Process(Long64_t entry)
{
   if(GetSelect()->EvalInstance(0) != 0)
      fEvList->Enter(entry);
   return kTRUE;
}

/** \class REvePointSelectorConsumer
\ingroup REve
REvePointSelectorConsumer is a virtual base for classes that can be
filled from TTree data via the REvePointSelector class.
*/

/** \class REvePointSelector
\ingroup REve
REvePointSelector is a sub-class of TSelectorDraw for direct
extraction of point-like data from a Tree.
*/

////////////////////////////////////////////////////////////////////////////////
/// Constructor.

REvePointSelector::REvePointSelector(TTree* t,
                                     REvePointSelectorConsumer* c,
                                     const char* vexp, const char* sel) :
   TSelectorDraw(),

   fSelectTree  (t),
   fConsumer  (c),
   fVarexp    (vexp),
   fSelection (sel),
   fSubIdExp  (),
   fSubIdNum  (0)
{
   SetInputList(&fInputList);
}

////////////////////////////////////////////////////////////////////////////////
/// Process the tree, select points matching 'selection'.

Long64_t REvePointSelector::Select(const char* selection)
{
   TString var(fVarexp);
   if (fSubIdExp.IsNull()) {
      fSubIdNum = 0;
   } else {
      fSubIdNum = fSubIdExp.CountChar(':') + 1;
      var += ":" + fSubIdExp;
   }

   TString sel;
   if (selection)
      sel = selection;
   else
      sel = fSelection;

   fInputList.Delete();
   fInputList.Add(new TNamed("varexp",    var.Data()));
   fInputList.Add(new TNamed("selection", sel.Data()));

   if (fConsumer)
      fConsumer->InitFill(fSubIdNum);

   if (fSelectTree)
      fSelectTree->Process(this, "goff");

   return fSelectedRows;
}

////////////////////////////////////////////////////////////////////////////////
/// Process tree 't', select points matching 'selection'.

Long64_t REvePointSelector::Select(TTree *t, const char *selection)
{
   fSelectTree = t;
   return Select(selection);
}

////////////////////////////////////////////////////////////////////////////////
/// Callback from tree-player after a chunk of data has been processed.
/// This is forwarded to the current point-consumer.

void REvePointSelector::TakeAction()
{
   fSelectedRows += fNfill;
   // printf("REvePointSelector::TakeAction nfill=%d, nall=%lld\n", fNfill, fSelectedRows);
   if (fConsumer) {
      fConsumer->TakeAction(this);
   }
}
<commit_msg>[reve] set ownership flag for fInputList<commit_after>// @(#)root/eve7:$Id$
// Authors: Matevz Tadel & Alja Mrak-Tadel: 2006, 2007

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

//______________________________________________________________________________
// TTreeTools
//
// Collection of classes for TTree interaction.

#include <ROOT/REveTreeTools.hxx>

#include "TTree.h"
#include "TTreeFormula.h"

using namespace ROOT::Experimental;

/** \class REveSelectorToEventList
\ingroup REve
TSelector that stores entry numbers of matching TTree entries into
an event-list.
*/

////////////////////////////////////////////////////////////////////////////////
/// Constructor.

REveSelectorToEventList::REveSelectorToEventList(TEventList* evl, const char* sel) :
   TSelectorDraw(), fEvList(evl)
{
   fInputList.SetOwner(kTRUE);
   fInputList.Add(new TNamed("varexp", ""));
   fInputList.Add(new TNamed("selection", sel));
   SetInputList(&fInputList);
}

////////////////////////////////////////////////////////////////////////////////
/// Process entry.

Bool_t REveSelectorToEventList::Process(Long64_t entry)
{
   if(GetSelect()->EvalInstance(0) != 0)
      fEvList->Enter(entry);
   return kTRUE;
}

/** \class REvePointSelectorConsumer
\ingroup REve
REvePointSelectorConsumer is a virtual base for classes that can be
filled from TTree data via the REvePointSelector class.
*/

/** \class REvePointSelector
\ingroup REve
REvePointSelector is a sub-class of TSelectorDraw for direct
extraction of point-like data from a Tree.
*/

////////////////////////////////////////////////////////////////////////////////
/// Constructor.

REvePointSelector::REvePointSelector(TTree* t,
                                     REvePointSelectorConsumer* c,
                                     const char* vexp, const char* sel) :
   TSelectorDraw(),

   fSelectTree  (t),
   fConsumer  (c),
   fVarexp    (vexp),
   fSelection (sel),
   fSubIdExp  (),
   fSubIdNum  (0)
{
   fInputList.SetOwner(kTRUE);
   SetInputList(&fInputList);
}

////////////////////////////////////////////////////////////////////////////////
/// Process the tree, select points matching 'selection'.

Long64_t REvePointSelector::Select(const char* selection)
{
   TString var(fVarexp);
   if (fSubIdExp.IsNull()) {
      fSubIdNum = 0;
   } else {
      fSubIdNum = fSubIdExp.CountChar(':') + 1;
      var += ":" + fSubIdExp;
   }

   TString sel;
   if (selection)
      sel = selection;
   else
      sel = fSelection;

   fInputList.Delete();
   fInputList.Add(new TNamed("varexp",    var.Data()));
   fInputList.Add(new TNamed("selection", sel.Data()));

   if (fConsumer)
      fConsumer->InitFill(fSubIdNum);

   if (fSelectTree)
      fSelectTree->Process(this, "goff");

   return fSelectedRows;
}

////////////////////////////////////////////////////////////////////////////////
/// Process tree 't', select points matching 'selection'.

Long64_t REvePointSelector::Select(TTree *t, const char *selection)
{
   fSelectTree = t;
   return Select(selection);
}

////////////////////////////////////////////////////////////////////////////////
/// Callback from tree-player after a chunk of data has been processed.
/// This is forwarded to the current point-consumer.

void REvePointSelector::TakeAction()
{
   fSelectedRows += fNfill;
   // printf("REvePointSelector::TakeAction nfill=%d, nall=%lld\n", fNfill, fSelectedRows);
   if (fConsumer) {
      fConsumer->TakeAction(this);
   }
}
<|endoftext|>


<commit_before><commit_msg>extract content type from classid<commit_after><|endoftext|>


<commit_before><commit_msg>Add support for configure changes using vfw32.<commit_after><|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (C) 2013 PX4 Development Team. All rights reserved.
 *   Author: Pavel Kirienko <pavel.kirienko@gmail.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. Neither the name PX4 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 <ch.h>
#include <hal.h>
#include <assert.h>
#include <errno.h>
#include <math.h>
#include <unistd.h>
#include <config/config.h>
#include <sys.h>
#include <led.h>
#include <console.h>
#include <watchdog.h>
#include <motor/motor.h>
#include <uavcan_node/uavcan_node.hpp>

namespace
{

int init()
{
	int res = 0;

	led_init();
	led_set_rgb(0.05, 0.05, 0.05);

	/*
	 * Config
	 */
	res = config_init();
	if (res) {
		return res;
	}

	/*
	 * Safety
	 */
	watchdog_init();

	/*
	 * UAVCAN node
	 */
	res = uavcan_node::init();
	if (res) {
		return res;
	}

	/*
	 * Motor control
	 */
	::usleep(10000);
	res = motor_init();
	if (res) {
		return res;
	}

	::usleep(10000);
	res = motor_test_hardware();
	if (res) {
		return res;
	}
	lowsyslog("Power stage OK\n");

	if (motor_test_motor()) {
		lowsyslog("Motor is not connected or damaged\n");
	} else {
		lowsyslog("Motor OK\n");
	}
	return 0;
}

__attribute__((noreturn))
void die(int status)
{
	uavcan_node::set_node_status_critical();
	::usleep(100000);
	lowsyslog("Init failed (%i)\n", status);
	// Really there is nothing left to do; just sit there and beep sadly:
	while (1) {
		motor_beep(100, 400);
		led_set_rgb(1, 0, 0);
		sleep(3);
	}
}

void do_startup_beep()
{
	motor_beep(1000, 100);
	::usleep(200 * 1000);
	motor_beep(1000, 100);
}

void print_banner()
{
	lowsyslog("\n\n\n");
	lowsyslog("\x1b\x5b\x48");      // Home sweet home
	lowsyslog("\x1b\x5b\x32\x4a");  // Clear
	lowsyslog("PX4ESC\n");
}

}

void application_halt_hook(void)
{
	motor_emergency();
	led_set_rgb(1, 0, 0);
}

// Debugging code, will be removed later
extern "C" uint64_t motor_timer_hnsec();

int main()
{
	halInit();
	chSysInit();
	sdStart(&STDOUT_SD, NULL);

	usleep(300000);
	print_banner();

	const int init_status = init();

	console_init();

	if (init_status) {
		die(init_status);
	}

	do_startup_beep();

	motor_confirm_initialization();

	chThdSetPriority(LOWPRIO);

	uavcan_node::set_node_status_ok();

#if !NDEBUG
	// Debugging code, will be removed later
	uint64_t prev_ts = motor_timer_hnsec();
#endif

	while (1) {
#if !NDEBUG
		// Timer debugging
		const uint64_t ts = motor_timer_hnsec();
		assert(ts > prev_ts);
		prev_ts = ts;
#endif

		chThdYield();
	}

	return 0;
}
<commit_msg>Removed debug code from main<commit_after>/****************************************************************************
 *
 *   Copyright (C) 2013 PX4 Development Team. All rights reserved.
 *   Author: Pavel Kirienko <pavel.kirienko@gmail.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. Neither the name PX4 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 <ch.h>
#include <hal.h>
#include <assert.h>
#include <errno.h>
#include <math.h>
#include <unistd.h>
#include <config/config.h>
#include <sys.h>
#include <led.h>
#include <console.h>
#include <watchdog.h>
#include <motor/motor.h>
#include <uavcan_node/uavcan_node.hpp>

namespace
{

int init()
{
	int res = 0;

	led_init();
	led_set_rgb(0.05, 0.05, 0.05);

	/*
	 * Config
	 */
	res = config_init();
	if (res) {
		return res;
	}

	/*
	 * Safety
	 */
	watchdog_init();

	/*
	 * UAVCAN node
	 */
	res = uavcan_node::init();
	if (res) {
		return res;
	}

	/*
	 * Motor control
	 */
	::usleep(10000);
	res = motor_init();
	if (res) {
		return res;
	}

	::usleep(10000);
	res = motor_test_hardware();
	if (res) {
		return res;
	}
	lowsyslog("Power stage OK\n");

	if (motor_test_motor()) {
		lowsyslog("Motor is not connected or damaged\n");
	} else {
		lowsyslog("Motor OK\n");
	}
	return 0;
}

__attribute__((noreturn))
void die(int status)
{
	uavcan_node::set_node_status_critical();
	::usleep(100000);
	lowsyslog("Init failed (%i)\n", status);
	// Really there is nothing left to do; just sit there and beep sadly:
	while (1) {
		motor_beep(100, 400);
		led_set_rgb(1, 0, 0);
		sleep(3);
	}
}

void do_startup_beep()
{
	motor_beep(1000, 100);
	::usleep(200 * 1000);
	motor_beep(1000, 100);
}

void print_banner()
{
	lowsyslog("\n\n\n");
	lowsyslog("\x1b\x5b\x48");      // Home sweet home
	lowsyslog("\x1b\x5b\x32\x4a");  // Clear
	lowsyslog("PX4ESC\n");
}

}

void application_halt_hook(void)
{
	motor_emergency();
	led_set_rgb(1, 0, 0);
}

int main()
{
	halInit();
	chSysInit();
	sdStart(&STDOUT_SD, NULL);

	usleep(300000);
	print_banner();

	const int init_status = init();

	console_init();

	if (init_status) {
		die(init_status);
	}

	do_startup_beep();

	motor_confirm_initialization();

	chThdSetPriority(LOWPRIO);

	uavcan_node::set_node_status_ok();

	while (1) {
		::sleep(1);
	}

	return 0;
}
<|endoftext|>


<commit_before>/* -*- mode: c++; c-basic-offset:4 -*-
    crypto/gui/decryptverifyresultwidget.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2007 Klarälvdalens Datakonsult AB

    Kleopatra is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    Kleopatra is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include <config-kleopatra.h>

#include "decryptverifyresultwidget.h"

#include <models/keycache.h>
#include <models/predicates.h>

#include <gpgme++/decryptionresult.h>
#include <gpgme++/verificationresult.h>
#include <gpgme++/error.h>
#include <gpgme++/key.h>

#include <KLocale>
#include <KIconLoader>

#include <QLayout>
#include <QLabel>
#include <QColor>
#include <QString>
#include <QTextDocument> // for Qt::escape

using namespace Kleo;
using namespace Kleo::Crypto::Gui;
using namespace GpgME;
using namespace boost;

static
// dup of same function in decryptverifycommand.cpp
const GpgME::Key & keyForSignature( const Signature & sig, const std::vector<Key> & keys ) {
    if ( const char * const fpr = sig.fingerprint() ) {
        const std::vector<Key>::const_iterator it
            = std::lower_bound( keys.begin(), keys.end(), fpr, _detail::ByFingerprint<std::less>() );
        if ( it != keys.end() && _detail::ByFingerprint<std::equal_to>()( *it, fpr ) )
            return *it;
    }
    static const Key null;
    return null;
}

static QString image( const char * img ) {
    // ### escape?
    return "iconPath( img, KIconLoader::Small ) + "\"/>";
}

static QColor color( const DecryptionResult & dr, const VerificationResult & vr ) {
    if ( !dr.isNull() && dr.error() )
        return Qt::red;
    if ( !vr.isNull() && vr.error() )
        return Qt::red;
    return Qt::gray;
}

static QColor color( const Signature & sig ) {
    if ( sig.summary() & GpgME::Signature::Red )
        return Qt::red;
    if ( sig.summary() & GpgME::Signature::Green )
        return Qt::green;
    return Qt::yellow;
}

DecryptVerifyResultWidget::DecryptVerifyResultWidget( QWidget * parent )
    : ResultDisplayWidget( parent ),
      m_box( new QVBoxLayout( resultWidget() ) )
{
    m_box->setMargin( 0 );
}

DecryptVerifyResultWidget::~DecryptVerifyResultWidget() {}

void DecryptVerifyResultWidget::setResult( const DecryptionResult & decryptionResult, const VerificationResult & verificationResult ) {

    while ( QLayoutItem * child = m_box->takeAt(0) )
        delete child;

    const QString decryptionResultString = formatDecryptionResult( decryptionResult, PublicKeyCache::instance()->findRecipients( decryptionResult ) );

    m_box->addWidget( new QLabel( decryptionResult.error() || decryptionResult.error().isCanceled()
                                  ? "<qt>" + decryptionResultString + "</qt>"
                                  : "<qt>" + decryptionResultString + "
" + formatVerificationResult( verificationResult ) + "</qt>", resultWidget() ) );
    setColor( color( decryptionResult, verificationResult ) );

    const std::vector<Signature> sigs = verificationResult.signatures();
    const std::vector<Key> signers = PublicKeyCache::instance()->findSigners( verificationResult );
    Q_FOREACH ( const Signature & sig, sigs )
        m_box->addWidget( formatSignatureWidget( new QLabel( resultWidget() ), sig, keyForSignature( sig, signers ) ) );
    m_box->addStretch( 1 );

    showResultWidget();
}

QString DecryptVerifyResultWidget::formatDecryptionResult( const DecryptionResult & res, const std::vector<Key> & recipients ) {

    if ( res.isNull() )
        return QString();

    const Error err = res.error();

    QString html;

    // Icon:
    html += image( err ? "dialog-error" : "dialog-ok" );

    // Summary:
    html += "";
    if ( err.isCanceled() )
        html += i18n("Decryption canceled.");
    else if ( err )
        html += i18n( "Decryption failed: %1.", Qt::escape( QString::fromLocal8Bit( err.asString() ) ) );
    else
        html += i18n("Decryption succeeded." );
    html += "";

    if ( err.isCanceled() || err || !res.numRecipients() )
        return html;

    // Details (if any):
    html += "
";

    if ( recipients.empty() )
        return html + "" + i18np( "One unknown recipient.", "%n unknown recipients.", res.numRecipients() ) + "";

    html += i18np( "Recipients:", "Recipients:", res.numRecipients() );
    if ( res.numRecipients() == 1 )
        return html + renderKey( recipients.front() );

    html += "
";
    Q_FOREACH( const Key & key, recipients )
        html += "
" + renderKey( key ) + "
";
    if ( recipients.size() < res.numRecipients() )
        html += "
" + i18np( "One unknown recipient", "%n unknown recipients",
                                   res.numRecipients() - recipients.size() ) + "
";

    return html + "
";
}

QString DecryptVerifyResultWidget::formatVerificationResult( const VerificationResult & res ) const {
    if ( res.isNull() )
        return QString();

    const Error err = res.error();

    QString html;

    // Icon:
    html += image( err ? "dialog-error" : "dialog-ok" );

    // Summary:
    html += "";
    if ( err.isCanceled() )
        html += i18n("Verification canceled.");
    else if ( err )
        html += i18n( "Verification failed: %1.", Qt::escape( QString::fromLocal8Bit( err.asString() ) ) );
    else
        html += i18n("Verification succeeded.");
    html += "";

    return html;
}

QString DecryptVerifyResultWidget::formatSignature( const Signature & sig, const Key & key ) {
    if ( sig.isNull() )
        return QString();

    const bool red   = (sig.summary() & Signature::Red);
    //const bool green = (sig.summary() & Signature::Green);
    const bool valid = (sig.summary() & Signature::Valid);

    if ( red )
        if ( key.isNull() )
            if ( const char * fpr = sig.fingerprint() )
                return i18n("Bad signature by unknown key %1: %2", QString::fromLatin1( fpr ), QString::fromLocal8Bit( sig.status().asString() ) );
            else
                return i18n("Bad signature by an unknown key: %1", QString::fromLocal8Bit( sig.status().asString() ) );
        else
            return i18n("Bad signature by %1: %2", renderKey( key ), QString::fromLocal8Bit( sig.status().asString() ) );

    else if ( valid )
        if ( key.isNull() )
            if ( const char * fpr = sig.fingerprint() )
                return i18n("Good signature by unknown key %1.", QString::fromLatin1( fpr ) );
            else
                return i18n("Good signature by an unknown key.");
        else
            return i18n("Good signature by %1.", renderKey( key ) );

    else
        if ( key.isNull() )
            if ( const char * fpr = sig.fingerprint() )
                return i18n("Invalid signature by unknown key %1: %2", QString::fromLatin1( fpr ), QString::fromLocal8Bit( sig.status().asString() ) );
            else
                return i18n("Invalid signature by an unknown key: %1", QString::fromLocal8Bit( sig.status().asString() ) );
        else
            return i18n("Invalid signature by %1: %2", renderKey( key ), QString::fromLocal8Bit( sig.status().asString() ) );
}

static const char * icon( const Signature & sig ) {
    if ( sig.summary() & GpgME::Signature::Green )
        return "dialog-ok";
    if ( sig.summary() & GpgME::Signature::Red )
        return "dialog-error";
    return "dialog-warning";
}

QLabel * DecryptVerifyResultWidget::formatSignatureWidget( QLabel * label, const Signature & sig, const Key & key ) {
    if ( !label )
        return label;
    connect( label, SIGNAL(linkActivated(QString)), this, SLOT(keyLinkActivated(QString)) );

    label->setStyleSheet( styleSheet( color( sig ) ) );
    label->setText( image( ::icon( sig ) ) + "" + formatSignature( sig, key ) + "" );

    return label;
}

#include "moc_decryptverifyresultwidget.cpp"
<commit_msg>Fix i18np calls: s/%n/%1<commit_after>/* -*- mode: c++; c-basic-offset:4 -*-
    crypto/gui/decryptverifyresultwidget.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2007 Klarälvdalens Datakonsult AB

    Kleopatra is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    Kleopatra is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include <config-kleopatra.h>

#include "decryptverifyresultwidget.h"

#include <models/keycache.h>
#include <models/predicates.h>

#include <gpgme++/decryptionresult.h>
#include <gpgme++/verificationresult.h>
#include <gpgme++/error.h>
#include <gpgme++/key.h>

#include <KLocale>
#include <KIconLoader>

#include <QLayout>
#include <QLabel>
#include <QColor>
#include <QString>
#include <QTextDocument> // for Qt::escape

using namespace Kleo;
using namespace Kleo::Crypto::Gui;
using namespace GpgME;
using namespace boost;

static
// dup of same function in decryptverifycommand.cpp
const GpgME::Key & keyForSignature( const Signature & sig, const std::vector<Key> & keys ) {
    if ( const char * const fpr = sig.fingerprint() ) {
        const std::vector<Key>::const_iterator it
            = std::lower_bound( keys.begin(), keys.end(), fpr, _detail::ByFingerprint<std::less>() );
        if ( it != keys.end() && _detail::ByFingerprint<std::equal_to>()( *it, fpr ) )
            return *it;
    }
    static const Key null;
    return null;
}

static QString image( const char * img ) {
    // ### escape?
    return "iconPath( img, KIconLoader::Small ) + "\"/>";
}

static QColor color( const DecryptionResult & dr, const VerificationResult & vr ) {
    if ( !dr.isNull() && dr.error() )
        return Qt::red;
    if ( !vr.isNull() && vr.error() )
        return Qt::red;
    return Qt::gray;
}

static QColor color( const Signature & sig ) {
    if ( sig.summary() & GpgME::Signature::Red )
        return Qt::red;
    if ( sig.summary() & GpgME::Signature::Green )
        return Qt::green;
    return Qt::yellow;
}

DecryptVerifyResultWidget::DecryptVerifyResultWidget( QWidget * parent )
    : ResultDisplayWidget( parent ),
      m_box( new QVBoxLayout( resultWidget() ) )
{
    m_box->setMargin( 0 );
}

DecryptVerifyResultWidget::~DecryptVerifyResultWidget() {}

void DecryptVerifyResultWidget::setResult( const DecryptionResult & decryptionResult, const VerificationResult & verificationResult ) {

    while ( QLayoutItem * child = m_box->takeAt(0) )
        delete child;

    const QString decryptionResultString = formatDecryptionResult( decryptionResult, PublicKeyCache::instance()->findRecipients( decryptionResult ) );

    m_box->addWidget( new QLabel( decryptionResult.error() || decryptionResult.error().isCanceled()
                                  ? "<qt>" + decryptionResultString + "</qt>"
                                  : "<qt>" + decryptionResultString + "
" + formatVerificationResult( verificationResult ) + "</qt>", resultWidget() ) );
    setColor( color( decryptionResult, verificationResult ) );

    const std::vector<Signature> sigs = verificationResult.signatures();
    const std::vector<Key> signers = PublicKeyCache::instance()->findSigners( verificationResult );
    Q_FOREACH ( const Signature & sig, sigs )
        m_box->addWidget( formatSignatureWidget( new QLabel( resultWidget() ), sig, keyForSignature( sig, signers ) ) );
    m_box->addStretch( 1 );

    showResultWidget();
}

QString DecryptVerifyResultWidget::formatDecryptionResult( const DecryptionResult & res, const std::vector<Key> & recipients ) {

    if ( res.isNull() )
        return QString();

    const Error err = res.error();

    QString html;

    // Icon:
    html += image( err ? "dialog-error" : "dialog-ok" );

    // Summary:
    html += "";
    if ( err.isCanceled() )
        html += i18n("Decryption canceled.");
    else if ( err )
        html += i18n( "Decryption failed: %1.", Qt::escape( QString::fromLocal8Bit( err.asString() ) ) );
    else
        html += i18n("Decryption succeeded." );
    html += "";

    if ( err.isCanceled() || err || !res.numRecipients() )
        return html;

    // Details (if any):
    html += "
";

    if ( recipients.empty() )
        return html + "" + i18np( "One unknown recipient.", "%1 unknown recipients.", res.numRecipients() ) + "";

    html += i18np( "Recipients:", "Recipients:", res.numRecipients() );
    if ( res.numRecipients() == 1 )
        return html + renderKey( recipients.front() );

    html += "
";
    Q_FOREACH( const Key & key, recipients )
        html += "
" + renderKey( key ) + "
";
    if ( recipients.size() < res.numRecipients() )
        html += "
" + i18np( "One unknown recipient", "%1 unknown recipients",
                                   res.numRecipients() - recipients.size() ) + "
";

    return html + "
";
}

QString DecryptVerifyResultWidget::formatVerificationResult( const VerificationResult & res ) const {
    if ( res.isNull() )
        return QString();

    const Error err = res.error();

    QString html;

    // Icon:
    html += image( err ? "dialog-error" : "dialog-ok" );

    // Summary:
    html += "";
    if ( err.isCanceled() )
        html += i18n("Verification canceled.");
    else if ( err )
        html += i18n( "Verification failed: %1.", Qt::escape( QString::fromLocal8Bit( err.asString() ) ) );
    else
        html += i18n("Verification succeeded.");
    html += "";

    return html;
}

QString DecryptVerifyResultWidget::formatSignature( const Signature & sig, const Key & key ) {
    if ( sig.isNull() )
        return QString();

    const bool red   = (sig.summary() & Signature::Red);
    //const bool green = (sig.summary() & Signature::Green);
    const bool valid = (sig.summary() & Signature::Valid);

    if ( red )
        if ( key.isNull() )
            if ( const char * fpr = sig.fingerprint() )
                return i18n("Bad signature by unknown key %1: %2", QString::fromLatin1( fpr ), QString::fromLocal8Bit( sig.status().asString() ) );
            else
                return i18n("Bad signature by an unknown key: %1", QString::fromLocal8Bit( sig.status().asString() ) );
        else
            return i18n("Bad signature by %1: %2", renderKey( key ), QString::fromLocal8Bit( sig.status().asString() ) );

    else if ( valid )
        if ( key.isNull() )
            if ( const char * fpr = sig.fingerprint() )
                return i18n("Good signature by unknown key %1.", QString::fromLatin1( fpr ) );
            else
                return i18n("Good signature by an unknown key.");
        else
            return i18n("Good signature by %1.", renderKey( key ) );

    else
        if ( key.isNull() )
            if ( const char * fpr = sig.fingerprint() )
                return i18n("Invalid signature by unknown key %1: %2", QString::fromLatin1( fpr ), QString::fromLocal8Bit( sig.status().asString() ) );
            else
                return i18n("Invalid signature by an unknown key: %1", QString::fromLocal8Bit( sig.status().asString() ) );
        else
            return i18n("Invalid signature by %1: %2", renderKey( key ), QString::fromLocal8Bit( sig.status().asString() ) );
}

static const char * icon( const Signature & sig ) {
    if ( sig.summary() & GpgME::Signature::Green )
        return "dialog-ok";
    if ( sig.summary() & GpgME::Signature::Red )
        return "dialog-error";
    return "dialog-warning";
}

QLabel * DecryptVerifyResultWidget::formatSignatureWidget( QLabel * label, const Signature & sig, const Key & key ) {
    if ( !label )
        return label;
    connect( label, SIGNAL(linkActivated(QString)), this, SLOT(keyLinkActivated(QString)) );

    label->setStyleSheet( styleSheet( color( sig ) ) );
    label->setText( image( ::icon( sig ) ) + "" + formatSignature( sig, key ) + "" );

    return label;
}

#include "moc_decryptverifyresultwidget.cpp"
<|endoftext|>


<commit_before>#include "test_helpers.hxx"

using namespace PGSTD;
using namespace pqxx;

namespace
{
binarystring make_binarystring(transaction_base &T, string content)
{
  return binarystring(T.exec("SELECT " + T.quote_raw(content))[0][0]);
}

void test_binarystring(transaction_base &T)
{
  binarystring b = make_binarystring(T, "");
  PQXX_CHECK(b.empty(), "Empty binarystring is not empty.");
  PQXX_CHECK_EQUAL(b.str(), "", "Empty binarystring doesn't work.");
  PQXX_CHECK_EQUAL(b.size(), 0u, "Empty binarystring has nonzero size.");
  PQXX_CHECK_EQUAL(b.length(), 0u, "Length/size mismatch.");
  PQXX_CHECK(b.begin() == b.end(), "Empty binarystring iterates.");
  PQXX_CHECK(b.rbegin() == b.rend(), "Empty binarystring reverse-iterates.");
  PQXX_CHECK_THROWS(b.at(0), out_of_range, "Empty binarystring accepts at().");

  b = make_binarystring(T, "z");
  PQXX_CHECK_EQUAL(b.str(), "z", "Basic nonempty binarystring is broken.");
  PQXX_CHECK(!b.empty(), "Nonempty binarystring is empty.");
  PQXX_CHECK_EQUAL(b.size(), 1u, "Bad binarystring size.");
  PQXX_CHECK_EQUAL(b.length(), 1u, "Length/size mismatch.");
  PQXX_CHECK(b.begin() != b.end(), "Nonempty binarystring does not iterate.");
  PQXX_CHECK(
	b.rbegin() != b.rend(),
	 "Nonempty binarystring does not reverse-iterate.");
  PQXX_CHECK(b.begin() + 1 == b.end(), "Bad iteration.");
  PQXX_CHECK(b.rbegin() + 1 == b.rend(), "Bad reverse iteration.");
  PQXX_CHECK(b.front() == 'z', "Unexpected front().");
  PQXX_CHECK(b.back() == 'z', "Unexpected back().");
  PQXX_CHECK(b.at(0) == 'z', "Unexpected data at index 0.");
  PQXX_CHECK_THROWS(b.at(1), out_of_range, "Failed to catch range error.");

  const string simple("ab");
  b = make_binarystring(T, simple);
  PQXX_CHECK_EQUAL(
	b.str(),
	simple,
	"Binary (un)escaping went wrong somewhere.");
  PQXX_CHECK_EQUAL(b.size(), simple.size(), "Escaping confuses length.");

  //const string bytes("\x01\x23\x23\xa1\x2b\x0c\xff");

  const string bytes_escaped(T.esc_raw(bytes));
  for (string::size_type i=0; i<bytes_escaped.size(); ++i)
  {
    const unsigned char uc = static_cast<unsigned char>(bytes_escaped[i]);
    PQXX_CHECK(uc <= 127, "Non-ASCII byte in escaped string.");
  }

  PQXX_CHECK_EQUAL(
	T.quote_raw(
		reinterpret_cast<const unsigned char *>(bytes.c_str()),
		 bytes.size()),
	T.quote(b),
	"quote_raw is broken");
  PQXX_CHECK_EQUAL(T.quote(b), T.quote_raw(bytes), "Binary quoting is broken.");
  PQXX_CHECK_EQUAL(
	binarystring(T.exec("SELECT " + T.quote(b))[0][0]).str(),
	bytes,
	"Binary string is not idempotent.");

  const string nully("a\0b", 3);
  b = make_binarystring(T, nully);
  PQXX_CHECK_EQUAL(b.str(), nully, "Nul byte broke binary (un)escaping.");
  PQXX_CHECK_EQUAL(b.size(), 3u, "Nul byte broke binarystring size.");

  b = make_binarystring(T, "foo");
  PQXX_CHECK_EQUAL(string(b.get(), 3), "foo", "get() appears broken.");

  binarystring b1 = make_binarystring(T, "1"), b2 = make_binarystring(T, "2");
  PQXX_CHECK_NOT_EQUAL(b1.get(), b2.get(), "Madness rules.");
  PQXX_CHECK_NOT_EQUAL(b1.str(), b2.str(), "Logic has no more meaning.");
  b1.swap(b2);
  PQXX_CHECK_NOT_EQUAL(b1.str(), b2.str(), "swap() equalized binarystrings.");
  PQXX_CHECK_NOT_EQUAL(b1.str(), "1", "swap() did not happen.");
  PQXX_CHECK_EQUAL(b1.str(), "2", "swap() is broken.");
  PQXX_CHECK_EQUAL(b2.str(), "1", "swap() went insane.");

  b = make_binarystring(T, "bar");
  b.swap(b);
  PQXX_CHECK_EQUAL(b.str(), "bar", "Self-swap confuses binarystring.");

  b = make_binarystring(T, "\\x");
  PQXX_CHECK_EQUAL(b.str(), "\\x", "Hex-escape header confused (un)escaping.");
}
} // namespace

PQXX_REGISTER_TEST(test_binarystring)
<commit_msg>Fixup to test change.<commit_after>#include "test_helpers.hxx"

using namespace PGSTD;
using namespace pqxx;

namespace
{
binarystring make_binarystring(transaction_base &T, string content)
{
  return binarystring(T.exec("SELECT " + T.quote_raw(content))[0][0]);
}

void test_binarystring(transaction_base &T)
{
  binarystring b = make_binarystring(T, "");
  PQXX_CHECK(b.empty(), "Empty binarystring is not empty.");
  PQXX_CHECK_EQUAL(b.str(), "", "Empty binarystring doesn't work.");
  PQXX_CHECK_EQUAL(b.size(), 0u, "Empty binarystring has nonzero size.");
  PQXX_CHECK_EQUAL(b.length(), 0u, "Length/size mismatch.");
  PQXX_CHECK(b.begin() == b.end(), "Empty binarystring iterates.");
  PQXX_CHECK(b.rbegin() == b.rend(), "Empty binarystring reverse-iterates.");
  PQXX_CHECK_THROWS(b.at(0), out_of_range, "Empty binarystring accepts at().");

  b = make_binarystring(T, "z");
  PQXX_CHECK_EQUAL(b.str(), "z", "Basic nonempty binarystring is broken.");
  PQXX_CHECK(!b.empty(), "Nonempty binarystring is empty.");
  PQXX_CHECK_EQUAL(b.size(), 1u, "Bad binarystring size.");
  PQXX_CHECK_EQUAL(b.length(), 1u, "Length/size mismatch.");
  PQXX_CHECK(b.begin() != b.end(), "Nonempty binarystring does not iterate.");
  PQXX_CHECK(
	b.rbegin() != b.rend(),
	 "Nonempty binarystring does not reverse-iterate.");
  PQXX_CHECK(b.begin() + 1 == b.end(), "Bad iteration.");
  PQXX_CHECK(b.rbegin() + 1 == b.rend(), "Bad reverse iteration.");
  PQXX_CHECK(b.front() == 'z', "Unexpected front().");
  PQXX_CHECK(b.back() == 'z', "Unexpected back().");
  PQXX_CHECK(b.at(0) == 'z', "Unexpected data at index 0.");
  PQXX_CHECK_THROWS(b.at(1), out_of_range, "Failed to catch range error.");

  const string simple("ab");
  b = make_binarystring(T, simple);
  PQXX_CHECK_EQUAL(
	b.str(),
	simple,
	"Binary (un)escaping went wrong somewhere.");
  PQXX_CHECK_EQUAL(b.size(), simple.size(), "Escaping confuses length.");

  const string simple_escaped(T.esc_raw(simple));
  for (string::size_type i=0; i<simple_escaped.size(); ++i)
  {
    const unsigned char uc = static_cast<unsigned char>(simple_escaped[i]);
    PQXX_CHECK(uc <= 127, "Non-ASCII byte in escaped string.");
  }

  PQXX_CHECK_EQUAL(
	T.quote_raw(
		reinterpret_cast<const unsigned char *>(simple.c_str()),
		 simple.size()),
	T.quote(b),
	"quote_raw is broken");
  PQXX_CHECK_EQUAL(
	T.quote(b),
	T.quote_raw(simple),
	"Binary quoting is broken.");
  PQXX_CHECK_EQUAL(
	binarystring(T.exec("SELECT " + T.quote(b))[0][0]).str(),
	simple,
	"Binary string is not idempotent.");

  const string bytes("\x01\x23\x23\xa1\x2b\x0c\xff");
  b = make_binarystring(T, bytes);
  PQXX_CHECK_EQUAL( b.str(), bytes, "Binary data breaks (un)escaping.");

  const string nully("a\0b", 3);
  b = make_binarystring(T, nully);
  PQXX_CHECK_EQUAL(b.str(), nully, "Nul byte broke binary (un)escaping.");
  PQXX_CHECK_EQUAL(b.size(), 3u, "Nul byte broke binarystring size.");

  b = make_binarystring(T, "foo");
  PQXX_CHECK_EQUAL(string(b.get(), 3), "foo", "get() appears broken.");

  binarystring b1 = make_binarystring(T, "1"), b2 = make_binarystring(T, "2");
  PQXX_CHECK_NOT_EQUAL(b1.get(), b2.get(), "Madness rules.");
  PQXX_CHECK_NOT_EQUAL(b1.str(), b2.str(), "Logic has no more meaning.");
  b1.swap(b2);
  PQXX_CHECK_NOT_EQUAL(b1.str(), b2.str(), "swap() equalized binarystrings.");
  PQXX_CHECK_NOT_EQUAL(b1.str(), "1", "swap() did not happen.");
  PQXX_CHECK_EQUAL(b1.str(), "2", "swap() is broken.");
  PQXX_CHECK_EQUAL(b2.str(), "1", "swap() went insane.");

  b = make_binarystring(T, "bar");
  b.swap(b);
  PQXX_CHECK_EQUAL(b.str(), "bar", "Self-swap confuses binarystring.");

  b = make_binarystring(T, "\\x");
  PQXX_CHECK_EQUAL(b.str(), "\\x", "Hex-escape header confused (un)escaping.");
}
} // namespace

PQXX_REGISTER_TEST(test_binarystring)
<|endoftext|>


<commit_before><commit_msg>fix combobox index -- after All and None item<commit_after><|endoftext|>


<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright (c) 2010, Rice University
*  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 Rice University 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.
*********************************************************************/

/* Author: Ioan Sucan */

#include "ompl/base/StateSampler.h"
#include "ompl/base/StateSpace.h"

void ompl::base::CompoundStateSampler::addSampler(const StateSamplerPtr &sampler, double weightImportance)
{
    samplers_.push_back(sampler);
    weightImportance_.push_back(weightImportance);
    samplerCount_ = samplers_.size();
}

void ompl::base::CompoundStateSampler::sampleUniform(State *state)
{
    State **comps = state->as<CompoundState>()->components;
    for (unsigned int i = 0 ; i < samplerCount_ ; ++i)
        samplers_[i]->sampleUniform(comps[i]);
}

void ompl::base::CompoundStateSampler::sampleUniformNear(State *state, const State *near, const double distance)
{
    State **comps = state->as<CompoundState>()->components;
    State **nearComps = near->as<CompoundState>()->components;
    for (unsigned int i = 0 ; i < samplerCount_ ; ++i)
        samplers_[i]->sampleUniformNear(comps[i], nearComps[i], weightImportance_[i] * distance);
}

void ompl::base::CompoundStateSampler::sampleGaussian(State *state, const State *mean, const double stdDev)
{
    State **comps = state->as<CompoundState>()->components;
    State **meanComps = mean->as<CompoundState>()->components;
    for (unsigned int i = 0 ; i < samplerCount_ ; ++i)
        samplers_[i]->sampleGaussian(comps[i], meanComps[i], stdDev);
}
<commit_msg>fixing a bug on how weights are used in sampling nearby states<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright (c) 2010, Rice University
*  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 Rice University 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.
*********************************************************************/

/* Author: Ioan Sucan */

#include "ompl/base/StateSampler.h"
#include "ompl/base/StateSpace.h"

void ompl::base::CompoundStateSampler::addSampler(const StateSamplerPtr &sampler, double weightImportance)
{
    samplers_.push_back(sampler);
    weightImportance_.push_back(weightImportance);
    samplerCount_ = samplers_.size();
}

void ompl::base::CompoundStateSampler::sampleUniform(State *state)
{
    State **comps = state->as<CompoundState>()->components;
    for (unsigned int i = 0 ; i < samplerCount_ ; ++i)
        samplers_[i]->sampleUniform(comps[i]);
}

void ompl::base::CompoundStateSampler::sampleUniformNear(State *state, const State *near, const double distance)
{
    State **comps = state->as<CompoundState>()->components;
    State **nearComps = near->as<CompoundState>()->components;
    for (unsigned int i = 0 ; i < samplerCount_ ; ++i)
        if (weightImportance_[i] > std::numeric_limits<double>::epsilon())
            samplers_[i]->sampleUniformNear(comps[i], nearComps[i], distance / weightImportance_[i]);
        else
            samplers_[i]->sampleUniform(comps[i]);
}

void ompl::base::CompoundStateSampler::sampleGaussian(State *state, const State *mean, const double stdDev)
{
    State **comps = state->as<CompoundState>()->components;
    State **meanComps = mean->as<CompoundState>()->components;
    for (unsigned int i = 0 ; i < samplerCount_ ; ++i)
        samplers_[i]->sampleGaussian(comps[i], meanComps[i], stdDev);
}
<|endoftext|>