<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2013-, Open Perception, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the copyright holder(s) nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */

/** \brief PCD 2 PNG converter
 *
 * This converter takes three inputs: names of the input PCD and output PNG files, and the name of the field.
 *
 * \author Sergey Alexandrov
 *
 */

#include <boost/lexical_cast.hpp>

#include <pcl/console/time.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/io/pcd_io.h>
#include <pcl/io/png_io.h>
#include <pcl/conversions.h>

using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;

void
printHelp (int, char **argv)
{
  std::cout << std::endl;
  std::cout << "****************************************************************************" << std::endl;
  std::cout << "*                                                                          *" << std::endl;
  std::cout << "*                       PCD 2 PNG CONVERTER - Usage Guide                  *" << std::endl;
  std::cout << "*                                                                          *" << std::endl;
  std::cout << "****************************************************************************" << std::endl;
  std::cout << std::endl;
  std::cout << "Usage: " << argv[0] << " [Options] input.pcd output.png" << std::endl;
  std::cout << std::endl;
  std::cout << "Options:" << std::endl;
  std::cout << "     --help   : Show this help" << std::endl;
  std::cout << "     --field  : Set the field to extract data from. Supported fields:"       << std::endl;
  std::cout << "                - normal"                                                    << std::endl;
  std::cout << "                * rgb (default)"                                             << std::endl;
  std::cout << "                - label"                                                     << std::endl;
  std::cout << "                - z"                                                         << std::endl;
  std::cout << "                - curvature"                                                 << std::endl;
  std::cout << "                - intensity"                                                 << std::endl;
  std::cout << "     --scale  : Apply scaling to extracted data (only for z, curvature, and" << std::endl;
  std::cout << "                intensity fields). Supported options:"                       << std::endl;
  std::cout << "                - <float> : Scale by a fixed number"                         << std::endl;
  std::cout << "                - auto    : Auto-scale to the full range"                    << std::endl;
  std::cout << "                - no      : No scaling"                                      << std::endl;
  std::cout << "                If the option is omitted then default scaling (depends on"   << std::endl;
  std::cout << "                the field type) will be used."                               << std::endl;
  std::cout << "     --colors : Choose color mapping mode for labels (only for label"        << std::endl;
  std::cout << "                field). Supported options:"                                  << std::endl;
  std::cout << "                * mono    : Use shades of gray (default)"                    << std::endl;
  std::cout << "                - rgb     : Use randomly generated RGB colors"               << std::endl;
  std::cout << std::endl;
  std::cout << "Note: The converter will try to use RGB field if '--field' option is not"    << std::endl;
  std::cout << "      supplied."                                                             << std::endl;
}

bool
loadCloud (const std::string &filename, pcl::PCLPointCloud2 &cloud)
{
  TicToc tt;
  print_highlight ("Loading "); print_value ("%s ", filename.c_str ());

  tt.tic ();
  if (loadPCDFile (filename, cloud) < 0)
    return (false);
  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n");
  print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());

  return (true);
}

void
saveImage (const std::string &filename, const pcl::PCLImage& image)
{
  TicToc tt;
  tt.tic ();
  print_highlight ("Saving "); print_value ("%s ", filename.c_str ());
  savePNGFile (filename, image);
  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", image.width * image.height); print_info (" points]\n");
}

template<typename T> bool
parseScaleOption (int argc, char** argv, T& pcie)
{
  std::string scaling = "default";
  pcl::console::parse_argument (argc, argv, "--scale", scaling);
  print_info ("Scaling: "); print_value ("%s\n", scaling.c_str());
  if (scaling == "default")
  {
    // scaling option omitted, use whatever defaults image extractor has
  }
  else if (scaling == "no")
  {
    pcie.setScalingMethod(pcie.SCALING_NO);
  }
  else if (scaling == "auto")
  {
    pcie.setScalingMethod(pcie.SCALING_FULL_RANGE);
  }
  else
  {
    try
    {
      float factor = boost::lexical_cast<float> (scaling);
      pcie.setScalingMethod(pcie.SCALING_FIXED_FACTOR);
      pcie.setScalingFactor(factor);
    }
    catch (boost::bad_lexical_cast)
    {
      print_error ("The value of --scale option should be \"no\", \"auto\", or a floating point number.\n");
      return false;
    }
  }
  return true;
}

template<typename T> bool
parseColorsOption (int argc, char** argv, T& pcie)
{
  std::string colors = "mono";
  pcl::console::parse_argument (argc, argv, "--colors", colors);
  print_info ("Colors: "); print_value ("%s\n", colors.c_str());
  if (colors == "mono")
  {
    pcie.setColorMode(pcie.COLORS_MONO);
  }
  else if (colors == "rgb")
  {
    pcie.setColorMode(pcie.COLORS_RGB_RANDOM);
  }
  else
  {
    return false;
  }
  return true;
}

/* ---[ */
int
main (int argc, char** argv)
{
  print_info ("Convert a PCD file to PNG format.\nFor more information, use: %s --help\n", argv[0]);

  if (argc < 3)
  {
    printHelp (argc, argv);
    return (-1);
  }

  // Parse the command line arguments for .pcd and .png files
  std::vector<int> pcd_file_index = parse_file_extension_argument (argc, argv, ".pcd");
  std::vector<int> png_file_index = parse_file_extension_argument (argc, argv, ".png");

  if (pcd_file_index.size () != 1 || png_file_index.size () != 1)
  {
    print_error ("Need one input PCD file and one output PNG file.\n");
    return (-1);
  }

  std::string pcd_filename = argv[pcd_file_index[0]];
  std::string png_filename = argv[png_file_index[0]];

  // Load the input file
  pcl::PCLPointCloud2::Ptr blob (new pcl::PCLPointCloud2);
  if (!loadCloud (pcd_filename, *blob))
  {
    print_error ("Unable to load PCD file.\n");
    return (-1);
  }

  // Check if the cloud is organized
  if (blob->height == 1)
  {
    print_error ("Input cloud is not organized.\n");
    return (-1);
  }

  std::string field_name = "rgb";
  parse_argument (argc, argv, "--field", field_name);
  print_info ("Field name: "); print_value ("%s\n", field_name.c_str());

  pcl::PCLImage image;
  bool extracted;
  if (field_name == "normal")
  {
    PointCloud<Normal> cloud;
    fromPCLPointCloud2 (*blob, cloud);
    PointCloudImageExtractorFromNormalField<Normal> pcie;
    extracted = pcie.extract(cloud, image);
  }
  else if (field_name == "rgb")
  {
    PointCloud<PointXYZRGB> cloud;
    fromPCLPointCloud2 (*blob, cloud);
    PointCloudImageExtractorFromRGBField<PointXYZRGB> pcie;
    extracted = pcie.extract(cloud, image);
  }
  else if (field_name == "label")
  {
    PointCloud<Label> cloud;
    fromPCLPointCloud2 (*blob, cloud);
    PointCloudImageExtractorFromLabelField<Label> pcie;
    if (!parseColorsOption(argc, argv, pcie))
      return (-1);
    extracted = pcie.extract(cloud, image);
  }
  else if (field_name == "z")
  {
    PointCloud<PointXYZ> cloud;
    fromPCLPointCloud2 (*blob, cloud);
    PointCloudImageExtractorFromZField<PointXYZ> pcie;
    if (!parseScaleOption(argc, argv, pcie))
      return (-1);
    extracted = pcie.extract(cloud, image);
  }
  else if (field_name == "curvature")
  {
    PointCloud<Normal> cloud;
    fromPCLPointCloud2 (*blob, cloud);
    PointCloudImageExtractorFromCurvatureField<Normal> pcie;
    if (!parseScaleOption(argc, argv, pcie))
      return (-1);
    extracted = pcie.extract(cloud, image);
  }
  else if (field_name == "intensity")
  {
    PointCloud<Intensity> cloud;
    fromPCLPointCloud2 (*blob, cloud);
    PointCloudImageExtractorFromIntensityField<Intensity> pcie;
    if (!parseScaleOption(argc, argv, pcie))
      return (-1);
    extracted = pcie.extract(cloud, image);
  }
  else
  {
    print_error ("Unsupported field \"%s\".\n", field_name.c_str());
    return (-1);
  }

  if (!extracted)
  {
    print_error ("Failed to extract an image from field \"%s\".\n", field_name.c_str());
    return (-1);
  }
  saveImage (png_filename, image);

  return (0);
}
<commit_msg>Update pcl_pcd2png tool to support Glasbey color mode<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2013-, Open Perception, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of the copyright holder(s) nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */

/** \brief PCD 2 PNG converter
 *
 * This converter takes three inputs: names of the input PCD and output PNG files, and the name of the field.
 *
 * \author Sergey Alexandrov
 *
 */

#include <boost/lexical_cast.hpp>

#include <pcl/console/time.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/io/pcd_io.h>
#include <pcl/io/png_io.h>
#include <pcl/conversions.h>

using namespace pcl;
using namespace pcl::io;
using namespace pcl::console;

