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

#include "chrome/browser/extensions/api/serial/serial_connection.h"

#include <sys/ioctl.h>
#include <termios.h>

#if defined(OS_LINUX)
#include <linux/serial.h>
#endif

#if defined(OS_MACOSX)
#include <IOKit/serial/ioss.h>
#endif

namespace extensions {

namespace {

// Convert an integral bit rate to a nominal one. Returns |true|
// if the conversion was successful and |false| otherwise.
bool BitrateToSpeedConstant(int bitrate, speed_t* speed) {
#define BITRATE_TO_SPEED_CASE(x) case x: *speed = B ## x; return true;
  switch (bitrate) {
    BITRATE_TO_SPEED_CASE(0)
    BITRATE_TO_SPEED_CASE(50)
    BITRATE_TO_SPEED_CASE(75)
    BITRATE_TO_SPEED_CASE(110)
    BITRATE_TO_SPEED_CASE(134)
    BITRATE_TO_SPEED_CASE(150)
    BITRATE_TO_SPEED_CASE(200)
    BITRATE_TO_SPEED_CASE(300)
    BITRATE_TO_SPEED_CASE(600)
    BITRATE_TO_SPEED_CASE(1200)
    BITRATE_TO_SPEED_CASE(1800)
    BITRATE_TO_SPEED_CASE(2400)
    BITRATE_TO_SPEED_CASE(4800)
    BITRATE_TO_SPEED_CASE(9600)
    BITRATE_TO_SPEED_CASE(19200)
    BITRATE_TO_SPEED_CASE(38400)
#if defined(OS_POSIX) && !defined(OS_MACOSX)
    BITRATE_TO_SPEED_CASE(57600)
    BITRATE_TO_SPEED_CASE(115200)
    BITRATE_TO_SPEED_CASE(230400)
    BITRATE_TO_SPEED_CASE(460800)
    BITRATE_TO_SPEED_CASE(576000)
    BITRATE_TO_SPEED_CASE(921600)
#endif
    default:
      return false;
  }
#undef BITRATE_TO_SPEED_CASE
}

// Convert a known nominal speed into an integral bitrate. Returns |true|
// if the conversion was successful and |false| otherwise.
bool SpeedConstantToBitrate(speed_t speed, int* bitrate) {
#define SPEED_TO_BITRATE_CASE(x) case B ## x: *bitrate = x; return true;
  switch (speed) {
    SPEED_TO_BITRATE_CASE(0)
    SPEED_TO_BITRATE_CASE(50)
    SPEED_TO_BITRATE_CASE(75)
    SPEED_TO_BITRATE_CASE(110)
    SPEED_TO_BITRATE_CASE(134)
    SPEED_TO_BITRATE_CASE(150)
    SPEED_TO_BITRATE_CASE(200)
    SPEED_TO_BITRATE_CASE(300)
    SPEED_TO_BITRATE_CASE(600)
    SPEED_TO_BITRATE_CASE(1200)
    SPEED_TO_BITRATE_CASE(1800)
    SPEED_TO_BITRATE_CASE(2400)
    SPEED_TO_BITRATE_CASE(4800)
    SPEED_TO_BITRATE_CASE(9600)
    SPEED_TO_BITRATE_CASE(19200)
    SPEED_TO_BITRATE_CASE(38400)
#if defined(OS_POSIX) && !defined(OS_MACOSX)
    SPEED_TO_BITRATE_CASE(57600)
    SPEED_TO_BITRATE_CASE(115200)
    SPEED_TO_BITRATE_CASE(230400)
    SPEED_TO_BITRATE_CASE(460800)
    SPEED_TO_BITRATE_CASE(576000)
    SPEED_TO_BITRATE_CASE(921600)
#endif
    default:
      return false;
  }
#undef SPEED_TO_BITRATE_CASE
}

bool SetCustomBitrate(base::PlatformFile file,
                      struct termios* config,
                      int bitrate) {
#if defined(OS_LINUX)
  struct serial_struct serial;
  if (ioctl(file, TIOCGSERIAL, &serial) < 0) {
    return false;
  }
  serial.flags = (serial.flags & ~ASYNC_SPD_MASK) | ASYNC_SPD_CUST;
  serial.custom_divisor = serial.baud_base / bitrate;
  if (serial.custom_divisor < 1) {
    serial.custom_divisor = 1;
  }
  cfsetispeed(config, B38400);
  cfsetospeed(config, B38400);
  return ioctl(file, TIOCSSERIAL, &serial) >= 0;
#elif defined(OS_MACOSX)
  speed_t speed = static_cast<speed_t>(bitrate);
  if (ioctl(file, IOSSIOSPEED, &speed) >= 0)
    return true;
  // Where IOSSIOSPEED is unsupported, attempt to set
  // the speed directly to the requested value.
  cfsetispeed(config, speed);
  cfsetospeed(config, speed);
  return true;
#else
  return false;
#endif
}

}  // namespace

bool SerialConnection::ConfigurePort(
    const api::serial::ConnectionOptions& options) {
  struct termios config;
  tcgetattr(file_, &config);
  if (options.bitrate.get()) {
    if (*options.bitrate >= 0) {
      speed_t bitrate_opt = B0;
      if (BitrateToSpeedConstant(*options.bitrate, &bitrate_opt)) {
        cfsetispeed(&config, bitrate_opt);
        cfsetospeed(&config, bitrate_opt);
      } else {
        // Attempt to set a custom speed.
        if (!SetCustomBitrate(file_, &config, *options.bitrate)) {
          return false;
        }
      }
    }
  }
  if (options.data_bits != api::serial::DATA_BITS_NONE) {
    config.c_cflag &= ~CSIZE;
    switch (options.data_bits) {
      case api::serial::DATA_BITS_SEVEN:
        config.c_cflag |= CS7;
        break;
      case api::serial::DATA_BITS_EIGHT:
      default:
        config.c_cflag |= CS8;
        break;
    }
  }
  if (options.parity_bit != api::serial::PARITY_BIT_NONE) {
    switch (options.parity_bit) {
      case api::serial::PARITY_BIT_EVEN:
        config.c_cflag |= PARENB;
        config.c_cflag &= ~PARODD;
        break;
      case api::serial::PARITY_BIT_ODD:
        config.c_cflag |= (PARODD | PARENB);
        break;
      case api::serial::PARITY_BIT_NO:
      default:
        config.c_cflag &= ~(PARODD | PARENB);
        break;
    }
  }
  if (options.stop_bits != api::serial::STOP_BITS_NONE) {
    switch (options.stop_bits) {
      case api::serial::STOP_BITS_TWO:
        config.c_cflag |= CSTOPB;
        break;
      case api::serial::STOP_BITS_ONE:
      default:
        config.c_cflag &= ~CSTOPB;
        break;
    }
  }
  if (options.cts_flow_control.get()) {
    if (*options.cts_flow_control){
      config.c_cflag |= CRTSCTS;
    } else {
      config.c_cflag &= ~CRTSCTS;
    }
  }
  return tcsetattr(file_, TCSANOW, &config) == 0;
}

bool SerialConnection::PostOpen() {
  struct termios config;
  tcgetattr(file_, &config);

  // Set flags for 'raw' operation
  config.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHONL | ISIG);
  config.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR |
                      ICRNL | IXON);
  config.c_oflag &= ~OPOST;

  // CLOCAL causes the system to disregard the DCD signal state.
  // CREAD enables reading from the port.
  config.c_cflag |= (CLOCAL | CREAD);

  return tcsetattr(file_, TCSANOW, &config) == 0;
}

bool SerialConnection::Flush() const {
  return tcflush(file_, TCIOFLUSH) == 0;
}

bool SerialConnection::GetControlSignals(
    api::serial::DeviceControlSignals* signals) const {
  int status;
  if (ioctl(file_, TIOCMGET, &status) == -1) {
    return false;
  }

  signals->dcd = (status & TIOCM_CAR) != 0;
  signals->cts = (status & TIOCM_CTS) != 0;
  signals->dsr = (status & TIOCM_DSR) != 0;
  signals->ri = (status & TIOCM_RI) != 0;
  return true;
}

bool SerialConnection::SetControlSignals(
    const api::serial::HostControlSignals& signals) {
  int status;

  if (ioctl(file_, TIOCMGET, &status) == -1) {
    return false;
  }

  if (signals.dtr.get()) {
    if (*signals.dtr) {
      status |= TIOCM_DTR;
    } else {
      status &= ~TIOCM_DTR;
    }
  }

  if (signals.rts.get()) {
    if (*signals.rts){
      status |= TIOCM_RTS;
    } else{
      status &= ~TIOCM_RTS;
    }
  }

  return ioctl(file_, TIOCMSET, &status) == 0;
}

bool SerialConnection::GetPortInfo(api::serial::ConnectionInfo* info) const {
  struct termios config;
  if (tcgetattr(file_, &config) == -1) {
    return false;
  }
  speed_t ispeed = cfgetispeed(&config);
  speed_t ospeed = cfgetospeed(&config);
  if (ispeed == ospeed) {
    int bitrate = 0;
    if (SpeedConstantToBitrate(ispeed, &bitrate)) {
      info->bitrate.reset(new int(bitrate));
    }
  }
  if ((config.c_cflag & CSIZE) == CS7) {
    info->data_bits = api::serial::DATA_BITS_SEVEN;
  } else if ((config.c_cflag & CSIZE) == CS8) {
    info->data_bits = api::serial::DATA_BITS_EIGHT;
  } else {
    info->data_bits = api::serial::DATA_BITS_NONE;
  }
  if (config.c_cflag & PARENB) {
    info->parity_bit = (config.c_cflag & PARODD) ? api::serial::PARITY_BIT_ODD
                                                 : api::serial::PARITY_BIT_EVEN;
  } else {
    info->parity_bit = api::serial::PARITY_BIT_NO;
  }
  info->stop_bits = (config.c_cflag & CSTOPB) ? api::serial::STOP_BITS_TWO
                                              : api::serial::STOP_BITS_ONE;
  info->cts_flow_control.reset(new bool((config.c_cflag & CRTSCTS) != 0));
  return true;
}

std::string SerialConnection::MaybeFixUpPortName(
    const std::string &port_name) {
  return port_name;
}

}  // namespace extensions
<commit_msg>Revert 249835 "Add fallback support for custom serial baud rates..."<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/api/serial/serial_connection.h"

#include <sys/ioctl.h>
#include <termios.h>

#if defined(OS_LINUX)
#include <linux/serial.h>
#endif

#if defined(OS_MACOSX)
#include <IOKit/serial/ioss.h>
#endif

