<commit_before>#include "RaZ/Audio/Sound.hpp"
#include "RaZ/Utils/FilePath.hpp"
#include "RaZ/Utils/StrUtils.hpp"

#include <AL/al.h>
#include <iostream>

namespace Raz {

namespace {

constexpr const char* recoverAlErrorStr(int errorCode) {
  switch (errorCode) {
    case AL_INVALID_NAME:      return "Invalid name";
    case AL_INVALID_ENUM:      return "Invalid enum";
    case AL_INVALID_VALUE:     return "Invalid value";
    case AL_INVALID_OPERATION: return "Invalid operation";
    case AL_OUT_OF_MEMORY:     return "Out of memory";
    case AL_NO_ERROR:          return "No error";
    default:                   return "Unknown error";
  }
}

inline void checkError(const std::string_view& errorMsg) {
  const int errorCode = alGetError();

  if (errorCode != AL_NO_ERROR)
    std::cerr << "[OpenAL] Error: " << errorMsg << " (" << recoverAlErrorStr(errorCode) << ")." << std::endl;
}

} // namespace

Sound::Sound() {
  alGetError(); // Flushing errors

  alGenBuffers(1, &m_buffer);
  checkError("Failed to create a sound buffer");

  alGenSources(1, &m_source);
  checkError("Failed to create a sound source");
}

Sound::Sound(Sound&& sound) noexcept
  : m_buffer{ std::exchange(sound.m_buffer, std::numeric_limits<unsigned int>::max()) },
    m_source{ std::exchange(sound.m_source, std::numeric_limits<unsigned int>::max()) },
    m_format{ sound.m_format },
    m_frequency{ sound.m_frequency },
    m_data{ std::move(sound.m_data) } {}

void Sound::load(const FilePath& filePath) {
  std::ifstream file(filePath, std::ios_base::in | std::ios_base::binary);

  if (!file)
    throw std::invalid_argument("Error: Couldn't open the sound file '" + filePath + "'");

  m_data.clear();

  const std::string format = StrUtils::toLowercaseCopy(filePath.recoverExtension().toUtf8());

  if (format == "wav")
    loadWav(file);
  else
    throw std::invalid_argument("Error: '" + format + "' sound format is not supported");

  alSourcei(m_source, AL_BUFFER, 0); // Detaching the previous buffer (if any) from the source

  alBufferData(m_buffer, static_cast<int>(m_format), m_data.data(), static_cast<int>(m_data.size()), m_frequency);
  checkError("Failed to send sound information to the buffer");

  alSourcei(m_source, AL_BUFFER, static_cast<int>(m_buffer));
  checkError("Failed to map the sound buffer to the source");
}

void Sound::setPitch(float pitch) const noexcept {
  assert("Error: The source's pitch must be positive." && pitch >= 0.f);

  alSourcef(m_source, AL_PITCH, pitch);
  checkError("Failed to set the source's pitch");
}

void Sound::setGain(float gain) const noexcept {
  assert("Error: The source's gain must be positive." && gain >= 0.f);

  alSourcef(m_source, AL_GAIN, gain);
  checkError("Failed to set the source's gain");
}

void Sound::setPosition(const Vec3f& position) const noexcept {
  alSource3f(m_source, AL_POSITION, position[0], position[1], position[2]);
  checkError("Failed to set the source's position");
}

void Sound::setVelocity(const Vec3f& velocity) const noexcept {
  alSource3f(m_source, AL_VELOCITY, velocity[0], velocity[1], velocity[2]);
  checkError("Failed to set the source's velocity");
}

void Sound::repeat(bool repeat) const noexcept {
  alSourcei(m_source, AL_LOOPING, repeat);
  checkError("Failed to change the sound's repeat state");
}

void Sound::play() const noexcept {
  if (isPlaying())
    return;

  alSourcePlay(m_source);
  checkError("Failed to play/resume the sound");
}

void Sound::pause() const noexcept {
  alSourcePause(m_source);
  checkError("Failed to pause the sound");
}

void Sound::stop() const noexcept {
  alSourceStop(m_source);
  checkError("Failed to stop the sound");
}

void Sound::rewind() const noexcept {
  alSourceRewind(m_source);
  checkError("Failed to rewind the sound");
}

SoundState Sound::recoverState() const noexcept {
  int state {};
  alGetSourcei(m_source, AL_SOURCE_STATE, &state);

  return static_cast<SoundState>(state);
}

float Sound::recoverElapsedTime() const noexcept {
  float seconds {};
  alGetSourcef(m_source, AL_SEC_OFFSET, &seconds);

  return (seconds / 60.f);
}

Sound& Sound::operator=(Sound&& sound) noexcept {
  std::swap(m_buffer, sound.m_buffer);
  std::swap(m_source, sound.m_source);

  m_format    = sound.m_format;
  m_frequency = sound.m_frequency;
  m_data      = std::move(sound.m_data);

  return *this;
}

Sound::~Sound() {
  if (m_source != std::numeric_limits<unsigned int>::max()) {
    alDeleteSources(1, &m_source);
    checkError("Failed to delete source");
  }

  if (m_buffer != std::numeric_limits<unsigned int>::max()) {
    alDeleteBuffers(1, &m_buffer);
    checkError("Failed to delete buffer");
  }
}

} // namespace Raz
<commit_msg>[Audio/Sound] Importing a sound file also stops the current one<commit_after>#include "RaZ/Audio/Sound.hpp"
#include "RaZ/Utils/FilePath.hpp"
#include "RaZ/Utils/StrUtils.hpp"

#include <AL/al.h>
#include <iostream>

namespace Raz {

namespace {

constexpr const char* recoverAlErrorStr(int errorCode) {
  switch (errorCode) {
    case AL_INVALID_NAME:      return "Invalid name";
    case AL_INVALID_ENUM:      return "Invalid enum";
    case AL_INVALID_VALUE:     return "Invalid value";
    case AL_INVALID_OPERATION: return "Invalid operation";
    case AL_OUT_OF_MEMORY:     return "Out of memory";
    case AL_NO_ERROR:          return "No error";
    default:                   return "Unknown error";
  }
}

inline void checkError(const std::string_view& errorMsg) {
  const int errorCode = alGetError();

  if (errorCode != AL_NO_ERROR)
    std::cerr << "[OpenAL] Error: " << errorMsg << " (" << recoverAlErrorStr(errorCode) << ")." << std::endl;
}

} // namespace

Sound::Sound() {
  alGetError(); // Flushing errors

  alGenBuffers(1, &m_buffer);
  checkError("Failed to create a sound buffer");

  alGenSources(1, &m_source);
  checkError("Failed to create a sound source");
}

Sound::Sound(Sound&& sound) noexcept
  : m_buffer{ std::exchange(sound.m_buffer, std::numeric_limits<unsigned int>::max()) },
    m_source{ std::exchange(sound.m_source, std::numeric_limits<unsigned int>::max()) },
    m_format{ sound.m_format },
    m_frequency{ sound.m_frequency },
    m_data{ std::move(sound.m_data) } {}

void Sound::load(const FilePath& filePath) {
  std::ifstream file(filePath, std::ios_base::in | std::ios_base::binary);

  if (!file)
    throw std::invalid_argument("Error: Couldn't open the sound file '" + filePath + "'");

  m_data.clear();

  const std::string format = StrUtils::toLowercaseCopy(filePath.recoverExtension().toUtf8());

  if (format == "wav")
    loadWav(file);
  else
    throw std::invalid_argument("Error: '" + format + "' sound format is not supported");

  stop(); // Making sure the sound isn't paused or currently playing
  alSourcei(m_source, AL_BUFFER, 0); // Detaching the previous buffer (if any) from the source

  alBufferData(m_buffer, static_cast<int>(m_format), m_data.data(), static_cast<int>(m_data.size()), m_frequency);
  checkError("Failed to send sound information to the buffer");

  alSourcei(m_source, AL_BUFFER, static_cast<int>(m_buffer));
  checkError("Failed to map the sound buffer to the source");
}

void Sound::setPitch(float pitch) const noexcept {
  assert("Error: The source's pitch must be positive." && pitch >= 0.f);

  alSourcef(m_source, AL_PITCH, pitch);
  checkError("Failed to set the source's pitch");
}

void Sound::setGain(float gain) const noexcept {
  assert("Error: The source's gain must be positive." && gain >= 0.f);

  alSourcef(m_source, AL_GAIN, gain);
  checkError("Failed to set the source's gain");
}

void Sound::setPosition(const Vec3f& position) const noexcept {
  alSource3f(m_source, AL_POSITION, position[0], position[1], position[2]);
  checkError("Failed to set the source's position");
}

void Sound::setVelocity(const Vec3f& velocity) const noexcept {
  alSource3f(m_source, AL_VELOCITY, velocity[0], velocity[1], velocity[2]);
  checkError("Failed to set the source's velocity");
}

void Sound::repeat(bool repeat) const noexcept {
  alSourcei(m_source, AL_LOOPING, repeat);
  checkError("Failed to change the sound's repeat state");
}

void Sound::play() const noexcept {
  if (isPlaying())
    return;

  alSourcePlay(m_source);
  checkError("Failed to play/resume the sound");
}

void Sound::pause() const noexcept {
  alSourcePause(m_source);
  checkError("Failed to pause the sound");
}

void Sound::stop() const noexcept {
  alSourceStop(m_source);
  checkError("Failed to stop the sound");
}

void Sound::rewind() const noexcept {
  alSourceRewind(m_source);
  checkError("Failed to rewind the sound");
}

SoundState Sound::recoverState() const noexcept {
  int state {};
  alGetSourcei(m_source, AL_SOURCE_STATE, &state);

  return static_cast<SoundState>(state);
}

float Sound::recoverElapsedTime() const noexcept {
  float seconds {};
  alGetSourcef(m_source, AL_SEC_OFFSET, &seconds);

  return (seconds / 60.f);
}

Sound& Sound::operator=(Sound&& sound) noexcept {
  std::swap(m_buffer, sound.m_buffer);
  std::swap(m_source, sound.m_source);

  m_format    = sound.m_format;
  m_frequency = sound.m_frequency;
  m_data      = std::move(sound.m_data);

  return *this;
}

Sound::~Sound() {
  if (m_source != std::numeric_limits<unsigned int>::max()) {
    alDeleteSources(1, &m_source);
    checkError("Failed to delete source");
  }

  if (m_buffer != std::numeric_limits<unsigned int>::max()) {
    alDeleteBuffers(1, &m_buffer);
    checkError("Failed to delete buffer");
  }
}

} // namespace Raz
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 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.
//
// This file defines the methods useful for uninstalling Chrome.

#include "chrome/installer/setup/uninstall.h"

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/registry.h"
#include "base/string_util.h"
#include "chrome/app/result_codes.h"
#include "chrome/installer/setup/setup.h"
#include "chrome/installer/setup/setup_constants.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/helper.h"
#include "chrome/installer/util/logging_installer.h"
#include "chrome/installer/util/shell_util.h"
#include "chrome/installer/util/version.h"