void
printHelp (int, char **argv)
{
  std::cout << std::endl;
  std::cout << "****************************************************************************" << std::endl;
  std::cout << "*                                                                          *" << std::endl;
  std::cout << "*                       PCD 2 PNG CONVERTER - Usage Guide                  *" << std::endl;
  std::cout << "*                                                                          *" << std::endl;
  std::cout << "****************************************************************************" << std::endl;
  std::cout << std::endl;
  std::cout << "Usage: " << argv[0] << " [Options] input.pcd output.png" << std::endl;
  std::cout << std::endl;
  std::cout << "Options:" << std::endl;
  std::cout << std::endl;
  std::cout << "     --help   : Show this help" << std::endl;
  std::cout << "     --field  : Set the field to extract data from. Supported fields:"       << std::endl;
  std::cout << "                - normal"                                                    << std::endl;
  std::cout << "                * rgb (default)"                                             << std::endl;
  std::cout << "                - label"                                                     << std::endl;
  std::cout << "                - z"                                                         << std::endl;
  std::cout << "                - curvature"                                                 << std::endl;
  std::cout << "                - intensity"                                                 << std::endl;
  std::cout << "     --scale  : Apply scaling to extracted data (only for z, curvature, and" << std::endl;
  std::cout << "                intensity fields). Supported options:"                       << std::endl;
  std::cout << "                - <float> : Scale by a fixed number"                         << std::endl;
  std::cout << "                - auto    : Auto-scale to the full range"                    << std::endl;
  std::cout << "                - no      : No scaling"                                      << std::endl;
  std::cout << "                If the option is omitted then default scaling (depends on"   << std::endl;
  std::cout << "                the field type) will be used."                               << std::endl;
  std::cout << "     --colors : Choose color mapping mode for labels (only for label"        << std::endl;
  std::cout << "                field). Supported options:"                                  << std::endl;
  std::cout << "                * mono    : Use shades of gray (default)"                    << std::endl;
  std::cout << "                - rgb     : Use randomly generated RGB colors"               << std::endl;
  std::cout << "                - glasbey : Use fixed colors from the Glasbey lookup table¹" << std::endl;
  std::cout << std::endl;
  std::cout << "Notes:"                                                                      << std::endl;
  std::cout << std::endl;
  std::cout << "¹) The Glasbey lookup table is a color table structured in a maximally"      << std::endl;
  std::cout << "   discontinuous manner. Adjacent color bins are chosen to be as distinct"   << std::endl;
  std::cout << "   from one another as possible (see http://fiji.sc/Glasbey)."               << std::endl;
  std::cout << "   The label with the smallest id will be assigned the first color from the" << std::endl;
  std::cout << "   table, the second smallest will have the second color, and so on. Thus,"  << std::endl;
  std::cout << "   if you have several clouds with the same labels, you will get repetitive" << std::endl;
  std::cout << "   consistently colored PNG images."                                         << std::endl;
}

bool
loadCloud (const std::string &filename, pcl::PCLPointCloud2 &cloud)
{
  TicToc tt;
  print_highlight ("Loading "); print_value ("%s ", filename.c_str ());

  tt.tic ();
  if (loadPCDFile (filename, cloud) < 0)
    return (false);
  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n");
  print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());

  return (true);
}

void
saveImage (const std::string &filename, const pcl::PCLImage& image)
{
  TicToc tt;
  tt.tic ();
  print_highlight ("Saving "); print_value ("%s ", filename.c_str ());
  savePNGFile (filename, image);
  print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" ms : "); print_value ("%d", image.width * image.height); print_info (" points]\n");
}

template<typename T> bool
parseScaleOption (int argc, char** argv, T& pcie)
{
  std::string scaling = "default";
  pcl::console::parse_argument (argc, argv, "--scale", scaling);
  print_info ("Scaling: "); print_value ("%s\n", scaling.c_str());
  if (scaling == "default")
  {
    // scaling option omitted, use whatever defaults image extractor has
  }
  else if (scaling == "no")
  {
    pcie.setScalingMethod(pcie.SCALING_NO);
  }
  else if (scaling == "auto")
  {
    pcie.setScalingMethod(pcie.SCALING_FULL_RANGE);
  }
  else
  {
    try
    {
      float factor = boost::lexical_cast<float> (scaling);
      pcie.setScalingMethod(pcie.SCALING_FIXED_FACTOR);
      pcie.setScalingFactor(factor);
    }
    catch (boost::bad_lexical_cast)
    {
      print_error ("The value of --scale option should be \"no\", \"auto\", or a floating point number.\n");
      return false;
    }
  }
  return true;
}

template<typename T> bool
parseColorsOption (int argc, char** argv, T& pcie)
{
  std::string colors = "mono";
  pcl::console::parse_argument (argc, argv, "--colors", colors);
  print_info ("Colors: "); print_value ("%s\n", colors.c_str());
  if (colors == "mono")
  {
    pcie.setColorMode(pcie.COLORS_MONO);
  }
  else if (colors == "rgb")
  {
    pcie.setColorMode(pcie.COLORS_RGB_RANDOM);
  }
  else if (colors == "glasbey")
  {
    pcie.setColorMode(pcie.COLORS_RGB_GLASBEY);
  }
  else
  {
    return false;
  }
  return true;
}

/* ---[ */
int
main (int argc, char** argv)
{
  print_info ("Convert a PCD file to PNG format.\nFor more information, use: %s --help\n", argv[0]);

  if (argc < 3 || pcl::console::find_switch (argc, argv, "--help"))
  {
    printHelp (argc, argv);
    return (-1);
  }

  // Parse the command line arguments for .pcd and .png files
  std::vector<int> pcd_file_index = parse_file_extension_argument (argc, argv, ".pcd");
  std::vector<int> png_file_index = parse_file_extension_argument (argc, argv, ".png");

  if (pcd_file_index.size () != 1 || png_file_index.size () != 1)
  {
    print_error ("Need one input PCD file and one output PNG file.\n");
    return (-1);
  }

  std::string pcd_filename = argv[pcd_file_index[0]];
  std::string png_filename = argv[png_file_index[0]];

  // Load the input file
  pcl::PCLPointCloud2::Ptr blob (new pcl::PCLPointCloud2);
  if (!loadCloud (pcd_filename, *blob))
  {
    print_error ("Unable to load PCD file.\n");
    return (-1);
  }

  // Check if the cloud is organized
  if (blob->height == 1)
  {
    print_error ("Input cloud is not organized.\n");
    return (-1);
  }

  std::string field_name = "rgb";
  parse_argument (argc, argv, "--field", field_name);
  print_info ("Field name: "); print_value ("%s\n", field_name.c_str());

  pcl::PCLImage image;
  bool extracted;
  if (field_name == "normal")
  {
    PointCloud<Normal> cloud;
    fromPCLPointCloud2 (*blob, cloud);
    PointCloudImageExtractorFromNormalField<Normal> pcie;
    extracted = pcie.extract(cloud, image);
  }
  else if (field_name == "rgb")
  {
    PointCloud<PointXYZRGB> cloud;
    fromPCLPointCloud2 (*blob, cloud);
    PointCloudImageExtractorFromRGBField<PointXYZRGB> pcie;
    extracted = pcie.extract(cloud, image);
  }
  else if (field_name == "label")
  {
    PointCloud<Label> cloud;
    fromPCLPointCloud2 (*blob, cloud);
    PointCloudImageExtractorFromLabelField<Label> pcie;
    if (!parseColorsOption(argc, argv, pcie))
      return (-1);
    extracted = pcie.extract(cloud, image);
  }
  else if (field_name == "z")
  {
    PointCloud<PointXYZ> cloud;
    fromPCLPointCloud2 (*blob, cloud);
    PointCloudImageExtractorFromZField<PointXYZ> pcie;
    if (!parseScaleOption(argc, argv, pcie))
      return (-1);
    extracted = pcie.extract(cloud, image);
  }
  else if (field_name == "curvature")
  {
    PointCloud<Normal> cloud;
    fromPCLPointCloud2 (*blob, cloud);
    PointCloudImageExtractorFromCurvatureField<Normal> pcie;
    if (!parseScaleOption(argc, argv, pcie))
      return (-1);
    extracted = pcie.extract(cloud, image);
  }
  else if (field_name == "intensity")
  {
    PointCloud<Intensity> cloud;
    fromPCLPointCloud2 (*blob, cloud);
    PointCloudImageExtractorFromIntensityField<Intensity> pcie;
    if (!parseScaleOption(argc, argv, pcie))
      return (-1);
    extracted = pcie.extract(cloud, image);
  }
  else
  {
    print_error ("Unsupported field \"%s\".\n", field_name.c_str());
    return (-1);
  }

  if (!extracted)
  {
    print_error ("Failed to extract an image from field \"%s\".\n", field_name.c_str());
    return (-1);
  }
  saveImage (png_filename, image);

  return (0);
}
<|endoftext|>


<commit_before>#include "Logging.h"

#include <QDebug>
#include <QFile>
#include <QDate>

Logging* Logging::instance_ = new Logging;

namespace
{
    QString LOG_DIR = "log/";
    QString LOG_NAME = "epsilon-hermes-";
    QString LOG_DATE_FORMAT = "yyyy-MM-dd";
    QString LOG_EXT = ".log";

    QString LOG_DATETIME_FORMAT = "yyyy-MM-dd-hh-mm-ss-zzz-t";
    QString DEBUG_MSG_FORMAT = "[%1] (%2, %3:%4) %5\n"; // datetime, file, function, line, msg
    QString NON_DEBUG_MSG_FORMAT = "[%1] (%2) %3\n"; // datetime, file, msg
}

void Logging::init(int level)
{
    qInstallMessageHandler(Logging::logMessageHandler);

    switch (level)
    {
        case 0:
            logLevel_ = Logging::DEBUG;
            break;

        case 1:
            logLevel_ = Logging::INFO;
            break;

        case 2:
            logLevel_ = Logging::WARNING;
            break;

        case 3:
            logLevel_ = Logging::CRITICAL;
            break;

        case 4:
            logLevel_ = Logging::FATAL;
            break;

        default:
            logLevel_ = Logging::DEBUG;
            qWarning() << "Configured log level unrecognized. "
                       << "DEBUG=0,INFO=1,WARNING=2,CRITICAL=3,FATAL=4. "
                       << "Defaulting to DEBUG.";
            break;
    }

    // Because Epsilon Hermes is meant for a solar car
    // and competitions do not include night racing
    // It is quite unlikely to for the date to change while the car is running
    // So this assumes the date will not change while Epsilon Hermes is running
    QString todayStr = QDate::currentDate().toString(LOG_DATE_FORMAT);
    QString logName = LOG_DIR + LOG_NAME + todayStr + LOG_EXT;
    logFile_.setFileName(logName);

    if (logFile_.open(QIODevice::ReadWrite))
    {
        logStream_.setDevice(&logFile_);
        qInfo() << "Logging Initialized";
    }
    else
    {
        qFatal("Logging initalization failed");
    }

}

QTextStream& Logging::logStream()
{
    return logStream_;
}