namespace extensions {

namespace {

// Convert an integral bit rate to a nominal one. Returns |true|
// if the conversion was successful and |false| otherwise.
bool BitrateToSpeedConstant(int bitrate, speed_t* speed) {
#define BITRATE_TO_SPEED_CASE(x) case x: *speed = B ## x; return true;
  switch (bitrate) {
    BITRATE_TO_SPEED_CASE(0)
    BITRATE_TO_SPEED_CASE(50)
    BITRATE_TO_SPEED_CASE(75)
    BITRATE_TO_SPEED_CASE(110)
    BITRATE_TO_SPEED_CASE(134)
    BITRATE_TO_SPEED_CASE(150)
    BITRATE_TO_SPEED_CASE(200)
    BITRATE_TO_SPEED_CASE(300)
    BITRATE_TO_SPEED_CASE(600)
    BITRATE_TO_SPEED_CASE(1200)
    BITRATE_TO_SPEED_CASE(1800)
    BITRATE_TO_SPEED_CASE(2400)
    BITRATE_TO_SPEED_CASE(4800)
    BITRATE_TO_SPEED_CASE(9600)
    BITRATE_TO_SPEED_CASE(19200)
    BITRATE_TO_SPEED_CASE(38400)
#if defined(OS_POSIX) && !defined(OS_MACOSX)
    BITRATE_TO_SPEED_CASE(57600)
    BITRATE_TO_SPEED_CASE(115200)
    BITRATE_TO_SPEED_CASE(230400)
    BITRATE_TO_SPEED_CASE(460800)
    BITRATE_TO_SPEED_CASE(576000)
    BITRATE_TO_SPEED_CASE(921600)
#endif
    default:
      return false;
  }
#undef BITRATE_TO_SPEED_CASE
}

// Convert a known nominal speed into an integral bitrate. Returns |true|
// if the conversion was successful and |false| otherwise.
bool SpeedConstantToBitrate(speed_t speed, int* bitrate) {
#define SPEED_TO_BITRATE_CASE(x) case B ## x: *bitrate = x; return true;
  switch (speed) {
    SPEED_TO_BITRATE_CASE(0)
    SPEED_TO_BITRATE_CASE(50)
    SPEED_TO_BITRATE_CASE(75)
    SPEED_TO_BITRATE_CASE(110)
    SPEED_TO_BITRATE_CASE(134)
    SPEED_TO_BITRATE_CASE(150)
    SPEED_TO_BITRATE_CASE(200)
    SPEED_TO_BITRATE_CASE(300)
    SPEED_TO_BITRATE_CASE(600)
    SPEED_TO_BITRATE_CASE(1200)
    SPEED_TO_BITRATE_CASE(1800)
    SPEED_TO_BITRATE_CASE(2400)
    SPEED_TO_BITRATE_CASE(4800)
    SPEED_TO_BITRATE_CASE(9600)
    SPEED_TO_BITRATE_CASE(19200)
    SPEED_TO_BITRATE_CASE(38400)
#if defined(OS_POSIX) && !defined(OS_MACOSX)
    SPEED_TO_BITRATE_CASE(57600)
    SPEED_TO_BITRATE_CASE(115200)
    SPEED_TO_BITRATE_CASE(230400)
    SPEED_TO_BITRATE_CASE(460800)
    SPEED_TO_BITRATE_CASE(576000)
    SPEED_TO_BITRATE_CASE(921600)
#endif
    default:
      return false;
  }
#undef SPEED_TO_BITRATE_CASE
}

bool SetCustomBitrate(base::PlatformFile file,
                      struct termios* config,
                      int bitrate) {
#if defined(OS_LINUX)
  struct serial_struct serial;
  if (ioctl(file, TIOCGSERIAL, &serial) < 0) {
    return false;
  }
  serial.flags = (serial.flags & ~ASYNC_SPD_MASK) | ASYNC_SPD_CUST;
  serial.custom_divisor = serial.baud_base / bitrate;
  if (serial.custom_divisor < 1) {
    serial.custom_divisor = 1;
  }
  cfsetispeed(config, B38400);
  cfsetospeed(config, B38400);
  return ioctl(file, TIOCSSERIAL, &serial) >= 0;
#elif defined(OS_MACOSX)
  speed_t speed = static_cast<speed_t>(bitrate);
  return ioctl(file, IOSSIOSPEED, &speed) != -1;
#else
  return false;
#endif
}

}  // namespace

bool SerialConnection::ConfigurePort(
    const api::serial::ConnectionOptions& options) {
  struct termios config;
  tcgetattr(file_, &config);
  if (options.bitrate.get()) {
    if (*options.bitrate >= 0) {
      speed_t bitrate_opt = B0;
      if (BitrateToSpeedConstant(*options.bitrate, &bitrate_opt)) {
        cfsetispeed(&config, bitrate_opt);
        cfsetospeed(&config, bitrate_opt);
      } else {
        // Attempt to set a custom speed.
        if (!SetCustomBitrate(file_, &config, *options.bitrate)) {
          return false;
        }
      }
    }
  }
  if (options.data_bits != api::serial::DATA_BITS_NONE) {
    config.c_cflag &= ~CSIZE;
    switch (options.data_bits) {
      case api::serial::DATA_BITS_SEVEN:
        config.c_cflag |= CS7;
        break;
      case api::serial::DATA_BITS_EIGHT:
      default:
        config.c_cflag |= CS8;
        break;
    }
  }
  if (options.parity_bit != api::serial::PARITY_BIT_NONE) {
    switch (options.parity_bit) {
      case api::serial::PARITY_BIT_EVEN:
        config.c_cflag |= PARENB;
        config.c_cflag &= ~PARODD;
        break;
      case api::serial::PARITY_BIT_ODD:
        config.c_cflag |= (PARODD | PARENB);
        break;
      case api::serial::PARITY_BIT_NO:
      default:
        config.c_cflag &= ~(PARODD | PARENB);
        break;
    }
  }
  if (options.stop_bits != api::serial::STOP_BITS_NONE) {
    switch (options.stop_bits) {
      case api::serial::STOP_BITS_TWO:
        config.c_cflag |= CSTOPB;
        break;
      case api::serial::STOP_BITS_ONE:
      default:
        config.c_cflag &= ~CSTOPB;
        break;
    }
  }
  if (options.cts_flow_control.get()) {
    if (*options.cts_flow_control){
      config.c_cflag |= CRTSCTS;
    } else {
      config.c_cflag &= ~CRTSCTS;
    }
  }
  return tcsetattr(file_, TCSANOW, &config) == 0;
}

bool SerialConnection::PostOpen() {
  struct termios config;
  tcgetattr(file_, &config);

  // Set flags for 'raw' operation
  config.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHONL | ISIG);
  config.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR |
                      ICRNL | IXON);
  config.c_oflag &= ~OPOST;

  // CLOCAL causes the system to disregard the DCD signal state.
  // CREAD enables reading from the port.
  config.c_cflag |= (CLOCAL | CREAD);

  return tcsetattr(file_, TCSANOW, &config) == 0;
}

bool SerialConnection::Flush() const {
  return tcflush(file_, TCIOFLUSH) == 0;
}

bool SerialConnection::GetControlSignals(
    api::serial::DeviceControlSignals* signals) const {
  int status;
  if (ioctl(file_, TIOCMGET, &status) == -1) {
    return false;
  }

  signals->dcd = (status & TIOCM_CAR) != 0;
  signals->cts = (status & TIOCM_CTS) != 0;
  signals->dsr = (status & TIOCM_DSR) != 0;
  signals->ri = (status & TIOCM_RI) != 0;
  return true;
}

bool SerialConnection::SetControlSignals(
    const api::serial::HostControlSignals& signals) {
  int status;

  if (ioctl(file_, TIOCMGET, &status) == -1) {
    return false;
  }

  if (signals.dtr.get()) {
    if (*signals.dtr) {
      status |= TIOCM_DTR;
    } else {
      status &= ~TIOCM_DTR;
    }
  }

  if (signals.rts.get()) {
    if (*signals.rts){
      status |= TIOCM_RTS;
    } else{
      status &= ~TIOCM_RTS;
    }
  }

  return ioctl(file_, TIOCMSET, &status) == 0;
}

bool SerialConnection::GetPortInfo(api::serial::ConnectionInfo* info) const {
  struct termios config;
  if (tcgetattr(file_, &config) == -1) {
    return false;
  }
  speed_t ispeed = cfgetispeed(&config);
  speed_t ospeed = cfgetospeed(&config);
  if (ispeed == ospeed) {
    int bitrate = 0;
    if (SpeedConstantToBitrate(ispeed, &bitrate)) {
      info->bitrate.reset(new int(bitrate));
    }
  }
  if ((config.c_cflag & CSIZE) == CS7) {
    info->data_bits = api::serial::DATA_BITS_SEVEN;
  } else if ((config.c_cflag & CSIZE) == CS8) {
    info->data_bits = api::serial::DATA_BITS_EIGHT;
  } else {
    info->data_bits = api::serial::DATA_BITS_NONE;
  }
  if (config.c_cflag & PARENB) {
    info->parity_bit = (config.c_cflag & PARODD) ? api::serial::PARITY_BIT_ODD
                                                 : api::serial::PARITY_BIT_EVEN;
  } else {
    info->parity_bit = api::serial::PARITY_BIT_NO;
  }
  info->stop_bits = (config.c_cflag & CSTOPB) ? api::serial::STOP_BITS_TWO
                                              : api::serial::STOP_BITS_ONE;
  info->cts_flow_control.reset(new bool((config.c_cflag & CRTSCTS) != 0));
  return true;
}

std::string SerialConnection::MaybeFixUpPortName(
    const std::string &port_name) {
  return port_name;
}

}  // namespace extensions
<|endoftext|>


<commit_before>// Copyright (c) 2011 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/stringprintf.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_install_dialog.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/browser/extensions/webstore_installer.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/common/notification_observer.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_service.h"
#include "net/base/mock_host_resolver.h"

namespace {

class WebstoreInstallListener : public WebstoreInstaller::Delegate {
 public:
  WebstoreInstallListener()
      : received_failure_(false), received_success_(false) {}

  void OnExtensionInstallSuccess(const std::string& id) OVERRIDE;
  void OnExtensionInstallFailure(const std::string& id,
                                 const std::string& error) OVERRIDE;
  void Wait();

  bool received_failure() const { return received_failure_; }
  bool received_success() const { return received_success_; }
  const std::string& id() const { return id_; }
  const std::string& error() const { return error_; }

 private:
  bool received_failure_;
  bool received_success_;
  std::string id_;
  std::string error_;
};

void WebstoreInstallListener::OnExtensionInstallSuccess(const std::string& id) {
  received_success_ = true;
  id_ = id;
  MessageLoopForUI::current()->Quit();
}

void WebstoreInstallListener::OnExtensionInstallFailure(
    const std::string& id, const std::string& error) {
  received_failure_ = true;
  id_ = id;
  error_ = error;
  MessageLoopForUI::current()->Quit();
}

void WebstoreInstallListener::Wait() {
  if (received_success_ || received_failure_)
    return;

  ui_test_utils::RunMessageLoop();
}

}  // namespace

// A base class for tests below.
class ExtensionWebstorePrivateApiTest : public ExtensionApiTest {
 public:
  void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(switches::kAppsGalleryURL,
        "http://www.example.com");
  }

  void SetUpInProcessBrowserTestFixture() OVERRIDE {
    // Start up the test server and get us ready for calling the install
    // API functions.
    host_resolver()->AddRule("www.example.com", "127.0.0.1");
    ASSERT_TRUE(test_server()->Start());
    BeginInstallWithManifestFunction::SetIgnoreUserGestureForTests(true);
    SetExtensionInstallDialogForManifestAutoConfirmForTests(true);
    ExtensionInstallUI::DisableFailureUIForTests();
  }

 protected:
  // Returns a test server URL, but with host 'www.example.com' so it matches
  // the web store app's extent that we set up via command line flags.
  GURL GetTestServerURL(const std::string& path) {
    GURL url = test_server()->GetURL(
        std::string("files/extensions/api_test/webstore_private/") + path);

    // Replace the host with 'www.example.com' so it matches the web store
    // app's extent.
    GURL::Replacements replace_host;
    std::string host_str("www.example.com");
    replace_host.SetHostStr(host_str);

    return url.ReplaceComponents(replace_host);
  }

  // Navigates to |page| and runs the Extension API test there. Any downloads
  // of extensions will return the contents of |crx_file|.
  bool RunInstallTest(const std::string& page, const std::string& crx_file) {
    GURL crx_url = GetTestServerURL(crx_file);
    CommandLine::ForCurrentProcess()->AppendSwitchASCII(
        switches::kAppsGalleryUpdateURL, crx_url.spec());

    GURL page_url = GetTestServerURL(page);
    return RunPageTest(page_url.spec());
  }

  ExtensionService* service() {
    return browser()->profile()->GetExtensionService();
  }
};

// Test cases where the user accepts the install confirmation dialog.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallAccepted) {
  ASSERT_TRUE(RunInstallTest("accepted.html", "extension.crx"));
}

// Tests passing a localized name.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallLocalized) {
  ASSERT_TRUE(RunInstallTest("localized.html", "localized_extension.crx"));
}