namespace {

// This functions checks for any Chrome instances that are
// running and first asks them to close politely by sending a Windows message.
// If there is an error while sending message or if there are still Chrome
// procesess active after the message has been sent, this function will try
// to kill them.
void CloseAllChromeProcesses() {
  for (int j = 0; j < 4; ++j) {
    std::wstring wnd_class(L"Chrome_WidgetWin_");
    wnd_class.append(IntToWString(j));
    HWND window = FindWindowEx(NULL, NULL, wnd_class.c_str(), NULL);
    while (window) {
      HWND tmpWnd = window;
      window = FindWindowEx(NULL, window, wnd_class.c_str(), NULL);
      if (!SendMessageTimeout(tmpWnd, WM_CLOSE, 0, 0, SMTO_BLOCK, 3000, NULL) &&
          (GetLastError() == ERROR_TIMEOUT)) {
        base::CleanupProcesses(installer_util::kChromeExe, 0,
                               ResultCodes::HUNG, NULL);
        return;
      }
    }
  }

  // If asking politely didn't work, wait for 15 seconds and then kill all
  // chrome.exe. This check is just in case Chrome is ignoring WM_CLOSE messages.
  base::CleanupProcesses(installer_util::kChromeExe, 15000,
                         ResultCodes::HUNG, NULL);
}

// This method deletes Chrome shortcut folder from Windows Start menu. It
// checks system_uninstall to see if the shortcut is in all users start menu
// or current user start menu.
void DeleteChromeShortcut(bool system_uninstall) {
  std::wstring shortcut_path;
  if (system_uninstall) {
    PathService::Get(base::DIR_COMMON_START_MENU, &shortcut_path);
    ShellUtil::RemoveChromeDesktopShortcut(ShellUtil::CURRENT_USER |
                                           ShellUtil::SYSTEM_LEVEL);
    ShellUtil::RemoveChromeQuickLaunchShortcut(ShellUtil::CURRENT_USER |
                                               ShellUtil::SYSTEM_LEVEL);
  } else {
    PathService::Get(base::DIR_START_MENU, &shortcut_path);
    ShellUtil::RemoveChromeDesktopShortcut(ShellUtil::CURRENT_USER);
    ShellUtil::RemoveChromeQuickLaunchShortcut(ShellUtil::CURRENT_USER);
  }
  if (shortcut_path.empty()) {
    LOG(ERROR) << "Failed to get location for shortcut.";
  } else {
    BrowserDistribution* dist = BrowserDistribution::GetDistribution();
    file_util::AppendToPath(&shortcut_path, dist->GetApplicationName());
    LOG(INFO) << "Deleting shortcut " << shortcut_path;
    if (!file_util::Delete(shortcut_path, true))
      LOG(ERROR) << "Failed to delete folder: " << shortcut_path;
  }
}

// Deletes all installed files of Chromium and Folders. Before deleting it
// needs to move setup.exe in a temp folder because the current process
// is using that file. It returns false when it can not get the path to
// installation folder, in all other cases it returns true even in case
// of error (only logs the error).
bool DeleteFilesAndFolders(const std::wstring& exe_path, bool system_uninstall,
    const installer::Version& installed_version) {
  std::wstring install_path(installer::GetChromeInstallPath(system_uninstall));
  if (install_path.empty()) {
    LOG(ERROR) << "Could not get installation destination path.";
    return false; // Nothing else we can do for uninstall, so we return.
  } else {
    LOG(INFO) << "install destination path: " << install_path;
  }

  std::wstring setup_exe(installer::GetInstallerPathUnderChrome(
      install_path, installed_version.GetString()));
  file_util::AppendToPath(&setup_exe, file_util::GetFilenameFromPath(exe_path));

  std::wstring temp_file;
  file_util::CreateTemporaryFileName(&temp_file);
  file_util::Move(setup_exe, temp_file);

  LOG(INFO) << "Deleting install path " << install_path;
  if (!file_util::Delete(install_path, true)) {
    LOG(ERROR) << "Failed to delete folder (1st try): " << install_path;
    // Try closing any running chrome processes and deleting files once again.
    CloseAllChromeProcesses();
    if (!file_util::Delete(install_path, true))
      LOG(ERROR) << "Failed to delete folder (2nd try): " << install_path;
  }

  // Now check and delete if the parent directories are empty
  // For example Google\Chrome or Chromium
  std::wstring parent_dir = file_util::GetDirectoryFromPath(install_path);
  if (!parent_dir.empty() && file_util::IsDirectoryEmpty(parent_dir)) {
    if (!file_util::Delete(parent_dir, true))
      LOG(ERROR) << "Failed to delete folder: " << parent_dir;
    parent_dir = file_util::GetDirectoryFromPath(parent_dir);
    if (!parent_dir.empty() &&
        file_util::IsDirectoryEmpty(parent_dir)) {
      if (!file_util::Delete(parent_dir, true))
        LOG(ERROR) << "Failed to delete folder: " << parent_dir;
    }
  }
  return true;
}

// This method tries to delete a registry key and logs an error message
// in case of failure. It returns true if deletion is successful,
// otherwise false.
bool DeleteRegistryKey(RegKey& key, const std::wstring& key_path) {
  LOG(INFO) << "Deleting registry key " << key_path;
  if (!key.DeleteKey(key_path.c_str())) {
    LOG(ERROR) << "Failed to delete registry key: " << key_path;
    return false;
  }
  return true;
}

// This method tries to delete a registry value and logs an error message
// in case of failure. It returns true if deletion is successful,
// otherwise false.
bool DeleteRegistryValue(HKEY reg_root, const std::wstring& key_path,
                         const std::wstring& value_name) {
  RegKey key(reg_root, key_path.c_str(), KEY_ALL_ACCESS);
  LOG(INFO) << "Deleting registry value " << value_name;
  if (!key.DeleteValue(value_name.c_str())) {
    LOG(ERROR) << "Failed to delete registry value: " << value_name;
    return false;
  }
  return true;
}

// This method checks if Chrome is currently running or if the user has
// cancelled the uninstall operation by clicking Cancel on the confirmation
// box that Chrome pops up.
installer_util::InstallStatus IsChromeActiveOrUserCancelled(
    bool system_uninstall) {
  static const std::wstring kCmdLineOptions(L" --uninstall");
  int32 exit_code = ResultCodes::NORMAL_EXIT;

  // Here we want to save user from frustration (in case of Chrome crashes)
  // and continue with the uninstallation as long as chrome.exe process exit
  // code is NOT one of the following:
  // - UNINSTALL_CHROME_ALIVE - chrome.exe is currently running
  // - UNINSTALL_USER_CANCEL - User cancelled uninstallation
  // - HUNG - chrome.exe was killed by HuntForZombieProcesses() (until we can
  //          give this method some brains and not kill chrome.exe launched
  //          by us, we will not uninstall if we get this return code).
  LOG(INFO) << "Launching Chrome to do uninstall tasks.";
  if (installer::LaunchChromeAndWaitForResult(system_uninstall,
                                              kCmdLineOptions,
                                              &exit_code)) {
    LOG(INFO) << "chrome.exe launched for uninstall confirmation returned: "
              << exit_code;
    if ((exit_code == ResultCodes::UNINSTALL_CHROME_ALIVE) ||
        (exit_code == ResultCodes::UNINSTALL_USER_CANCEL) ||
        (exit_code == ResultCodes::HUNG))
      return installer_util::UNINSTALL_CANCELLED;
  } else {
    LOG(ERROR) << "Failed to launch chrome.exe for uninstall confirmation.";
  }

  return installer_util::UNINSTALL_CONFIRMED;
}
}  // namespace

installer_util::InstallStatus installer_setup::UninstallChrome(
    const std::wstring& exe_path, bool system_uninstall,
    const installer::Version& installed_version,
    bool remove_all, bool force_uninstall) {
  if (!force_uninstall) {
    installer_util::InstallStatus status =
        IsChromeActiveOrUserCancelled(system_uninstall);
    if (status != installer_util::UNINSTALL_CONFIRMED)
      return status;
  } else {
    // Since --force-uninstall command line option is used, we are going to
    // do silent uninstall. Try to close all running Chrome instances.
    CloseAllChromeProcesses();
  }

  // Chrome is not in use so lets uninstall Chrome by deleting various files
  // and registry entries. Here we will just make best effort and keep going
  // in case of errors.
  // First delete shortcuts from Start->Programs, Desktop & Quick Launch.
  DeleteChromeShortcut(system_uninstall);

  // Delete the registry keys (Uninstall key and Version key).
  HKEY reg_root = system_uninstall ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
  RegKey key(reg_root, L"", KEY_ALL_ACCESS);
  BrowserDistribution* dist = BrowserDistribution::GetDistribution();
  DeleteRegistryKey(key, dist->GetUninstallRegPath());
  DeleteRegistryKey(key, dist->GetVersionKey());

  // Delete Software\Classes\ChromeHTML,
  // Software\Clients\StartMenuInternet\chrome.exe and
  // Software\RegisteredApplications\Chrome
  std::wstring html_prog_id(ShellUtil::kRegClasses);
  file_util::AppendToPath(&html_prog_id, ShellUtil::kChromeHTMLProgId);
  DeleteRegistryKey(key, html_prog_id);

  std::wstring set_access_key(ShellUtil::kRegStartMenuInternet);
  file_util::AppendToPath(&set_access_key, installer_util::kChromeExe);
  DeleteRegistryKey(key, set_access_key);

  DeleteRegistryValue(reg_root, ShellUtil::kRegRegisteredApplications,
                      dist->GetApplicationName());

  // Cleanup Software\Classes\Applications\chrome.exe and OpenWithList
  RegKey hklm_key(HKEY_LOCAL_MACHINE, L"", KEY_ALL_ACCESS);
  std::wstring app_key(ShellUtil::kRegClasses);
  file_util::AppendToPath(&app_key, L"Applications");
  file_util::AppendToPath(&app_key, installer_util::kChromeExe);
  DeleteRegistryKey(key, app_key);
  if (remove_all)
    DeleteRegistryKey(hklm_key, app_key);
  for (int i = 0; ShellUtil::kFileAssociations[i] != NULL; i++) {
    std::wstring open_with_key(ShellUtil::kRegClasses);
    file_util::AppendToPath(&open_with_key, ShellUtil::kFileAssociations[i]);
    file_util::AppendToPath(&open_with_key, L"OpenWithList");
    file_util::AppendToPath(&open_with_key, installer_util::kChromeExe);
    DeleteRegistryKey(key, open_with_key);
    if (remove_all)
      DeleteRegistryKey(hklm_key, open_with_key);
  }
  key.Close();

  // Delete shared registry keys as well (these require admin rights) if
  // remove_all option is specified.
  if (remove_all) {
    DeleteRegistryKey(hklm_key, set_access_key);
    DeleteRegistryKey(hklm_key, html_prog_id);
    DeleteRegistryValue(HKEY_LOCAL_MACHINE,
                        ShellUtil::kRegRegisteredApplications,
                        dist->GetApplicationName());

    // Delete media player registry key that exists only in HKLM.
    std::wstring reg_path(installer::kMediaPlayerRegPath);
    file_util::AppendToPath(&reg_path, installer_util::kChromeExe);
    DeleteRegistryKey(hklm_key, reg_path);
    hklm_key.Close();
  }

  // Finally delete all the files from Chrome folder after moving setup.exe
  // to a temp location.
  if (!DeleteFilesAndFolders(exe_path, system_uninstall, installed_version))
    return installer_util::UNINSTALL_FAILED;

  LOG(INFO) << "Uninstallation complete. Launching Uninstall survey.";
  dist->DoPostUninstallOperations(installed_version);
  return installer_util::UNINSTALL_SUCCESSFUL;
}

<commit_msg>Don't launch uninstall survey for forced user-level uninstalls<commit_after>// Copyright (c) 2006-2008 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.
//
// This file defines the methods useful for uninstalling Chrome.

#include "chrome/installer/setup/uninstall.h"

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/registry.h"
#include "base/string_util.h"
#include "chrome/app/result_codes.h"
#include "chrome/installer/setup/setup.h"
#include "chrome/installer/setup/setup_constants.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/helper.h"
#include "chrome/installer/util/logging_installer.h"
#include "chrome/installer/util/shell_util.h"
#include "chrome/installer/util/version.h"