Logging::LogLevel Logging::logLevel()
{
    return logLevel_;
}

Logging* Logging::instance()
{
    if (!instance_)
    {
        instance_ = new Logging;
    }

    return instance_;
}

// private

Logging::Logging()
    : logLevel_(LogLevel::INFO)
{
}

Logging::~Logging()
{
    logFile_.close();
}

void Logging::logMessageHandler(
    QtMsgType type,
    const QMessageLogContext& ctx,
    const QString& msg)
{
    // Construct string for current date time in UTC
    QDateTime nowDateTime = QDateTime::currentDateTimeUtc();
    QString nowStr = nowDateTime.toString(LOG_DATETIME_FORMAT);

    // Construct message
    QString logMsg;

    if (instance()->logLevel() == LogLevel::DEBUG)
    {
        logMsg = QString(DEBUG_MSG_FORMAT).arg(
                     nowStr,
                     ctx.file,
                     ctx.function,
                     QString::number(ctx.line),
                     msg);
    }
    else
    {
        logMsg = QString(NON_DEBUG_MSG_FORMAT).arg(
                     nowStr,
                     ctx.file,
                     msg);
    }

    // Prepend log level
    switch (type)
    {
        case QtDebugMsg:
            if (instance()->logLevel() > LogLevel::DEBUG)
            {
                return;
            }

            logMsg = "DEBUG: " + logMsg;
            break;

        case QtInfoMsg:
            if (instance()->logLevel() > LogLevel::INFO)
            {
                return;
            }

            logMsg = "INFO: " + logMsg;
            break;

        case QtWarningMsg:
            if (instance()->logLevel() > LogLevel::WARNING)
            {
                return;
            }

            logMsg = "WARNING: " + logMsg;
            break;

        case QtCriticalMsg:
            if (instance()->logLevel() > LogLevel::CRITICAL)
            {
                return;
            }

            logMsg = "CRITICAL: " + logMsg;
            break;

        case QtFatalMsg:
            logMsg = "FATAL: " + logMsg;
            break;
    }

    // Finally print to file, and also to stderr if DEBUG
    instance()->logStream() << logMsg;
    fprintf(stderr, "%s", logMsg.toLocal8Bit().constData());

    // Abort program is FATAl call
    if (type == QtFatalMsg)
    {
        abort();
    }
}
<commit_msg>write to file working<commit_after>#include "Logging.h"

#include <QDebug>
#include <QFile>
#include <QDate>

Logging* Logging::instance_ = new Logging;

namespace
{
    QString LOG_DIR = "log/";
    QString LOG_NAME = "epsilon-hermes-";
    QString LOG_DATE_FORMAT = "yyyy-MM-dd";
    QString LOG_EXT = ".log";

    QString LOG_DATETIME_FORMAT = "yyyy-MM-dd-hh-mm-ss-zzz-t";
    QString DEBUG_MSG_FORMAT = "[%1] (%2, %3:%4) %5\n"; // datetime, file, function, line, msg
    QString NON_DEBUG_MSG_FORMAT = "[%1] (%2) %3\n"; // datetime, file, msg
}

void Logging::init(int level)
{
    qInstallMessageHandler(Logging::logMessageHandler);

    switch (level)
    {
        case 0:
            logLevel_ = Logging::DEBUG;
            break;

        case 1:
            logLevel_ = Logging::INFO;
            break;

        case 2:
            logLevel_ = Logging::WARNING;
            break;

        case 3:
            logLevel_ = Logging::CRITICAL;
            break;

        case 4:
            logLevel_ = Logging::FATAL;
            break;

        default:
            logLevel_ = Logging::DEBUG;
            qWarning() << "Configured log level unrecognized. "
                       << "DEBUG=0,INFO=1,WARNING=2,CRITICAL=3,FATAL=4. "
                       << "Defaulting to DEBUG.";
            break;
    }

    // Because Epsilon Hermes is meant for a solar car
    // and competitions do not include night racing
    // It is quite unlikely to for the date to change while the car is running
    // So this assumes the date will not change while Epsilon Hermes is running
    QString todayStr = QDate::currentDate().toString(LOG_DATE_FORMAT);
    QString logName = LOG_DIR + LOG_NAME + todayStr + LOG_EXT;
    logFile_.setFileName(logName);

    if (logFile_.open(QIODevice::WriteOnly | QIODevice::Append))
    {
        logStream_.setDevice(&logFile_);
        qInfo() << "Logging Initialized";
    }
    else
    {
        qFatal("Logging initalization failed");
    }

}

QTextStream& Logging::logStream()
{
    return logStream_;
}

Logging::LogLevel Logging::logLevel()
{
    return logLevel_;
}

Logging* Logging::instance()
{
    if (!instance_)
    {
        instance_ = new Logging;
    }

    return instance_;
}

// private

Logging::Logging()
    : logLevel_(LogLevel::INFO)
{
}

Logging::~Logging()
{
    logFile_.close();
}