// Now test the case where the user cancels the confirmation dialog.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallCancelled) {
  SetExtensionInstallDialogForManifestAutoConfirmForTests(false);
  ASSERT_TRUE(RunInstallTest("cancelled.html", "extension.crx"));
}

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallNoGesture) {
  BeginInstallFunction::SetIgnoreUserGestureForTests(false);
  ASSERT_TRUE(RunInstallTest("no_user_gesture.html", "extension.crx"));
}

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
                       IncorrectManifest1) {
  WebstoreInstallListener listener;
  WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);
  ASSERT_TRUE(RunInstallTest("incorrect_manifest1.html", "extension.crx"));
  listener.Wait();
  ASSERT_TRUE(listener.received_failure());
  ASSERT_EQ("Manifest file is invalid.", listener.error());
}

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
                       IncorrectManifest2) {
  WebstoreInstallListener listener;
  WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);
  ASSERT_TRUE(RunInstallTest("incorrect_manifest2.html", "extension.crx"));
  listener.Wait();
  EXPECT_TRUE(listener.received_failure());
  ASSERT_EQ("Manifest file is invalid.", listener.error());
}

// Tests that we can request an app installed bubble (instead of the default
// UI when an app is installed).
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
                       AppInstallBubble) {
  WebstoreInstallListener listener;
  WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);
  ASSERT_TRUE(RunInstallTest("app_install_bubble.html", "app.crx"));
  listener.Wait();
  ASSERT_TRUE(listener.received_success());
  ASSERT_EQ("iladmdjkfniedhfhcfoefgojhgaiaccc", listener.id());
}

// Tests using the iconUrl parameter to the install function.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
                       IconUrl) {
  ASSERT_TRUE(RunInstallTest("icon_url.html", "extension.crx"));
}
<commit_msg>Fix flaky AppInstallBundle test.<commit_after>// Copyright (c) 2011 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/stringprintf.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_install_dialog.h"
#include "chrome/browser/extensions/extension_install_ui.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_webstore_private_api.h"
#include "chrome/browser/extensions/webstore_installer.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/common/notification_observer.h"
#include "content/common/notification_registrar.h"
#include "content/common/notification_service.h"
#include "net/base/mock_host_resolver.h"

namespace {

class WebstoreInstallListener : public WebstoreInstaller::Delegate {
 public:
  WebstoreInstallListener()
      : received_failure_(false), received_success_(false), waiting_(false) {}

  void OnExtensionInstallSuccess(const std::string& id) OVERRIDE;
  void OnExtensionInstallFailure(const std::string& id,
                                 const std::string& error) OVERRIDE;
  void Wait();

  bool received_failure() const { return received_failure_; }
  bool received_success() const { return received_success_; }
  const std::string& id() const { return id_; }
  const std::string& error() const { return error_; }

 private:
  bool received_failure_;
  bool received_success_;
  bool waiting_;
  std::string id_;
  std::string error_;
};

void WebstoreInstallListener::OnExtensionInstallSuccess(const std::string& id) {
  received_success_ = true;
  id_ = id;

  if (waiting_) {
    waiting_ = false;
    MessageLoopForUI::current()->Quit();
  }
}

void WebstoreInstallListener::OnExtensionInstallFailure(
    const std::string& id, const std::string& error) {
  received_failure_ = true;
  id_ = id;
  error_ = error;

  if (waiting_) {
    waiting_ = false;
    MessageLoopForUI::current()->Quit();
  }
}

void WebstoreInstallListener::Wait() {
  if (received_success_ || received_failure_)
    return;

  waiting_ = true;
  ui_test_utils::RunMessageLoop();
}

}  // namespace

// A base class for tests below.
class ExtensionWebstorePrivateApiTest : public ExtensionApiTest {
 public:
  void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    ExtensionApiTest::SetUpCommandLine(command_line);
    command_line->AppendSwitchASCII(switches::kAppsGalleryURL,
        "http://www.example.com");
  }

  void SetUpInProcessBrowserTestFixture() OVERRIDE {
    // Start up the test server and get us ready for calling the install
    // API functions.
    host_resolver()->AddRule("www.example.com", "127.0.0.1");
    ASSERT_TRUE(test_server()->Start());
    BeginInstallWithManifestFunction::SetIgnoreUserGestureForTests(true);
    SetExtensionInstallDialogForManifestAutoConfirmForTests(true);
    ExtensionInstallUI::DisableFailureUIForTests();
  }

 protected:
  // Returns a test server URL, but with host 'www.example.com' so it matches
  // the web store app's extent that we set up via command line flags.
  GURL GetTestServerURL(const std::string& path) {
    GURL url = test_server()->GetURL(
        std::string("files/extensions/api_test/webstore_private/") + path);

    // Replace the host with 'www.example.com' so it matches the web store
    // app's extent.
    GURL::Replacements replace_host;
    std::string host_str("www.example.com");
    replace_host.SetHostStr(host_str);

    return url.ReplaceComponents(replace_host);
  }

  // Navigates to |page| and runs the Extension API test there. Any downloads
  // of extensions will return the contents of |crx_file|.
  bool RunInstallTest(const std::string& page, const std::string& crx_file) {
    GURL crx_url = GetTestServerURL(crx_file);
    CommandLine::ForCurrentProcess()->AppendSwitchASCII(
        switches::kAppsGalleryUpdateURL, crx_url.spec());

    GURL page_url = GetTestServerURL(page);
    return RunPageTest(page_url.spec());
  }

  ExtensionService* service() {
    return browser()->profile()->GetExtensionService();
  }
};

// Test cases where the user accepts the install confirmation dialog.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallAccepted) {
  ASSERT_TRUE(RunInstallTest("accepted.html", "extension.crx"));
}

// Tests passing a localized name.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallLocalized) {
  ASSERT_TRUE(RunInstallTest("localized.html", "localized_extension.crx"));
}

// Now test the case where the user cancels the confirmation dialog.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallCancelled) {
  SetExtensionInstallDialogForManifestAutoConfirmForTests(false);
  ASSERT_TRUE(RunInstallTest("cancelled.html", "extension.crx"));
}

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest, InstallNoGesture) {
  BeginInstallFunction::SetIgnoreUserGestureForTests(false);
  ASSERT_TRUE(RunInstallTest("no_user_gesture.html", "extension.crx"));
}

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
                       IncorrectManifest1) {
  WebstoreInstallListener listener;
  WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);
  ASSERT_TRUE(RunInstallTest("incorrect_manifest1.html", "extension.crx"));
  listener.Wait();
  ASSERT_TRUE(listener.received_failure());
  ASSERT_EQ("Manifest file is invalid.", listener.error());
}

IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
                       IncorrectManifest2) {
  WebstoreInstallListener listener;
  WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);
  ASSERT_TRUE(RunInstallTest("incorrect_manifest2.html", "extension.crx"));
  listener.Wait();
  EXPECT_TRUE(listener.received_failure());
  ASSERT_EQ("Manifest file is invalid.", listener.error());
}

// Tests that we can request an app installed bubble (instead of the default
// UI when an app is installed).
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
                       AppInstallBubble) {
  WebstoreInstallListener listener;
  WebstorePrivateApi::SetWebstoreInstallerDelegateForTesting(&listener);
  ASSERT_TRUE(RunInstallTest("app_install_bubble.html", "app.crx"));
  listener.Wait();
  ASSERT_TRUE(listener.received_success());
  ASSERT_EQ("iladmdjkfniedhfhcfoefgojhgaiaccc", listener.id());
}

// Tests using the iconUrl parameter to the install function.
IN_PROC_BROWSER_TEST_F(ExtensionWebstorePrivateApiTest,
                       IconUrl) {
  ASSERT_TRUE(RunInstallTest("icon_url.html", "extension.crx"));
}
<|endoftext|>


<commit_before>#include "StdAfx.h"
#include "TiffParser.h"

/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

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

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

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

    http://www.klauspost.com
*/

namespace RawSpeed {

TiffParser::TiffParser(FileMap* inputData): mInput(inputData), mRootIFD(0) {
  host_endian = getHostEndianness();
}

TiffParser::~TiffParser(void) {
  if (mRootIFD)
    delete mRootIFD;
  mRootIFD = NULL;
}

#ifdef CHECKSIZE
#undef CHECKSIZE
#endif
#ifdef CHECKPTR
#undef CHECKPTR
#endif

#define CHECKSIZE(A) if (A >= mInput->getSize()) throw TiffParserException("Error reading TIFF structure (size out of bounds). File Corrupt")
#define CHECKPTR(A) if ((int)A >= ((int)(mInput->data) + size))) throw TiffParserException("Error reading TIFF structure (size out of bounds). File Corrupt")

void TiffParser::parseData() {
  const unsigned char* data = mInput->getData(0);
  if (mInput->getSize() < 16)
    throw TiffParserException("Not a TIFF file (size too small)");
  if (data[0] != 0x49 || data[1] != 0x49) {
    tiff_endian = big;
    if (data[0] != 0x4D || data[1] != 0x4D)
      throw TiffParserException("Not a TIFF file (ID)");

    if (data[3] != 42)
      throw TiffParserException("Not a TIFF file (magic 42)");
  } else {
    tiff_endian = little;
    if (data[2] != 42 && data[2] != 0x52 && data[2] != 0x55) // ORF has 0x52, RW2 0x55 - Brillant!
      throw TiffParserException("Not a TIFF file (magic 42)");
  }

  if (tiff_endian == host_endian)
    mRootIFD = new TiffIFD();
  else
    mRootIFD = new TiffIFDBE();

  uint32 nextIFD;
  data = mInput->getData(4);
  if (tiff_endian == host_endian) {
    nextIFD = *(int*)data;
  } else {
    nextIFD = (unsigned int)data[0] << 24 | (unsigned int)data[1] << 16 | (unsigned int)data[2] << 8 | (unsigned int)data[3];
  }
  while (nextIFD) {
    CHECKSIZE(nextIFD);

    if (tiff_endian == host_endian)
      mRootIFD->mSubIFD.push_back(new TiffIFD(mInput, nextIFD));
    else
      mRootIFD->mSubIFD.push_back(new TiffIFDBE(mInput, nextIFD));

    nextIFD = mRootIFD->mSubIFD.back()->getNextIFD();
  }
}

RawDecoder* TiffParser::getDecoder() {
  vector<TiffIFD*> potentials;
  potentials = mRootIFD->getIFDsWithTag(DNGVERSION);

  if (!potentials.empty()) {  // We have a dng image entry
    TiffIFD *t = potentials[0];
    const unsigned char* c = t->getEntry(DNGVERSION)->getData();
    if (c[0] > 1)
      throw TiffParserException("DNG version too new.");
    if (c[1] > 2)
      throw TiffParserException("DNG version not supported.");
    return new DngDecoder(mRootIFD, mInput);
  }

  potentials = mRootIFD->getIFDsWithTag(MAKE);

  if (!potentials.empty()) {  // We have make entry
    for (vector<TiffIFD*>::iterator i = potentials.begin(); i != potentials.end(); ++i) {
      string make = (*i)->getEntry(MAKE)->getString();
      TrimSpaces(make);
      if (!make.compare("Canon")) {
        return new Cr2Decoder(mRootIFD, mInput);
      }
      if (!make.compare("NIKON CORPORATION")) {
        return new NefDecoder(mRootIFD, mInput);
      }
      if (!make.compare("NIKON")) {
        return new NefDecoder(mRootIFD, mInput);
      }
      if (!make.compare("OLYMPUS IMAGING CORP.")) {
        return new OrfDecoder(mRootIFD, mInput);
      }
      if (!make.compare("SONY")) {
        return new ArwDecoder(mRootIFD, mInput);
      }
      if (!make.compare("PENTAX Corporation ")) {
        return new PefDecoder(mRootIFD, mInput);
      }
      if (!make.compare("PENTAX")) {
        return new PefDecoder(mRootIFD, mInput);
      }
      if (!make.compare("Panasonic")) {
        return new Rw2Decoder(mRootIFD, mInput);
      }
      if (!make.compare("SAMSUNG")) {
        return new SrwDecoder(mRootIFD, mInput);
      }
    }
  }
  throw TiffParserException("No decoder found. Sorry.");
  return NULL;
}

} // namespace RawSpeed
<commit_msg>Attempt to decode all v1.x DNG images.<commit_after>#include "StdAfx.h"
#include "TiffParser.h"

/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

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

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

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

    http://www.klauspost.com
*/