namespace {

// This functions checks for any Chrome instances that are
// running and first asks them to close politely by sending a Windows message.
// If there is an error while sending message or if there are still Chrome
// procesess active after the message has been sent, this function will try
// to kill them.
void CloseAllChromeProcesses() {
  for (int j = 0; j < 4; ++j) {
    std::wstring wnd_class(L"Chrome_WidgetWin_");
    wnd_class.append(IntToWString(j));
    HWND window = FindWindowEx(NULL, NULL, wnd_class.c_str(), NULL);
    while (window) {
      HWND tmpWnd = window;
      window = FindWindowEx(NULL, window, wnd_class.c_str(), NULL);
      if (!SendMessageTimeout(tmpWnd, WM_CLOSE, 0, 0, SMTO_BLOCK, 3000, NULL) &&
          (GetLastError() == ERROR_TIMEOUT)) {
        base::CleanupProcesses(installer_util::kChromeExe, 0,
                               ResultCodes::HUNG, NULL);
        return;
      }
    }
  }

  // If asking politely didn't work, wait for 15 seconds and then kill all
  // chrome.exe. This check is just in case Chrome is ignoring WM_CLOSE messages.
  base::CleanupProcesses(installer_util::kChromeExe, 15000,
                         ResultCodes::HUNG, NULL);
}

// This method deletes Chrome shortcut folder from Windows Start menu. It
// checks system_uninstall to see if the shortcut is in all users start menu
// or current user start menu.
void DeleteChromeShortcut(bool system_uninstall) {
  std::wstring shortcut_path;
  if (system_uninstall) {
    PathService::Get(base::DIR_COMMON_START_MENU, &shortcut_path);
    ShellUtil::RemoveChromeDesktopShortcut(ShellUtil::CURRENT_USER |
                                           ShellUtil::SYSTEM_LEVEL);
    ShellUtil::RemoveChromeQuickLaunchShortcut(ShellUtil::CURRENT_USER |
                                               ShellUtil::SYSTEM_LEVEL);
  } else {
    PathService::Get(base::DIR_START_MENU, &shortcut_path);
    ShellUtil::RemoveChromeDesktopShortcut(ShellUtil::CURRENT_USER);
    ShellUtil::RemoveChromeQuickLaunchShortcut(ShellUtil::CURRENT_USER);
  }
  if (shortcut_path.empty()) {
    LOG(ERROR) << "Failed to get location for shortcut.";
  } else {
    BrowserDistribution* dist = BrowserDistribution::GetDistribution();
    file_util::AppendToPath(&shortcut_path, dist->GetApplicationName());
    LOG(INFO) << "Deleting shortcut " << shortcut_path;
    if (!file_util::Delete(shortcut_path, true))
      LOG(ERROR) << "Failed to delete folder: " << shortcut_path;
  }
}

// Deletes all installed files of Chromium and Folders. Before deleting it
// needs to move setup.exe in a temp folder because the current process
// is using that file. It returns false when it can not get the path to
// installation folder, in all other cases it returns true even in case
// of error (only logs the error).
bool DeleteFilesAndFolders(const std::wstring& exe_path, bool system_uninstall,
    const installer::Version& installed_version) {
  std::wstring install_path(installer::GetChromeInstallPath(system_uninstall));
  if (install_path.empty()) {
    LOG(ERROR) << "Could not get installation destination path.";
    return false; // Nothing else we can do for uninstall, so we return.
  } else {
    LOG(INFO) << "install destination path: " << install_path;
  }

  std::wstring setup_exe(installer::GetInstallerPathUnderChrome(
      install_path, installed_version.GetString()));
  file_util::AppendToPath(&setup_exe, file_util::GetFilenameFromPath(exe_path));

  std::wstring temp_file;
  file_util::CreateTemporaryFileName(&temp_file);
  file_util::Move(setup_exe, temp_file);

  LOG(INFO) << "Deleting install path " << install_path;
  if (!file_util::Delete(install_path, true)) {
    LOG(ERROR) << "Failed to delete folder (1st try): " << install_path;
    // Try closing any running chrome processes and deleting files once again.
    CloseAllChromeProcesses();
    if (!file_util::Delete(install_path, true))
      LOG(ERROR) << "Failed to delete folder (2nd try): " << install_path;
  }

  // Now check and delete if the parent directories are empty
  // For example Google\Chrome or Chromium
  std::wstring parent_dir = file_util::GetDirectoryFromPath(install_path);
  if (!parent_dir.empty() && file_util::IsDirectoryEmpty(parent_dir)) {
    if (!file_util::Delete(parent_dir, true))
      LOG(ERROR) << "Failed to delete folder: " << parent_dir;
    parent_dir = file_util::GetDirectoryFromPath(parent_dir);
    if (!parent_dir.empty() &&
        file_util::IsDirectoryEmpty(parent_dir)) {
      if (!file_util::Delete(parent_dir, true))
        LOG(ERROR) << "Failed to delete folder: " << parent_dir;
    }
  }
  return true;
}

// This method tries to delete a registry key and logs an error message
// in case of failure. It returns true if deletion is successful,
// otherwise false.
bool DeleteRegistryKey(RegKey& key, const std::wstring& key_path) {
  LOG(INFO) << "Deleting registry key " << key_path;
  if (!key.DeleteKey(key_path.c_str())) {
    LOG(ERROR) << "Failed to delete registry key: " << key_path;
    return false;
  }
  return true;
}

// This method tries to delete a registry value and logs an error message
// in case of failure. It returns true if deletion is successful,
// otherwise false.
bool DeleteRegistryValue(HKEY reg_root, const std::wstring& key_path,
                         const std::wstring& value_name) {
  RegKey key(reg_root, key_path.c_str(), KEY_ALL_ACCESS);
  LOG(INFO) << "Deleting registry value " << value_name;
  if (!key.DeleteValue(value_name.c_str())) {
    LOG(ERROR) << "Failed to delete registry value: " << value_name;
    return false;
  }
  return true;
}

// This method checks if Chrome is currently running or if the user has
// cancelled the uninstall operation by clicking Cancel on the confirmation
// box that Chrome pops up.
installer_util::InstallStatus IsChromeActiveOrUserCancelled(
    bool system_uninstall) {
  static const std::wstring kCmdLineOptions(L" --uninstall");
  int32 exit_code = ResultCodes::NORMAL_EXIT;

  // Here we want to save user from frustration (in case of Chrome crashes)
  // and continue with the uninstallation as long as chrome.exe process exit
  // code is NOT one of the following:
  // - UNINSTALL_CHROME_ALIVE - chrome.exe is currently running
  // - UNINSTALL_USER_CANCEL - User cancelled uninstallation
  // - HUNG - chrome.exe was killed by HuntForZombieProcesses() (until we can
  //          give this method some brains and not kill chrome.exe launched
  //          by us, we will not uninstall if we get this return code).
  LOG(INFO) << "Launching Chrome to do uninstall tasks.";
  if (installer::LaunchChromeAndWaitForResult(system_uninstall,
                                              kCmdLineOptions,
                                              &exit_code)) {
    LOG(INFO) << "chrome.exe launched for uninstall confirmation returned: "
              << exit_code;
    if ((exit_code == ResultCodes::UNINSTALL_CHROME_ALIVE) ||
        (exit_code == ResultCodes::UNINSTALL_USER_CANCEL) ||
        (exit_code == ResultCodes::HUNG))
      return installer_util::UNINSTALL_CANCELLED;
  } else {
    LOG(ERROR) << "Failed to launch chrome.exe for uninstall confirmation.";
  }

  return installer_util::UNINSTALL_CONFIRMED;
}
}  // namespace

installer_util::InstallStatus installer_setup::UninstallChrome(
    const std::wstring& exe_path, bool system_uninstall,
    const installer::Version& installed_version,
    bool remove_all, bool force_uninstall) {
  if (!force_uninstall) {
    installer_util::InstallStatus status =
        IsChromeActiveOrUserCancelled(system_uninstall);
    if (status != installer_util::UNINSTALL_CONFIRMED)
      return status;
  } else {
    // Since --force-uninstall command line option is used, we are going to
    // do silent uninstall. Try to close all running Chrome instances.
    CloseAllChromeProcesses();
  }

  // Chrome is not in use so lets uninstall Chrome by deleting various files
  // and registry entries. Here we will just make best effort and keep going
  // in case of errors.
  // First delete shortcuts from Start->Programs, Desktop & Quick Launch.
  DeleteChromeShortcut(system_uninstall);

  // Delete the registry keys (Uninstall key and Version key).
  HKEY reg_root = system_uninstall ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
  RegKey key(reg_root, L"", KEY_ALL_ACCESS);
  BrowserDistribution* dist = BrowserDistribution::GetDistribution();
  DeleteRegistryKey(key, dist->GetUninstallRegPath());
  DeleteRegistryKey(key, dist->GetVersionKey());

  // Delete Software\Classes\ChromeHTML,
  // Software\Clients\StartMenuInternet\chrome.exe and
  // Software\RegisteredApplications\Chrome
  std::wstring html_prog_id(ShellUtil::kRegClasses);
  file_util::AppendToPath(&html_prog_id, ShellUtil::kChromeHTMLProgId);
  DeleteRegistryKey(key, html_prog_id);

  std::wstring set_access_key(ShellUtil::kRegStartMenuInternet);
  file_util::AppendToPath(&set_access_key, installer_util::kChromeExe);
  DeleteRegistryKey(key, set_access_key);

  DeleteRegistryValue(reg_root, ShellUtil::kRegRegisteredApplications,
                      dist->GetApplicationName());

  // Cleanup Software\Classes\Applications\chrome.exe and OpenWithList
  RegKey hklm_key(HKEY_LOCAL_MACHINE, L"", KEY_ALL_ACCESS);
  std::wstring app_key(ShellUtil::kRegClasses);
  file_util::AppendToPath(&app_key, L"Applications");
  file_util::AppendToPath(&app_key, installer_util::kChromeExe);
  DeleteRegistryKey(key, app_key);
  if (remove_all)
    DeleteRegistryKey(hklm_key, app_key);
  for (int i = 0; ShellUtil::kFileAssociations[i] != NULL; i++) {
    std::wstring open_with_key(ShellUtil::kRegClasses);
    file_util::AppendToPath(&open_with_key, ShellUtil::kFileAssociations[i]);
    file_util::AppendToPath(&open_with_key, L"OpenWithList");
    file_util::AppendToPath(&open_with_key, installer_util::kChromeExe);
    DeleteRegistryKey(key, open_with_key);
    if (remove_all)
      DeleteRegistryKey(hklm_key, open_with_key);
  }
  key.Close();

  // Delete shared registry keys as well (these require admin rights) if
  // remove_all option is specified.
  if (remove_all) {
    DeleteRegistryKey(hklm_key, set_access_key);
    DeleteRegistryKey(hklm_key, html_prog_id);
    DeleteRegistryValue(HKEY_LOCAL_MACHINE,
                        ShellUtil::kRegRegisteredApplications,
                        dist->GetApplicationName());

    // Delete media player registry key that exists only in HKLM.
    std::wstring reg_path(installer::kMediaPlayerRegPath);
    file_util::AppendToPath(&reg_path, installer_util::kChromeExe);
    DeleteRegistryKey(hklm_key, reg_path);
    hklm_key.Close();
  }

  // Finally delete all the files from Chrome folder after moving setup.exe
  // to a temp location.
  if (!DeleteFilesAndFolders(exe_path, system_uninstall, installed_version))
    return installer_util::UNINSTALL_FAILED;

  if (!force_uninstall) {
    LOG(INFO) << "Uninstallation complete. Launching Uninstall survey.";
    dist->DoPostUninstallOperations(installed_version);
  }
  return installer_util::UNINSTALL_SUCCESSFUL;
}

<|endoftext|>


<commit_before>#ifndef MJOLNIR_READ_INPUT_FILE
#define MJOLNIR_READ_INPUT_FILE
#include <extlib/toml/toml.hpp>
#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/core/constants.hpp>
#include <mjolnir/core/SimulatorBase.hpp>
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/util/get_toml_value.hpp>
#include <mjolnir/util/logger.hpp>
#include <mjolnir/input/read_units.hpp>
#include <memory>

namespace mjolnir
{

template<typename realT>
std::unique_ptr<SimulatorBase>
read_boundary(const toml::Table& data)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_SCOPE(read_boundary(const toml::Table& data), 0);

    // [simulator] can be provided in a different file. in that case, the table
    // has `file_name` field. In that case, input_path is also needed to
    // determine the location of the file.

    std::string boundary;

    const auto& simulator =
        get_toml_value<toml::Table>(data, "simulator", "<root>");

    if(simulator.count("file_name") == 1)
    {
        const auto filename = toml::get<std::string>(simulator.at("file_name"));
        std::string input_path; //default: empty

        const auto& files = get_toml_value<toml::Table>(data, "files", "<root>");
        if(files.count("input_path") == 1)
        {
            input_path = toml::get<std::string>(files.at("input_path"));
        }

        const auto& sim = toml::parse(input_path + filename);
        boundary = get_toml_value<std::string>(
                sim, "boundary_type", "[simulator]");
    }
    else
    {
        boundary = get_toml_value<std::string>(
                simulator, "boundary_type", "[simulator]");
    }

    if(boundary == "Unlimited")
    {
        MJOLNIR_LOG_INFO("boundary is UnlimitedBoundary");
        return read_units<SimulatorTraits<realT, UnlimitedBoundary>>(data);
    }
    else if(boundary == "PeriodicCuboid")
    {
        MJOLNIR_LOG_INFO("boundary is CuboidalPeriodicBoudanry");
        return read_units<SimulatorTraits<realT, CuboidalPeriodicBoundary>>(data);
    }
    else
    {
        throw_exception<std::runtime_error>("mjolnir::read_boundary: "
            "invalid boundary: neither 'Unlimited' or 'PeriodicCuboid' -> ",
            boundary);
    }
}