void Logging::logMessageHandler(
    QtMsgType type,
    const QMessageLogContext& ctx,
    const QString& msg)
{
    // Construct string for current date time in UTC
    QDateTime nowDateTime = QDateTime::currentDateTimeUtc();
    QString nowStr = nowDateTime.toString(LOG_DATETIME_FORMAT);

    // Construct message
    QString logMsg;

    if (instance()->logLevel() == LogLevel::DEBUG)
    {
        logMsg = QString(DEBUG_MSG_FORMAT).arg(
                     nowStr,
                     ctx.file,
                     ctx.function,
                     QString::number(ctx.line),
                     msg);
    }
    else
    {
        logMsg = QString(NON_DEBUG_MSG_FORMAT).arg(
                     nowStr,
                     ctx.file,
                     msg);
    }

    // Prepend log level
    switch (type)
    {
        case QtDebugMsg:
            if (instance()->logLevel() > LogLevel::DEBUG)
            {
                return;
            }

            logMsg = "DEBUG: " + logMsg;
            break;

        case QtInfoMsg:
            if (instance()->logLevel() > LogLevel::INFO)
            {
                return;
            }

            logMsg = "INFO: " + logMsg;
            break;

        case QtWarningMsg:
            if (instance()->logLevel() > LogLevel::WARNING)
            {
                return;
            }

            logMsg = "WARNING: " + logMsg;
            break;

        case QtCriticalMsg:
            if (instance()->logLevel() > LogLevel::CRITICAL)
            {
                return;
            }

            logMsg = "CRITICAL: " + logMsg;
            break;

        case QtFatalMsg:
            logMsg = "FATAL: " + logMsg;
            break;
    }

    // Finally print to file, and also to stderr if DEBUG
    instance()->logStream() << logMsg;
    instance()->logStream().flush();
    fprintf(stderr, "%s", logMsg.toLocal8Bit().constData());

    // Abort program is FATAl call
    if (type == QtFatalMsg)
    {
        abort();
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 Chan Beom Park
 */

#include "lhefevent.h"

namespace lhef {
std::ostream& operator<<(std::ostream& os, const EventInfo& evinfo) {
    os << "EventInfo {nup=" << evinfo.nup
       << ",idprup=" << evinfo.idprup
       << ",xwgtup=" << evinfo.xwgtup
       << ",scalup=" << evinfo.scalup
       << ",aqedup=" << evinfo.aqedup
       << ",aqcdup=" << evinfo.aqcdup << "}";
    return os;
}

std::ostream& operator<<(std::ostream& os, const Particle& p) {
    os << "Particle {idup=" << p.idup
       << ",istup=" << p.istup
       << ",mothup=(" << p.mothup.first << "," << p.mothup.second << ")"
       << ",icolup=(" << p.icolup.first << "," << p.icolup.second << ")"
       << "pup=(";
    for (auto momentum : p.pup) {
        os << momentum << ",";
    }
    os.seekp(-1, std::ios_base::cur);
    os << ")"
       << ",vtimup=" << p.vtimup
       << ",spinup=" << p.spinup << "}";
    return os;
}

std::ostream& operator<<(std::ostream& os, const EventEntry& ps) {
    os << "[";
    for (auto p : ps.particles) {
        os << "(" << p.first
           << "," << p.second << "),";
    }
    os.seekp(-1, std::ios_base::cur);
    os << "]";
    return os;
}

std::ostream& operator<<(std::ostream& os, const Event& e) {
    os << "Event ("
       << e.event.first << ","
       << e.event.second << ")";
    return os;
}

void SkipTillEventLine(std::istream *is) {
    std::string line;
    while (std::getline(*is, line)
           && line.find("<event") == std::string::npos) {
        continue;
    }
}

std::string EventLines(std::istream *is) {
    SkipTillEventLine(is);

    std::string event_line(""), line;
    while (std::getline(*is, line)) {
        if (line.find("</event") == std::string::npos) {
            event_line += line + '\n';
        } else {
            break;
        }
    }
    return event_line;
}
}  // namespace lhef
<commit_msg>Skip comment line<commit_after>/*
 * Copyright (c) 2014 Chan Beom Park
 */

#include "lhefevent.h"
#include <string>

namespace lhef {
std::ostream& operator<<(std::ostream& os, const EventInfo& evinfo) {
    os << "EventInfo {nup=" << evinfo.nup
       << ",idprup=" << evinfo.idprup
       << ",xwgtup=" << evinfo.xwgtup
       << ",scalup=" << evinfo.scalup
       << ",aqedup=" << evinfo.aqedup
       << ",aqcdup=" << evinfo.aqcdup << "}";
    return os;
}

std::ostream& operator<<(std::ostream& os, const Particle& p) {
    os << "Particle {idup=" << p.idup
       << ",istup=" << p.istup
       << ",mothup=(" << p.mothup.first << "," << p.mothup.second << ")"
       << ",icolup=(" << p.icolup.first << "," << p.icolup.second << ")"
       << "pup=(";
    for (auto momentum : p.pup) {
        os << momentum << ",";
    }
    os.seekp(-1, std::ios_base::cur);
    os << ")"
       << ",vtimup=" << p.vtimup
       << ",spinup=" << p.spinup << "}";
    return os;
}

std::ostream& operator<<(std::ostream& os, const EventEntry& ps) {
    os << "[";
    for (auto p : ps.particles) {
        os << "(" << p.first
           << "," << p.second << "),";
    }
    os.seekp(-1, std::ios_base::cur);
    os << "]";
    return os;
}

std::ostream& operator<<(std::ostream& os, const Event& e) {
    os << "Event ("
       << e.event.first << ","
       << e.event.second << ")";
    return os;
}

void SkipTillEventLine(std::istream *is) {
    std::string line;
    while (std::getline(*is, line)
           && line.find("<event") == std::string::npos) {
        continue;
    }
}

std::string EventLines(std::istream *is) {
    SkipTillEventLine(is);

    std::string event_line(""), line;
    while (std::getline(*is, line)) {
        if (line.find("</event") == std::string::npos) {
            if (line.front() == '#') {  // comment line
                continue;
            } else {
                event_line += line + '\n';
            }
        } else {
            break;
        }
    }
    return event_line;
}
}  // namespace lhef
<|endoftext|>


<commit_before>// -*- coding: us-ascii-unix -*-
#include <stdexcept>
#include <fstream>
#include "wx/dir.h"
#include "formats/png/file-png.hh"
#include "test-sys/test-name.hh"
#include "text/char-constants.hh"
#include "text/formatting.hh"
#include "tests/test-util/file-handling.hh"
#include "tests/test-util/image-table.hh"

namespace faint{

FilePath get_test_load_path(const FileName& filename){
  return make_absolute_file_path("test-data/" + filename.Str()).Visit(
    [](const FilePath& path){
      return path;
    },
    []() -> FilePath{
      throw std::logic_error("Could not create absolute path");
    });
}

static OrError<Bitmap> load_png(const FilePath& path){
  if (path.Extension() == FileExtension("png")){
    return read_png(path);
  }
  return space_sep("Unsupported extension:", path.Extension().Str());
}

Bitmap load_test_image(const FileName& fileName){
  const auto path = get_test_load_path(fileName);
  return load_png(path).Visit(
    [](const Bitmap& bmp){
      return bmp;
    },
    [&](const utf8_string&) -> Bitmap{
      throw std::runtime_error(std::string("load_test_image failed loading \"") +
        path.Str().c_str() + "\"");
    });
}

static SaveResult save_as_png(const Bitmap& bmp, const FilePath& path){
  return write_png(path, bmp, PngColorType::RGB_ALPHA);
}

FilePath save_test_image(const Bitmap& bmp, const FileName& filename){
  const auto outPath = get_test_save_path(filename);
  save_as_png(bmp, outPath);
  return outPath;
}

FilePath get_test_save_path(const FileName& fileName){
  DirPath out("out");
  if (!exists(out)){
    make_dir(out);
  }

  DirPath testDir(wxString("out/") + get_test_name());
  if (!exists(testDir)){
    make_dir(testDir);
  }

  return make_absolute_file_path(utf8_string("out/" +
      get_test_name() + "/" +
      fileName.Str().str())).Get();
}

void save_image_table(const ImageTable& table){
  std::ofstream f(get_test_save_path(FileName("index.html")).Str().c_str());
  f << table.ToHtml();
}

utf8_string u8_chars(){
  utf8_string s;
  s += utf8_char(hyphen);
  s += utf8_char(246);
  return s;
}

FileName suffix_u8_chars(const FileName& f){
  auto p = split_extension(f);
  return FileName(p.first + u8_chars() + p.second);
}

} // namespace
<commit_msg>Added another unicode character to file unit tests<commit_after>// -*- coding: us-ascii-unix -*-
#include <stdexcept>
#include <fstream>
#include "wx/dir.h"
#include "formats/png/file-png.hh"
#include "test-sys/test-name.hh"
#include "text/char-constants.hh"
#include "text/formatting.hh"
#include "tests/test-util/file-handling.hh"
#include "tests/test-util/image-table.hh"

namespace faint{

FilePath get_test_load_path(const FileName& filename){
  return make_absolute_file_path("test-data/" + filename.Str()).Visit(
    [](const FilePath& path){
      return path;
    },
    []() -> FilePath{
      throw std::logic_error("Could not create absolute path");
    });
}

static OrError<Bitmap> load_png(const FilePath& path){
  if (path.Extension() == FileExtension("png")){
    return read_png(path);
  }
  return space_sep("Unsupported extension:", path.Extension().Str());
}

Bitmap load_test_image(const FileName& fileName){
  const auto path = get_test_load_path(fileName);
  return load_png(path).Visit(
    [](const Bitmap& bmp){
      return bmp;
    },
    [&](const utf8_string&) -> Bitmap{
      throw std::runtime_error(std::string("load_test_image failed loading \"") +
        path.Str().c_str() + "\"");
    });
}

static SaveResult save_as_png(const Bitmap& bmp, const FilePath& path){
  return write_png(path, bmp, PngColorType::RGB_ALPHA);
}

FilePath save_test_image(const Bitmap& bmp, const FileName& filename){
  const auto outPath = get_test_save_path(filename);
  save_as_png(bmp, outPath);
  return outPath;
}

FilePath get_test_save_path(const FileName& fileName){
  DirPath out("out");
  if (!exists(out)){
    make_dir(out);
  }

  DirPath testDir(wxString("out/") + get_test_name());
  if (!exists(testDir)){
    make_dir(testDir);
  }

  return make_absolute_file_path(utf8_string("out/" +
      get_test_name() + "/" +
      fileName.Str().str())).Get();
}

void save_image_table(const ImageTable& table){
  std::ofstream f(get_test_save_path(FileName("index.html")).Str().c_str());
  f << table.ToHtml();
}

utf8_string u8_chars(){
  utf8_string s;
  s += utf8_char(hyphen);
  s += utf8_char(246);
  s += utf8_char(1576);
  return s;
}

FileName suffix_u8_chars(const FileName& f){
  auto p = split_extension(f);
  return FileName(p.first + u8_chars() + p.second);
}

} // namespace
<|endoftext|>


<commit_before>/*
 *
 * Copyright 2015, Google Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "test/core/util/test_config.h"
#include "test/core/util/port.h"
#include "test/cpp/util/echo.grpc.pb.h"
#include "src/core/support/env.h"
#include <grpc++/channel_arguments.h>
#include <grpc++/channel_interface.h>
#include <grpc++/client_context.h>
#include <grpc++/create_channel.h>
#include <grpc++/credentials.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc++/server_credentials.h>
#include <grpc++/status.h>
#include <gtest/gtest.h>
#include <grpc/grpc.h>
#include <grpc/grpc_zookeeper.h>
#include <zookeeper/zookeeper.h>

using grpc::cpp::test::util::EchoRequest;
using grpc::cpp::test::util::EchoResponse;

namespace grpc {
namespace testing {

class ZookeeperTestServiceImpl
    : public ::grpc::cpp::test::util::TestService::Service {
 public:
  Status Echo(ServerContext* context, const EchoRequest* request,
              EchoResponse* response) GRPC_OVERRIDE {
    response->set_message(request->message());
    return Status::OK;
  }
};

class ZookeeperTest : public ::testing::Test {
 protected:
  ZookeeperTest() {}

  void SetUp() GRPC_OVERRIDE {
    SetUpZookeeper();

    // Setup two servers
    int port1 = grpc_pick_unused_port_or_die();
    int port2 = grpc_pick_unused_port_or_die();
    server1_ = SetUpServer(port1);
    server2_ = SetUpServer(port2);

    // Register service /test in zookeeper
    RegisterService("/test", "test");

    // Register service instance /test/1 in zookeeper
    string value = "{\"host\":\"localhost\",\"port\":\"" + std::to_string(port1) + "\"}";
    RegisterService("/test/1", value);

    // Register service instance /test/2 in zookeeper
    value = "{\"host\":\"localhost\",\"port\":\"" + std::to_string(port2) + "\"}";
    RegisterService("/test/2", value);
  }

  std::unique_ptr<Server> SetUpServer(int port) {
    string server_address = "localhost:" + std::to_string(port);

    ServerBuilder builder;
    builder.AddListeningPort(server_address, InsecureServerCredentials());
    builder.RegisterService(&service_);
    std::unique_ptr<Server> server = builder.BuildAndStart();
    return server;
  }

  // Require zookeeper server running beforehand
  void SetUpZookeeper() {
    // Find zookeeper server address in environment
    // Default is localhost:2181
    zookeeper_address_ = "localhost:2181";
    char* addr = gpr_getenv("GRPC_ZOOKEEPER_SERVER_TEST");
    if (addr != NULL) {
      string addr_str(addr);
      zookeeper_address_ = addr_str;
      gpr_free(addr);
    }
    gpr_log(GPR_DEBUG, zookeeper_address_.c_str());

    // Connect to zookeeper server
    zoo_set_debug_level(ZOO_LOG_LEVEL_WARN);
    zookeeper_handle_ = zookeeper_init(zookeeper_address_.c_str(), NULL, 15000, 0, 0, 0);
    GPR_ASSERT(zookeeper_handle_ != NULL);

    // Register zookeeper name resolver in grpc
    grpc_zookeeper_register();
  }

  void RegisterService(string name, string value) {
    char *path = (char *)gpr_malloc(name.size());

    int status = zoo_exists(zookeeper_handle_, name.c_str(), 0, NULL);
    if (status == ZNONODE) {
      status = zoo_create(zookeeper_handle_, name.c_str(), value.c_str(), value.size(), &ZOO_OPEN_ACL_UNSAFE, 0, path, name.size());
    } else {
      status = zoo_set(zookeeper_handle_, name.c_str(), value.c_str(), value.size(), -1);
    }
    gpr_free(path);
    GPR_ASSERT(status == 0);
  }

  void DeleteService(string name) {
    int status = zoo_delete(zookeeper_handle_, name.c_str(), -1);
    GPR_ASSERT(status == 0);
  }

  void TearDown() GRPC_OVERRIDE {
    server1_->Shutdown();
    server2_->Shutdown();
    zookeeper_close(zookeeper_handle_);
  }

  void ResetStub() {
    string target = "zookeeper://" + zookeeper_address_ + "/test";
    channel_ = CreateChannel(target, InsecureCredentials(), ChannelArguments());
    stub_ = std::move(grpc::cpp::test::util::TestService::NewStub(channel_));
  }

  std::shared_ptr<ChannelInterface> channel_;
  std::unique_ptr<grpc::cpp::test::util::TestService::Stub> stub_;
  std::unique_ptr<Server> server1_;
  std::unique_ptr<Server> server2_;
  ZookeeperTestServiceImpl service_;
  zhandle_t* zookeeper_handle_;
  string zookeeper_address_;
};

// Test zookeeper state change between two RPCs
// TODO: Handle leaked objects
TEST_F(ZookeeperTest, ZookeeperStateChangeTwoRpc) {
  ResetStub();

  // First RPC
  EchoRequest request1;
  EchoResponse response1;
  ClientContext context1;
  context1.set_authority("test");
  request1.set_message("Hello");
  Status s1 = stub_->Echo(&context1, request1, &response1);
  EXPECT_EQ(response1.message(), request1.message());
  EXPECT_TRUE(s1.ok());

  // Zookeeper state change
  DeleteService("/test/2");
  sleep(1);

  // Second RPC
  EchoRequest request2;
  EchoResponse response2;
  ClientContext context2;
  context2.set_authority("test");
  request2.set_message("World");
  Status s2 = stub_->Echo(&context2, request2, &response2);
  EXPECT_EQ(response2.message(), request2.message());
  EXPECT_TRUE(s2.ok());
}

}  // namespace testing
}  // namespace grpc

int main(int argc, char** argv) {
  grpc_test_init(argc, argv);
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>Formatting zookeeper_test<commit_after>/*
 *
 * Copyright 2015, Google Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include "test/core/util/test_config.h"
#include "test/core/util/port.h"
#include "test/cpp/util/echo.grpc.pb.h"
#include "src/core/support/env.h"
#include <grpc++/channel_arguments.h>
#include <grpc++/channel_interface.h>
#include <grpc++/client_context.h>
#include <grpc++/create_channel.h>
#include <grpc++/credentials.h>
#include <grpc++/server.h>
#include <grpc++/server_builder.h>
#include <grpc++/server_context.h>
#include <grpc++/server_credentials.h>
#include <grpc++/status.h>
#include <gtest/gtest.h>
#include <grpc/grpc.h>
#include <grpc/grpc_zookeeper.h>
#include <zookeeper/zookeeper.h>

using grpc::cpp::test::util::EchoRequest;
using grpc::cpp::test::util::EchoResponse;

namespace grpc {
namespace testing {

class ZookeeperTestServiceImpl
    : public ::grpc::cpp::test::util::TestService::Service {
 public:
  Status Echo(ServerContext* context, const EchoRequest* request,
              EchoResponse* response) GRPC_OVERRIDE {
    response->set_message(request->message());
    return Status::OK;
  }
};

class ZookeeperTest : public ::testing::Test {
 protected:
  ZookeeperTest() {}

  void SetUp() GRPC_OVERRIDE {
    SetUpZookeeper();

    // Setup two servers
    int port1 = grpc_pick_unused_port_or_die();
    int port2 = grpc_pick_unused_port_or_die();
    server1_ = SetUpServer(port1);
    server2_ = SetUpServer(port2);

    // Register service /test in zookeeper
    RegisterService("/test", "test");

    // Register service instance /test/1 in zookeeper
    string value =
        "{\"host\":\"localhost\",\"port\":\"" + std::to_string(port1) + "\"}";
    RegisterService("/test/1", value);

    // Register service instance /test/2 in zookeeper
    value =
        "{\"host\":\"localhost\",\"port\":\"" + std::to_string(port2) + "\"}";
    RegisterService("/test/2", value);
  }

  std::unique_ptr<Server> SetUpServer(int port) {
    string server_address = "localhost:" + std::to_string(port);

    ServerBuilder builder;
    builder.AddListeningPort(server_address, InsecureServerCredentials());
    builder.RegisterService(&service_);
    std::unique_ptr<Server> server = builder.BuildAndStart();
    return server;
  }

  // Require zookeeper server running beforehand
  void SetUpZookeeper() {
    // Find zookeeper server address in environment
    // Default is localhost:2181
    zookeeper_address_ = "localhost:2181";
    char* addr = gpr_getenv("GRPC_ZOOKEEPER_SERVER_TEST");
    if (addr != NULL) {
      string addr_str(addr);
      zookeeper_address_ = addr_str;
      gpr_free(addr);
    }
    gpr_log(GPR_DEBUG, zookeeper_address_.c_str());

    // Connect to zookeeper server
    zoo_set_debug_level(ZOO_LOG_LEVEL_WARN);
    zookeeper_handle_ =
        zookeeper_init(zookeeper_address_.c_str(), NULL, 15000, 0, 0, 0);
    GPR_ASSERT(zookeeper_handle_ != NULL);

    // Register zookeeper name resolver in grpc
    grpc_zookeeper_register();
  }

  void RegisterService(string name, string value) {
    char* path = (char*)gpr_malloc(name.size());

    int status = zoo_exists(zookeeper_handle_, name.c_str(), 0, NULL);
    if (status == ZNONODE) {
      status =
          zoo_create(zookeeper_handle_, name.c_str(), value.c_str(),
                     value.size(), &ZOO_OPEN_ACL_UNSAFE, 0, path, name.size());
    } else {
      status = zoo_set(zookeeper_handle_, name.c_str(), value.c_str(),
                       value.size(), -1);
    }
    gpr_free(path);
    GPR_ASSERT(status == 0);
  }

  void DeleteService(string name) {
    int status = zoo_delete(zookeeper_handle_, name.c_str(), -1);
    GPR_ASSERT(status == 0);
  }

  void TearDown() GRPC_OVERRIDE {
    server1_->Shutdown();
    server2_->Shutdown();
    zookeeper_close(zookeeper_handle_);
  }

  void ResetStub() {
    string target = "zookeeper://" + zookeeper_address_ + "/test";
    channel_ = CreateChannel(target, InsecureCredentials(), ChannelArguments());
    stub_ = std::move(grpc::cpp::test::util::TestService::NewStub(channel_));
  }

  std::shared_ptr<ChannelInterface> channel_;
  std::unique_ptr<grpc::cpp::test::util::TestService::Stub> stub_;
  std::unique_ptr<Server> server1_;
  std::unique_ptr<Server> server2_;
  ZookeeperTestServiceImpl service_;
  zhandle_t* zookeeper_handle_;
  string zookeeper_address_;
};

// Test zookeeper state change between two RPCs
// TODO: Handle leaked objects
TEST_F(ZookeeperTest, ZookeeperStateChangeTwoRpc) {
  ResetStub();

  // First RPC
  EchoRequest request1;
  EchoResponse response1;
  ClientContext context1;
  context1.set_authority("test");
  request1.set_message("Hello");
  Status s1 = stub_->Echo(&context1, request1, &response1);
  EXPECT_EQ(response1.message(), request1.message());
  EXPECT_TRUE(s1.ok());

  // Zookeeper state change
  DeleteService("/test/2");
  sleep(1);

  // Second RPC
  EchoRequest request2;
  EchoResponse response2;
  ClientContext context2;
  context2.set_authority("test");
  request2.set_message("World");
  Status s2 = stub_->Echo(&context2, request2, &response2);
  EXPECT_EQ(response2.message(), request2.message());
  EXPECT_TRUE(s2.ok());
}

}  // namespace testing
}  // namespace grpc

int main(int argc, char** argv) {
  grpc_test_init(argc, argv);
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>// FlicManager.cpp

/*
* (C) Copyright 2015 Noah Roth
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* 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.
*
*/

#include "stdafx.hpp"
#include "FlicManager.hpp"

using namespace RCT3Asset;

void FlicManager::Add(Texture& tex)
{
	_textures.push_back(&tex);
}

unsigned int FlicManager::GetDataSize()
{
	return _textures.size() * sizeof(FlicRawData);
}

void FlicManager::CreateAndAssign(OvlFile& ovl)
{
	unsigned int headerIndex = ovl.AddStructureHeader(GetHeader());

	DataEntry& entry = ovl.CreateEntry(OvlType::Common, 2, GetDataSize());

	FlicRawData* raw = reinterpret_cast<FlicRawData*>(entry.Data);

	for (int i = 0; i < _textures.size(); i++)
	{
		raw[i].FlicInfoPtr = &raw[i].FlicInfo;
		ovl.AddPointer(Ptr(raw[i].FlicInfoPtr));

		raw[i].FlicInfo.FlicDataPtr = nullptr;
		raw[i].FlicInfo.Unknown01 = _textures[i]->FlicUnknown01;
		raw[i].FlicInfo.Unknown02 = _textures[i]->FlicUnknown02;

		_textures[i]->FlicAssign(&raw[i].FlicInfo);

		//ovl.GetLog().Debug("FLIC: ptrToFlicInfo = " + STR((unsigned int)&raw[i].FlicInfo));

		_textures[i]->FlicAssign(&raw[i].FlicInfoPtr);

		//ovl.GetLog().Debug("FLIC: ptrToFlicInfoPtr = " + STR((unsigned int)&raw[i].FlicInfoPtr));

		_textures[i]->FlicMade(true);

		DataInfo info(headerIndex, &raw[i].FlicInfo, 0);

		// extra data

		unsigned int extraDataSize = sizeof(FlicHeader) + _textures[i]->MipDataSize() + _textures[i]->ImageDataSize();
		ExtraData extra = ovl.CreateAndAddExtraData(extraDataSize, OvlType::Common);

		info.ExtraData.push_back(extra);

		unsigned char* extraData = extra.Data;

		FlicHeader* flicHeader = reinterpret_cast<FlicHeader*>(extraData);
		extraData += sizeof(FlicHeader);

		flicHeader->Format = _textures[i]->Mips[0].GetImage().GetFlicFormat();
		flicHeader->Height = _textures[i]->Dimension();
		flicHeader->Width = _textures[i]->Dimension();
		flicHeader->MipCount = _textures[i]->Mips.size();

		// mips

		MipHeader* mip;
		for (int j = 0; j < _textures[i]->Mips.size(); j++)
		{
			mip = reinterpret_cast<MipHeader*>(extraData);
			extraData += sizeof(MipHeader);

			TexImage& image = _textures[i]->Mips[j].GetImage();

			mip->Blocks = image.Blocks();
			mip->Pitch = image.Pitch();
			mip->Height = image.Dimension();
			mip->Width = image.Dimension();

			image.CopyDataTo(extraData);
			extraData += image.GetDataSize();
		}

		ovl.AddDataInfo(info, OvlType::Common);

		ovl.GetLog().Info("FlicManager::CreateAndAssign(..): Created & assigned Flic data.");
	}
}

StructureHeader FlicManager::GetHeader()
{
	StructureHeader h;
	h.LoaderType = OvlLoaderType::FDGK;
	h.StructName = "Flic";
	h.StructID = "flic";
	h.TypeNumber = 2;
	return h;
}<commit_msg>Misc refactoring<commit_after>// FlicManager.cpp

/*
* (C) Copyright 2015 Noah Roth
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* 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.
*
*/

#include "stdafx.hpp"
#include "FlicManager.hpp"

using namespace RCT3Asset;

void FlicManager::Add(Texture& tex)
{
	_textures.push_back(&tex);
}

unsigned int FlicManager::GetDataSize()
{
	return _textures.size() * sizeof(FlicRawData);
}

void FlicManager::CreateAndAssign(OvlFile& ovl)
{
	unsigned int headerIndex = ovl.AddStructureHeader(GetHeader());

	DataEntry& entry = ovl.CreateEntry(OvlType::Common, 2, GetDataSize());

	FlicRawData* raw = reinterpret_cast<FlicRawData*>(entry.Data);

	for (int i = 0; i < _textures.size(); i++)
	{
		raw[i].FlicInfoPtr = &raw[i].FlicInfo;
		ovl.AddPointer(Ptr(raw[i].FlicInfoPtr));

		raw[i].FlicInfo.FlicDataPtr = nullptr;
		raw[i].FlicInfo.Unknown01 = _textures[i]->FlicUnknown01;
		raw[i].FlicInfo.Unknown02 = _textures[i]->FlicUnknown02;

		_textures[i]->FlicAssign(&raw[i].FlicInfo);
		_textures[i]->FlicAssign(&raw[i].FlicInfoPtr);
		_textures[i]->FlicMade(true);

		DataInfo info(headerIndex, &raw[i].FlicInfo, 0);

		// extra data

		unsigned int extraDataSize = sizeof(FlicHeader) + _textures[i]->MipDataSize() + _textures[i]->ImageDataSize();
		ExtraData extra = ovl.CreateAndAddExtraData(extraDataSize, OvlType::Common);

		info.ExtraData.push_back(extra);

		unsigned char* extraData = extra.Data;

		FlicHeader* flicHeader = reinterpret_cast<FlicHeader*>(extraData);
		extraData += sizeof(FlicHeader);

		flicHeader->Format = _textures[i]->Mips[0].GetImage().GetFlicFormat();
		flicHeader->Height = _textures[i]->Dimension();
		flicHeader->Width = _textures[i]->Dimension();
		flicHeader->MipCount = _textures[i]->Mips.size();

		// mips

		MipHeader* mip;
		for (int j = 0; j < _textures[i]->Mips.size(); j++)
		{
			mip = reinterpret_cast<MipHeader*>(extraData);
			extraData += sizeof(MipHeader);

			TexImage& image = _textures[i]->Mips[j].GetImage();

			mip->Blocks = image.Blocks();
			mip->Pitch = image.Pitch();
			mip->Height = image.Dimension();
			mip->Width = image.Dimension();

			image.CopyDataTo(extraData);
			extraData += image.GetDataSize();
		}

		ovl.AddDataInfo(info, OvlType::Common);

		ovl.GetLog().Info("FlicManager::CreateAndAssign(..): Created & assigned Flic data.");
	}
}

StructureHeader FlicManager::GetHeader()
{
	StructureHeader h;
	h.LoaderType = OvlLoaderType::FDGK;
	h.StructName = "Flic";
	h.StructID = "flic";
	h.TypeNumber = 2;
	return h;
}<|endoftext|>


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

#include "chrome/browser/diagnostics/diagnostics_main.h"

#if defined(OS_POSIX)
#include <stdio.h>
#include <unistd.h>
#endif

#include <iostream>

#include "app/app_paths.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/i18n/icu_util.h"
#include "base/string_util.h"
#include "base/sys_string_conversions.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/diagnostics/diagnostics_model.h"
#include "chrome/common/chrome_paths.h"

#if defined(OS_WIN)
#include "base/win_util.h"
#endif

namespace {
// This is a minimalistic interface to wrap the platform console.  This will be
// eventually replaced by a view that can be subclassed for each platform and
// that the approved look and feel.
class SimpleConsole {
 public:
  enum Color {
    DEFAULT,
    RED,
    GREEN,
  };

  virtual ~SimpleConsole() { }

  // Init must be called before using any other method. If it returns
  // false there would be no console output.
  virtual bool Init() = 0;

  // Writes a string to the console with the current color.
  virtual bool Write(const std::wstring& text) = 0;

  // Reads a string from the console. Internally it may be limited to 256
  // characters.
  virtual bool Read(std::wstring* txt) = 0;

  // Sets the foreground and background color.
  virtual bool SetColor(Color color) = 0;

  // Create an appropriate SimpleConsole instance.  May return NULL if there is
  // no implementation for the current platform.
  static SimpleConsole* Create();
};

#if defined(OS_WIN)
// Wrapper for the windows console operating in high-level IO mode.
class WinConsole : public SimpleConsole {
 public:
  // The ctor allocates a console always. This avoids having to ask
  // the user to start chrome from a command prompt.
  WinConsole()
      : std_out_(INVALID_HANDLE_VALUE),
        std_in_(INVALID_HANDLE_VALUE)  {
  }

  virtual ~WinConsole() {
    ::FreeConsole();
  }

  virtual bool Init() {
    ::AllocConsole();
    return SetIOHandles();
  }

  virtual bool Write(const std::wstring& txt) {
    DWORD sz = txt.size();
    return (TRUE == ::WriteConsoleW(std_out_, txt.c_str(), sz, &sz, NULL));
  }

  // Reads a string from the console. Internally it is limited to 256
  // characters.
  virtual bool Read(std::wstring* txt) {
    wchar_t buf[256];
    DWORD read = sizeof(buf) - sizeof(buf[0]);
    if (!::ReadConsoleW(std_in_, buf, read, &read, NULL))
      return false;
    // Note that |read| is in bytes.
    txt->assign(buf, read/2);
    return true;
  }

  // Sets the foreground and background color.
  virtual bool SetColor(Color color) {
    uint16 color_combo =
        FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE|FOREGROUND_INTENSITY;
    switch (color) {
      case RED:
        color_combo = FOREGROUND_RED|FOREGROUND_INTENSITY;
        break;
      case GREEN:
        color_combo = FOREGROUND_GREEN|FOREGROUND_INTENSITY;
        break;
      case DEFAULT:
        break;
      default:
        NOTREACHED();
    }
    return (TRUE == ::SetConsoleTextAttribute(std_out_, color_combo));
  }

 private:
  bool SetIOHandles() {
    std_out_ = ::GetStdHandle(STD_OUTPUT_HANDLE);
    std_in_ = ::GetStdHandle(STD_INPUT_HANDLE);
    return ((std_out_ != INVALID_HANDLE_VALUE) &&
            (std_in_ != INVALID_HANDLE_VALUE));
  }

  // The input and output handles to the screen. They seem to be
  // implemented as pipes but they have non-documented protocol.
  HANDLE std_out_;
  HANDLE std_in_;

  DISALLOW_COPY_AND_ASSIGN(WinConsole);
};

SimpleConsole* SimpleConsole::Create() {
  return new WinConsole();
}

#elif defined(OS_POSIX)

class PosixConsole : public SimpleConsole {
 public:
  PosixConsole() { }

  virtual bool Init() {
    // Technically, we should also check the terminal capabilities before using
    // color, but in practice this is unlikely to be an issue.
    use_color_ = isatty(STDOUT_FILENO);
    return true;
  }

  virtual bool Write(const std::wstring& text) {
    printf("%s", base::SysWideToNativeMB(text).c_str());
    return true;
  }

  virtual bool Read(std::wstring* txt) {
    std::string input;
    if (!std::getline(std::cin, input)) {
      std::cin.clear();
      return false;
    }
    *txt = UTF8ToWide(input);
    return true;
  }

  virtual bool SetColor(Color color) {
    if (!use_color_)
      return false;

    const char* code = "\033[m";
    switch (color) {
      case RED:
        code = "\033[1;31m";
        break;
      case GREEN:
        code = "\033[1;32m";
        break;
      case DEFAULT:
        break;
      default:
        NOTREACHED();
    }
    printf("%s", code);
    return true;
  }

 private:
  bool use_color_;

  DISALLOW_COPY_AND_ASSIGN(PosixConsole);
};

SimpleConsole* SimpleConsole::Create() {
  return new PosixConsole();
}

#else  // !defined(OS_WIN) && !defined(OS_POSIX)

SimpleConsole* SimpleConsole::Create() {
  return NULL;
}
#endif

// This class wraps a SimpleConsole for the specific use case of
// writing the results of the diagnostic tests.
// TODO(cpu) figure out the localization strategy.
class TestWriter {
 public:
  // The |console| must be valid and properly initialized. This
  // class does not own it.
  explicit TestWriter(SimpleConsole* console) : console_(console) {
  }

  // Write an informational line of text in white over black.
  bool WriteInfoText(const std::wstring& txt) {
    console_->SetColor(SimpleConsole::DEFAULT);
    return console_->Write(txt);
  }

  // Write a result block. It consist of two lines. The first line
  // has [PASS] or [FAIL] with |name| and the second line has
  // the text in |extra|.
  bool WriteResult(bool success, const std::wstring& name,
                   const std::wstring& extra) {
    if (success) {
      console_->SetColor(SimpleConsole::GREEN);
      console_->Write(L"[PASS] ");
    } else {
      console_->SetColor(SimpleConsole::RED);
      console_->Write(L"[FAIL] ");
    }
    WriteInfoText(name + L"\n");
    std::wstring second_line(L"   ");
    second_line.append(extra);
    return WriteInfoText(second_line + L"\n\n");
  }

 private:

  SimpleConsole* console_;

  DISALLOW_COPY_AND_ASSIGN(TestWriter);
};

std::wstring PrintableUSCurrentTime() {
  base::Time::Exploded exploded = {0};
  base::Time::Now().UTCExplode(&exploded);
  return StringPrintf(L"%d:%d:%d.%d:%d:%d",
      exploded.year, exploded.month, exploded.day_of_month,
      exploded.hour, exploded.minute, exploded.second);
}

// This class is a basic test controller. In this design the view (TestWriter)
// and the model (DiagnosticsModel) do not talk to each other directly but they
// are mediated by the controller. This has a name: 'passive view'.
// More info at http://martinfowler.com/eaaDev/PassiveScreen.html
class TestController : public DiagnosticsModel::Observer {
 public:
  explicit TestController(TestWriter* writer) : writer_(writer) {
  }

  // Run all the diagnostics of |model| and invoke the view as the model
  // callbacks arrive.
  void Run(DiagnosticsModel* model) {
    std::wstring title(L"Chrome Diagnostics Mode (");
    writer_->WriteInfoText(title.append(PrintableUSCurrentTime()) + L")\n");
    if (!model) {
      writer_->WriteResult(false, L"Diagnostics start", L"model is null");
      return;
    }
    bool icu_result = icu_util::Initialize();
    if (!icu_result) {
      writer_->WriteResult(false, L"Diagnostics start", L"ICU failure");
      return;
    }
    int count = model->GetTestAvailableCount();
    writer_->WriteInfoText(StringPrintf(L"%d available test(s)\n\n", count));
    model->RunAll(this);
  }

  // Next four are overriden from DiagnosticsModel::Observer
  virtual void OnProgress(int id, int percent, DiagnosticsModel* model) {
  }

  virtual void OnSkipped(int id, DiagnosticsModel* model) {
    // TODO(cpu): display skipped tests.
  }

  virtual void OnFinished(int id, DiagnosticsModel* model) {
    // As each test completes we output the results.
    ShowResult(model->GetTest(id));
  }

  virtual void OnDoneAll(DiagnosticsModel* model) {
    writer_->WriteInfoText(L"DONE\n\n");
  }

 private:
  void ShowResult(DiagnosticsModel::TestInfo& test_info) {
    bool success = (DiagnosticsModel::TEST_OK == test_info.GetResult());
    writer_->WriteResult(success, UTF16ToWide(test_info.GetTitle()),
                         UTF16ToWide(test_info.GetAdditionalInfo()));
  }

  DiagnosticsModel* model_;
  TestWriter* writer_;

  DISALLOW_COPY_AND_ASSIGN(TestController);
};
}  // namespace

// This entry point is called from ChromeMain() when very few things
// have been initialized. To wit:
// -(win)   Breakpad
// -(macOS) base::EnableTerminationOnHeapCorruption()
// -(macOS) base::EnableTerminationOnOutOfMemory()
// -(all)   RegisterInvalidParamHandler()
// -(all)   base::AtExitManager::AtExitManager()
// -(macOS) base::ScopedNSAutoreleasePool
// -(posix) Singleton<base::GlobalDescriptors>::Set(kPrimaryIPCChannel)
// -(linux) Singleton<base::GlobalDescriptors>::Set(kCrashDumpSignal)
// -(posix) setlocale(LC_ALL,..)
// -(all)   CommandLine::Init();

int DiagnosticsMain(const CommandLine& command_line) {
  // If we can't initialize the console exit right away.
  SimpleConsole* console = SimpleConsole::Create();
  if (!console || !console->Init())
    return 1;

  // We need to have the path providers registered. They both
  // return void so there is no early error signal that we can use.
  app::RegisterPathProvider();
  chrome::RegisterPathProvider();

  TestWriter writer(console);
  DiagnosticsModel* model = MakeDiagnosticsModel(command_line);
  TestController controller(&writer);

  // Run all the diagnostic tests.
  controller.Run(model);
  delete model;

  // The "press enter to continue" prompt isn't very unixy, so only do that on
  // Windows.
#if defined(OS_WIN)
  // Block here so the user can see the results.
  writer.WriteInfoText(L"Press [enter] to continue\n");
  std::wstring txt;
  console->Read(&txt);
#endif
  delete console;
  return 0;
}
<commit_msg>Coverity issues 9318, 9319: Uninitialized members in diagnostics_main.cc<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/diagnostics/diagnostics_main.h"

#if defined(OS_POSIX)
#include <stdio.h>
#include <unistd.h>
#endif

#include <iostream>

#include "app/app_paths.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/i18n/icu_util.h"
#include "base/string_util.h"
#include "base/sys_string_conversions.h"
#include "base/time.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/diagnostics/diagnostics_model.h"
#include "chrome/common/chrome_paths.h"

#if defined(OS_WIN)
#include "base/win_util.h"
#endif

namespace {
// This is a minimalistic interface to wrap the platform console.  This will be
// eventually replaced by a view that can be subclassed for each platform and
// that the approved look and feel.
class SimpleConsole {
 public:
  enum Color {
    DEFAULT,
    RED,
    GREEN,
  };

  virtual ~SimpleConsole() { }

  // Init must be called before using any other method. If it returns
  // false there would be no console output.
  virtual bool Init() = 0;

  // Writes a string to the console with the current color.
  virtual bool Write(const std::wstring& text) = 0;

  // Reads a string from the console. Internally it may be limited to 256
  // characters.
  virtual bool Read(std::wstring* txt) = 0;

  // Sets the foreground and background color.
  virtual bool SetColor(Color color) = 0;

  // Create an appropriate SimpleConsole instance.  May return NULL if there is
  // no implementation for the current platform.
  static SimpleConsole* Create();
};

#if defined(OS_WIN)
// Wrapper for the windows console operating in high-level IO mode.
class WinConsole : public SimpleConsole {
 public:
  // The ctor allocates a console always. This avoids having to ask
  // the user to start chrome from a command prompt.
  WinConsole()
      : std_out_(INVALID_HANDLE_VALUE),
        std_in_(INVALID_HANDLE_VALUE)  {
  }

  virtual ~WinConsole() {
    ::FreeConsole();
  }

  virtual bool Init() {
    ::AllocConsole();
    return SetIOHandles();
  }

  virtual bool Write(const std::wstring& txt) {
    DWORD sz = txt.size();
    return (TRUE == ::WriteConsoleW(std_out_, txt.c_str(), sz, &sz, NULL));
  }

  // Reads a string from the console. Internally it is limited to 256
  // characters.
  virtual bool Read(std::wstring* txt) {
    wchar_t buf[256];
    DWORD read = sizeof(buf) - sizeof(buf[0]);
    if (!::ReadConsoleW(std_in_, buf, read, &read, NULL))
      return false;
    // Note that |read| is in bytes.
    txt->assign(buf, read/2);
    return true;
  }

  // Sets the foreground and background color.
  virtual bool SetColor(Color color) {
    uint16 color_combo =
        FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE|FOREGROUND_INTENSITY;
    switch (color) {
      case RED:
        color_combo = FOREGROUND_RED|FOREGROUND_INTENSITY;
        break;
      case GREEN:
        color_combo = FOREGROUND_GREEN|FOREGROUND_INTENSITY;
        break;
      case DEFAULT:
        break;
      default:
        NOTREACHED();
    }
    return (TRUE == ::SetConsoleTextAttribute(std_out_, color_combo));
  }

 private:
  bool SetIOHandles() {
    std_out_ = ::GetStdHandle(STD_OUTPUT_HANDLE);
    std_in_ = ::GetStdHandle(STD_INPUT_HANDLE);
    return ((std_out_ != INVALID_HANDLE_VALUE) &&
            (std_in_ != INVALID_HANDLE_VALUE));
  }

  // The input and output handles to the screen. They seem to be
  // implemented as pipes but they have non-documented protocol.
  HANDLE std_out_;
  HANDLE std_in_;

  DISALLOW_COPY_AND_ASSIGN(WinConsole);
};

SimpleConsole* SimpleConsole::Create() {
  return new WinConsole();
}

#elif defined(OS_POSIX)

class PosixConsole : public SimpleConsole {
 public:
  PosixConsole() : use_color_(false) { }

  virtual bool Init() {
    // Technically, we should also check the terminal capabilities before using
    // color, but in practice this is unlikely to be an issue.
    use_color_ = isatty(STDOUT_FILENO);
    return true;
  }

  virtual bool Write(const std::wstring& text) {
    printf("%s", base::SysWideToNativeMB(text).c_str());
    return true;
  }

  virtual bool Read(std::wstring* txt) {
    std::string input;
    if (!std::getline(std::cin, input)) {
      std::cin.clear();
      return false;
    }
    *txt = UTF8ToWide(input);
    return true;
  }

  virtual bool SetColor(Color color) {
    if (!use_color_)
      return false;

    const char* code = "\033[m";
    switch (color) {
      case RED:
        code = "\033[1;31m";
        break;
      case GREEN:
        code = "\033[1;32m";
        break;
      case DEFAULT:
        break;
      default:
        NOTREACHED();
    }
    printf("%s", code);
    return true;
  }

 private:
  bool use_color_;

  DISALLOW_COPY_AND_ASSIGN(PosixConsole);
};

SimpleConsole* SimpleConsole::Create() {
  return new PosixConsole();
}

#else  // !defined(OS_WIN) && !defined(OS_POSIX)

SimpleConsole* SimpleConsole::Create() {
  return NULL;
}
#endif

// This class wraps a SimpleConsole for the specific use case of
// writing the results of the diagnostic tests.
// TODO(cpu) figure out the localization strategy.
class TestWriter {
 public:
  // The |console| must be valid and properly initialized. This
  // class does not own it.
  explicit TestWriter(SimpleConsole* console) : console_(console) {
  }

  // Write an informational line of text in white over black.
  bool WriteInfoText(const std::wstring& txt) {
    console_->SetColor(SimpleConsole::DEFAULT);
    return console_->Write(txt);
  }

  // Write a result block. It consist of two lines. The first line
  // has [PASS] or [FAIL] with |name| and the second line has
  // the text in |extra|.
  bool WriteResult(bool success, const std::wstring& name,
                   const std::wstring& extra) {
    if (success) {
      console_->SetColor(SimpleConsole::GREEN);
      console_->Write(L"[PASS] ");
    } else {
      console_->SetColor(SimpleConsole::RED);
      console_->Write(L"[FAIL] ");
    }
    WriteInfoText(name + L"\n");
    std::wstring second_line(L"   ");
    second_line.append(extra);
    return WriteInfoText(second_line + L"\n\n");
  }

 private:

  SimpleConsole* console_;

  DISALLOW_COPY_AND_ASSIGN(TestWriter);
};

std::wstring PrintableUSCurrentTime() {
  base::Time::Exploded exploded = {0};
  base::Time::Now().UTCExplode(&exploded);
  return StringPrintf(L"%d:%d:%d.%d:%d:%d",
      exploded.year, exploded.month, exploded.day_of_month,
      exploded.hour, exploded.minute, exploded.second);
}

// This class is a basic test controller. In this design the view (TestWriter)
// and the model (DiagnosticsModel) do not talk to each other directly but they
// are mediated by the controller. This has a name: 'passive view'.
// More info at http://martinfowler.com/eaaDev/PassiveScreen.html
class TestController : public DiagnosticsModel::Observer {
 public:
  explicit TestController(TestWriter* writer)
      : model_(NULL),
        writer_(writer) {
  }

  // Run all the diagnostics of |model| and invoke the view as the model
  // callbacks arrive.
  void Run(DiagnosticsModel* model) {
    std::wstring title(L"Chrome Diagnostics Mode (");
    writer_->WriteInfoText(title.append(PrintableUSCurrentTime()) + L")\n");
    if (!model) {
      writer_->WriteResult(false, L"Diagnostics start", L"model is null");
      return;
    }
    bool icu_result = icu_util::Initialize();
    if (!icu_result) {
      writer_->WriteResult(false, L"Diagnostics start", L"ICU failure");
      return;
    }
    int count = model->GetTestAvailableCount();
    writer_->WriteInfoText(StringPrintf(L"%d available test(s)\n\n", count));
    model->RunAll(this);
  }

  // Next four are overridden from DiagnosticsModel::Observer.
  virtual void OnProgress(int id, int percent, DiagnosticsModel* model) {
  }

  virtual void OnSkipped(int id, DiagnosticsModel* model) {
    // TODO(cpu): display skipped tests.
  }

  virtual void OnFinished(int id, DiagnosticsModel* model) {
    // As each test completes we output the results.
    ShowResult(model->GetTest(id));
  }

  virtual void OnDoneAll(DiagnosticsModel* model) {
    writer_->WriteInfoText(L"DONE\n\n");
  }

 private:
  void ShowResult(DiagnosticsModel::TestInfo& test_info) {
    bool success = (DiagnosticsModel::TEST_OK == test_info.GetResult());
    writer_->WriteResult(success, UTF16ToWide(test_info.GetTitle()),
                         UTF16ToWide(test_info.GetAdditionalInfo()));
  }

  DiagnosticsModel* model_;
  TestWriter* writer_;

  DISALLOW_COPY_AND_ASSIGN(TestController);
};
}  // namespace

// This entry point is called from ChromeMain() when very few things
// have been initialized. To wit:
// -(win)   Breakpad
// -(macOS) base::EnableTerminationOnHeapCorruption()
// -(macOS) base::EnableTerminationOnOutOfMemory()
// -(all)   RegisterInvalidParamHandler()
// -(all)   base::AtExitManager::AtExitManager()
// -(macOS) base::ScopedNSAutoreleasePool
// -(posix) Singleton<base::GlobalDescriptors>::Set(kPrimaryIPCChannel)
// -(linux) Singleton<base::GlobalDescriptors>::Set(kCrashDumpSignal)
// -(posix) setlocale(LC_ALL,..)
// -(all)   CommandLine::Init();

int DiagnosticsMain(const CommandLine& command_line) {
  // If we can't initialize the console exit right away.
  SimpleConsole* console = SimpleConsole::Create();
  if (!console || !console->Init())
    return 1;

  // We need to have the path providers registered. They both
  // return void so there is no early error signal that we can use.
  app::RegisterPathProvider();
  chrome::RegisterPathProvider();

  TestWriter writer(console);
  DiagnosticsModel* model = MakeDiagnosticsModel(command_line);
  TestController controller(&writer);

  // Run all the diagnostic tests.
  controller.Run(model);
  delete model;

  // The "press enter to continue" prompt isn't very unixy, so only do that on
  // Windows.
#if defined(OS_WIN)
  // Block here so the user can see the results.
  writer.WriteInfoText(L"Press [enter] to continue\n");
  std::wstring txt;
  console->Read(&txt);
#endif
  delete console;
  return 0;
}
<|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 <gtk/gtk.h>

#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/gtk/view_id_util.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"

class ViewIDTest : public InProcessBrowserTest {
 public:
  ViewIDTest() : root_window_(NULL) {}

  void CheckViewID(ViewID id, bool should_have) {
    if (!root_window_)
      root_window_ = GTK_WIDGET(browser()->window()->GetNativeHandle());

    ASSERT_TRUE(root_window_);
    EXPECT_EQ(should_have, !!ViewIDUtil::GetWidget(root_window_, id))
        << " Failed id=" << id;
  }

 private:
  GtkWidget* root_window_;
};

IN_PROC_BROWSER_TEST_F(ViewIDTest, Basic) {
  // Make sure FindBar is created to test
  // VIEW_ID_FIND_IN_PAGE_TEXT_FIELD and VIEW_ID_FIND_IN_PAGE.
  browser()->ShowFindBar();

  for (int i = VIEW_ID_TOOLBAR; i < VIEW_ID_PREDEFINED_COUNT; ++i) {
    // http://crbug.com/21152
    if (i == VIEW_ID_BOOKMARK_MENU)
      continue;

    // Extension shelf is being removed, http://crbug.com/25106.
    if (i == VIEW_ID_DEV_EXTENSION_SHELF)
      continue;

    // The following ids are used only in views implementation.
    if (i == VIEW_ID_CONTENTS_SPLIT ||
        i == VIEW_ID_INFO_BAR_CONTAINER ||
        i == VIEW_ID_DOWNLOAD_SHELF) {
      continue;
    }

    CheckViewID(static_cast<ViewID>(i), true);
  }

  CheckViewID(VIEW_ID_PREDEFINED_COUNT, false);
}

IN_PROC_BROWSER_TEST_F(ViewIDTest, Delegate) {
  CheckViewID(VIEW_ID_TAB_0, true);
  CheckViewID(VIEW_ID_TAB_1, false);

  browser()->OpenURL(GURL(chrome::kAboutBlankURL), GURL(),
                     NEW_BACKGROUND_TAB, PageTransition::TYPED);

  CheckViewID(VIEW_ID_TAB_0, true);
  CheckViewID(VIEW_ID_TAB_1, true);
}
<commit_msg>Fixes linux browser_test do to adding new id.<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 <gtk/gtk.h>

#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/gtk/view_id_util.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/in_process_browser_test.h"

class ViewIDTest : public InProcessBrowserTest {
 public:
  ViewIDTest() : root_window_(NULL) {}

  void CheckViewID(ViewID id, bool should_have) {
    if (!root_window_)
      root_window_ = GTK_WIDGET(browser()->window()->GetNativeHandle());

    ASSERT_TRUE(root_window_);
    EXPECT_EQ(should_have, !!ViewIDUtil::GetWidget(root_window_, id))
        << " Failed id=" << id;
  }

 private:
  GtkWidget* root_window_;
};

IN_PROC_BROWSER_TEST_F(ViewIDTest, Basic) {
  // Make sure FindBar is created to test
  // VIEW_ID_FIND_IN_PAGE_TEXT_FIELD and VIEW_ID_FIND_IN_PAGE.
  browser()->ShowFindBar();

  for (int i = VIEW_ID_TOOLBAR; i < VIEW_ID_PREDEFINED_COUNT; ++i) {
    // http://crbug.com/21152
    if (i == VIEW_ID_BOOKMARK_MENU)
      continue;

    // Extension shelf is being removed, http://crbug.com/25106.
    if (i == VIEW_ID_DEV_EXTENSION_SHELF)
      continue;

    // The following ids are used only in views implementation.
    if (i == VIEW_ID_CONTENTS_SPLIT ||
        i == VIEW_ID_INFO_BAR_CONTAINER ||
        i == VIEW_ID_DOWNLOAD_SHELF ||
        i == VIEW_ID_BOOKMARK_BAR_ELEMENT) {
      continue;
    }

    CheckViewID(static_cast<ViewID>(i), true);
  }

  CheckViewID(VIEW_ID_PREDEFINED_COUNT, false);
}

IN_PROC_BROWSER_TEST_F(ViewIDTest, Delegate) {
  CheckViewID(VIEW_ID_TAB_0, true);
  CheckViewID(VIEW_ID_TAB_1, false);

  browser()->OpenURL(GURL(chrome::kAboutBlankURL), GURL(),
                     NEW_BACKGROUND_TAB, PageTransition::TYPED);

  CheckViewID(VIEW_ID_TAB_0, true);
  CheckViewID(VIEW_ID_TAB_1, true);
}
<|endoftext|>