namespace RawSpeed {

TiffParser::TiffParser(FileMap* inputData): mInput(inputData), mRootIFD(0) {
  host_endian = getHostEndianness();
}

TiffParser::~TiffParser(void) {
  if (mRootIFD)
    delete mRootIFD;
  mRootIFD = NULL;
}

#ifdef CHECKSIZE
#undef CHECKSIZE
#endif
#ifdef CHECKPTR
#undef CHECKPTR
#endif

#define CHECKSIZE(A) if (A >= mInput->getSize()) throw TiffParserException("Error reading TIFF structure (size out of bounds). File Corrupt")
#define CHECKPTR(A) if ((int)A >= ((int)(mInput->data) + size))) throw TiffParserException("Error reading TIFF structure (size out of bounds). File Corrupt")

void TiffParser::parseData() {
  const unsigned char* data = mInput->getData(0);
  if (mInput->getSize() < 16)
    throw TiffParserException("Not a TIFF file (size too small)");
  if (data[0] != 0x49 || data[1] != 0x49) {
    tiff_endian = big;
    if (data[0] != 0x4D || data[1] != 0x4D)
      throw TiffParserException("Not a TIFF file (ID)");

    if (data[3] != 42)
      throw TiffParserException("Not a TIFF file (magic 42)");
  } else {
    tiff_endian = little;
    if (data[2] != 42 && data[2] != 0x52 && data[2] != 0x55) // ORF has 0x52, RW2 0x55 - Brillant!
      throw TiffParserException("Not a TIFF file (magic 42)");
  }

  if (tiff_endian == host_endian)
    mRootIFD = new TiffIFD();
  else
    mRootIFD = new TiffIFDBE();

  uint32 nextIFD;
  data = mInput->getData(4);
  if (tiff_endian == host_endian) {
    nextIFD = *(int*)data;
  } else {
    nextIFD = (unsigned int)data[0] << 24 | (unsigned int)data[1] << 16 | (unsigned int)data[2] << 8 | (unsigned int)data[3];
  }
  while (nextIFD) {
    CHECKSIZE(nextIFD);

    if (tiff_endian == host_endian)
      mRootIFD->mSubIFD.push_back(new TiffIFD(mInput, nextIFD));
    else
      mRootIFD->mSubIFD.push_back(new TiffIFDBE(mInput, nextIFD));

    nextIFD = mRootIFD->mSubIFD.back()->getNextIFD();
  }
}

RawDecoder* TiffParser::getDecoder() {
  vector<TiffIFD*> potentials;
  potentials = mRootIFD->getIFDsWithTag(DNGVERSION);

  if (!potentials.empty()) {  // We have a dng image entry
    TiffIFD *t = potentials[0];
    const unsigned char* c = t->getEntry(DNGVERSION)->getData();
    if (c[0] > 1)
      throw TiffParserException("DNG version too new.");
    return new DngDecoder(mRootIFD, mInput);
  }

  potentials = mRootIFD->getIFDsWithTag(MAKE);

  if (!potentials.empty()) {  // We have make entry
    for (vector<TiffIFD*>::iterator i = potentials.begin(); i != potentials.end(); ++i) {
      string make = (*i)->getEntry(MAKE)->getString();
      TrimSpaces(make);
      if (!make.compare("Canon")) {
        return new Cr2Decoder(mRootIFD, mInput);
      }
      if (!make.compare("NIKON CORPORATION")) {
        return new NefDecoder(mRootIFD, mInput);
      }
      if (!make.compare("NIKON")) {
        return new NefDecoder(mRootIFD, mInput);
      }
      if (!make.compare("OLYMPUS IMAGING CORP.")) {
        return new OrfDecoder(mRootIFD, mInput);
      }
      if (!make.compare("SONY")) {
        return new ArwDecoder(mRootIFD, mInput);
      }
      if (!make.compare("PENTAX Corporation ")) {
        return new PefDecoder(mRootIFD, mInput);
      }
      if (!make.compare("PENTAX")) {
        return new PefDecoder(mRootIFD, mInput);
      }
      if (!make.compare("Panasonic")) {
        return new Rw2Decoder(mRootIFD, mInput);
      }
      if (!make.compare("SAMSUNG")) {
        return new SrwDecoder(mRootIFD, mInput);
      }
    }
  }
  throw TiffParserException("No decoder found. Sorry.");
  return NULL;
}

} // namespace RawSpeed
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/**
  \file    SBVRGeogen.cpp
  \author  Jens Krueger
           SCI Institute
           University of Utah
  \date    September 2008
*/

#include <algorithm>
#include <limits>
#include "SBVRGeogen.h"

#include <Basics/MathTools.h>

static bool EpsilonEqual(float a, float b);
static bool CheckOrdering(FLOATVECTOR3& a, FLOATVECTOR3& b, FLOATVECTOR3& c);
static void SortPoints(std::vector<POS3TEX3_VERTEX> &fArray);

SBVRGeogen::SBVRGeogen(void) :
  m_fSamplingModifier(1.0f),
  m_fMinZ(0),
  m_vAspect(1,1,1),
  m_vSize(1,1,1),
  m_vTexCoordMin(0,0,0),
  m_vTexCoordMax(1,1,1),
  m_iMinLayers(100),
  m_vGlobalAspect(1,1,1),
  m_vGlobalSize(1,1,1),
  m_vLODSize(1,1,1)
{
  m_pfBBOXStaticVertex[0] = FLOATVECTOR3(-0.5, 0.5,-0.5);
  m_pfBBOXStaticVertex[1] = FLOATVECTOR3( 0.5, 0.5,-0.5);
  m_pfBBOXStaticVertex[2] = FLOATVECTOR3( 0.5, 0.5, 0.5);
  m_pfBBOXStaticVertex[3] = FLOATVECTOR3(-0.5, 0.5, 0.5);
  m_pfBBOXStaticVertex[4] = FLOATVECTOR3(-0.5,-0.5,-0.5);
  m_pfBBOXStaticVertex[5] = FLOATVECTOR3( 0.5,-0.5,-0.5);
  m_pfBBOXStaticVertex[6] = FLOATVECTOR3( 0.5,-0.5, 0.5);
  m_pfBBOXStaticVertex[7] = FLOATVECTOR3(-0.5,-0.5, 0.5);

  m_pfBBOXVertex[0] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[1] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[2] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[3] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[4] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[5] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[6] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[7] = FLOATVECTOR3(0,0,0);
}

SBVRGeogen::~SBVRGeogen(void)
{
}

void SBVRGeogen::SetTransformation(const FLOATMATRIX4& matTransform, bool bForceUpdate) {
  if (bForceUpdate || m_matTransform != matTransform)  {
    m_matTransform = matTransform;
    InitBBOX();
    ComputeGeometry();
  }
}

// Finds the point with the minimum position in Z.
struct vertex_min_z : public std::binary_function<POS3TEX3_VERTEX,
                                                  POS3TEX3_VERTEX,
                                                  bool> {
  bool operator()(const POS3TEX3_VERTEX &a, const POS3TEX3_VERTEX &b) const {
    return (a.m_vPos.z < b.m_vPos.z);
  }
};

void SBVRGeogen::InitBBOX() {

  FLOATVECTOR3 vVertexScale(m_vAspect);

  m_pfBBOXVertex[0] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[0]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMin.x,m_vTexCoordMax.y,m_vTexCoordMin.z));
  m_pfBBOXVertex[1] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[1]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMax.x,m_vTexCoordMax.y,m_vTexCoordMin.z));
  m_pfBBOXVertex[2] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[2]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMax.x,m_vTexCoordMax.y,m_vTexCoordMax.z));
  m_pfBBOXVertex[3] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[3]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMin.x,m_vTexCoordMax.y,m_vTexCoordMax.z));
  m_pfBBOXVertex[4] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[4]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMin.x,m_vTexCoordMin.y,m_vTexCoordMin.z));
  m_pfBBOXVertex[5] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[5]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMax.x,m_vTexCoordMin.y,m_vTexCoordMin.z));
  m_pfBBOXVertex[6] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[6]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMax.x,m_vTexCoordMin.y,m_vTexCoordMax.z));
  m_pfBBOXVertex[7] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[7]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMin.x,m_vTexCoordMin.y,m_vTexCoordMax.z));

  // find the minimum z value
  m_fMinZ = (*std::min_element(m_pfBBOXVertex, m_pfBBOXVertex+8,
                               vertex_min_z())).m_vPos.z;
}

static bool ComputeIntersection(float z,
                                const POS3TEX3_VERTEX &plA,
                                const POS3TEX3_VERTEX &plB,
                                std::vector<POS3TEX3_VERTEX>& vHits)
{
  /*
     returns NO INTERSECTION if the line of the 2 points a,b is
     1. in front of the intersection plane
     2. behind the intersection plane
     3. parallel to the intersection plane (both points have "pretty much" the same z)
  */
  if ((z > plA.m_vPos.z && z > plB.m_vPos.z) ||
      (z < plA.m_vPos.z && z < plB.m_vPos.z) ||
      (EpsilonEqual(plA.m_vPos.z, plB.m_vPos.z))) {
    return false;
  }

  float fAlpha = (z - plA.m_vPos.z) /
                 (plA.m_vPos.z - plB.m_vPos.z);

  POS3TEX3_VERTEX vHit;

  vHit.m_vPos.x = plA.m_vPos.x + (plA.m_vPos.x - plB.m_vPos.x) * fAlpha;
  vHit.m_vPos.y = plA.m_vPos.y + (plA.m_vPos.y - plB.m_vPos.y) * fAlpha;
  vHit.m_vPos.z = z;

  vHit.m_vTex = plA.m_vTex + (plA.m_vTex - plB.m_vTex) * fAlpha;

  vHits.push_back(vHit);

  return true;
}

// Functor to identify the point with the lowest `y' coordinate.
struct vertex_min : public std::binary_function<POS3TEX3_VERTEX,
                                                POS3TEX3_VERTEX,
                                                bool> {
  bool operator()(const POS3TEX3_VERTEX &a, const POS3TEX3_VERTEX &b) const {
    return (a.m_vPos.y < b.m_vPos.y);
  }
};

void SBVRGeogen::Triangulate(std::vector<POS3TEX3_VERTEX> &fArray) {
  // move bottom element to front of array
  std::swap(fArray[0],
            *std::min_element(fArray.begin(), fArray.end(), vertex_min()));
  // sort points according to gradient
  SortPoints(fArray);

  // convert to triangles
  for (UINT32 i=0; i<(fArray.size()-2) ; i++) {
    m_vSliceTriangles.push_back(fArray[0]);
    m_vSliceTriangles.push_back(fArray[i+1]);
    m_vSliceTriangles.push_back(fArray[i+2]);
  }
}

bool SBVRGeogen::ComputeLayerGeometry(float fDepth) {
  std::vector<POS3TEX3_VERTEX> vLayerPoints;
  vLayerPoints.reserve(12);

  ComputeIntersection(fDepth, m_pfBBOXVertex[0], m_pfBBOXVertex[1],
                      vLayerPoints);
  ComputeIntersection(fDepth, m_pfBBOXVertex[1], m_pfBBOXVertex[2],
                      vLayerPoints);
  ComputeIntersection(fDepth, m_pfBBOXVertex[2], m_pfBBOXVertex[3],
                      vLayerPoints);
  ComputeIntersection(fDepth, m_pfBBOXVertex[3], m_pfBBOXVertex[0],
                      vLayerPoints);

  ComputeIntersection(fDepth, m_pfBBOXVertex[4], m_pfBBOXVertex[5],
                      vLayerPoints);
  ComputeIntersection(fDepth, m_pfBBOXVertex[5], m_pfBBOXVertex[6],
                      vLayerPoints);
  ComputeIntersection(fDepth, m_pfBBOXVertex[6], m_pfBBOXVertex[7],
                      vLayerPoints);
  ComputeIntersection(fDepth, m_pfBBOXVertex[7], m_pfBBOXVertex[4],
                      vLayerPoints);

  ComputeIntersection(fDepth, m_pfBBOXVertex[4], m_pfBBOXVertex[0],
                      vLayerPoints);
  ComputeIntersection(fDepth, m_pfBBOXVertex[5], m_pfBBOXVertex[1],
                      vLayerPoints);
  ComputeIntersection(fDepth, m_pfBBOXVertex[6], m_pfBBOXVertex[2],
                      vLayerPoints);
  ComputeIntersection(fDepth, m_pfBBOXVertex[7], m_pfBBOXVertex[3],
                      vLayerPoints);

  if (vLayerPoints.size() <= 2) {
    return false;
  }

  Triangulate(vLayerPoints);
  return true;
}