inline std::unique_ptr<SimulatorBase>
read_precision(const toml::Table& data)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_SCOPE(read_precision(const toml::Table& data), 0);

    // [simulator] can be provided in a different file. in that case, the table
    // has `file_name` field. In that case, input_path is also needed to
    // determine the location of the file.

    std::string prec;

    const auto& simulator =
        get_toml_value<toml::Table>(data, "simulator", "<root>");

    if(simulator.count("file_name") == 1)
    {
        const auto filename = toml::get<std::string>(simulator.at("file_name"));
        std::string input_path; //default: empty

        const auto& files = get_toml_value<toml::Table>(data, "files", "<root>");
        if(files.count("input_path") == 1)
        {
            input_path = toml::get<std::string>(files.at("input_path"));
        }

        const auto& sim = toml::parse(input_path + filename);
        prec = get_toml_value<std::string>(sim, "precision", "[simulator]");
    }
    else
    {
        prec = get_toml_value<std::string>(simulator, "precision", "[simulator]");
    }

    if(prec == "double")
    {
        MJOLNIR_LOG_INFO("precision is double");
        return read_boundary<double>(data);
    }
    else if(prec == "float")
    {
        MJOLNIR_LOG_INFO("precision is float");
        return read_boundary<float>(data);
    }
    else
    {
        throw_exception<std::runtime_error>("mjolnir::read_precision: "
            "invalid precision: neither 'double' or 'float' -> ", prec);
    }
}

inline std::unique_ptr<SimulatorBase>
read_input_file(const std::string& filename)
{
    const auto data = toml::parse(filename);

    // initializing logger by using output_path and output_prefix ...
    const auto& files = get_toml_value<toml::Table>(data, "files", "<root>");
    const auto  path  = get_toml_value<std::string>(files, "output_path", "[files]");

    // XXX:  Here, this code assumes POSIX. it does not support windows.
    // TODO: Consider using Boost.filesystem to manage path and files
    //       in more elegant and powerful way? After switching C++17,
    //       we can re-write that into std::filesystem.

    const std::string logger_name = path + get_toml_value<std::string>(
            files, "output_prefix", "[files]") + ".log";
    MJOLNIR_SET_DEFAULT_LOGGER(logger_name);

    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_SCOPE(read_input_file(const toml::Table& data), 0);

    return read_precision(data); // read all the settings recursively...
}

}// mjolnir
#endif// MJOLNIR_READ_INPUT_FILE
<commit_msg>add LOG_NOTICE to read_input_files<commit_after>#ifndef MJOLNIR_READ_INPUT_FILE
#define MJOLNIR_READ_INPUT_FILE
#include <extlib/toml/toml.hpp>
#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/core/constants.hpp>
#include <mjolnir/core/SimulatorBase.hpp>
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/util/get_toml_value.hpp>
#include <mjolnir/util/logger.hpp>
#include <mjolnir/input/read_units.hpp>
#include <memory>

namespace mjolnir
{

template<typename realT>
std::unique_ptr<SimulatorBase>
read_boundary(const toml::Table& data)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_SCOPE(read_boundary(const toml::Table& data), 0);

    // [simulator] can be provided in a different file. in that case, the table
    // has `file_name` field. In that case, input_path is also needed to
    // determine the location of the file.

    std::string boundary;

    const auto& simulator =
        get_toml_value<toml::Table>(data, "simulator", "<root>");

    if(simulator.count("file_name") == 1)
    {
        const auto filename = toml::get<std::string>(simulator.at("file_name"));
        std::string input_path; //default: empty

        const auto& files = get_toml_value<toml::Table>(data, "files", "<root>");
        if(files.count("input_path") == 1)
        {
            input_path = toml::get<std::string>(files.at("input_path"));
        }

        const auto& sim = toml::parse(input_path + filename);
        boundary = get_toml_value<std::string>(
                sim, "boundary_type", "[simulator]");
    }
    else
    {
        boundary = get_toml_value<std::string>(
                simulator, "boundary_type", "[simulator]");
    }

    if(boundary == "Unlimited")
    {
        MJOLNIR_LOG_NOTICE("Boundary Condition is Unlimited");
        return read_units<SimulatorTraits<realT, UnlimitedBoundary>>(data);
    }
    else if(boundary == "PeriodicCuboid")
    {
        MJOLNIR_LOG_NOTICE("Boundary Condition is CuboidalPeriodic");
        return read_units<SimulatorTraits<realT, CuboidalPeriodicBoundary>>(data);
    }
    else
    {
        throw_exception<std::runtime_error>("mjolnir::read_boundary: "
            "invalid boundary: neither 'Unlimited' or 'PeriodicCuboid' -> ",
            boundary);
    }
}

inline std::unique_ptr<SimulatorBase>
read_precision(const toml::Table& data)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_SCOPE(read_precision(const toml::Table& data), 0);

    // [simulator] can be provided in a different file. in that case, the table
    // has `file_name` field. In that case, input_path is also needed to
    // determine the location of the file.

    std::string prec;

    const auto& simulator =
        get_toml_value<toml::Table>(data, "simulator", "<root>");

    if(simulator.count("file_name") == 1)
    {
        const auto filename = toml::get<std::string>(simulator.at("file_name"));
        std::string input_path; //default: empty

        const auto& files = get_toml_value<toml::Table>(data, "files", "<root>");
        if(files.count("input_path") == 1)
        {
            input_path = toml::get<std::string>(files.at("input_path"));
        }

        const auto& sim = toml::parse(input_path + filename);
        prec = get_toml_value<std::string>(sim, "precision", "[simulator]");
    }
    else
    {
        prec = get_toml_value<std::string>(simulator, "precision", "[simulator]");
    }

    if(prec == "double")
    {
        MJOLNIR_LOG_NOTICE("precision is double");
        return read_boundary<double>(data);
    }
    else if(prec == "float")
    {
        MJOLNIR_LOG_NOTICE("precision is float");
        return read_boundary<float>(data);
    }
    else
    {
        throw_exception<std::runtime_error>("mjolnir::read_precision: "
            "invalid precision: neither 'double' or 'float' -> ", prec);
    }
}

inline std::unique_ptr<SimulatorBase>
read_input_file(const std::string& filename)
{
    // here, logger name is not given yet. output status directory on console.
    std::cerr << "-- reading and parsing toml file `" << filename << "` ... ";
    const auto data = toml::parse(filename);
    std::cerr << " successfully parsed." << std::endl;

    // initializing logger by using output_path and output_prefix ...
    const auto& files = get_toml_value<toml::Table>(data, "files", "<root>");
    const auto  path  = get_toml_value<std::string>(files, "output_path", "[files]");

    // XXX:  Here, this code assumes POSIX. it does not support windows.
    // TODO: Consider using Boost.filesystem to manage path and files
    //       in more elegant and powerful way? After switching C++17,
    //       we can re-write that with <filesystem>.

    const std::string logger_name = path + get_toml_value<std::string>(
            files, "output_prefix", "[files]") + ".log";
    MJOLNIR_SET_DEFAULT_LOGGER(logger_name);
    MJOLNIR_GET_DEFAULT_LOGGER();

    MJOLNIR_LOG_NOTICE("the log file is `", logger_name, '`');
    MJOLNIR_SCOPE(read_input_file(const toml::Table& data), 0);

    return read_precision(data); // read all the settings recursively...
}

}// mjolnir
#endif// MJOLNIR_READ_INPUT_FILE
<|endoftext|>


<commit_before><commit_msg>Last checkin contained a typo. Fixing.<commit_after><|endoftext|>


<commit_before>#ifndef MJOLNIR_READ_INTEGRATOR
#define MJOLNIR_READ_INTEGRATOR
#include <extlib/toml/toml.hpp>
#include <mjolnir/core/VelocityVerletStepper.hpp>
#include <mjolnir/core/UnderdampedLangevinStepper.hpp>
#include <mjolnir/util/logger.hpp>

namespace mjolnir
{

template<typename traitsT>
VelocityVerletStepper<traitsT>
read_velocity_verlet_stepper(const toml::value& simulator)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_SCOPE(read_velocity_verlet_stepper(), 0);
    typedef typename traitsT::real_type real_type;

    const real_type delta_t = toml::find<real_type>(simulator, "delta_t");
    MJOLNIR_LOG_INFO("delta_t = ", delta_t);

    return VelocityVerletStepper<traitsT>(delta_t);
}

template<typename traitsT>
UnderdampedLangevinStepper<traitsT>
read_underdamped_langevin_stepper(const toml::Table& simulator)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_SCOPE(read_underdamped_langevin_stepper(), 0);
    typedef typename traitsT::real_type real_type;

    const auto seed       = toml::find<std::uint32_t>(simulator, "seed");
    const auto parameters = toml::find<toml::array>(simulator, "parameters");

    std::vector<real_type> gamma(parameters.size());
    for(const auto& params : parameters)
    {
        const auto idx = toml::find<std::size_t>(params, "index");
        const auto  gm = toml::expect<real_type>(params, u8"γ").or_other(
                         toml::expect<real_type>(params, "gamma")).unwrap();
        if(gamma.size() <= idx){gamma.resize(idx+1);}
        gamma.at(idx) = gm;

        MJOLNIR_LOG_INFO("idx = ", idx, ", gamma = ", gm);
    }

    const real_type delta_t = toml::find<real_type>(simulator, "delta_t");
    MJOLNIR_LOG_INFO("delta_t = ", delta_t);

    return UnderdampedLangevinStepper<traitsT>(delta_t, std::move(gamma),
            RandomNumberGenerator<traitsT>(seed));
}

}
#endif// MJOLNIR_READ_INTEGRATOR
<commit_msg>fix some typoes in read_integrator<commit_after>#ifndef MJOLNIR_READ_INTEGRATOR
#define MJOLNIR_READ_INTEGRATOR
#include <extlib/toml/toml.hpp>
#include <mjolnir/core/VelocityVerletStepper.hpp>
#include <mjolnir/core/UnderdampedLangevinStepper.hpp>
#include <mjolnir/util/logger.hpp>

namespace mjolnir
{

template<typename traitsT>
VelocityVerletStepper<traitsT>
read_velocity_verlet_stepper(const toml::value& simulator)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_SCOPE(read_velocity_verlet_stepper(), 0);
    typedef typename traitsT::real_type real_type;

    const real_type delta_t = toml::find<real_type>(simulator, "delta_t");
    MJOLNIR_LOG_INFO("delta_t = ", delta_t);

    return VelocityVerletStepper<traitsT>(delta_t);
}

template<typename traitsT>
UnderdampedLangevinStepper<traitsT>
read_underdamped_langevin_stepper(const toml::value& simulator)
{
    MJOLNIR_GET_DEFAULT_LOGGER();
    MJOLNIR_SCOPE(read_underdamped_langevin_stepper(), 0);
    typedef typename traitsT::real_type real_type;

    const auto seed       = toml::find<std::uint32_t>(simulator, "seed");
    const auto parameters = toml::find<toml::array>(simulator, "parameters");

    std::vector<real_type> gamma(parameters.size());
    for(const auto& params : parameters)
    {
        const auto idx = toml::find<std::size_t>(params, "index");
        const auto  gm = toml::expect<real_type>(params, u8"γ").or_other(
                         toml::expect<real_type>(params, "gamma")).unwrap();
        if(gamma.size() <= idx){gamma.resize(idx+1);}
        gamma.at(idx) = gm;

        MJOLNIR_LOG_INFO("idx = ", idx, ", gamma = ", gm);
    }

    const real_type delta_t = toml::find<real_type>(simulator, "delta_t");
    MJOLNIR_LOG_INFO("delta_t = ", delta_t);

    return UnderdampedLangevinStepper<traitsT>(delta_t, std::move(gamma),
            RandomNumberGenerator<traitsT>(seed));
}

} // mjolnir
#endif// MJOLNIR_READ_INTEGRATOR
<|endoftext|>


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

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/gfx/point.h"
#include "base/gfx/rect.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/view_ids.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/javascript_test_util.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
#include "views/event.h"

#if defined(OS_MACOSX)
// window->GetViewBounds is not implemented
// window->SimulateOSMouseMove is not implemented
// http://code.google.com/p/chromium/issues/detail?id=26102
#define MAYBE_TestOnMouseOut DISABLED_TestOnMouseOut
#elif defined(OS_WIN)
// Test succeeds locally, flaky on trybot
// http://code.google.com/p/chromium/issues/detail?id=26349
#define MAYBE_TestOnMouseOut DISABLED_TestOnMouseOut
#endif

namespace {

class MouseLeaveTest : public UITest {
 public:
  MouseLeaveTest() {
    dom_automation_enabled_ = true;
    show_window_ = true;
  }

  DISALLOW_COPY_AND_ASSIGN(MouseLeaveTest);
};

TEST_F(MouseLeaveTest, MAYBE_TestOnMouseOut) {
  GURL test_url = GetTestUrl(L"", L"mouseleave.html");

  scoped_refptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab.get());
  scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
  scoped_refptr<WindowProxy> window = browser->GetWindow();

  gfx::Rect tab_view_bounds;
  ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER, &tab_view_bounds,
                                    true));
  gfx::Point in_content_point(
      tab_view_bounds.x() + tab_view_bounds.width() / 2,
      tab_view_bounds.y() + 10);
  gfx::Point above_content_point(
      tab_view_bounds.x() + tab_view_bounds.width() / 2,
      tab_view_bounds.y() - 2);

  // Start by moving the point just above the content.
  ASSERT_TRUE(window->SimulateOSMouseMove(above_content_point));

  // Navigate to the test html page.
  tab->NavigateToURL(test_url);

  const int timeout_ms = 5 * action_max_timeout_ms();
  const int check_interval_ms = action_max_timeout_ms() / 10;

  // Wait for the onload() handler to complete so we can do the
  // next part of the test.
  ASSERT_TRUE(WaitUntilCookieValue(
      tab.get(), test_url, "__state", check_interval_ms, timeout_ms,
      "initial"));

  // Move the cursor to the top-center of the content, which will trigger
  // a javascript onMouseOver event.
  ASSERT_TRUE(window->SimulateOSMouseMove(in_content_point));

  // Wait on the correct intermediate value of the cookie.
  ASSERT_TRUE(WaitUntilCookieValue(
      tab.get(), test_url, "__state", check_interval_ms, timeout_ms,
      "initial,entered"));

  // Move the cursor above the content again, which should trigger
  // a javascript onMouseOut event.
  ASSERT_TRUE(window->SimulateOSMouseMove(above_content_point));

  // Wait on the correct final value of the cookie.
  ASSERT_TRUE(WaitUntilCookieValue(
      tab.get(), test_url, "__state", check_interval_ms, timeout_ms,
      "initial,entered,left"));
}

}  // namespace
<commit_msg>Marking one more as flaky test. This failed 3 times out of 20 invocations.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/gfx/point.h"
#include "base/gfx/rect.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/values.h"
#include "chrome/browser/view_ids.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/javascript_test_util.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
#include "views/event.h"

#if defined(OS_MACOSX)
// window->GetViewBounds is not implemented
// window->SimulateOSMouseMove is not implemented
// http://code.google.com/p/chromium/issues/detail?id=26102
#define MAYBE_TestOnMouseOut DISABLED_TestOnMouseOut
#elif defined(OS_WIN)
// Test succeeds locally, flaky on trybot
// http://code.google.com/p/chromium/issues/detail?id=26349
#define MAYBE_TestOnMouseOut DISABLED_TestOnMouseOut
#elif defined(OS_LINUX) && defined(TOOLKIT_VIEWS)
// Test is flaky on linux/views build.
// http://crbug.com/28808.
#define MAYBE_TestOnMouseOut FLAKY_TestOnMouseOut
#endif

namespace {

class MouseLeaveTest : public UITest {
 public:
  MouseLeaveTest() {
    dom_automation_enabled_ = true;
    show_window_ = true;
  }

  DISALLOW_COPY_AND_ASSIGN(MouseLeaveTest);
};

TEST_F(MouseLeaveTest, MAYBE_TestOnMouseOut) {
  GURL test_url = GetTestUrl(L"", L"mouseleave.html");

  scoped_refptr<TabProxy> tab(GetActiveTab());
  ASSERT_TRUE(tab.get());
  scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
  scoped_refptr<WindowProxy> window = browser->GetWindow();

  gfx::Rect tab_view_bounds;
  ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER, &tab_view_bounds,
                                    true));
  gfx::Point in_content_point(
      tab_view_bounds.x() + tab_view_bounds.width() / 2,
      tab_view_bounds.y() + 10);
  gfx::Point above_content_point(
      tab_view_bounds.x() + tab_view_bounds.width() / 2,
      tab_view_bounds.y() - 2);

  // Start by moving the point just above the content.
  ASSERT_TRUE(window->SimulateOSMouseMove(above_content_point));

  // Navigate to the test html page.
  tab->NavigateToURL(test_url);

  const int timeout_ms = 5 * action_max_timeout_ms();
  const int check_interval_ms = action_max_timeout_ms() / 10;

  // Wait for the onload() handler to complete so we can do the
  // next part of the test.
  ASSERT_TRUE(WaitUntilCookieValue(
      tab.get(), test_url, "__state", check_interval_ms, timeout_ms,
      "initial"));

  // Move the cursor to the top-center of the content, which will trigger
  // a javascript onMouseOver event.
  ASSERT_TRUE(window->SimulateOSMouseMove(in_content_point));

  // Wait on the correct intermediate value of the cookie.
  ASSERT_TRUE(WaitUntilCookieValue(
      tab.get(), test_url, "__state", check_interval_ms, timeout_ms,
      "initial,entered"));

  // Move the cursor above the content again, which should trigger
  // a javascript onMouseOut event.
  ASSERT_TRUE(window->SimulateOSMouseMove(above_content_point));

  // Wait on the correct final value of the cookie.
  ASSERT_TRUE(WaitUntilCookieValue(
      tab.get(), test_url, "__state", check_interval_ms, timeout_ms,
      "initial,entered,left"));
}

}  // namespace
<|endoftext|>


<commit_before>#if DMUSIC_TSF_SUPPORT
#include <cassert>
#include <dmusic/SoundFontPlayer.h>
#include <memory>
#include <cmath>
#define TSF_IMPLEMENTATION
#include "../utils/common/tsf.h"
using namespace DirectMusic;
using namespace DirectMusic::DLS;

static float gainToDecibels(float gain) {
    return 10 * log10(gain);
}

SoundFontPlayer::SoundFontPlayer(tsf* soundfont,
    std::uint8_t bankLo, std::uint8_t bankHi, std::uint8_t patch,
    const DirectMusic::DLS::DownloadableSound& dls,
    std::uint32_t sampleRate,
    std::uint32_t channels,
    float volume,
    float pan)
    : InstrumentPlayer(bankLo, bankHi, patch, dls, sampleRate, channels, volume, pan)
    , m_soundfont(nullptr)
    , m_vol(volume)
    , m_channels(channels) {
    assert(channels <= 2);
    std::uint32_t bank = (bankHi << 16) + bankLo;

    m_pan = pan < -1 ? -1 : pan > 1 ? 1 : pan;
    m_soundfont = soundfont;

    m_preset = tsf_get_presetindex(m_soundfont, 0, patch);
    assert(m_preset >= 0);

    float volFactorRight = sqrt((m_pan + 1) / 2);
    float volFactorLeft = sqrt((-m_pan + 1) / 2);

    tsf_set_preset_panning(m_soundfont, m_preset, volFactorLeft, volFactorRight);
    tsf_set_preset_gain(m_soundfont, m_preset, gainToDecibels(volume));
    tsf_increase_refcount(m_soundfont);
}

SoundFontPlayer::~SoundFontPlayer() {
    tsf_decrease_refcount(m_soundfont);
}

std::uint32_t SoundFontPlayer::renderBlock(std::int16_t *buffer, std::uint32_t count, float volume, bool mix) noexcept {
    if (!mix) {
        tsf_render_short(m_soundfont, buffer, count / m_channels, 0);
    }
    return count;
}

/// Instructs the synthesizer to start playing a note
void SoundFontPlayer::noteOn(std::uint8_t note, std::uint8_t velocity) {
    tsf_note_on(m_soundfont, m_preset, note, velocity / 255.0f);
}

/// Instructs the synthesizer to stop playing a note
void SoundFontPlayer::noteOff(std::uint8_t note, std::uint8_t velocity) {
    tsf_note_off(m_soundfont, m_preset, note);
}

void SoundFontPlayer::allNotesOff() {
    tsf_all_notes_off(m_soundfont, m_preset);
}

/// Sends a "channel pressure" message
void SoundFontPlayer::channelPressure(std::uint8_t val) {}

/// Sends a "polyphonic aftertouch" message to a note
void SoundFontPlayer::polyAftertouch(std::uint8_t note, std::uint8_t val) {}

/// Sends a "control change" message
void SoundFontPlayer::controlChange(DirectMusic::Midi::Control control, std::int32_t val) {}

/// Sends a "program change" (aka "patch change") message
void SoundFontPlayer::programChange(std::uint8_t program) {}

/// Sends a "pitch bend" message
void SoundFontPlayer::pitchBend(std::int16_t val) {}

PlayerFactory SoundFontPlayer::createFactory(const std::string& file) {
    tsf* soundfont = tsf_load_filename(file.c_str());

    return [soundfont](std::uint8_t bankLo, std::uint8_t bankHi, std::uint8_t patch,
        const GUID& bandGuid, const DownloadableSound& dls, std::uint32_t sampleRate, std::uint32_t chans, float vol, float pan) {

        TSFOutputMode outputMode = chans == 1 ? TSF_MONO : TSF_STEREO_INTERLEAVED;
        tsf_set_output(soundfont, outputMode, sampleRate, 0);

        return std::static_pointer_cast<InstrumentPlayer>(std::shared_ptr<SoundFontPlayer>{
            new SoundFontPlayer(soundfont, bankLo, bankHi, patch, dls, sampleRate, chans, vol, pan)
        });
    };
}

PlayerFactory SoundFontPlayer::createMultiFactory(const std::string dir) {
    std::shared_ptr<std::map<GUID, tsf*>> soundfonts = std::make_shared<std::map<GUID, tsf*>>();
    return [soundfonts, dir](std::uint8_t bankLo, std::uint8_t bankHi, std::uint8_t patch,
        const GUID& bandGuid, const DownloadableSound& dls, std::uint32_t sampleRate, std::uint32_t chans, float vol, float pan) {
        tsf* soundfont;
        if (soundfonts->find(bandGuid) == soundfonts->end()) {
            soundfont = tsf_load_filename((dir + "/" + bandGuid.toString() + ".sf2").c_str());
            soundfonts->operator[](bandGuid) = soundfont;
        } else {
            soundfont = soundfonts->at(bandGuid);
        }

        TSFOutputMode outputMode = chans == 1 ? TSF_MONO : TSF_STEREO_INTERLEAVED;
        tsf_set_output(soundfont, outputMode, sampleRate, 0);

        return std::static_pointer_cast<InstrumentPlayer>(std::shared_ptr<SoundFontPlayer>{
            new SoundFontPlayer(soundfont, bankLo, bankHi, patch, dls, sampleRate, chans, vol, pan)
        });
    };
}

#endif<commit_msg>Provide some better errors if loading a soundfont fails<commit_after>#if DMUSIC_TSF_SUPPORT
#include <cassert>
#include <exception>
#include <dmusic/SoundFontPlayer.h>
#include <memory>
#include <cmath>
#define TSF_IMPLEMENTATION
#include "../utils/common/tsf.h"
using namespace DirectMusic;
using namespace DirectMusic::DLS;

static float gainToDecibels(float gain) {
    return 10 * log10(gain);
}

SoundFontPlayer::SoundFontPlayer(tsf* soundfont,
    std::uint8_t bankLo, std::uint8_t bankHi, std::uint8_t patch,
    const DirectMusic::DLS::DownloadableSound& dls,
    std::uint32_t sampleRate,
    std::uint32_t channels,
    float volume,
    float pan)
    : InstrumentPlayer(bankLo, bankHi, patch, dls, sampleRate, channels, volume, pan)
    , m_soundfont(nullptr)
    , m_vol(volume)
    , m_channels(channels) {
    assert(channels <= 2);
    std::uint32_t bank = (bankHi << 16) + bankLo;

    m_pan = pan < -1 ? -1 : pan > 1 ? 1 : pan;
    m_soundfont = soundfont;

    m_preset = tsf_get_presetindex(m_soundfont, 0, patch);
    assert(m_preset >= 0);

    float volFactorRight = sqrt((m_pan + 1) / 2);
    float volFactorLeft = sqrt((-m_pan + 1) / 2);

    tsf_set_preset_panning(m_soundfont, m_preset, volFactorLeft, volFactorRight);
    tsf_set_preset_gain(m_soundfont, m_preset, gainToDecibels(volume));
    tsf_increase_refcount(m_soundfont);
}