float SBVRGeogen::GetLayerDistance() {
  return (0.5f * 1.0f/m_fSamplingModifier * (m_vAspect/FLOATVECTOR3(m_vSize))).minVal(); //float(m_vAspect.minVal())/float(std::max(m_vSize.maxVal(),m_iMinLayers));
}

float SBVRGeogen::GetOpacityCorrection() {
  return 1.0f/m_fSamplingModifier * (FLOATVECTOR3(m_vGlobalSize)/FLOATVECTOR3(m_vLODSize)).maxVal();//  GetLayerDistance()*m_vSize.maxVal();
}

void SBVRGeogen::ComputeGeometry() {
  m_vSliceTriangles.clear();

  float fDepth = m_fMinZ;
  float fLayerDistance = GetLayerDistance();

  while (ComputeLayerGeometry(fDepth)) fDepth += fLayerDistance;
}

void SBVRGeogen::SetVolumeData(const FLOATVECTOR3& vAspect, const UINTVECTOR3& vSize) {
  m_vGlobalAspect = vAspect;
  m_vGlobalSize = vSize;
}

void SBVRGeogen::SetLODData(const UINTVECTOR3& vSize) {
  m_vLODSize = vSize;
}

void SBVRGeogen::SetBrickData(const FLOATVECTOR3& vAspect,
                              const UINTVECTOR3& vSize,
                              const FLOATVECTOR3& vTexCoordMin,
                              const FLOATVECTOR3& vTexCoordMax) {
  m_vAspect       = vAspect;
  m_vSize         = vSize;
  m_vTexCoordMin  = vTexCoordMin;
  m_vTexCoordMax  = vTexCoordMax;
  InitBBOX();
}

static bool EpsilonEqual(float a, float b) {
  return fabs(a-b) <= std::numeric_limits<float>::epsilon();
}

static bool CheckOrdering(FLOATVECTOR3& a, FLOATVECTOR3& b, FLOATVECTOR3& c) {
  float g1 = (a[1]-c[1])/(a[0]-c[0]),
        g2 = (b[1]-c[1])/(b[0]-c[0]);

  if (EpsilonEqual(a[0],c[0])) return (g2 < 0) || (EpsilonEqual(g2,0) && b[0] < c[0]);
  if (EpsilonEqual(b[0],c[0])) return (g1 > 0) || (EpsilonEqual(g1,0) && a[0] > c[0]);

  if (a[0] < c[0])
    if (b[0] < c[0]) return g1 < g2; else return false;
  else
    if (b[0] < c[0]) return true; else return g1 < g2;
}

/// @todo: should be replaced with std::sort.
static void SortPoints(std::vector<POS3TEX3_VERTEX> &fArray) {
  // for small arrays, this bubble sort actually beats qsort.
  for (UINT32 i= 1;i<fArray.size();++i)
    for (UINT32 j = 1;j<fArray.size()-i;++j)
      if (!CheckOrdering(fArray[j].m_vPos,fArray[j+1].m_vPos,fArray[0].m_vPos))
        std::swap(fArray[j], fArray[j+1]);
}
<commit_msg>Move sorting to its own method.<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/**
  \file    SBVRGeogen.cpp
  \author  Jens Krueger
           SCI Institute
           University of Utah
  \date    September 2008
*/

#include <algorithm>
#include <limits>
#include "SBVRGeogen.h"

#include <Basics/MathTools.h>

static bool EpsilonEqual(float a, float b);
static bool CheckOrdering(FLOATVECTOR3& a, FLOATVECTOR3& b, FLOATVECTOR3& c);
static void SortPoints(std::vector<POS3TEX3_VERTEX> &fArray);

SBVRGeogen::SBVRGeogen(void) :
  m_fSamplingModifier(1.0f),
  m_fMinZ(0),
  m_vAspect(1,1,1),
  m_vSize(1,1,1),
  m_vTexCoordMin(0,0,0),
  m_vTexCoordMax(1,1,1),
  m_iMinLayers(100),
  m_vGlobalAspect(1,1,1),
  m_vGlobalSize(1,1,1),
  m_vLODSize(1,1,1)
{
  m_pfBBOXStaticVertex[0] = FLOATVECTOR3(-0.5, 0.5,-0.5);
  m_pfBBOXStaticVertex[1] = FLOATVECTOR3( 0.5, 0.5,-0.5);
  m_pfBBOXStaticVertex[2] = FLOATVECTOR3( 0.5, 0.5, 0.5);
  m_pfBBOXStaticVertex[3] = FLOATVECTOR3(-0.5, 0.5, 0.5);
  m_pfBBOXStaticVertex[4] = FLOATVECTOR3(-0.5,-0.5,-0.5);
  m_pfBBOXStaticVertex[5] = FLOATVECTOR3( 0.5,-0.5,-0.5);
  m_pfBBOXStaticVertex[6] = FLOATVECTOR3( 0.5,-0.5, 0.5);
  m_pfBBOXStaticVertex[7] = FLOATVECTOR3(-0.5,-0.5, 0.5);

  m_pfBBOXVertex[0] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[1] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[2] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[3] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[4] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[5] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[6] = FLOATVECTOR3(0,0,0);
  m_pfBBOXVertex[7] = FLOATVECTOR3(0,0,0);
}

SBVRGeogen::~SBVRGeogen(void)
{
}

void SBVRGeogen::SetTransformation(const FLOATMATRIX4& matTransform, bool bForceUpdate) {
  if (bForceUpdate || m_matTransform != matTransform)  {
    m_matTransform = matTransform;
    InitBBOX();
    ComputeGeometry();
  }
}

// Finds the point with the minimum position in Z.
struct vertex_min_z : public std::binary_function<POS3TEX3_VERTEX,
                                                  POS3TEX3_VERTEX,
                                                  bool> {
  bool operator()(const POS3TEX3_VERTEX &a, const POS3TEX3_VERTEX &b) const {
    return (a.m_vPos.z < b.m_vPos.z);
  }
};

void SBVRGeogen::InitBBOX() {

  FLOATVECTOR3 vVertexScale(m_vAspect);

  m_pfBBOXVertex[0] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[0]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMin.x,m_vTexCoordMax.y,m_vTexCoordMin.z));
  m_pfBBOXVertex[1] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[1]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMax.x,m_vTexCoordMax.y,m_vTexCoordMin.z));
  m_pfBBOXVertex[2] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[2]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMax.x,m_vTexCoordMax.y,m_vTexCoordMax.z));
  m_pfBBOXVertex[3] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[3]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMin.x,m_vTexCoordMax.y,m_vTexCoordMax.z));
  m_pfBBOXVertex[4] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[4]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMin.x,m_vTexCoordMin.y,m_vTexCoordMin.z));
  m_pfBBOXVertex[5] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[5]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMax.x,m_vTexCoordMin.y,m_vTexCoordMin.z));
  m_pfBBOXVertex[6] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[6]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMax.x,m_vTexCoordMin.y,m_vTexCoordMax.z));
  m_pfBBOXVertex[7] = POS3TEX3_VERTEX(FLOATVECTOR4(m_pfBBOXStaticVertex[7]*vVertexScale,1.0f) * m_matTransform, FLOATVECTOR3(m_vTexCoordMin.x,m_vTexCoordMin.y,m_vTexCoordMax.z));

  // find the minimum z value
  m_fMinZ = (*std::min_element(m_pfBBOXVertex, m_pfBBOXVertex+8,
                               vertex_min_z())).m_vPos.z;
}

static bool ComputeIntersection(float z,
                                const POS3TEX3_VERTEX &plA,
                                const POS3TEX3_VERTEX &plB,
                                std::vector<POS3TEX3_VERTEX>& vHits)
{
  /*
     returns NO INTERSECTION if the line of the 2 points a,b is
     1. in front of the intersection plane
     2. behind the intersection plane
     3. parallel to the intersection plane (both points have "pretty much" the same z)
  */
  if ((z > plA.m_vPos.z && z > plB.m_vPos.z) ||
      (z < plA.m_vPos.z && z < plB.m_vPos.z) ||
      (EpsilonEqual(plA.m_vPos.z, plB.m_vPos.z))) {
    return false;
  }

  float fAlpha = (z - plA.m_vPos.z) /
                 (plA.m_vPos.z - plB.m_vPos.z);

  POS3TEX3_VERTEX vHit;

  vHit.m_vPos.x = plA.m_vPos.x + (plA.m_vPos.x - plB.m_vPos.x) * fAlpha;
  vHit.m_vPos.y = plA.m_vPos.y + (plA.m_vPos.y - plB.m_vPos.y) * fAlpha;
  vHit.m_vPos.z = z;

  vHit.m_vTex = plA.m_vTex + (plA.m_vTex - plB.m_vTex) * fAlpha;

  vHits.push_back(vHit);

  return true;
}

// Functor to identify the point with the lowest `y' coordinate.
struct vertex_min : public std::binary_function<POS3TEX3_VERTEX,
                                                POS3TEX3_VERTEX,
                                                bool> {
  bool operator()(const POS3TEX3_VERTEX &a, const POS3TEX3_VERTEX &b) const {
    return (a.m_vPos.y < b.m_vPos.y);
  }
};

// Sorts a vector
static void SortByGradient(std::vector<POS3TEX3_VERTEX>& fArray)
{
  // move bottom element to front of array
  if(fArray.empty()) { return; }
  std::swap(fArray[0],
            *std::min_element(fArray.begin(), fArray.end(), vertex_min()));
  if(fArray.size() > 2) {
    // sort points according to gradient
    SortPoints(fArray);
  }
}

void SBVRGeogen::Triangulate(std::vector<POS3TEX3_VERTEX> &fArray) {
  SortByGradient(fArray);

  // convert to triangles
  for (UINT32 i=0; i<(fArray.size()-2) ; i++) {
    m_vSliceTriangles.push_back(fArray[0]);
    m_vSliceTriangles.push_back(fArray[i+1]);
    m_vSliceTriangles.push_back(fArray[i+2]);
  }
}

bool SBVRGeogen::ComputeLayerGeometry(float fDepth) {
  std::vector<POS3TEX3_VERTEX> vLayerPoints;
  vLayerPoints.reserve(12);

  ComputeIntersection(fDepth, m_pfBBOXVertex[0], m_pfBBOXVertex[1],
                      vLayerPoints);
  ComputeIntersection(fDepth, m_pfBBOXVertex[1], m_pfBBOXVertex[2],
                      vLayerPoints);
  ComputeIntersection(fDepth, m_pfBBOXVertex[2], m_pfBBOXVertex[3],
                      vLayerPoints);
  ComputeIntersection(fDepth, m_pfBBOXVertex[3], m_pfBBOXVertex[0],
                      vLayerPoints);

  ComputeIntersection(fDepth, m_pfBBOXVertex[4], m_pfBBOXVertex[5],
                      vLayerPoints);
  ComputeIntersection(fDepth, m_pfBBOXVertex[5], m_pfBBOXVertex[6],
                      vLayerPoints);
  ComputeIntersection(fDepth, m_pfBBOXVertex[6], m_pfBBOXVertex[7],
                      vLayerPoints);
  ComputeIntersection(fDepth, m_pfBBOXVertex[7], m_pfBBOXVertex[4],
                      vLayerPoints);

  ComputeIntersection(fDepth, m_pfBBOXVertex[4], m_pfBBOXVertex[0],
                      vLayerPoints);
  ComputeIntersection(fDepth, m_pfBBOXVertex[5], m_pfBBOXVertex[1],
                      vLayerPoints);
  ComputeIntersection(fDepth, m_pfBBOXVertex[6], m_pfBBOXVertex[2],
                      vLayerPoints);
  ComputeIntersection(fDepth, m_pfBBOXVertex[7], m_pfBBOXVertex[3],
                      vLayerPoints);

  if (vLayerPoints.size() <= 2) {
    return false;
  }

  Triangulate(vLayerPoints);
  return true;
}