SoundFontPlayer::~SoundFontPlayer() {
    tsf_decrease_refcount(m_soundfont);
}

std::uint32_t SoundFontPlayer::renderBlock(std::int16_t *buffer, std::uint32_t count, float volume, bool mix) noexcept {
    if (!mix) {
        tsf_render_short(m_soundfont, buffer, count / m_channels, 0);
    }
    return count;
}

/// Instructs the synthesizer to start playing a note
void SoundFontPlayer::noteOn(std::uint8_t note, std::uint8_t velocity) {
    tsf_note_on(m_soundfont, m_preset, note, velocity / 255.0f);
}

/// Instructs the synthesizer to stop playing a note
void SoundFontPlayer::noteOff(std::uint8_t note, std::uint8_t velocity) {
    tsf_note_off(m_soundfont, m_preset, note);
}

void SoundFontPlayer::allNotesOff() {
    tsf_all_notes_off(m_soundfont, m_preset);
}

/// Sends a "channel pressure" message
void SoundFontPlayer::channelPressure(std::uint8_t val) {}

/// Sends a "polyphonic aftertouch" message to a note
void SoundFontPlayer::polyAftertouch(std::uint8_t note, std::uint8_t val) {}

/// Sends a "control change" message
void SoundFontPlayer::controlChange(DirectMusic::Midi::Control control, std::int32_t val) {}

/// Sends a "program change" (aka "patch change") message
void SoundFontPlayer::programChange(std::uint8_t program) {}

/// Sends a "pitch bend" message
void SoundFontPlayer::pitchBend(std::int16_t val) {}

PlayerFactory SoundFontPlayer::createFactory(const std::string& file) {
    tsf* soundfont = tsf_load_filename(file.c_str());
    if (soundfont == nullptr) {
        throw std::runtime_error("Cannot open " + file);
    }

    return [soundfont](std::uint8_t bankLo, std::uint8_t bankHi, std::uint8_t patch,
        const GUID& bandGuid, const DownloadableSound& dls, std::uint32_t sampleRate, std::uint32_t chans, float vol, float pan) {

        TSFOutputMode outputMode = chans == 1 ? TSF_MONO : TSF_STEREO_INTERLEAVED;
        tsf_set_output(soundfont, outputMode, sampleRate, 0);

        return std::static_pointer_cast<InstrumentPlayer>(std::shared_ptr<SoundFontPlayer>{
            new SoundFontPlayer(soundfont, bankLo, bankHi, patch, dls, sampleRate, chans, vol, pan)
        });
    };
}

PlayerFactory SoundFontPlayer::createMultiFactory(const std::string dir) {
    std::shared_ptr<std::map<GUID, tsf*>> soundfonts = std::make_shared<std::map<GUID, tsf*>>();
    return [soundfonts, dir](std::uint8_t bankLo, std::uint8_t bankHi, std::uint8_t patch,
        const GUID& bandGuid, const DownloadableSound& dls, std::uint32_t sampleRate, std::uint32_t chans, float vol, float pan) {
        tsf* soundfont;
        if (soundfonts->find(bandGuid) == soundfonts->end()) {
            auto file = dir + "/" + bandGuid.toString() + ".sf2";
            soundfont = tsf_load_filename(file.c_str());
            if (soundfont == nullptr) {
                throw std::runtime_error("Cannot open " + file);
            }
            soundfonts->operator[](bandGuid) = soundfont;
        } else {
            soundfont = soundfonts->at(bandGuid);
        }

        TSFOutputMode outputMode = chans == 1 ? TSF_MONO : TSF_STEREO_INTERLEAVED;
        tsf_set_output(soundfont, outputMode, sampleRate, 0);

        return std::static_pointer_cast<InstrumentPlayer>(std::shared_ptr<SoundFontPlayer>{
            new SoundFontPlayer(soundfont, bankLo, bankHi, patch, dls, sampleRate, chans, vol, pan)
        });
    };
}

#endif<|endoftext|>


<commit_before>#pragma once

#include "../StandardInclude.hpp"
#include "../EntityInclude.hpp"

#include "../StateInterface.hpp"

class Ripple
{
public:
	Point Location;
	int Radius;

	// 新しいインスタンスを初期化します
	Ripple(Point location, int radius)
	{
		Location = location;
		Radius = radius;
	}

	void Draw()
	{
		SetDrawBlendMode(DX_BLENDMODE_ALPHA, (int)(255 * 0.5));
		DrawCircle(Location.GetX(), Location.GetY(), Radius, 0xffffff, 0);
		SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 0);
	}
};

class GameTitle : public StateInterface
{
public: static GameTitle &GetInstance(void) { static auto instance = GameTitle(); return instance; }
private: GameTitle() { }

public:
	bool IsInitial = true;
	int LogoHandle;
	int FontHandle;
	vector<Ripple> Ripples;

	// 場面名を取得します
	string StateName()
	{
		return "Title";
	}

	// 更新(ターゲット時のみ)
	void Update()
	{
		if (IsInitial)
		{
			IsInitial = false;

			LogoHandle = LoadGraph("Image/logo.png", 1);
			FontHandle = CreateFontToHandle("メイリオ", 25, 5, DX_FONTTYPE_ANTIALIASING_8X8);
		}

		random_device r;

		if ((int)((double)r() / 0xffffffff * 1000) < 5)
		{
			int x = (int)((double)r() / 0xffffffff * 1280);
			int y = (int)((double)r() / 0xffffffff * 720);

			Ripples.push_back(Ripple(Point(x, y), 0));
		}

		auto it = Ripples.begin();
		while (it != Ripples.end())
		{
			(*it).Radius += 3;

			if ((*it).Radius > 1280 * 1.42)
				it = Ripples.erase(it);
			else
				it++;
		}
	}

	// 描画(常時)
	void Draw(StateEventArgs e)
	{
		if (e.IsActive())
		{
			for (auto ripple : Ripples)
				ripple.Draw();

			DrawFormatString(0, 0, 0xffffff, "波紋数: %d", Ripples.size());

			auto screenRightBottom = Core::GetInstance().ScreenSize.GetWidthHeightAsPoint();
			auto screenCenter = screenRightBottom / 2;

			int imageSize[2];
			GetGraphSize(LogoHandle, &imageSize[0], &imageSize[1]);
			auto logoRightBottom = Point(imageSize[0], imageSize[1]);
			auto logoCenter = logoRightBottom / 2;

			// logo
			auto logoLocation = screenCenter - logoCenter;
			logoLocation.AddY(-150);
			DrawGraph(logoLocation.GetX(), logoLocation.GetY(), LogoHandle, 1);

			// menu
			auto itemCenter = screenCenter;
			Size boxSize(screenRightBottom.GetX() / 3, 40);

			itemCenter.AddY(100);
			DrawMenuItem(itemCenter, boxSize, "Start");

			itemCenter.AddY(60);
			DrawMenuItem(itemCenter, boxSize, "Setting");

			itemCenter.AddY(60);
			DrawMenuItem(itemCenter, boxSize, "End");
		}
	}

	void DrawMenuItem(Point centerPosition, Size boxSize, const char *text)
	{
		SetDrawBlendMode(DX_BLENDMODE_ALPHA, (int)(255 * 0.7));
		boxSize = boxSize / 2;
		DrawBox(centerPosition.GetX() - boxSize.GetWidth(), centerPosition.GetY() - boxSize.GetHeight(), centerPosition.GetX() + boxSize.GetWidth(), centerPosition.GetY() + boxSize.GetHeight(), 0xffffff, 0);
		SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 0);
		DrawStringToHandle(centerPosition.GetX() - GetDrawStringWidthToHandle(text, strlen(text), FontHandle) / 2, centerPosition.GetY() - 25 / 2, text, 0xffffff, FontHandle);
	}
};<commit_msg>Update<commit_after>#pragma once

#include "../StandardInclude.hpp"
#include "../EntityInclude.hpp"

#include "../StateInterface.hpp"

class Ripple
{
public:
	Point Location;
	int Radius;

	// 新しいインスタンスを初期化します
	Ripple(Point location, int radius)
	{
		Location = location;
		Radius = radius;
	}

	void Draw()
	{
		SetDrawBlendMode(DX_BLENDMODE_ALPHA, (int)(255 * 0.5));
		DrawCircle(Location.GetX(), Location.GetY(), Radius, 0xffffff, 0);
		SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 0);
	}
};

class GameTitle : public StateInterface
{
public: static GameTitle &GetInstance(void) { static auto instance = GameTitle(); return instance; }
private: GameTitle() { }

public:
	bool IsInitial = true;
	int LogoHandle;
	int FontHandle;
	vector<Ripple> Ripples;

	// 場面名を取得します
	string StateName()
	{
		return "Title";
	}

	// 更新(ターゲット時のみ)
	void Update()
	{
		if (IsInitial)
		{
			IsInitial = false;

			LogoHandle = LoadGraph("Image/logo.png", 1);
			FontHandle = CreateFontToHandle("メイリオ", 25, 5, DX_FONTTYPE_ANTIALIASING_8X8);
		}

		random_device r;

		int rVal = (int)((double)r() / 0xffffffff * 1000);
		if ((rVal < 5 && Ripples.size() < 3) || (rVal < 100 && Ripples.size() == 0))
		{
			int x = (int)((double)r() / 0xffffffff * 1280);
			int y = (int)((double)r() / 0xffffffff * 720);

			Ripples.push_back(Ripple(Point(x, y), 0));
		}

		auto it = Ripples.begin();
		while (it != Ripples.end())
		{
			(*it).Radius += 3;

			if ((*it).Radius > 1280 * 1.42)
				it = Ripples.erase(it);
			else
				it++;
		}
	}

	// 描画(常時)
	void Draw(StateEventArgs e)
	{
		if (e.IsActive())
		{
			for (auto ripple : Ripples)
				ripple.Draw();

			auto screenRightBottom = Core::GetInstance().ScreenSize.GetWidthHeightAsPoint();
			auto screenCenter = screenRightBottom / 2;

			int imageSize[2];
			GetGraphSize(LogoHandle, &imageSize[0], &imageSize[1]);
			auto logoRightBottom = Point(imageSize[0], imageSize[1]);
			auto logoCenter = logoRightBottom / 2;

			// logo
			auto logoLocation = screenCenter - logoCenter;
			logoLocation.AddY(-150);
			DrawGraph(logoLocation.GetX(), logoLocation.GetY(), LogoHandle, 1);

			// menu
			auto itemCenter = screenCenter;
			Size boxSize(screenRightBottom.GetX() / 3, 40);

			itemCenter.AddY(100);
			DrawMenuItem(itemCenter, boxSize, "Start");

			itemCenter.AddY(60);
			DrawMenuItem(itemCenter, boxSize, "Setting");

			itemCenter.AddY(60);
			DrawMenuItem(itemCenter, boxSize, "End");
		}
	}

	void DrawMenuItem(Point centerPosition, Size boxSize, const char *text)
	{
		SetDrawBlendMode(DX_BLENDMODE_ALPHA, (int)(255 * 0.7));
		boxSize = boxSize / 2;
		DrawBox(centerPosition.GetX() - boxSize.GetWidth(), centerPosition.GetY() - boxSize.GetHeight(), centerPosition.GetX() + boxSize.GetWidth(), centerPosition.GetY() + boxSize.GetHeight(), 0xffffff, 0);
		SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 0);
		DrawStringToHandle(centerPosition.GetX() - GetDrawStringWidthToHandle(text, strlen(text), FontHandle) / 2, centerPosition.GetY() - 25 / 2, text, 0xffffff, FontHandle);
	}
};<|endoftext|>


<commit_before>//
// Created by Sam on 9/25/2017.
//

#include "../include/Game/Core/Game.h"
#include "../include/Game/Core/Player.h"
#include "../include/Network/Server.h"

#include <iostream>
#include "boost/thread.hpp"

int main()
{
    try
    {
        std::cout << "Initializing io_service..." << std::endl;
        boost::asio::io_service io_service;
        std::cout << "Starting server..." << std::endl;
        Server* server = new Server(io_service, 8888);
        std::cout << "Server started!" << std::endl;

        // Run the blocking io_service method run()
        boost::thread ioThread(
        boost::bind(&boost::asio::io_service::run, &io_service));

        // Consistently try to find games.
        while (true)
        {
            if (server->queue.size() >= 2)
            {
                // Get the two players who have been in queue the longest.
                std::cout << "Found 2 players in queue!" << std::endl;

                std::cout << server->queue.size() << " players in queue!" << std::endl;

                // Remove the first 2 players and check if they are still connected.
                Player* firstPlayer = server->queue.front();
                std::cout << firstPlayer->name << " was selected for a game..." << std::endl;
                server->queue.pop();

                Player* secondPlayer = server->queue.front();
                std::cout << secondPlayer->name << " was selected for a game..." << std::endl;
                server->queue.pop();

                std::cout << server->queue.size() << " players in queue!" << std::endl;

                std::cout << "Starting game between " << firstPlayer->name << " and " << secondPlayer->name << "..." << std::endl;

                Game* newGame = new Game({ firstPlayer, secondPlayer }, server);
                newGame->Start();
            }
        }
    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }

    return 0;
}
<commit_msg>Commented out the rudimentary matchmaking<commit_after>//
// Created by Sam on 9/25/2017.
//

#include "../include/Game/Core/Game.h"
#include "../include/Game/Core/Player.h"
#include "../include/Network/Server.h"

#include <iostream>
#include <boost/asio/io_service.hpp>
#include <boost/thread.hpp>

int main()
{
    try
    {
        std::cout << "Initializing io_service..." << std::endl;
        boost::asio::io_service io_service;
        std::cout << "Starting server..." << std::endl;
        Server* server = new Server(io_service, 8888);
        std::cout << "Server started!" << std::endl;

        // Run the blocking io_service method run()
        boost::thread ioThread(
        boost::bind(&boost::asio::io_service::run, &io_service));

        // Consistently try to find games.
        while (true)
        {
//            if (server->queue.size() >= 2)
//            {
//                // Get the two players who have been in queue the longest.
//                std::cout << "Found 2 players in queue!" << std::endl;
//
//                std::cout << server->queue.size() << " players in queue!" << std::endl;
//
//                // Remove the first 2 players and check if they are still connected.
//                Player* firstPlayer = server->queue.front();
//                std::cout << firstPlayer->name << " was selected for a game..." << std::endl;
//                server->queue.pop();
//
//                Player* secondPlayer = server->queue.front();
//                std::cout << secondPlayer->name << " was selected for a game..." << std::endl;
//                server->queue.pop();
//
//                std::cout << server->queue.size() << " players in queue!" << std::endl;
//
//                std::cout << "Starting game between " << firstPlayer->name << " and " << secondPlayer->name << "..." << std::endl;
//
//                //Game* newGame = new Game({ firstPlayer, secondPlayer }, server);
//                //newGame->Start();
//            }
        }
    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }

    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2015 Matthew Harvey
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "activity_filter.hpp"
#include "exact_activity_filter.hpp"
#include "ordinary_activity_filter.hpp"
#include "regex_activity_filter.hpp"
#include "string_utilities.hpp"
#include "true_activity_filter.hpp"
#include <cassert>
#include <string>

using std::string;

namespace swx
{

ActivityFilter*
ActivityFilter::create(string const& p_comparitor, Type p_type)
{
    switch (p_type)
    {
    case Type::ordinary:
        return new OrdinaryActivityFilter(p_comparitor);
    case Type::exact:
        return new ExactActivityFilter(p_comparitor);
    case Type::regex:
        return new RegexActivityFilter(p_comparitor);
    case Type::always_true:
        return new TrueActivityFilter;
    default:
        assert (false);  // we should never reach here
    }
}

ActivityFilter::~ActivityFilter() = default;

bool
ActivityFilter::matches(string const& p_str) const
{
    return does_match(p_str);
}

string
ActivityFilter::replace(string const& p_old_str, string const& p_substitution) const
{
    return
        matches(p_old_str) ?
        squash(do_replace(p_old_str, p_substitution)) :
        p_old_str;
}

string
ActivityFilter::do_replace(string const& p_old_str, string const& p_substitution) const
{
    (void)p_old_str;  // silence compiler warning re. unused param.
    return p_substitution;
}

}  // namespace swx
<commit_msg>Appease minor compiler warning<commit_after>/*
 * Copyright 2015 Matthew Harvey
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "activity_filter.hpp"
#include "exact_activity_filter.hpp"
#include "ordinary_activity_filter.hpp"
#include "regex_activity_filter.hpp"
#include "string_utilities.hpp"
#include "true_activity_filter.hpp"
#include <cassert>
#include <string>

using std::string;

namespace swx
{

ActivityFilter*
ActivityFilter::create(string const& p_comparitor, Type p_type)
{
    switch (p_type)
    {
    case Type::ordinary:
        return new OrdinaryActivityFilter(p_comparitor);
    case Type::exact:
        return new ExactActivityFilter(p_comparitor);
    case Type::regex:
        return new RegexActivityFilter(p_comparitor);
    case Type::always_true:
        return new TrueActivityFilter;
    default:
        assert (false);  // we should never reach here
        return nullptr;  // appease compiler warning
    }
}

ActivityFilter::~ActivityFilter() = default;

bool
ActivityFilter::matches(string const& p_str) const
{
    return does_match(p_str);
}

string
ActivityFilter::replace(string const& p_old_str, string const& p_substitution) const
{
    return
        matches(p_old_str) ?
        squash(do_replace(p_old_str, p_substitution)) :
        p_old_str;
}

string
ActivityFilter::do_replace(string const& p_old_str, string const& p_substitution) const
{
    (void)p_old_str;  // silence compiler warning re. unused param.
    return p_substitution;
}

}  // namespace swx
<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "util.h"
#include "init.h"
#include "rpcclient.h"
#include "rpcprotocol.h"
#include "ui_interface.h" /* for _(...) */
#include "chainparams.h"

#include <boost/filesystem/operations.hpp>

//////////////////////////////////////////////////////////////////////////////
//
// Start
//
static bool AppInitRPC(int argc, char* argv[])
{
    //
    // Parameters
    //
    ParseParameters(argc, argv);
    if (!boost::filesystem::is_directory(GetDataDir(false)))
    {
        fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
        return false;
    }
    try {
        ReadConfigFile(mapArgs, mapMultiArgs);
    } catch(std::exception &e) {
        fprintf(stderr,"Error reading configuration file: %s\n", e.what());
        return false;
    }
    // Check for -testnet or -regtest parameter (TestNet() calls are only valid after this clause)
    if (!SelectParamsFromCommandLine()) {
        fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n");
        return false;
    }

    if (argc<2 || mapArgs.count("-?") || mapArgs.count("--help"))
    {
        // First part of help message is specific to RPC client
        std::string strUsage = _("Bitcoin Core RPC client version") + " " + FormatFullVersion() + "\n\n" +
            _("Usage:") + "\n" +
              "  bitcoin-cli [options] <command> [params]  " + _("Send command to Bitcoin Core") + "\n" +
              "  bitcoin-cli [options] help                " + _("List commands") + "\n" +
              "  bitcoin-cli [options] help <command>      " + _("Get help for a command") + "\n";

        strUsage += "\n" + HelpMessageCli(true);

        fprintf(stdout, "%s", strUsage.c_str());
        return false;
    }
    return true;
}

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

    try
    {
        if(!AppInitRPC(argc, argv))
            return abs(RPC_MISC_ERROR);
    }
    catch (std::exception& e) {
        PrintExceptionContinue(&e, "AppInitRPC()");
        return abs(RPC_MISC_ERROR);
    } catch (...) {
        PrintExceptionContinue(NULL, "AppInitRPC()");
        return abs(RPC_MISC_ERROR);
    }

    int ret = abs(RPC_MISC_ERROR);
    try
    {
        ret = CommandLineRPC(argc, argv);
    }
    catch (std::exception& e) {
        PrintExceptionContinue(&e, "CommandLineRPC()");
    } catch (...) {
        PrintExceptionContinue(NULL, "CommandLineRPC()");
    }
    return ret;
}
<commit_msg>Rebranding: RPC/CLI client<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "util.h"
#include "init.h"
#include "rpcclient.h"
#include "rpcprotocol.h"
#include "ui_interface.h" /* for _(...) */
#include "chainparams.h"

#include <boost/filesystem/operations.hpp>

//////////////////////////////////////////////////////////////////////////////
//
// Start
//
static bool AppInitRPC(int argc, char* argv[])
{
    //
    // Parameters
    //
    ParseParameters(argc, argv);
    if (!boost::filesystem::is_directory(GetDataDir(false)))
    {
        fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
        return false;
    }
    try {
        ReadConfigFile(mapArgs, mapMultiArgs);
    } catch(std::exception &e) {
        fprintf(stderr,"Error reading configuration file: %s\n", e.what());
        return false;
    }
    // Check for -testnet or -regtest parameter (TestNet() calls are only valid after this clause)
    if (!SelectParamsFromCommandLine()) {
        fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n");
        return false;
    }

    if (argc<2 || mapArgs.count("-?") || mapArgs.count("--help"))
    {
        // First part of help message is specific to RPC client
        std::string strUsage = _("Omni Core RPC client version") + " " + FormatFullVersion() + "\n\n" +
            _("Usage:") + "\n" +
              "  mastercore-cli [options] <command> [params]  " + _("Send command to Omni Core") + "\n" +
              "  mastercore-cli [options] help                " + _("List commands") + "\n" +
              "  mastercore-cli [options] help <command>      " + _("Get help for a command") + "\n";

        strUsage += "\n" + HelpMessageCli(true);

        fprintf(stdout, "%s", strUsage.c_str());
        return false;
    }
    return true;
}

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

    try
    {
        if(!AppInitRPC(argc, argv))
            return abs(RPC_MISC_ERROR);
    }
    catch (std::exception& e) {
        PrintExceptionContinue(&e, "AppInitRPC()");
        return abs(RPC_MISC_ERROR);
    } catch (...) {
        PrintExceptionContinue(NULL, "AppInitRPC()");
        return abs(RPC_MISC_ERROR);
    }

    int ret = abs(RPC_MISC_ERROR);
    try
    {
        ret = CommandLineRPC(argc, argv);
    }
    catch (std::exception& e) {
        PrintExceptionContinue(&e, "CommandLineRPC()");
    } catch (...) {
        PrintExceptionContinue(NULL, "CommandLineRPC()");
    }
    return ret;
}
<|endoftext|>


<commit_before>
#include "lispInterface.h"

#include <iostream>

#include <time.h>

#ifdef __PRAXIS_LINUX__
#include <unistd.h>
#include <X11/Xlib.h>
#include "GL/openglut.h"
extern Display * g_pAppDisplay;
extern int g_nLastBreakTime;
#endif

#ifdef __PRAXIS_WINDOWS__
#include <windows.h>
extern "C"
{
    extern HWND g_AppHWND;
    extern int g_nLastBreakTime;
}
#endif

s7_scheme * g_pLisp = 0;
std::string g_sLispOutput;
std::string g_sLispError;

int g_nLispTraceVerbosity = 0;

static s7_pointer our_sleep(s7_scheme *sc, s7_pointer args)
{
#ifdef __PRAXIS_LINUX__
    usleep(1000000);
#endif
#ifdef __PRAXIS_WINDOWS__
    Sleep(1000);
#endif
    return(s7_f(sc));
}

void lispInit()
{
    g_pLisp = s7_init();

    s7_define_function(g_pLisp, "sleep", our_sleep, 0, 0, false, "(sleep) sleeps");
}

#if 0
void lispEndHook(s7_scheme *sc, bool *all_done)
{
    if(g_nLispTraceVerbosity > 0)
    {
        std::string sCode = s7_object_to_c_string(sc, s7_get_main_stack_code(sc));
        s7_pointer curenv = s7_current_environment(sc);
        s7_pointer vars = s7_environment_to_list(sc, curenv);
        std::string sEnvironment = s7_object_to_c_string(sc, vars);
        int nStackDepth = s7_get_stack_depth(sc) - 2; // or 3

        char * sCaller1 = s7_get_main_stack_caller(sc);
        s7_pointer result = s7_get_value(sc);

        std::string sCaller = "";
        if(sCaller1 != 0)
            sCaller = std::string(sCaller1); // s7_object_to_c_string(sc, caller);

        std::string sResult = "";
        if(result != 0)
            sResult = s7_object_to_c_string(sc, result);

        for(int i = 0; i < nStackDepth; i++)
            std::cout << "-- ";

        std::cout << sResult << std::endl;
    }
}
#endif