float SBVRGeogen::GetLayerDistance() {
  return (0.5f * 1.0f/m_fSamplingModifier * (m_vAspect/FLOATVECTOR3(m_vSize))).minVal(); //float(m_vAspect.minVal())/float(std::max(m_vSize.maxVal(),m_iMinLayers));
}

float SBVRGeogen::GetOpacityCorrection() {
  return 1.0f/m_fSamplingModifier * (FLOATVECTOR3(m_vGlobalSize)/FLOATVECTOR3(m_vLODSize)).maxVal();//  GetLayerDistance()*m_vSize.maxVal();
}

void SBVRGeogen::ComputeGeometry() {
  m_vSliceTriangles.clear();

  float fDepth = m_fMinZ;
  float fLayerDistance = GetLayerDistance();

  while (ComputeLayerGeometry(fDepth)) fDepth += fLayerDistance;
}

void SBVRGeogen::SetVolumeData(const FLOATVECTOR3& vAspect, const UINTVECTOR3& vSize) {
  m_vGlobalAspect = vAspect;
  m_vGlobalSize = vSize;
}

void SBVRGeogen::SetLODData(const UINTVECTOR3& vSize) {
  m_vLODSize = vSize;
}

void SBVRGeogen::SetBrickData(const FLOATVECTOR3& vAspect,
                              const UINTVECTOR3& vSize,
                              const FLOATVECTOR3& vTexCoordMin,
                              const FLOATVECTOR3& vTexCoordMax) {
  m_vAspect       = vAspect;
  m_vSize         = vSize;
  m_vTexCoordMin  = vTexCoordMin;
  m_vTexCoordMax  = vTexCoordMax;
  InitBBOX();
}

static bool EpsilonEqual(float a, float b) {
  return fabs(a-b) <= std::numeric_limits<float>::epsilon();
}

static bool CheckOrdering(FLOATVECTOR3& a, FLOATVECTOR3& b, FLOATVECTOR3& c) {
  float g1 = (a[1]-c[1])/(a[0]-c[0]),
        g2 = (b[1]-c[1])/(b[0]-c[0]);

  if (EpsilonEqual(a[0],c[0])) return (g2 < 0) || (EpsilonEqual(g2,0) && b[0] < c[0]);
  if (EpsilonEqual(b[0],c[0])) return (g1 > 0) || (EpsilonEqual(g1,0) && a[0] > c[0]);

  if (a[0] < c[0])
    if (b[0] < c[0]) return g1 < g2; else return false;
  else
    if (b[0] < c[0]) return true; else return g1 < g2;
}

/// @todo: should be replaced with std::sort.
static void SortPoints(std::vector<POS3TEX3_VERTEX> &fArray) {
  // for small arrays, this bubble sort actually beats qsort.
  for (UINT32 i= 1;i<fArray.size();++i)
    for (UINT32 j = 1;j<fArray.size()-i;++j)
      if (!CheckOrdering(fArray[j].m_vPos,fArray[j+1].m_vPos,fArray[0].m_vPos))
        std::swap(fArray[j], fArray[j+1]);
}
<|endoftext|>


<commit_before>#include "Runtime/CFactoryMgr.hpp"

#include <algorithm>
#include <array>
#include <cctype>
#include <iterator>

#include "Runtime/CStopwatch.hpp"
#include "Runtime/IObj.hpp"

namespace urde {
constexpr std::array TypeTable{
    FOURCC('CLSN'), FOURCC('CMDL'), FOURCC('CSKR'), FOURCC('ANIM'), FOURCC('CINF'), FOURCC('TXTR'), FOURCC('PLTT'),
    FOURCC('FONT'), FOURCC('ANCS'), FOURCC('EVNT'), FOURCC('MADF'), FOURCC('MLVL'), FOURCC('MREA'), FOURCC('MAPW'),
    FOURCC('MAPA'), FOURCC('SAVW'), FOURCC('SAVA'), FOURCC('PART'), FOURCC('WPSC'), FOURCC('SWHC'), FOURCC('DPSC'),
    FOURCC('ELSC'), FOURCC('CRSC'), FOURCC('AFSM'), FOURCC('DCLN'), FOURCC('AGSC'), FOURCC('ATBL'), FOURCC('CSNG'),
    FOURCC('STRG'), FOURCC('SCAN'), FOURCC('PATH'), FOURCC('DGRP'), FOURCC('HMAP'), FOURCC('CTWK'), FOURCC('FRME'),
    FOURCC('HINT'), FOURCC('MAPU'), FOURCC('DUMB'), FOURCC('OIDS'),
};

CFactoryFnReturn CFactoryMgr::MakeObject(const SObjectTag& tag, urde::CInputStream& in,
                                         const CVParamTransfer& paramXfer, CObjectReference* selfRef) {
  auto search = m_factories.find(tag.type);
  if (search == m_factories.end())
    return {};

  return search->second(tag, in, paramXfer, selfRef);
}

bool CFactoryMgr::CanMakeMemory(const urde::SObjectTag& tag) const {
  auto search = m_memFactories.find(tag.type);
  return search != m_memFactories.cend();
}

CFactoryFnReturn CFactoryMgr::MakeObjectFromMemory(const SObjectTag& tag, std::unique_ptr<u8[]>&& buf, int size,
                                                   bool compressed, const CVParamTransfer& paramXfer,
                                                   CObjectReference* selfRef) {
  std::unique_ptr<u8[]> localBuf = std::move(buf);

  auto search = m_memFactories.find(tag.type);
  if (search != m_memFactories.cend()) {
    if (compressed) {
      std::unique_ptr<CInputStream> compRead = std::make_unique<athena::io::MemoryReader>(localBuf.get(), size);
      u32 decompLen = compRead->readUint32Big();
      CZipInputStream r(std::move(compRead));
      std::unique_ptr<u8[]> decompBuf = r.readUBytes(decompLen);
      return search->second(tag, std::move(decompBuf), decompLen, paramXfer, selfRef);
    } else {
      return search->second(tag, std::move(localBuf), size, paramXfer, selfRef);
    }
  } else {
    auto search = m_factories.find(tag.type);
    if (search == m_factories.end())
      return {};

    if (compressed) {
      std::unique_ptr<CInputStream> compRead = std::make_unique<athena::io::MemoryReader>(localBuf.get(), size);
      compRead->readUint32Big();
      CZipInputStream r(std::move(compRead));
      return search->second(tag, r, paramXfer, selfRef);
    } else {
      CMemoryInStream r(localBuf.get(), size);
      return search->second(tag, r, paramXfer, selfRef);
    }
  }
}

CFactoryMgr::ETypeTable CFactoryMgr::FourCCToTypeIdx(FourCC fcc) {
  for (size_t i = 0; i < 4; ++i) {
    fcc.getChars()[i] = char(std::toupper(fcc.getChars()[i]));
  }

  const auto search =
      std::find_if(TypeTable.cbegin(), TypeTable.cend(), [fcc](const FourCC& test) { return test == fcc; });
  if (search == TypeTable.cend()) {
    return ETypeTable::Invalid;
  }
  return ETypeTable(std::distance(TypeTable.cbegin(), search));
}

FourCC CFactoryMgr::TypeIdxToFourCC(ETypeTable fcc) { return TypeTable[size_t(fcc)]; }

} // namespace urde
<commit_msg>CFactoryMgr: Resolve variable shadowing warning in MakeObjectFromMemory()<commit_after>#include "Runtime/CFactoryMgr.hpp"

#include <algorithm>
#include <array>
#include <cctype>
#include <iterator>

#include "Runtime/CStopwatch.hpp"
#include "Runtime/IObj.hpp"

namespace urde {
constexpr std::array TypeTable{
    FOURCC('CLSN'), FOURCC('CMDL'), FOURCC('CSKR'), FOURCC('ANIM'), FOURCC('CINF'), FOURCC('TXTR'), FOURCC('PLTT'),
    FOURCC('FONT'), FOURCC('ANCS'), FOURCC('EVNT'), FOURCC('MADF'), FOURCC('MLVL'), FOURCC('MREA'), FOURCC('MAPW'),
    FOURCC('MAPA'), FOURCC('SAVW'), FOURCC('SAVA'), FOURCC('PART'), FOURCC('WPSC'), FOURCC('SWHC'), FOURCC('DPSC'),
    FOURCC('ELSC'), FOURCC('CRSC'), FOURCC('AFSM'), FOURCC('DCLN'), FOURCC('AGSC'), FOURCC('ATBL'), FOURCC('CSNG'),
    FOURCC('STRG'), FOURCC('SCAN'), FOURCC('PATH'), FOURCC('DGRP'), FOURCC('HMAP'), FOURCC('CTWK'), FOURCC('FRME'),
    FOURCC('HINT'), FOURCC('MAPU'), FOURCC('DUMB'), FOURCC('OIDS'),
};

CFactoryFnReturn CFactoryMgr::MakeObject(const SObjectTag& tag, urde::CInputStream& in,
                                         const CVParamTransfer& paramXfer, CObjectReference* selfRef) {
  auto search = m_factories.find(tag.type);
  if (search == m_factories.end())
    return {};

  return search->second(tag, in, paramXfer, selfRef);
}

bool CFactoryMgr::CanMakeMemory(const urde::SObjectTag& tag) const {
  auto search = m_memFactories.find(tag.type);
  return search != m_memFactories.cend();
}

CFactoryFnReturn CFactoryMgr::MakeObjectFromMemory(const SObjectTag& tag, std::unique_ptr<u8[]>&& buf, int size,
                                                   bool compressed, const CVParamTransfer& paramXfer,
                                                   CObjectReference* selfRef) {
  std::unique_ptr<u8[]> localBuf = std::move(buf);

  const auto memFactoryIter = m_memFactories.find(tag.type);
  if (memFactoryIter != m_memFactories.cend()) {
    if (compressed) {
      std::unique_ptr<CInputStream> compRead = std::make_unique<athena::io::MemoryReader>(localBuf.get(), size);
      const u32 decompLen = compRead->readUint32Big();
      CZipInputStream r(std::move(compRead));
      std::unique_ptr<u8[]> decompBuf = r.readUBytes(decompLen);
      return memFactoryIter->second(tag, std::move(decompBuf), decompLen, paramXfer, selfRef);
    } else {
      return memFactoryIter->second(tag, std::move(localBuf), size, paramXfer, selfRef);
    }
  } else {
    const auto factoryIter = m_factories.find(tag.type);
    if (factoryIter == m_factories.end()) {
      return {};
    }

    if (compressed) {
      std::unique_ptr<CInputStream> compRead = std::make_unique<athena::io::MemoryReader>(localBuf.get(), size);
      compRead->readUint32Big();
      CZipInputStream r(std::move(compRead));
      return factoryIter->second(tag, r, paramXfer, selfRef);
    } else {
      CMemoryInStream r(localBuf.get(), size);
      return factoryIter->second(tag, r, paramXfer, selfRef);
    }
  }
}

CFactoryMgr::ETypeTable CFactoryMgr::FourCCToTypeIdx(FourCC fcc) {
  for (size_t i = 0; i < 4; ++i) {
    fcc.getChars()[i] = char(std::toupper(fcc.getChars()[i]));
  }

  const auto search =
      std::find_if(TypeTable.cbegin(), TypeTable.cend(), [fcc](const FourCC& test) { return test == fcc; });
  if (search == TypeTable.cend()) {
    return ETypeTable::Invalid;
  }
  return ETypeTable(std::distance(TypeTable.cbegin(), search));
}

FourCC CFactoryMgr::TypeIdxToFourCC(ETypeTable fcc) { return TypeTable[size_t(fcc)]; }

} // namespace urde
<|endoftext|>


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

// History UI tests

#include "base/file_path.h"
#include "chrome/browser/view_ids.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/test/ui_test_utils.h"
#include "gfx/rect.h"
#include "views/event.h"

namespace {

const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
const FilePath::CharType* kHistoryDir = FILE_PATH_LITERAL("History");

}  // namespace

class HistoryTester : public UITest {
 protected:
  HistoryTester() : UITest() { }

  virtual void SetUp() {
    show_window_ = true;
    UITest::SetUp();
  }
};

TEST_F(HistoryTester, VerifyHistoryLength1) {
  // Test the history length for the following page transitions.
  //   -open-> Page 1.

  const FilePath test_case_1(
      FILE_PATH_LITERAL("history_length_test_page_1.html"));
  GURL url_1 = ui_test_utils::GetTestUrl(FilePath(kHistoryDir), test_case_1);
  NavigateToURL(url_1);
  WaitForFinish("History_Length_Test_1", "1", url_1, kTestCompleteCookie,
                kTestCompleteSuccess, action_max_timeout_ms());
}

// Disabled, http://crbug.com/39785.
// TODO(yuzo): Fix the following flaky (hence disabled) tests.
// These tests are flaky because automatic and user-initiated transitions are
// distinguished based on the interval between page load and redirect.
TEST_F(HistoryTester, DISABLED_VerifyHistoryLength2) {
  // Test the history length for the following page transitions.
  //   -open-> Page 2 -redirect-> Page 3.

  const FilePath test_case_2(
      FILE_PATH_LITERAL("history_length_test_page_2.html"));
  GURL url_2 = ui_test_utils::GetTestUrl(FilePath(kHistoryDir), test_case_2);
  NavigateToURL(url_2);
  WaitForFinish("History_Length_Test_2", "1", url_2, kTestCompleteCookie,
                kTestCompleteSuccess, action_max_timeout_ms());
}

// Disabled, http://crbug.com/39785.
TEST_F(HistoryTester, DISABLED_VerifyHistoryLength3) {
  // Test the history length for the following page transitions.
  //   -open-> Page 4 -navigate_backward-> Page 3 -navigate_backward->Page 1
  //   -navigate_forward-> Page 3 -navigate_forward-> Page 4

  const FilePath test_case_3(
      FILE_PATH_LITERAL("history_length_test_page_4.html"));
  GURL url_3 = ui_test_utils::GetTestUrl(FilePath(kHistoryDir), test_case_3);
  NavigateToURL(url_3);
  WaitForFinish("History_Length_Test_3", "1", url_3, kTestCompleteCookie,
                kTestCompleteSuccess, action_max_timeout_ms());
}

#if defined(OS_WIN) || defined(OS_LINUX)
TEST_F(HistoryTester, ConsiderRedirectAfterGestureAsUserInitiated) {
  // Test the history length for the following page transition.
  //
  // -open-> Page 11 -slow_redirect-> Page 12.
  //
  // If redirect occurs after a user gesture, e.g., mouse click, the
  // redirect is more likely to be user-initiated rather than automatic.
  // Therefore, Page 11 should be in the history in addition to Page 12.

  const FilePath test_case(
      FILE_PATH_LITERAL("history_length_test_page_11.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kHistoryDir), test_case);
  NavigateToURL(url);
  WaitForFinish("History_Length_Test_11", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, action_max_timeout_ms());

  // Simulate click. This only works for Windows.
  scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
  ASSERT_TRUE(browser.get());
  scoped_refptr<WindowProxy> window = browser->GetWindow();
  ASSERT_TRUE(window.get());
  gfx::Rect tab_view_bounds;
  ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER, &tab_view_bounds,
                                    true));
  ASSERT_TRUE(
      window->SimulateOSClick(tab_view_bounds.CenterPoint(),
                              views::Event::EF_LEFT_BUTTON_DOWN));

  NavigateToURL(GURL("javascript:redirectToPage12()"));
  WaitForFinish("History_Length_Test_12", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, action_max_timeout_ms());
}
#endif  // defined(OS_WIN) || defined(OS_LINUX)