void lispBeginHook(s7_scheme *sc, bool *all_done)
{
#if 0
    if(g_nLispTraceVerbosity > 0)
    {
        std::string sCode = s7_object_to_c_string(sc, s7_get_main_stack_code(sc));
        s7_pointer curenv = s7_current_environment(sc);
        s7_pointer vars = s7_environment_to_list(sc, curenv);
        std::string sEnvironment = s7_object_to_c_string(sc, vars);
        int nStackDepth = s7_get_stack_depth(sc) - 2; // or 3

        char * sCaller1 = s7_get_main_stack_caller(sc);
        s7_pointer result = s7_get_value(sc);

        std::string sCaller = "";
        if(sCaller1 != 0)
            sCaller = std::string(sCaller1); // s7_object_to_c_string(sc, caller);

        std::string sResult = "";
        if(result != 0)
            sResult = s7_object_to_c_string(sc, result);

        for(int i = 0; i < nStackDepth; i++)
            std::cout << "-- ";

        std::cout << "[" << sCaller << "] " << sEnvironment << " : " << sCode << std::endl;
    }
#endif

#ifdef __PRAXIS_WINDOWS__
    if(::GetAsyncKeyState(VK_LCONTROL) != 0 && ::GetAsyncKeyState(0x51) != 0) // Ctrl-Q pressed
    {
        // Break detected. Check the time since last break.

        // If its too low, ignore.
        int nTime = ::timeGetTime();
        if(nTime < (g_nLastBreakTime + 200))
            return;

        // If its high enough, then break.
        g_nLastBreakTime = nTime;

        *all_done = true;
    }
#endif

#ifdef __PRAXIS_LINUX__
    if(g_pAppDisplay)
    {
        char keys_return[32];
        XQueryKeymap(g_pAppDisplay, keys_return);

        if(keys_return[3] == 1 && keys_return[4] == 32)
        {
            // Break detected. Check the time since last break.

            // If its too low, ignore.
            int nTime = glutGet(GLUT_ELAPSED_TIME);
            if(nTime < (g_nLastBreakTime + 200))
                return;

            // If its high enough, then break.
            g_nLastBreakTime = nTime;

            *all_done = true;
        }
    }
#endif
}

bool lispCall(std::string sCmd)
{
    g_sLispOutput = "";
    g_sLispError = "";

    s7_pointer old_port;
    int gc_loc = -1;
    const char *errmsg = NULL;

    /* trap error messages */
    old_port = s7_set_current_error_port(g_pLisp, s7_open_output_string(g_pLisp));
    if (old_port != s7_nil(g_pLisp))
        gc_loc = s7_gc_protect(g_pLisp, old_port);

    s7_set_begin_hook(g_pLisp, lispBeginHook);
    //s7_set_end_hook(g_pLisp, lispEndHook);
    s7_pointer val = s7_eval_c_string(g_pLisp, sCmd.c_str());
    s7_set_begin_hook(g_pLisp, NULL);
    //s7_set_end_hook(g_pLisp, NULL);

    g_sLispOutput = s7_object_to_c_string(g_pLisp, val);

    /* look for error messages */
    errmsg = s7_get_output_string(g_pLisp, s7_current_error_port(g_pLisp));

    if(errmsg)
        g_sLispError = errmsg;

    s7_close_output_port(g_pLisp, s7_current_error_port(g_pLisp));
    s7_set_current_error_port(g_pLisp, old_port);
    if (gc_loc != -1)
        s7_gc_unprotect_at(g_pLisp, gc_loc);

    return true;
}

std::string & lispGetError()
{
    return g_sLispError;
}

std::string & lispGetOutput()
{
    return g_sLispOutput;
}

void lispClearError()
{
    g_sLispError = "";
}

void lispClearOutput()
{
    g_sLispOutput = "";
}

void lispClose()
{
    // nuthin?
}

#if 0
extern "C"
{

#include <math.h>

// s7 requires this for its g_log function
double round(double number)
{
    return number < 0.0 ? ceil(number - 0.5) : floor(number + 0.5);
}

}
#endif
<commit_msg>lispCall capturing error and output<commit_after>
#include "lispInterface.h"

#include <iostream>

#include <time.h>

#ifdef __PRAXIS_LINUX__
#include <unistd.h>
#include <X11/Xlib.h>
#include "GL/openglut.h"
extern Display * g_pAppDisplay;
extern int g_nLastBreakTime;
#endif

#ifdef __PRAXIS_WINDOWS__
#include <windows.h>
extern "C"
{
    extern HWND g_AppHWND;
    extern int g_nLastBreakTime;
}
#endif

s7_scheme * g_pLisp = 0;
std::string g_sLispOutput;
std::string g_sLispError;

int g_nLispTraceVerbosity = 0;

static s7_pointer our_sleep(s7_scheme *sc, s7_pointer args)
{
#ifdef __PRAXIS_LINUX__
    usleep(1000000);
#endif
#ifdef __PRAXIS_WINDOWS__
    Sleep(1000);
#endif
    return(s7_f(sc));
}

void lispInit()
{
    g_pLisp = s7_init();

    s7_define_function(g_pLisp, "sleep", our_sleep, 0, 0, false, "(sleep) sleeps");
}

#if 0
void lispEndHook(s7_scheme *sc, bool *all_done)
{
    if(g_nLispTraceVerbosity > 0)
    {
        std::string sCode = s7_object_to_c_string(sc, s7_get_main_stack_code(sc));
        s7_pointer curenv = s7_current_environment(sc);
        s7_pointer vars = s7_environment_to_list(sc, curenv);
        std::string sEnvironment = s7_object_to_c_string(sc, vars);
        int nStackDepth = s7_get_stack_depth(sc) - 2; // or 3

        char * sCaller1 = s7_get_main_stack_caller(sc);
        s7_pointer result = s7_get_value(sc);

        std::string sCaller = "";
        if(sCaller1 != 0)
            sCaller = std::string(sCaller1); // s7_object_to_c_string(sc, caller);

        std::string sResult = "";
        if(result != 0)
            sResult = s7_object_to_c_string(sc, result);

        for(int i = 0; i < nStackDepth; i++)
            std::cout << "-- ";

        std::cout << sResult << std::endl;
    }
}
#endif

void lispBeginHook(s7_scheme *sc, bool *all_done)
{
#if 0
    if(g_nLispTraceVerbosity > 0)
    {
        std::string sCode = s7_object_to_c_string(sc, s7_get_main_stack_code(sc));
        s7_pointer curenv = s7_current_environment(sc);
        s7_pointer vars = s7_environment_to_list(sc, curenv);
        std::string sEnvironment = s7_object_to_c_string(sc, vars);
        int nStackDepth = s7_get_stack_depth(sc) - 2; // or 3

        char * sCaller1 = s7_get_main_stack_caller(sc);
        s7_pointer result = s7_get_value(sc);

        std::string sCaller = "";
        if(sCaller1 != 0)
            sCaller = std::string(sCaller1); // s7_object_to_c_string(sc, caller);

        std::string sResult = "";
        if(result != 0)
            sResult = s7_object_to_c_string(sc, result);

        for(int i = 0; i < nStackDepth; i++)
            std::cout << "-- ";

        std::cout << "[" << sCaller << "] " << sEnvironment << " : " << sCode << std::endl;
    }
#endif

#ifdef __PRAXIS_WINDOWS__
    if(::GetAsyncKeyState(VK_LCONTROL) != 0 && ::GetAsyncKeyState(0x51) != 0) // Ctrl-Q pressed
    {
        // Break detected. Check the time since last break.

        // If its too low, ignore.
        int nTime = ::timeGetTime();
        if(nTime < (g_nLastBreakTime + 200))
            return;

        // If its high enough, then break.
        g_nLastBreakTime = nTime;

        *all_done = true;
    }
#endif

#ifdef __PRAXIS_LINUX__
    if(g_pAppDisplay)
    {
        char keys_return[32];
        XQueryKeymap(g_pAppDisplay, keys_return);

        if(keys_return[3] == 1 && keys_return[4] == 32)
        {
            // Break detected. Check the time since last break.

            // If its too low, ignore.
            int nTime = glutGet(GLUT_ELAPSED_TIME);
            if(nTime < (g_nLastBreakTime + 200))
                return;

            // If its high enough, then break.
            g_nLastBreakTime = nTime;

            *all_done = true;
        }
    }
#endif
}

#if 0
bool lispCall(std::string sCmd)
{
    g_sLispOutput = "";
    g_sLispError = "";

    s7_pointer old_port;
    int gc_loc = -1;
    const char *errmsg = NULL;

    /* trap error messages */
    old_port = s7_set_current_error_port(g_pLisp, s7_open_output_string(g_pLisp));
    if (old_port != s7_nil(g_pLisp))
        gc_loc = s7_gc_protect(g_pLisp, old_port);

    s7_set_begin_hook(g_pLisp, lispBeginHook);
    //s7_set_end_hook(g_pLisp, lispEndHook);
    s7_pointer val = s7_eval_c_string(g_pLisp, sCmd.c_str());
    s7_set_begin_hook(g_pLisp, NULL);
    //s7_set_end_hook(g_pLisp, NULL);

    g_sLispOutput = s7_object_to_c_string(g_pLisp, val);

    /* look for error messages */
    errmsg = s7_get_output_string(g_pLisp, s7_current_error_port(g_pLisp));

    if(errmsg)
        g_sLispError = errmsg;

    s7_close_output_port(g_pLisp, s7_current_error_port(g_pLisp));
    s7_set_current_error_port(g_pLisp, old_port);
    if (gc_loc != -1)
        s7_gc_unprotect_at(g_pLisp, gc_loc);

    return true;
}
#endif
bool lispCall(std::string sCmd)
{
    s7_pointer old_error_port;
    s7_pointer old_output_port;
    int gc_loc_error = -1;
    int gc_loc_output = -1;
    const char *errmsg = NULL;
    const char *outmsg = NULL;

    /* trap error messages */
    old_error_port = s7_set_current_error_port(g_pLisp, s7_open_output_string(g_pLisp));
    if (old_error_port != s7_nil(g_pLisp))
        gc_loc_error = s7_gc_protect(g_pLisp, old_error_port);

    /* trap output messages */
    old_output_port = s7_set_current_output_port(g_pLisp, s7_open_output_string(g_pLisp));
    if (old_output_port != s7_nil(g_pLisp))
        gc_loc_output = s7_gc_protect(g_pLisp, old_output_port);

    //lispCall(sCmd);
    g_sLispOutput = "";
    g_sLispError = "";

    s7_set_begin_hook(g_pLisp, lispBeginHook);
    s7_pointer val = s7_eval_c_string(g_pLisp, sCmd.c_str());
    s7_set_begin_hook(g_pLisp, NULL);

    g_sLispOutput = s7_object_to_c_string(g_pLisp, val);

    /* retrieve error messages */
    errmsg = s7_get_output_string(g_pLisp, s7_current_error_port(g_pLisp));
    if(errmsg)
        g_sLispError = errmsg;

    /* retrieve output messages */
    outmsg = s7_get_output_string(g_pLisp, s7_current_output_port(g_pLisp));
    if(outmsg)
      g_sLispOutput = std::string(outmsg) + g_sLispOutput;

    /* restore error port */
    s7_close_output_port(g_pLisp, s7_current_error_port(g_pLisp));
    s7_set_current_error_port(g_pLisp, old_error_port);
    if (gc_loc_error != -1)
      s7_gc_unprotect_at(g_pLisp, gc_loc_error);

    /* restore output port */
    s7_close_output_port(g_pLisp, s7_current_output_port(g_pLisp));
    s7_set_current_output_port(g_pLisp, old_output_port);
    if (gc_loc_output != -1)
      s7_gc_unprotect_at(g_pLisp, gc_loc_output);

    return true;
}

std::string & lispGetError()
{
    return g_sLispError;
}

std::string & lispGetOutput()
{
    return g_sLispOutput;
}

void lispClearError()
{
    g_sLispError = "";
}

void lispClearOutput()
{
    g_sLispOutput = "";
}

void lispClose()
{
    // nuthin?
}

#if 0
extern "C"
{

#include <math.h>

// s7 requires this for its g_log function
double round(double number)
{
    return number < 0.0 ? ceil(number - 0.5) : floor(number + 0.5);
}

}
#endif
<|endoftext|>