TEST_F(HistoryTester, ConsiderSlowRedirectAsUserInitiated) {
  // Test the history length for the following page transition.
  //
  // -open-> Page 21 -redirect-> Page 22.
  //
  // If redirect occurs more than 5 seconds later after the page is loaded,
  // the redirect is likely to be user-initiated.
  // Therefore, Page 21 should be in the history in addition to Page 22.

  const FilePath test_case(
      FILE_PATH_LITERAL("history_length_test_page_21.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kHistoryDir), test_case);
  NavigateToURL(url);
  WaitForFinish("History_Length_Test_21", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, action_max_timeout_ms());
}
<commit_msg>Switch failing HistoryTester tests from DISABLED to FAILS<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// History UI tests

#include "base/file_path.h"
#include "chrome/browser/view_ids.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "chrome/test/ui_test_utils.h"
#include "gfx/rect.h"
#include "views/event.h"

namespace {

const char kTestCompleteCookie[] = "status";
const char kTestCompleteSuccess[] = "OK";
const FilePath::CharType* kHistoryDir = FILE_PATH_LITERAL("History");

}  // namespace

class HistoryTester : public UITest {
 protected:
  HistoryTester() : UITest() { }

  virtual void SetUp() {
    show_window_ = true;
    UITest::SetUp();
  }
};

TEST_F(HistoryTester, VerifyHistoryLength1) {
  // Test the history length for the following page transitions.
  //   -open-> Page 1.

  const FilePath test_case_1(
      FILE_PATH_LITERAL("history_length_test_page_1.html"));
  GURL url_1 = ui_test_utils::GetTestUrl(FilePath(kHistoryDir), test_case_1);
  NavigateToURL(url_1);
  WaitForFinish("History_Length_Test_1", "1", url_1, kTestCompleteCookie,
                kTestCompleteSuccess, action_max_timeout_ms());
}

// TODO(yuzo): Fix the following failing tests. http://crbug.com/39785
// These tests are broken because automatic and user-initiated transitions are
// distinguished based on the interval between page load and redirect.
TEST_F(HistoryTester, FAILS_VerifyHistoryLength2) {
  // Test the history length for the following page transitions.
  //   -open-> Page 2 -redirect-> Page 3.

  const FilePath test_case_2(
      FILE_PATH_LITERAL("history_length_test_page_2.html"));
  GURL url_2 = ui_test_utils::GetTestUrl(FilePath(kHistoryDir), test_case_2);
  NavigateToURL(url_2);
  WaitForFinish("History_Length_Test_2", "1", url_2, kTestCompleteCookie,
                kTestCompleteSuccess, action_max_timeout_ms());
}

// Fails consistently: http://crbug.com/39785
TEST_F(HistoryTester, FAILS_VerifyHistoryLength3) {
  // Test the history length for the following page transitions.
  //   -open-> Page 4 -navigate_backward-> Page 3 -navigate_backward->Page 1
  //   -navigate_forward-> Page 3 -navigate_forward-> Page 4

  const FilePath test_case_3(
      FILE_PATH_LITERAL("history_length_test_page_4.html"));
  GURL url_3 = ui_test_utils::GetTestUrl(FilePath(kHistoryDir), test_case_3);
  NavigateToURL(url_3);
  WaitForFinish("History_Length_Test_3", "1", url_3, kTestCompleteCookie,
                kTestCompleteSuccess, action_max_timeout_ms());
}

#if defined(OS_WIN) || defined(OS_LINUX)
TEST_F(HistoryTester, ConsiderRedirectAfterGestureAsUserInitiated) {
  // Test the history length for the following page transition.
  //
  // -open-> Page 11 -slow_redirect-> Page 12.
  //
  // If redirect occurs after a user gesture, e.g., mouse click, the
  // redirect is more likely to be user-initiated rather than automatic.
  // Therefore, Page 11 should be in the history in addition to Page 12.

  const FilePath test_case(
      FILE_PATH_LITERAL("history_length_test_page_11.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kHistoryDir), test_case);
  NavigateToURL(url);
  WaitForFinish("History_Length_Test_11", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, action_max_timeout_ms());

  // Simulate click. This only works for Windows.
  scoped_refptr<BrowserProxy> browser = automation()->GetBrowserWindow(0);
  ASSERT_TRUE(browser.get());
  scoped_refptr<WindowProxy> window = browser->GetWindow();
  ASSERT_TRUE(window.get());
  gfx::Rect tab_view_bounds;
  ASSERT_TRUE(window->GetViewBounds(VIEW_ID_TAB_CONTAINER, &tab_view_bounds,
                                    true));
  ASSERT_TRUE(
      window->SimulateOSClick(tab_view_bounds.CenterPoint(),
                              views::Event::EF_LEFT_BUTTON_DOWN));

  NavigateToURL(GURL("javascript:redirectToPage12()"));
  WaitForFinish("History_Length_Test_12", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, action_max_timeout_ms());
}
#endif  // defined(OS_WIN) || defined(OS_LINUX)

TEST_F(HistoryTester, ConsiderSlowRedirectAsUserInitiated) {
  // Test the history length for the following page transition.
  //
  // -open-> Page 21 -redirect-> Page 22.
  //
  // If redirect occurs more than 5 seconds later after the page is loaded,
  // the redirect is likely to be user-initiated.
  // Therefore, Page 21 should be in the history in addition to Page 22.

  const FilePath test_case(
      FILE_PATH_LITERAL("history_length_test_page_21.html"));
  GURL url = ui_test_utils::GetTestUrl(FilePath(kHistoryDir), test_case);
  NavigateToURL(url);
  WaitForFinish("History_Length_Test_21", "1", url, kTestCompleteCookie,
                kTestCompleteSuccess, action_max_timeout_ms());
}
<|endoftext|>


<commit_before>//===- CoverageReport.cpp - Code coverage report -------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class implements rendering of a code coverage report.
//
//===----------------------------------------------------------------------===//

#include "CoverageReport.h"
#include "CoverageSummary.h"
#include "RenderingSupport.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/FileSystem.h"

using namespace llvm;
namespace {
/// \brief Helper struct which prints trimmed and aligned columns.
struct Column {
  enum TrimKind { NoTrim, LeftTrim, RightTrim };

  enum AlignmentKind { LeftAlignment, RightAlignment };

  StringRef Str;
  unsigned Width;
  TrimKind Trim;
  AlignmentKind Alignment;

  Column(StringRef Str, unsigned Width)
      : Str(Str), Width(Width), Trim(NoTrim), Alignment(LeftAlignment) {}

  Column &set(TrimKind Value) {
    Trim = Value;
    return *this;
  }

  Column &set(AlignmentKind Value) {
    Alignment = Value;
    return *this;
  }

  void render(raw_ostream &OS) const;
};
raw_ostream &operator<<(raw_ostream &OS, const Column &Value) {
  Value.render(OS);
  return OS;
}
}

void Column::render(raw_ostream &OS) const {
  if (Str.size() <= Width) {
    if (Alignment == RightAlignment) {
      OS.indent(Width - Str.size());
      OS << Str;
      return;
    }
    OS << Str;
    OS.indent(Width - Str.size());
    return;
  }

  switch (Trim) {
  case NoTrim:
    OS << Str.substr(0, Width);
    break;
  case LeftTrim:
    OS << "..." << Str.substr(Str.size() - Width + 3);
    break;
  case RightTrim:
    OS << Str.substr(0, Width - 3) << "...";
    break;
  }
}

static Column column(StringRef Str, unsigned Width) {
  return Column(Str, Width);
}

template <typename T>
static Column column(StringRef Str, unsigned Width, const T &Value) {
  return Column(Str, Width).set(Value);
}

static const unsigned FileReportColumns[] = {25, 10, 8, 8, 10, 10};
static const unsigned FunctionReportColumns[] = {25, 10, 8, 8, 10, 8, 8};

/// \brief Prints a horizontal divider which spans across the given columns.
template <typename T, size_t N>
static void renderDivider(T (&Columns)[N], raw_ostream &OS) {
  unsigned Length = 0;
  for (unsigned I = 0; I < N; ++I)
    Length += Columns[I];
  for (unsigned I = 0; I < Length; ++I)
    OS << '-';
}

/// \brief Return the color which correponds to the coverage
/// percentage of a certain metric.
template <typename T>
static raw_ostream::Colors determineCoveragePercentageColor(const T &Info) {
  if (Info.isFullyCovered())
    return raw_ostream::GREEN;
  return Info.getPercentCovered() >= 80.0 ? raw_ostream::YELLOW
                                          : raw_ostream::RED;
}

void CoverageReport::render(const FileCoverageSummary &File, raw_ostream &OS) {
  OS << column(File.Name, FileReportColumns[0], Column::LeftTrim)
     << format("%*zd", FileReportColumns[1], File.RegionCoverage.NumRegions);
  Options.colored_ostream(OS, File.RegionCoverage.isFullyCovered()
                                  ? raw_ostream::GREEN
                                  : raw_ostream::RED)
      << format("%*zd", FileReportColumns[2], File.RegionCoverage.NotCovered);
  Options.colored_ostream(OS,
                          determineCoveragePercentageColor(File.RegionCoverage))
      << format("%*.2f", FileReportColumns[3] - 1,
                File.RegionCoverage.getPercentCovered()) << '%';
  OS << format("%*zd", FileReportColumns[4],
               File.FunctionCoverage.NumFunctions);
  Options.colored_ostream(
      OS, determineCoveragePercentageColor(File.FunctionCoverage))
      << format("%*.2f", FileReportColumns[5] - 1,
                File.FunctionCoverage.getPercentCovered()) << '%';
  OS << "\n";
}

void CoverageReport::render(const FunctionCoverageSummary &Function,
                            raw_ostream &OS) {
  OS << column(Function.Name, FunctionReportColumns[0], Column::RightTrim)
     << format("%*zd", FunctionReportColumns[1],
               Function.RegionCoverage.NumRegions);
  Options.colored_ostream(OS, Function.RegionCoverage.isFullyCovered()
                                  ? raw_ostream::GREEN
                                  : raw_ostream::RED)
      << format("%*zd", FunctionReportColumns[2],
                Function.RegionCoverage.NotCovered);
  Options.colored_ostream(
      OS, determineCoveragePercentageColor(Function.RegionCoverage))
      << format("%*.2f", FunctionReportColumns[3] - 1,
                Function.RegionCoverage.getPercentCovered()) << '%';
  OS << format("%*zd", FunctionReportColumns[4],
               Function.LineCoverage.NumLines);
  Options.colored_ostream(OS, Function.LineCoverage.isFullyCovered()
                                  ? raw_ostream::GREEN
                                  : raw_ostream::RED)
      << format("%*zd", FunctionReportColumns[5],
                Function.LineCoverage.NotCovered);
  Options.colored_ostream(
      OS, determineCoveragePercentageColor(Function.LineCoverage))
      << format("%*.2f", FunctionReportColumns[6] - 1,
                Function.LineCoverage.getPercentCovered()) << '%';
  OS << "\n";
}

void CoverageReport::renderFunctionReports(raw_ostream &OS) {
  bool isFirst = true;
  for (const auto &File : Summary.getFileSummaries()) {
    if (isFirst)
      isFirst = false;
    else
      OS << "\n";
    OS << "File '" << File.Name << "':\n";
    OS << column("Name", FunctionReportColumns[0])
       << column("Regions", FunctionReportColumns[1], Column::RightAlignment)
       << column("Miss", FunctionReportColumns[2], Column::RightAlignment)
       << column("Cover", FunctionReportColumns[3], Column::RightAlignment)
       << column("Lines", FunctionReportColumns[4], Column::RightAlignment)
       << column("Miss", FunctionReportColumns[5], Column::RightAlignment)
       << column("Cover", FunctionReportColumns[6], Column::RightAlignment);
    OS << "\n";
    renderDivider(FunctionReportColumns, OS);
    OS << "\n";
    for (const auto &Function : File.FunctionSummaries)
      render(Function, OS);
    renderDivider(FunctionReportColumns, OS);
    OS << "\n";
    render(FunctionCoverageSummary("TOTAL", /*ExecutionCount=*/0,
                                   File.RegionCoverage, File.LineCoverage),
           OS);
  }
}

void CoverageReport::renderFileReports(raw_ostream &OS) {
  OS << column("Filename", FileReportColumns[0])
     << column("Regions", FileReportColumns[1], Column::RightAlignment)
     << column("Miss", FileReportColumns[2], Column::RightAlignment)
     << column("Cover", FileReportColumns[3], Column::RightAlignment)
     << column("Functions", FileReportColumns[4], Column::RightAlignment)
     << column("Executed", FileReportColumns[5], Column::RightAlignment)
     << "\n";
  renderDivider(FileReportColumns, OS);
  OS << "\n";
  for (const auto &File : Summary.getFileSummaries())
    render(File, OS);
  renderDivider(FileReportColumns, OS);
  OS << "\n";
  render(Summary.getCombinedFileSummaries(), OS);
}
<commit_msg>llvm-cov/CoverageReport.cpp: Quick fix for msvcrt, since width specifier "z" is unavailable.<commit_after>//===- CoverageReport.cpp - Code coverage report -------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This class implements rendering of a code coverage report.
//
//===----------------------------------------------------------------------===//

#include "CoverageReport.h"
#include "CoverageSummary.h"
#include "RenderingSupport.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/FileSystem.h"

using namespace llvm;
namespace {
/// \brief Helper struct which prints trimmed and aligned columns.
struct Column {
  enum TrimKind { NoTrim, LeftTrim, RightTrim };

  enum AlignmentKind { LeftAlignment, RightAlignment };

  StringRef Str;
  unsigned Width;
  TrimKind Trim;
  AlignmentKind Alignment;

  Column(StringRef Str, unsigned Width)
      : Str(Str), Width(Width), Trim(NoTrim), Alignment(LeftAlignment) {}

  Column &set(TrimKind Value) {
    Trim = Value;
    return *this;
  }

  Column &set(AlignmentKind Value) {
    Alignment = Value;
    return *this;
  }

  void render(raw_ostream &OS) const;
};
raw_ostream &operator<<(raw_ostream &OS, const Column &Value) {
  Value.render(OS);
  return OS;
}
}

void Column::render(raw_ostream &OS) const {
  if (Str.size() <= Width) {
    if (Alignment == RightAlignment) {
      OS.indent(Width - Str.size());
      OS << Str;
      return;
    }
    OS << Str;
    OS.indent(Width - Str.size());
    return;
  }

  switch (Trim) {
  case NoTrim:
    OS << Str.substr(0, Width);
    break;
  case LeftTrim:
    OS << "..." << Str.substr(Str.size() - Width + 3);
    break;
  case RightTrim:
    OS << Str.substr(0, Width - 3) << "...";
    break;
  }
}

static Column column(StringRef Str, unsigned Width) {
  return Column(Str, Width);
}

template <typename T>
static Column column(StringRef Str, unsigned Width, const T &Value) {
  return Column(Str, Width).set(Value);
}

static const unsigned FileReportColumns[] = {25, 10, 8, 8, 10, 10};
static const unsigned FunctionReportColumns[] = {25, 10, 8, 8, 10, 8, 8};

/// \brief Prints a horizontal divider which spans across the given columns.
template <typename T, size_t N>
static void renderDivider(T (&Columns)[N], raw_ostream &OS) {
  unsigned Length = 0;
  for (unsigned I = 0; I < N; ++I)
    Length += Columns[I];
  for (unsigned I = 0; I < Length; ++I)
    OS << '-';
}

/// \brief Return the color which correponds to the coverage
/// percentage of a certain metric.
template <typename T>
static raw_ostream::Colors determineCoveragePercentageColor(const T &Info) {
  if (Info.isFullyCovered())
    return raw_ostream::GREEN;
  return Info.getPercentCovered() >= 80.0 ? raw_ostream::YELLOW
                                          : raw_ostream::RED;
}

void CoverageReport::render(const FileCoverageSummary &File, raw_ostream &OS) {
  OS << column(File.Name, FileReportColumns[0], Column::LeftTrim)
     << format("%*u", FileReportColumns[1], (unsigned)File.RegionCoverage.NumRegions);
  Options.colored_ostream(OS, File.RegionCoverage.isFullyCovered()
                                  ? raw_ostream::GREEN
                                  : raw_ostream::RED)
      << format("%*u", FileReportColumns[2], (unsigned)File.RegionCoverage.NotCovered);
  Options.colored_ostream(OS,
                          determineCoveragePercentageColor(File.RegionCoverage))
      << format("%*.2f", FileReportColumns[3] - 1,
                File.RegionCoverage.getPercentCovered()) << '%';
  OS << format("%*u", FileReportColumns[4],
               (unsigned)File.FunctionCoverage.NumFunctions);
  Options.colored_ostream(
      OS, determineCoveragePercentageColor(File.FunctionCoverage))
      << format("%*.2f", FileReportColumns[5] - 1,
                File.FunctionCoverage.getPercentCovered()) << '%';
  OS << "\n";
}

void CoverageReport::render(const FunctionCoverageSummary &Function,
                            raw_ostream &OS) {
  OS << column(Function.Name, FunctionReportColumns[0], Column::RightTrim)
     << format("%*u", FunctionReportColumns[1],
               (unsigned)Function.RegionCoverage.NumRegions);
  Options.colored_ostream(OS, Function.RegionCoverage.isFullyCovered()
                                  ? raw_ostream::GREEN
                                  : raw_ostream::RED)
      << format("%*u", FunctionReportColumns[2],
                (unsigned)Function.RegionCoverage.NotCovered);
  Options.colored_ostream(
      OS, determineCoveragePercentageColor(Function.RegionCoverage))
      << format("%*.2f", FunctionReportColumns[3] - 1,
                Function.RegionCoverage.getPercentCovered()) << '%';
  OS << format("%*u", FunctionReportColumns[4],
               (unsigned)Function.LineCoverage.NumLines);
  Options.colored_ostream(OS, Function.LineCoverage.isFullyCovered()
                                  ? raw_ostream::GREEN
                                  : raw_ostream::RED)
      << format("%*u", FunctionReportColumns[5],
                (unsigned)Function.LineCoverage.NotCovered);
  Options.colored_ostream(
      OS, determineCoveragePercentageColor(Function.LineCoverage))
      << format("%*.2f", FunctionReportColumns[6] - 1,
                Function.LineCoverage.getPercentCovered()) << '%';
  OS << "\n";
}

void CoverageReport::renderFunctionReports(raw_ostream &OS) {
  bool isFirst = true;
  for (const auto &File : Summary.getFileSummaries()) {
    if (isFirst)
      isFirst = false;
    else
      OS << "\n";
    OS << "File '" << File.Name << "':\n";
    OS << column("Name", FunctionReportColumns[0])
       << column("Regions", FunctionReportColumns[1], Column::RightAlignment)
       << column("Miss", FunctionReportColumns[2], Column::RightAlignment)
       << column("Cover", FunctionReportColumns[3], Column::RightAlignment)
       << column("Lines", FunctionReportColumns[4], Column::RightAlignment)
       << column("Miss", FunctionReportColumns[5], Column::RightAlignment)
       << column("Cover", FunctionReportColumns[6], Column::RightAlignment);
    OS << "\n";
    renderDivider(FunctionReportColumns, OS);
    OS << "\n";
    for (const auto &Function : File.FunctionSummaries)
      render(Function, OS);
    renderDivider(FunctionReportColumns, OS);
    OS << "\n";
    render(FunctionCoverageSummary("TOTAL", /*ExecutionCount=*/0,
                                   File.RegionCoverage, File.LineCoverage),
           OS);
  }
}

void CoverageReport::renderFileReports(raw_ostream &OS) {
  OS << column("Filename", FileReportColumns[0])
     << column("Regions", FileReportColumns[1], Column::RightAlignment)
     << column("Miss", FileReportColumns[2], Column::RightAlignment)
     << column("Cover", FileReportColumns[3], Column::RightAlignment)
     << column("Functions", FileReportColumns[4], Column::RightAlignment)
     << column("Executed", FileReportColumns[5], Column::RightAlignment)
     << "\n";
  renderDivider(FileReportColumns, OS);
  OS << "\n";
  for (const auto &File : Summary.getFileSummaries())
    render(File, OS);
  renderDivider(FileReportColumns, OS);
  OS << "\n";
  render(Summary.getCombinedFileSummaries(), OS);
}
<|endoftext|>