<commit_before>/*=========================================================================
 *
 *  Copyright 2011-2013 The University of North Carolina at Chapel Hill
 *  All rights reserved.
 *
 *  Licensed under the MADAI Software License. You may obtain a copy of
 *  this license at
 *
 *         https://madai-public.cs.unc.edu/software/license/
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include <cstdio>
#include <cstdlib>
#include <iostream>

#include "GaussianDistribution.h"
#include "LatinHypercubeGenerator.h"
#include "Parameter.h"
#include "UniformDistribution.h"

#include "madaisys/SystemTools.hxx"

static const char usage[] =
  "usage:\n"
  "  generateTrainingPoints [options] ParametersFile OutputDirectory\n"
  "\n"
  "ParametersFile is a file containing a list of parameters and their ranges\n"
  "\n"
  "  The file should be a text file with a separate line for each parameter\n"
  "  listing the name of the parameter followed by a numeric minimum and maximum\n"
  "  defining the range of the parameter, such as\n"
  "\n"
  "  temperature 245.2 288.0\n"
  "  pressure 4.7 5.9\n"
  "  ...\n"
  "\n"
  "OutputDirectory is a path to the name of the directory containing the parameter files\n"
  "\n"
  "Options:\n"
  "\n"
  "  -h,--help                          Display help message.\n"
  "\n"
  "  -v,--verbose                       Print extra information.\n"
  "\n"
  "  -f,--format {directories,emulator} Select the output format."
  "\n"
  "  -p,--percentile                    Partition space by parameter prior\n"
  "                                     distribution percentile.\n"
  "\n"
  "  -s,--stddev <value>                Number of standard deviations from\n"
  "                                     mean of a parameter's Gaussian\n"
  "                                     distributed prior to include in the\n"
  "                                     sampling.\n"
  "\n";

typedef enum {
  DIRECTORIES_FORMAT, // Pratt format
  EMULATOR_FORMAT     // GaussianProcessEmulator format
} FormatType;

struct CommandLineOptions {
  bool verbose;
  const char * parametersFile;  // First non-flag argument.
  const char * outputDirectory; // Second non-flag argument.
  FormatType formatType;        // Type of the output
  bool partitionSpaceByPercentile;
  double standardDeviations;
};

std::string LowerCase( char * buffer )
{
  std::string outBuffer( buffer );

  std::transform( outBuffer.begin(), outBuffer.end(),
                  outBuffer.begin(), ::tolower );

  return outBuffer;
}

bool ParseCommandLineOptions( int argc, char* argv[], struct CommandLineOptions & options)
{
  // Default values for command-line options
  options.verbose = false;
  options.parametersFile = NULL;
  options.outputDirectory = NULL;
  options.formatType = DIRECTORIES_FORMAT;
  options.partitionSpaceByPercentile = false;
  options.standardDeviations = 3.0;

  // Parse options
  int argIndex;
  for ( argIndex = 1; argIndex < argc; ++argIndex ) {
    std::string argString( argv[ argIndex ] );

    if ( argString == "-v" || argString == "--verbose" ) {
      options.verbose = true;
    } else if ( argString == "-h" || argString == "--help" ) {
      std::cerr << usage;
      return false;
    } else if ( argString == "-f" || argString == "--format" ) {
      if ( argIndex + 1 < argc ) {
        std::string argString2 = LowerCase( argv[ argIndex + 1 ] );
        if ( argString2 == "directories" ) {
          options.formatType = DIRECTORIES_FORMAT;
        } else if ( argString2 == "emulator" ) {
          options.formatType = EMULATOR_FORMAT;
        } else {
          std::cerr << "Unknown format type '" << argString2 << "' provided to '"
                    << argString << "'. Expected 'directories' or 'emulator'.\n";
          return false;
        }
        argIndex++;
      } else {
        std::cerr << "No format type provided to argument '" << argString
                  << "'. Expected 'directories' or 'emulator'.\n";
        return false;
      }
    } else if ( argString == "-p" || argString == "--percentile" ) {
      options.partitionSpaceByPercentile = true;
    } else if ( argString == "-s" || argString == "--stddev" ) {
      if ( argIndex + 1 < argc ) {
        argIndex++;
        std::string argString2( argv[ argIndex ] );
        options.standardDeviations = atof( argString2.c_str() );
        if ( options.standardDeviations == 0.0 ) {
          std::cerr << "Standard deviations set to 0.0 is not valid. "
                    << "Did you supply a number to '" << argString
                    << "'?\n";
          return false;
        }
        std::cout << "argString2: " << argString2 << options.standardDeviations << std::endl;
      } else {
        std::cerr << "Missing value for '" << argString << "'.\n";
        return false;
      }
    } else {
      break; // No switch
    }
  }

  if ( argIndex < argc ) {
    options.parametersFile = argv[ argIndex++ ];
  } else {
    std::cerr << usage;
    return false;
  }

  if ( argIndex < argc ) {
    options.outputDirectory = argv[ argIndex++ ];
  } else {
    std::cerr << usage;
    return false;
  }

  if ( argIndex < argc ) {
    std::cerr << "Extra arguments after '" << options.outputDirectory << "'\n";
    return false;
  }

  // Everything went well
  return true;
}

bool ReadParameters( const struct CommandLineOptions & options,
                     std::vector< madai::Parameter > & parameters )
{
  parameters.clear();

  FILE *fp = fopen( options.parametersFile, "r" );
  if ( !fp ) {
    return false;
  }

  if ( options.verbose ) {
    std::cout << "Opened file '" << options.parametersFile << "'\n";
  }

  char buffer[4096];

  // Parse each parameter as it is listed on a line
  while ( 1 == fscanf( fp, "%4095s", buffer ) ) {
    std::string parameterName( buffer );

    if ( options.verbose ) {
      std::cout << "Read parameter '" << parameterName << "' ";
    }

    if ( 1 != fscanf( fp, "%4095s", buffer ) ) {
      std::cerr << "Could not read distribution type\n";
      fclose( fp );
      return false;
    }

    std::string distributionType( LowerCase( buffer ) );

    if ( options.verbose ) {
      std::cout << "which is of type '" << distributionType << "' ";
    }

    madai::Distribution *distribution = NULL;
    madai::UniformDistribution uniform;
    madai::GaussianDistribution gaussian;

    if ( distributionType == "uniform" ) {
      // Parse minimum and maximum values
      double minimum, maximum;
      if ( 2 != fscanf( fp, "%lf %lf", &minimum, &maximum ) ) {
        std::cerr << "Could not read uniform distribution minimum and maximum\n";
        fclose( fp );
        return false;
      }

      if ( options.verbose ) {
        std::cout << "with range [" << minimum << ", " << maximum << "]\n";
      }

      uniform.SetMinimum( minimum );
      uniform.SetMaximum( maximum );
      distribution = &uniform;

    } else if ( distributionType == "gaussian" ) {
      // Parse mean and standard deviation
      double mean, standardDeviation;
      if ( 2 != fscanf( fp, "%lf %lf", &mean, &standardDeviation ) ) {
        std::cerr << "Could not read Gaussian distribution mean and standard deviation\n";
        fclose( fp );
        return false;
      }

      if ( options.verbose ) {
        std::cout << "with mean " << mean << " and standard deviation "
                  << standardDeviation << "\n";
      }

      gaussian.SetMean( mean );
      gaussian.SetStandardDeviation( standardDeviation );
      distribution = &gaussian;
    } else {
      std::cerr << "Unknown distribution type '" << distributionType << "'\n";
      fclose( fp );
      return false;
    }

    parameters.push_back( madai::Parameter( parameterName, *distribution ) );
  }

  fclose( fp );

  // Everything went okay
  return true;
}

bool WriteDirectoriesFormat( const struct CommandLineOptions & options,
                             const std::vector< madai::Parameter > & parameters,
                             const std::vector< madai::Sample > & samples ) {
  // Create the directory structure
  bool directoryCreated = madaisys::SystemTools::MakeDirectory( options.outputDirectory );
  if ( !directoryCreated ) {
    std::cerr << "Could not create directory '" << options.outputDirectory
              << "'\n";
    return false;
  }

  std::string directory( options.outputDirectory );
  std::string experimental_results( directory + "/experimental_results" );
  std::string model_outputs( directory + "/model_outputs" );
  std::string statistical_analysis( directory + "/statistical_analysis" );

  directoryCreated = directoryCreated &&
    madaisys::SystemTools::MakeDirectory( experimental_results.c_str() );
  directoryCreated = directoryCreated &&
    madaisys::SystemTools::MakeDirectory( model_outputs.c_str() );
  directoryCreated = directoryCreated &&
    madaisys::SystemTools::MakeDirectory( statistical_analysis.c_str() );

  // Now create the run directories
  for ( size_t i = 0; i < samples.size(); ++i ) {
    const madai::Sample & sample = samples[i];

    char buffer[128];
    sprintf( buffer, "/model_outputs/run%04d", static_cast<int>( i ) );
    std::string runDirectory( directory + std::string( buffer ) );

    std::cout << runDirectory << "\n";

    directoryCreated = directoryCreated &&
      madaisys::SystemTools::MakeDirectory( runDirectory.c_str() );

    // Write the parameters to the parameters.dat file
    std::string parametersFile( runDirectory + "/parameters.dat" );
    FILE *fp = fopen( parametersFile.c_str(), "w" );
    if ( !fp ) {
      std::cerr << "Could not open file '" << parametersFile << "'\n";
      return false;
    }

    assert( parameters.size() == sample.m_ParameterValues.size() );
    for ( size_t j = 0; j < parameters.size(); ++j ) {
      fprintf( fp, "%s %f\n",
               parameters[ j ].m_Name.c_str(),
               sample.m_ParameterValues[ j ] );
    }

    fclose( fp );
  }

  return true;
}

bool WriteEmulatorFormat( const struct CommandLineOptions & options,
                          const std::vector< madai::Parameter > & parameters,
                          const std::vector< madai::Sample > & samples ) {
  // Create the output directory
  bool directoryCreated = madaisys::SystemTools::MakeDirectory( options.outputDirectory );
  if ( !directoryCreated ) {
    std::cerr << "Could not create directory '" << options.outputDirectory
              << "'\n";
    return false;
  }

  // Open the output file
  std::string outputFile( options.outputDirectory );
  outputFile += "/emulator.dat";
  FILE * fp = fopen( outputFile.c_str(), "w" );
  if ( !fp ) {
    std::cerr << "Could not create output file '" << outputFile << "'\n";
    return false;
  }

  // Print VERSION
  fprintf( fp, "VERSION 1\n" );

  // Print the PARAMETERS
  fprintf( fp, "PARAMETERS\n" );

  for ( size_t i = 0; i < parameters.size(); ++i ) {
    fprintf( fp, "%s ", parameters[i].m_Name.c_str() );
    const madai::Distribution * priorDistribution =
      parameters[i].GetPriorDistribution();
    const madai::UniformDistribution * uniformDistribution =
      dynamic_cast< const madai::UniformDistribution *>( priorDistribution );
    const madai::GaussianDistribution * gaussianDistribution =
      dynamic_cast< const madai::GaussianDistribution *>( priorDistribution );
    if ( uniformDistribution ) {
      fprintf( fp, "UNIFORM %f %f\n",
               uniformDistribution->GetMinimum(),
               uniformDistribution->GetMaximum() );
    } else if ( gaussianDistribution ) {
      fprintf( fp, "GAUSSIAN %f %f\n",
               gaussianDistribution->GetMean(),
               gaussianDistribution->GetStandardDeviation() );
    } else {
      std::cerr << "Unknown prior type\n";
      return false;
    }
  }

  // Print training points
  fprintf( fp, "NUMBER_OF_TRAINING_POINTS %d\n",
           static_cast< int >( samples.size() ) );

  // Print parameter values at training points
  fprintf( fp, "PARAMETER_VALUES\n" );

  for ( size_t i = 0; i < samples.size(); ++i ) {
    const madai::Sample & sample = samples[i];

    for ( size_t j = 0; j < sample.m_ParameterValues.size(); ++j ) {
      fprintf( fp, "%f ", sample.m_ParameterValues[j] );
    }
    fprintf( fp, "\n" );
  }

  fclose( fp );

  return true;
}

int main( int argc, char * argv[] ) {
  struct CommandLineOptions options;
  if ( !ParseCommandLineOptions( argc, argv, options ) ) {
    return EXIT_FAILURE;
  }

  if ( options.verbose ) {
    std::cout << "Options: \n";
    std::cout << "  --verbose: " << options.verbose << "\n";
    std::cout << "  --format: ";
    if ( options.formatType == DIRECTORIES_FORMAT ) std::cout << "directories\n";
    if ( options.formatType == EMULATOR_FORMAT ) std::cout << "emulator\n";
    std::cout << "  --percentile: " << options.partitionSpaceByPercentile << "\n";
    std::cout << "  --stddev: " << options.standardDeviations << "\n";
    std::cout << "  ParametersFile: " << options.parametersFile << "\n";
    std::cout << "  OutputDirectory: " << options.outputDirectory << "\n";
  }

  // Read in parameter priors
  std::vector< madai::Parameter > parameters;
  bool parametersRead = ReadParameters( options, parameters );
  if ( !parametersRead ) {
    std::cerr << "Could not read parameters from prior file '"
              << options.parametersFile << "'" << std::endl;
    return EXIT_FAILURE;
  }

  // Create the Latin hypercube sampling
  madai::LatinHypercubeGenerator sampleGenerator;
  std::vector< madai::Sample > samples = sampleGenerator.Generate( 100, parameters );
  sampleGenerator.SetStandardDeviations( options.standardDeviations );
  sampleGenerator.SetPartitionSpaceByPercentile( options.partitionSpaceByPercentile );

  if ( options.formatType == DIRECTORIES_FORMAT ) {
    WriteDirectoriesFormat( options, parameters, samples );
  } else if ( options.formatType == EMULATOR_FORMAT ) {
    WriteEmulatorFormat( options, parameters, samples );
  } else {
    std::cerr << "Unknown output format type" << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

<commit_msg>Fixed bug where latin hypercube generator settings were being set after samples were generated<commit_after>/*=========================================================================
 *
 *  Copyright 2011-2013 The University of North Carolina at Chapel Hill
 *  All rights reserved.
 *
 *  Licensed under the MADAI Software License. You may obtain a copy of
 *  this license at
 *
 *         https://madai-public.cs.unc.edu/software/license/
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include <cstdio>
#include <cstdlib>
#include <iostream>

#include "GaussianDistribution.h"
#include "LatinHypercubeGenerator.h"
#include "Parameter.h"
#include "UniformDistribution.h"

#include "madaisys/SystemTools.hxx"

static const char usage[] =
  "usage:\n"
  "  generateTrainingPoints [options] ParametersFile OutputDirectory\n"
  "\n"
  "ParametersFile is a file containing a list of parameters and their ranges\n"
  "\n"
  "  The file should be a text file with a separate line for each parameter\n"
  "  listing the name of the parameter followed by a numeric minimum and maximum\n"
  "  defining the range of the parameter, such as\n"
  "\n"
  "  temperature 245.2 288.0\n"
  "  pressure 4.7 5.9\n"
  "  ...\n"
  "\n"
  "OutputDirectory is a path to the name of the directory containing the parameter files\n"
  "\n"
  "Options:\n"
  "\n"
  "  -h,--help                          Display help message.\n"
  "\n"
  "  -v,--verbose                       Print extra information.\n"
  "\n"
  "  -f,--format {directories,emulator} Select the output format."
  "\n"
  "  -p,--percentile                    Partition space by parameter prior\n"
  "                                     distribution percentile.\n"
  "\n"
  "  -s,--stddev <value>                Number of standard deviations from\n"
  "                                     mean of a parameter's Gaussian\n"
  "                                     distributed prior to include in the\n"
  "                                     sampling.\n"
  "\n";

typedef enum {
  DIRECTORIES_FORMAT, // Pratt format
  EMULATOR_FORMAT     // GaussianProcessEmulator format
} FormatType;

struct CommandLineOptions {
  bool verbose;
  const char * parametersFile;  // First non-flag argument.
  const char * outputDirectory; // Second non-flag argument.
  FormatType formatType;        // Type of the output
  bool partitionSpaceByPercentile;
  double standardDeviations;
};

std::string LowerCase( char * buffer )
{
  std::string outBuffer( buffer );

  std::transform( outBuffer.begin(), outBuffer.end(),
                  outBuffer.begin(), ::tolower );

  return outBuffer;
}

bool ParseCommandLineOptions( int argc, char* argv[], struct CommandLineOptions & options)
{
  // Default values for command-line options
  options.verbose = false;
  options.parametersFile = NULL;
  options.outputDirectory = NULL;
  options.formatType = DIRECTORIES_FORMAT;
  options.partitionSpaceByPercentile = false;
  options.standardDeviations = 3.0;

  // Parse options
  int argIndex;
  for ( argIndex = 1; argIndex < argc; ++argIndex ) {
    std::string argString( argv[ argIndex ] );

    if ( argString == "-v" || argString == "--verbose" ) {
      options.verbose = true;
    } else if ( argString == "-h" || argString == "--help" ) {
      std::cerr << usage;
      return false;
    } else if ( argString == "-f" || argString == "--format" ) {
      if ( argIndex + 1 < argc ) {
        std::string argString2 = LowerCase( argv[ argIndex + 1 ] );
        if ( argString2 == "directories" ) {
          options.formatType = DIRECTORIES_FORMAT;
        } else if ( argString2 == "emulator" ) {
          options.formatType = EMULATOR_FORMAT;
        } else {
          std::cerr << "Unknown format type '" << argString2 << "' provided to '"
                    << argString << "'. Expected 'directories' or 'emulator'.\n";
          return false;
        }
        argIndex++;
      } else {
        std::cerr << "No format type provided to argument '" << argString
                  << "'. Expected 'directories' or 'emulator'.\n";
        return false;
      }
    } else if ( argString == "-p" || argString == "--percentile" ) {
      options.partitionSpaceByPercentile = true;
    } else if ( argString == "-s" || argString == "--stddev" ) {
      if ( argIndex + 1 < argc ) {
        argIndex++;
        std::string argString2( argv[ argIndex ] );
        options.standardDeviations = atof( argString2.c_str() );
        if ( options.standardDeviations == 0.0 ) {
          std::cerr << "Standard deviations set to 0.0 is not valid. "
                    << "Did you supply a number to '" << argString
                    << "'?\n";
          return false;
        }
        std::cout << "argString2: " << argString2 << options.standardDeviations << std::endl;
      } else {
        std::cerr << "Missing value for '" << argString << "'.\n";
        return false;
      }
    } else {
      break; // No switch
    }
  }

  if ( argIndex < argc ) {
    options.parametersFile = argv[ argIndex++ ];
  } else {
    std::cerr << usage;
    return false;
  }

  if ( argIndex < argc ) {
    options.outputDirectory = argv[ argIndex++ ];
  } else {
    std::cerr << usage;
    return false;
  }

  if ( argIndex < argc ) {
    std::cerr << "Extra arguments after '" << options.outputDirectory << "'\n";
    return false;
  }

  // Everything went well
  return true;
}

bool ReadParameters( const struct CommandLineOptions & options,
                     std::vector< madai::Parameter > & parameters )
{
  parameters.clear();

  FILE *fp = fopen( options.parametersFile, "r" );
  if ( !fp ) {
    return false;
  }

  if ( options.verbose ) {
    std::cout << "Opened file '" << options.parametersFile << "'\n";
  }

  char buffer[4096];

  // Parse each parameter as it is listed on a line
  while ( 1 == fscanf( fp, "%4095s", buffer ) ) {
    std::string parameterName( buffer );

    if ( options.verbose ) {
      std::cout << "Read parameter '" << parameterName << "' ";
    }

    if ( 1 != fscanf( fp, "%4095s", buffer ) ) {
      std::cerr << "Could not read distribution type\n";
      fclose( fp );
      return false;
    }

    std::string distributionType( LowerCase( buffer ) );

    if ( options.verbose ) {
      std::cout << "which is of type '" << distributionType << "' ";
    }

    madai::Distribution *distribution = NULL;
    madai::UniformDistribution uniform;
    madai::GaussianDistribution gaussian;

    if ( distributionType == "uniform" ) {
      // Parse minimum and maximum values
      double minimum, maximum;
      if ( 2 != fscanf( fp, "%lf %lf", &minimum, &maximum ) ) {
        std::cerr << "Could not read uniform distribution minimum and maximum\n";
        fclose( fp );
        return false;
      }

      if ( options.verbose ) {
        std::cout << "with range [" << minimum << ", " << maximum << "]\n";
      }

      uniform.SetMinimum( minimum );
      uniform.SetMaximum( maximum );
      distribution = &uniform;

    } else if ( distributionType == "gaussian" ) {
      // Parse mean and standard deviation
      double mean, standardDeviation;
      if ( 2 != fscanf( fp, "%lf %lf", &mean, &standardDeviation ) ) {
        std::cerr << "Could not read Gaussian distribution mean and standard deviation\n";
        fclose( fp );
        return false;
      }

      if ( options.verbose ) {
        std::cout << "with mean " << mean << " and standard deviation "
                  << standardDeviation << "\n";
      }

      gaussian.SetMean( mean );
      gaussian.SetStandardDeviation( standardDeviation );
      distribution = &gaussian;
    } else {
      std::cerr << "Unknown distribution type '" << distributionType << "'\n";
      fclose( fp );
      return false;
    }

    parameters.push_back( madai::Parameter( parameterName, *distribution ) );
  }

  fclose( fp );

  // Everything went okay
  return true;
}

bool WriteDirectoriesFormat( const struct CommandLineOptions & options,
                             const std::vector< madai::Parameter > & parameters,
                             const std::vector< madai::Sample > & samples ) {
  // Create the directory structure
  bool directoryCreated = madaisys::SystemTools::MakeDirectory( options.outputDirectory );
  if ( !directoryCreated ) {
    std::cerr << "Could not create directory '" << options.outputDirectory
              << "'\n";
    return false;
  }

  std::string directory( options.outputDirectory );
  std::string experimental_results( directory + "/experimental_results" );
  std::string model_outputs( directory + "/model_outputs" );
  std::string statistical_analysis( directory + "/statistical_analysis" );

  directoryCreated = directoryCreated &&
    madaisys::SystemTools::MakeDirectory( experimental_results.c_str() );
  directoryCreated = directoryCreated &&
    madaisys::SystemTools::MakeDirectory( model_outputs.c_str() );
  directoryCreated = directoryCreated &&
    madaisys::SystemTools::MakeDirectory( statistical_analysis.c_str() );

  // Now create the run directories
  for ( size_t i = 0; i < samples.size(); ++i ) {
    const madai::Sample & sample = samples[i];

    char buffer[128];
    sprintf( buffer, "/model_outputs/run%04d", static_cast<int>( i ) );
    std::string runDirectory( directory + std::string( buffer ) );

    std::cout << runDirectory << "\n";

    directoryCreated = directoryCreated &&
      madaisys::SystemTools::MakeDirectory( runDirectory.c_str() );

    // Write the parameters to the parameters.dat file
    std::string parametersFile( runDirectory + "/parameters.dat" );
    FILE *fp = fopen( parametersFile.c_str(), "w" );
    if ( !fp ) {
      std::cerr << "Could not open file '" << parametersFile << "'\n";
      return false;
    }

    assert( parameters.size() == sample.m_ParameterValues.size() );
    for ( size_t j = 0; j < parameters.size(); ++j ) {
      fprintf( fp, "%s %f\n",
               parameters[ j ].m_Name.c_str(),
               sample.m_ParameterValues[ j ] );
    }

    fclose( fp );
  }

  return true;
}

bool WriteEmulatorFormat( const struct CommandLineOptions & options,
                          const std::vector< madai::Parameter > & parameters,
                          const std::vector< madai::Sample > & samples ) {
  // Create the output directory
  bool directoryCreated = madaisys::SystemTools::MakeDirectory( options.outputDirectory );
  if ( !directoryCreated ) {
    std::cerr << "Could not create directory '" << options.outputDirectory
              << "'\n";
    return false;
  }

  // Open the output file
  std::string outputFile( options.outputDirectory );
  outputFile += "/emulator.dat";
  FILE * fp = fopen( outputFile.c_str(), "w" );
  if ( !fp ) {
    std::cerr << "Could not create output file '" << outputFile << "'\n";
    return false;
  }

  // Print VERSION
  fprintf( fp, "VERSION 1\n" );

  // Print the PARAMETERS
  fprintf( fp, "PARAMETERS\n" );

  for ( size_t i = 0; i < parameters.size(); ++i ) {
    fprintf( fp, "%s ", parameters[i].m_Name.c_str() );
    const madai::Distribution * priorDistribution =
      parameters[i].GetPriorDistribution();
    const madai::UniformDistribution * uniformDistribution =
      dynamic_cast< const madai::UniformDistribution *>( priorDistribution );
    const madai::GaussianDistribution * gaussianDistribution =
      dynamic_cast< const madai::GaussianDistribution *>( priorDistribution );
    if ( uniformDistribution ) {
      fprintf( fp, "UNIFORM %f %f\n",
               uniformDistribution->GetMinimum(),
               uniformDistribution->GetMaximum() );
    } else if ( gaussianDistribution ) {
      fprintf( fp, "GAUSSIAN %f %f\n",
               gaussianDistribution->GetMean(),
               gaussianDistribution->GetStandardDeviation() );
    } else {
      std::cerr << "Unknown prior type\n";
      return false;
    }
  }

  // Print training points
  fprintf( fp, "NUMBER_OF_TRAINING_POINTS %d\n",
           static_cast< int >( samples.size() ) );

  // Print parameter values at training points
  fprintf( fp, "PARAMETER_VALUES\n" );

  for ( size_t i = 0; i < samples.size(); ++i ) {
    const madai::Sample & sample = samples[i];

    for ( size_t j = 0; j < sample.m_ParameterValues.size(); ++j ) {
      fprintf( fp, "%f ", sample.m_ParameterValues[j] );
    }
    fprintf( fp, "\n" );
  }

  fclose( fp );

  return true;
}

int main( int argc, char * argv[] ) {
  struct CommandLineOptions options;
  if ( !ParseCommandLineOptions( argc, argv, options ) ) {
    return EXIT_FAILURE;
  }

  if ( options.verbose ) {
    std::cout << "Options: \n";
    std::cout << "  --verbose: " << options.verbose << "\n";
    std::cout << "  --format: ";
    if ( options.formatType == DIRECTORIES_FORMAT ) std::cout << "directories\n";
    if ( options.formatType == EMULATOR_FORMAT ) std::cout << "emulator\n";
    std::cout << "  --percentile: " << options.partitionSpaceByPercentile << "\n";
    std::cout << "  --stddev: " << options.standardDeviations << "\n";
    std::cout << "  ParametersFile: " << options.parametersFile << "\n";
    std::cout << "  OutputDirectory: " << options.outputDirectory << "\n";
  }

  // Read in parameter priors
  std::vector< madai::Parameter > parameters;
  bool parametersRead = ReadParameters( options, parameters );
  if ( !parametersRead ) {
    std::cerr << "Could not read parameters from prior file '"
              << options.parametersFile << "'" << std::endl;
    return EXIT_FAILURE;
  }

  // Create the Latin hypercube sampling
  madai::LatinHypercubeGenerator sampleGenerator;
  sampleGenerator.SetStandardDeviations( options.standardDeviations );
  sampleGenerator.SetPartitionSpaceByPercentile( options.partitionSpaceByPercentile );

  std::vector< madai::Sample > samples = sampleGenerator.Generate( 100, parameters );

  if ( options.formatType == DIRECTORIES_FORMAT ) {
    WriteDirectoriesFormat( options, parameters, samples );
  } else if ( options.formatType == EMULATOR_FORMAT ) {
    WriteEmulatorFormat( options, parameters, samples );
  } else {
    std::cerr << "Unknown output format type" << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}

<|endoftext|>


<commit_before>/* ****************************************************************************
*
* FILE                     main_samsonKiller.cpp
*
* AUTHOR                   Ken Zangelin
*
* CREATION DATE            Feb 25 2011
*
*/
#include "parseArgs.h"          // parseArgs
#include "paUsage.h"            // paUsage
#include "traceLevels.h"        // Trace levels

#include "Endpoint.h"           // Endpoint
#include "ports.h"              // SPAWNER_PORT, CONTROLLER_PORT, WORKER_PORT
#include "iomConnect.h"         // iomConnect
#include "iomMsgSend.h"         // iomMsgSend

/* ****************************************************************************
*
* Option variables
*/
char             name[80];

/* ****************************************************************************
*
* parse arguments
*/
PaArgument paArgs[] =
{
	{ " ",            name,        "NAME",        PaString,  PaOpt,  PaND,   PaNL,   PaNL,  "name of prcess to kill"         },

	PA_END_OF_ARGS
};

/* ****************************************************************************
*
* killProcess -
*/
static int killProcess(const char* name, unsigned short port)
{
	ss::Endpoint  ep;
	ss::Endpoint  me;

	ep.name = name;
	ep.wFd  = iomConnect("localhost", port);

	if (ep.wFd == -1)
	{
		printf("error connecting to %s at 'localhost', port %d - probably means the process isn't running\n", name, port);
		return 3;
	}

	me.name = "samsonKiller";

	if (iomMsgSend(&ep, &me, ss::Message::Die, ss::Message::Msg) != 0)
	{
		printf("error sending 'Die' message to endpoint (port %d)\n", port);
		return 4;
	}

	return 0;
}

/* ****************************************************************************
*
* main -
*/
int main(int argC, const char *argV[])
{
	name[0] = 0;

	paParse(paArgs, argC, (char**) argV, 1, false);

#if 0
	printf("Started with arguments:\n");
	for (int ix = 0; ix < argC; ix++)
		printf("  %02d: '%s'\n", ix, argV[ix]);
#endif

	if (name[0] != 0)
	{
		if ((strcasecmp(name, "worker") == 0) || (strcasecmp(name, "samsonWorker") == 0))
            return killProcess("samsonWorker", WORKER_PORT);
		else if ((strcasecmp(name, "controller") == 0) || (strcasecmp(name, "samsonController") == 0))
            return killProcess("samsonController", CONTROLLER_PORT);
		else if ((strcasecmp(name, "spawner") == 0) || (strcasecmp(name, "samsonSpawner") == 0))
			return killProcess("samsonSpawner", SPAWNER_PORT);
		else if (strcasecmp(name, "all") == 0)
		{
		   killProcess("samsonWorker",     WORKER_PORT);
		   killProcess("samsonController", CONTROLLER_PORT);
		   killProcess("samsonSpawner",    SPAWNER_PORT);

		   return 0;
		}
		else
		{
			printf("non-familiar process '%s'\n", name);
			exit(1);
		}
	}

	return 0;
}
<commit_msg>samsonKiller now uses 'killall' if Die fails<commit_after>/* ****************************************************************************
*
* FILE                     main_samsonKiller.cpp
*
* AUTHOR                   Ken Zangelin
*
* CREATION DATE            Feb 25 2011
*
*/
#include "parseArgs.h"          // parseArgs
#include "paUsage.h"            // paUsage
#include "traceLevels.h"        // Trace levels

#include "Endpoint.h"           // Endpoint
#include "ports.h"              // SPAWNER_PORT, CONTROLLER_PORT, WORKER_PORT
#include "iomConnect.h"         // iomConnect
#include "iomMsgSend.h"         // iomMsgSend

/* ****************************************************************************
*
* Option variables
*/
char             name[80];

/* ****************************************************************************
*
* parse arguments
*/
PaArgument paArgs[] =
{
	{ " ",            name,        "NAME",        PaString,  PaOpt,  (long) "all",   PaNL,   PaNL,  "name of prcess to kill"         },

	PA_END_OF_ARGS
};

/* ****************************************************************************
*
* sysKill -
*/
static void sysKill(const char* name)
{
	char com[256];

	snprintf(com, sizeof(com), "killall -9 %s > /dev/null 2>&1", name);
	system(com);
	printf("Killed %s\n", name);
}

/* ****************************************************************************
*
* killProcess -
*/
static int killProcess(const char* name, unsigned short port)
{
	ss::Endpoint  ep;
	ss::Endpoint  me;
	int           s;

	ep.name = name;
	ep.wFd  = iomConnect("localhost", port);
	LM_M(("%s: ep.wFd == %d", name, ep.wFd));
	me.name = "samsonKiller";

	if ((ep.wFd == -1) || ((s = iomMsgSend(&ep, &me, ss::Message::Die, ss::Message::Msg)) != 0))
	{
		LM_M(("%s: s = %d", name, s));
		sysKill(name);
	}
	else
	{
		int fd = iomConnect("localhost", port);

		LM_M(("%s: second connect: fd == %d", name, fd));
		if (fd != -1)
			sysKill(name);
		else
			printf("killed '%s'\n", name);
	}

	return 0;
}

/* ****************************************************************************
*
* main -
*/
int main(int argC, const char *argV[])
{
	name[0] = 0;

	paConfig("log to file", (void*) true);
	paParse(paArgs, argC, (char**) argV, 1, false);

	if (name[0] != 0)
	{
		if ((strcasecmp(name, "worker") == 0) || (strcasecmp(name, "samsonWorker") == 0))
            return killProcess("samsonWorker", WORKER_PORT);
		else if ((strcasecmp(name, "controller") == 0) || (strcasecmp(name, "samsonController") == 0))
            return killProcess("samsonController", CONTROLLER_PORT);
		else if ((strcasecmp(name, "spawner") == 0) || (strcasecmp(name, "samsonSpawner") == 0))
			return killProcess("samsonSpawner", SPAWNER_PORT);
		else if (strcasecmp(name, "all") == 0)
		{
		   killProcess("samsonWorker",     WORKER_PORT);
		   killProcess("samsonController", CONTROLLER_PORT);
		   killProcess("samsonSpawner",    SPAWNER_PORT);

		   return 0;
		}
		else
		{
			printf("non-familiar process '%s'\n", name);
			exit(1);
		}
	}

	return 0;
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief default handler for error handling and json in-/output
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "RestBaseHandler.h"

#include "Basics/logging.h"
#include "Basics/tri-strings.h"
#include "Basics/StringBufferAdapter.h"
#include "Basics/StringUtils.h"
#include "Rest/HttpRequest.h"
#include "Rest/HttpResponse.h"

using namespace std;
using namespace triagens::basics;
using namespace triagens::rest;
using namespace triagens::admin;

typedef arangodb::velocypack::Dumper<StringBufferAdapter, false> StringBufferDumper;

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief constructor
////////////////////////////////////////////////////////////////////////////////

RestBaseHandler::RestBaseHandler (HttpRequest* request)
  : HttpHandler(request) {
}

// -----------------------------------------------------------------------------
// --SECTION--                                                   Handler methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

void RestBaseHandler::handleError (Exception const& ex) {
  generateError(HttpResponse::responseCode(ex.code()),
                ex.code(),
                ex.what());
}

// -----------------------------------------------------------------------------
// --SECTION--                                                    public methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a result from JSON
////////////////////////////////////////////////////////////////////////////////

void RestBaseHandler::generateResult (TRI_json_t const* json) {
  generateResult(HttpResponse::OK, json);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a result from JSON
////////////////////////////////////////////////////////////////////////////////

void RestBaseHandler::generateResult (HttpResponse::HttpResponseCode code,
                                      TRI_json_t const* json) {
  _response = createResponse(code);
  _response->setContentType("application/json; charset=utf-8");

  int res = TRI_StringifyJson(_response->body().stringBuffer(), json);

  if (res != TRI_ERROR_NO_ERROR) {
    generateError(HttpResponse::SERVER_ERROR,
                  TRI_ERROR_INTERNAL,
                  "cannot generate output");
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a result from VelocyPack
////////////////////////////////////////////////////////////////////////////////

void RestBaseHandler::generateResult (VPackSlice& slice) {
  generateResult(HttpResponse::OK, slice);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a result from VelocyPack
////////////////////////////////////////////////////////////////////////////////

void RestBaseHandler::generateResult (HttpResponse::HttpResponseCode code,
                                      VPackSlice& slice) {
  _response = createResponse(code);
  _response->setContentType("application/json; charset=utf-8");

  StringBufferAdapter buffer(_response->body().stringBuffer());

  StringBufferDumper dumper(buffer);
  try {
    dumper.dump(slice);
  }
  catch (...) {
    generateError(HttpResponse::SERVER_ERROR,
                  TRI_ERROR_INTERNAL,
                  "cannot generate output");
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a cancel message
////////////////////////////////////////////////////////////////////////////////

void RestBaseHandler::generateCanceled () {
  VPackBuilder builder;
  builder.add(VPackValue(VPackValueType::Object));
  builder.add("error", VPackValue(true));
  builder.add("code", VPackValue((int32_t) HttpResponse::REQUEST_TIMEOUT));
  builder.add("errorNum", VPackValue((int32_t) TRI_ERROR_REQUEST_CANCELED));
  builder.add("errorMessage", VPackValue("request canceled"));
  builder.close();

  VPackSlice slice(builder.start());
  generateResult(HttpResponse::REQUEST_TIMEOUT, slice);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generates an error
////////////////////////////////////////////////////////////////////////////////

void RestBaseHandler::generateError (HttpResponse::HttpResponseCode code,
                                     int errorCode) {
  char const* message = TRI_errno_string(errorCode);

  if (message) {
    generateError(code, errorCode, std::string(message));
  }
  else {
    generateError(code, errorCode, std::string("unknown error"));
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generates an error
////////////////////////////////////////////////////////////////////////////////

void RestBaseHandler::generateError (HttpResponse::HttpResponseCode code, int errorCode, std::string const& message) {

  _response = createResponse(code);
  _response->setContentType("application/json; charset=utf-8");

  _response->body().appendText("{\"error\":true,\"errorMessage\":\"");
  if (message.empty()) {
    // prevent empty error messages
    _response->body().appendText(TRI_errno_string(errorCode));
  }
  else {
    _response->body().appendText(StringUtils::escapeUnicode(message));
  }

  _response->body().appendText("\",\"code\":");
  _response->body().appendInteger(code);
  _response->body().appendText(",\"errorNum\":");
  _response->body().appendInteger(errorCode);
  _response->body().appendText("}");
}

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>RestBaseHandler now uses VelocyPack internally<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief default handler for error handling and json in-/output
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "RestBaseHandler.h"

#include "Basics/logging.h"
#include "Basics/tri-strings.h"
#include "Basics/StringBufferAdapter.h"
#include "Basics/StringUtils.h"
#include "Rest/HttpRequest.h"
#include "Rest/HttpResponse.h"

using namespace std;
using namespace triagens::basics;
using namespace triagens::rest;
using namespace triagens::admin;

typedef arangodb::velocypack::Dumper<StringBufferAdapter, false> StringBufferDumper;

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief constructor
////////////////////////////////////////////////////////////////////////////////

RestBaseHandler::RestBaseHandler (HttpRequest* request)
  : HttpHandler(request) {
}

// -----------------------------------------------------------------------------
// --SECTION--                                                   Handler methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

void RestBaseHandler::handleError (Exception const& ex) {
  generateError(HttpResponse::responseCode(ex.code()),
                ex.code(),
                ex.what());
}

// -----------------------------------------------------------------------------
// --SECTION--                                                    public methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a result from JSON
////////////////////////////////////////////////////////////////////////////////

void RestBaseHandler::generateResult (TRI_json_t const* json) {
  generateResult(HttpResponse::OK, json);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a result from JSON
////////////////////////////////////////////////////////////////////////////////

void RestBaseHandler::generateResult (HttpResponse::HttpResponseCode code,
                                      TRI_json_t const* json) {
  _response = createResponse(code);
  _response->setContentType("application/json; charset=utf-8");

  int res = TRI_StringifyJson(_response->body().stringBuffer(), json);

  if (res != TRI_ERROR_NO_ERROR) {
    generateError(HttpResponse::SERVER_ERROR,
                  TRI_ERROR_INTERNAL,
                  "cannot generate output");
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a result from VelocyPack
////////////////////////////////////////////////////////////////////////////////

void RestBaseHandler::generateResult (VPackSlice& slice) {
  generateResult(HttpResponse::OK, slice);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a result from VelocyPack
////////////////////////////////////////////////////////////////////////////////

void RestBaseHandler::generateResult (HttpResponse::HttpResponseCode code,
                                      VPackSlice& slice) {
  _response = createResponse(code);
  _response->setContentType("application/json; charset=utf-8");

  StringBufferAdapter buffer(_response->body().stringBuffer());

  StringBufferDumper dumper(buffer);
  try {
    dumper.dump(slice);
  }
  catch (...) {
    generateError(HttpResponse::SERVER_ERROR,
                  TRI_ERROR_INTERNAL,
                  "cannot generate output");
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generates a cancel message
////////////////////////////////////////////////////////////////////////////////

void RestBaseHandler::generateCanceled () {
  VPackBuilder builder;
  try {
    builder.add(VPackValue(VPackValueType::Object));
    builder.add("error", VPackValue(true));
    builder.add("code", VPackValue((int32_t) HttpResponse::REQUEST_TIMEOUT));
    builder.add("errorNum", VPackValue((int32_t) TRI_ERROR_REQUEST_CANCELED));
    builder.add("errorMessage", VPackValue("request canceled"));
    builder.close();

    VPackSlice slice(builder.start());
    generateResult(HttpResponse::REQUEST_TIMEOUT, slice);
  } catch (...) {
    generateError(HttpResponse::SERVER_ERROR,
                  TRI_ERROR_INTERNAL,
                  "cannot generate output");
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generates an error
////////////////////////////////////////////////////////////////////////////////

void RestBaseHandler::generateError (HttpResponse::HttpResponseCode code,
                                     int errorCode) {
  char const* message = TRI_errno_string(errorCode);

  if (message) {
    generateError(code, errorCode, std::string(message));
  }
  else {
    generateError(code, errorCode, std::string("unknown error"));
  }
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generates an error
////////////////////////////////////////////////////////////////////////////////

void RestBaseHandler::generateError (HttpResponse::HttpResponseCode code, int errorCode, std::string const& message) {

  _response = createResponse(code);
  _response->setContentType("application/json; charset=utf-8");

  VPackBuilder builder;
  try {
    builder.add(VPackValue(VPackValueType::Object));
    builder.add("error", VPackValue(true));
    if (message.empty()) {
      // prevent empty error messages
      builder.add("errorMessage", VPackValue(TRI_errno_string(errorCode)));
    }
    else {
      builder.add("errorMessage", VPackValue(StringUtils::escapeUnicode(message)));
    }
    builder.add("code", VPackValue(code));
    builder.add("errorNum", VPackValue(errorCode));
    builder.close();
    VPackSlice slice(builder.start());
    StringBufferAdapter buffer(_response->body().stringBuffer());
    StringBufferDumper dumper(buffer);
    dumper.dump(slice);
  }
  catch (...) {
    // Building the error response failed
  }
}

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: tcommuni.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-18 16:03:49 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2002
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2002 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#if SUPD >= 380
#include <svtools/communi.hxx>
#else
#include <communi.hxx>
#endif
#include <tools/link.hxx>
#include <svtools/svarray.hxx>

#include <vos/thread.hxx>

#ifndef _STRING_LIST
DECLARE_LIST( StringList, String * );
#define _STRING_LIST
#endif

class Process;

class CommunicationManagerClientViaSocketTT : public CommunicationManagerClientViaSocket
{
public:
    CommunicationManagerClientViaSocketTT();

    virtual BOOL StartCommunication();
    virtual BOOL StartCommunication( String aApp, String aParams );

protected:
    virtual BOOL RetryConnect();
    BOOL bApplicationStarted;
    Time aFirstRetryCall;
    String aAppPath;
    String aAppParams;
    Process *pProcess;
};

String GetHostConfig();
ULONG GetTTPortConfig();
ULONG GetUnoPortConfig();

<commit_msg>INTEGRATION: CWS ause04 (1.2.22); FILE MERGED 2003/07/31 12:47:54 gh 1.2.22.1: removed 'if SUPD' precompiler stuff<commit_after>/*************************************************************************
 *
 *  $RCSfile: tcommuni.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2003-08-25 15:47:30 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2002
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2002 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2002 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <svtools/communi.hxx>
#include <tools/link.hxx>
#include <svtools/svarray.hxx>

#include <vos/thread.hxx>

#ifndef _STRING_LIST
DECLARE_LIST( StringList, String * );
#define _STRING_LIST
#endif

class Process;

class CommunicationManagerClientViaSocketTT : public CommunicationManagerClientViaSocket
{
public:
    CommunicationManagerClientViaSocketTT();

    virtual BOOL StartCommunication();
    virtual BOOL StartCommunication( String aApp, String aParams );

protected:
    virtual BOOL RetryConnect();
    BOOL bApplicationStarted;
    Time aFirstRetryCall;
    String aAppPath;
    String aAppParams;
    Process *pProcess;
};

String GetHostConfig();
ULONG GetTTPortConfig();
ULONG GetUnoPortConfig();

<|endoftext|>


<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-CHROMIUM file.

#include "brightray/browser/browser_main_parts.h"

#include <stdlib.h>
#include <sys/stat.h>
#include <string>

#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "brightray/browser/browser_context.h"
#include "brightray/browser/devtools_manager_delegate.h"
#include "brightray/browser/web_ui_controller_factory.h"
#include "brightray/common/application_info.h"
#include "brightray/common/main_delegate.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "media/base/localized_strings.h"
#include "net/proxy/proxy_resolver_v8.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/material_design/material_design_controller.h"

#if defined(USE_AURA)
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/wm/core/wm_state.h"
#endif

#if defined(TOOLKIT_VIEWS)
#include "brightray/browser/views/views_delegate.h"
#endif

#if defined(USE_X11)
#include "base/environment.h"
#include "base/nix/xdg_util.h"
#include "base/path_service.h"
#include "base/threading/thread_task_runner_handle.h"
#include "brightray/browser/brightray_paths.h"
#include "chrome/browser/ui/libgtkui/gtk_ui.h"
#include "ui/base/x/x11_util.h"
#include "ui/base/x/x11_util_internal.h"
#include "ui/views/linux_ui/linux_ui.h"
#endif

#if defined(OS_WIN)
#include "ui/base/cursor/cursor_loader_win.h"
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/gfx/platform_font_win.h"
#endif

#if defined(OS_LINUX)
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h"
#endif

namespace brightray {

// defined in browser_main_parts_mac
void OverrideMacAppLogsPath();

namespace {

#if defined(OS_WIN)
// gfx::Font callbacks
void AdjustUIFont(LOGFONT* logfont) {
  l10n_util::AdjustUIFont(logfont);
}

int GetMinimumFontSize() {
  return 10;
}
#endif

#if defined(USE_X11)
// Indicates that we're currently responding to an IO error (by shutting down).
bool g_in_x11_io_error_handler = false;

// Number of seconds to wait for UI thread to get an IO error if we get it on
// the background thread.
const int kWaitForUIThreadSeconds = 10;

void OverrideLinuxAppDataPath() {
  base::FilePath path;
  if (PathService::Get(DIR_APP_DATA, &path))
    return;
  std::unique_ptr<base::Environment> env(base::Environment::Create());
  path = base::nix::GetXDGDirectory(env.get(),
                                    base::nix::kXdgConfigHomeEnvVar,
                                    base::nix::kDotConfigDir);
  PathService::Override(DIR_APP_DATA, path);
}

void OverrideWinAppLogsPath() {
  std::string appName = GetApplicationName();
  std::string logPath = "%HOMEDRIVE%%HOMEPATH%\\AppData\\Roaming\\";
  std::string appLogPath = logPath + appName + "\\logs";

  int status = mkdir(appLogPath.c_str(), S_IRWXU | S_IRGRP | S_IROTH);

  PathService::Override(DIR_APP_LOGS, base::FilePath(appLogPath));
}

void OverrideLinuxAppLogsPath() {
  std::string appName = GetApplicationName();
  std::string homePath = std:string(getenv("HOME"));
  std::string appLogPath = homePath + "/.config/" + appName + "/logs";

  int status = mkdir(appLogPath.c_str(), S_IRWXU | S_IRGRP | S_IROTH);

  PathService::Override(DIR_APP_LOGS, base::FilePath(appLogPath));
  return;
}

int BrowserX11ErrorHandler(Display* d, XErrorEvent* error) {
  if (!g_in_x11_io_error_handler) {
    base::ThreadTaskRunnerHandle::Get()->PostTask(
        FROM_HERE, base::Bind(&ui::LogErrorEventDescription, d, *error));
  }
  return 0;
}

// This function is used to help us diagnose crash dumps that happen
// during the shutdown process.
NOINLINE void WaitingForUIThreadToHandleIOError() {
  // Ensure function isn't optimized away.
  asm("");
  sleep(kWaitForUIThreadSeconds);
}

int BrowserX11IOErrorHandler(Display* d) {
  if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
    // Wait for the UI thread (which has a different connection to the X server)
    // to get the error. We can't call shutdown from this thread without
    // tripping an error. Doing it through a function so that we'll be able
    // to see it in any crash dumps.
    WaitingForUIThreadToHandleIOError();
    return 0;
  }

  // If there's an IO error it likely means the X server has gone away.
  // If this CHECK fails, then that means SessionEnding() below triggered some
  // code that tried to talk to the X server, resulting in yet another error.
  CHECK(!g_in_x11_io_error_handler);

  g_in_x11_io_error_handler = true;
  LOG(ERROR) << "X IO error received (X server probably went away)";
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());

  return 0;
}

int X11EmptyErrorHandler(Display* d, XErrorEvent* error) {
  return 0;
}

int X11EmptyIOErrorHandler(Display* d) {
  return 0;
}
#endif

base::string16 MediaStringProvider(media::MessageId id) {
  switch (id) {
    case media::DEFAULT_AUDIO_DEVICE_NAME:
      return base::ASCIIToUTF16("Default");
#if defined(OS_WIN)
    case media::COMMUNICATIONS_AUDIO_DEVICE_NAME:
      return base::ASCIIToUTF16("Communications");
#endif
    default:
      return base::string16();
  }
}

}  // namespace

BrowserMainParts::BrowserMainParts() {
}

BrowserMainParts::~BrowserMainParts() {
}

void BrowserMainParts::PreEarlyInitialization() {
  std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList);
  feature_list->InitializeFromCommandLine("", "");
  base::FeatureList::SetInstance(std::move(feature_list));
#if defined(OS_MACOSX)
  OverrideMacAppLogsPath();
#endif
#if defined(OS_LINUX)
  OverrideLinuxAppLogsPath();
#endif
#if defined(OS_WIN)
  OverrideWinAppLogsPath();
#endif
#if defined(USE_X11)
  views::LinuxUI::SetInstance(BuildGtkUi());
  OverrideLinuxAppDataPath();

  // Installs the X11 error handlers for the browser process used during
  // startup. They simply print error messages and exit because
  // we can't shutdown properly while creating and initializing services.
  ui::SetX11ErrorHandlers(nullptr, nullptr);
#endif
}

void BrowserMainParts::ToolkitInitialized() {
  ui::MaterialDesignController::Initialize();

#if defined(USE_AURA) && defined(USE_X11)
  views::LinuxUI::instance()->Initialize();
#endif

#if defined(USE_AURA)
  wm_state_.reset(new wm::WMState);
#endif

#if defined(TOOLKIT_VIEWS)
  views_delegate_.reset(new ViewsDelegate);
#endif

#if defined(OS_WIN)
  gfx::PlatformFontWin::adjust_font_callback = &AdjustUIFont;
  gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize;

  wchar_t module_name[MAX_PATH] = { 0 };
  if (GetModuleFileName(NULL, module_name, MAX_PATH))
    ui::CursorLoaderWin::SetCursorResourceModule(module_name);
#endif
}

void BrowserMainParts::PreMainMessageLoopStart() {
#if defined(OS_MACOSX)
  l10n_util::OverrideLocaleWithCocoaLocale();
#endif
  InitializeResourceBundle("");
#if defined(OS_MACOSX)
  InitializeMainNib();
#endif
  media::SetLocalizedStringProvider(MediaStringProvider);
}

void BrowserMainParts::PreMainMessageLoopRun() {
  content::WebUIControllerFactory::RegisterFactory(
      WebUIControllerFactory::GetInstance());

  // --remote-debugging-port
  auto command_line = base::CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kRemoteDebuggingPort))
    DevToolsManagerDelegate::StartHttpHandler();
}

void BrowserMainParts::PostMainMessageLoopStart() {
#if defined(USE_X11)
  // Installs the X11 error handlers for the browser process after the
  // main message loop has started. This will allow us to exit cleanly
  // if X exits before us.
  ui::SetX11ErrorHandlers(BrowserX11ErrorHandler, BrowserX11IOErrorHandler);
#endif
#if defined(OS_LINUX)
  bluez::DBusBluezManagerWrapperLinux::Initialize();
#endif
}

void BrowserMainParts::PostMainMessageLoopRun() {
#if defined(USE_X11)
  // Unset the X11 error handlers. The X11 error handlers log the errors using a
  // |PostTask()| on the message-loop. But since the message-loop is in the
  // process of terminating, this can cause errors.
  ui::SetX11ErrorHandlers(X11EmptyErrorHandler, X11EmptyIOErrorHandler);
#endif
}

int BrowserMainParts::PreCreateThreads() {
#if defined(USE_AURA)
  display::Screen* screen = views::CreateDesktopScreen();
  display::Screen::SetScreenInstance(screen);
#if defined(USE_X11)
  views::LinuxUI::instance()->UpdateDeviceScaleFactor();
#endif
#endif

  if (!views::LayoutProvider::Get())
    layout_provider_.reset(new views::LayoutProvider());

  return 0;
}

void BrowserMainParts::PostDestroyThreads() {
#if defined(OS_LINUX)
  device::BluetoothAdapterFactory::Shutdown();
  bluez::DBusBluezManagerWrapperLinux::Shutdown();
#endif
}

}  // namespace brightray
<commit_msg>fix incorrect std namespacing<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-CHROMIUM file.

#include "brightray/browser/browser_main_parts.h"

#include <stdlib.h>
#include <sys/stat.h>
#include <string>

#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "brightray/browser/browser_context.h"
#include "brightray/browser/devtools_manager_delegate.h"
#include "brightray/browser/web_ui_controller_factory.h"
#include "brightray/common/application_info.h"
#include "brightray/common/main_delegate.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "media/base/localized_strings.h"
#include "net/proxy/proxy_resolver_v8.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/material_design/material_design_controller.h"

#if defined(USE_AURA)
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/wm/core/wm_state.h"
#endif

#if defined(TOOLKIT_VIEWS)
#include "brightray/browser/views/views_delegate.h"
#endif

#if defined(USE_X11)
#include "base/environment.h"
#include "base/nix/xdg_util.h"
#include "base/path_service.h"
#include "base/threading/thread_task_runner_handle.h"
#include "brightray/browser/brightray_paths.h"
#include "chrome/browser/ui/libgtkui/gtk_ui.h"
#include "ui/base/x/x11_util.h"
#include "ui/base/x/x11_util_internal.h"
#include "ui/views/linux_ui/linux_ui.h"
#endif

#if defined(OS_WIN)
#include "ui/base/cursor/cursor_loader_win.h"
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/gfx/platform_font_win.h"
#endif

#if defined(OS_LINUX)
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h"
#endif

namespace brightray {

// defined in browser_main_parts_mac
void OverrideMacAppLogsPath();

namespace {

#if defined(OS_WIN)
// gfx::Font callbacks
void AdjustUIFont(LOGFONT* logfont) {
  l10n_util::AdjustUIFont(logfont);
}

int GetMinimumFontSize() {
  return 10;
}
#endif

#if defined(USE_X11)
// Indicates that we're currently responding to an IO error (by shutting down).
bool g_in_x11_io_error_handler = false;

// Number of seconds to wait for UI thread to get an IO error if we get it on
// the background thread.
const int kWaitForUIThreadSeconds = 10;

void OverrideLinuxAppDataPath() {
  base::FilePath path;
  if (PathService::Get(DIR_APP_DATA, &path))
    return;
  std::unique_ptr<base::Environment> env(base::Environment::Create());
  path = base::nix::GetXDGDirectory(env.get(),
                                    base::nix::kXdgConfigHomeEnvVar,
                                    base::nix::kDotConfigDir);
  PathService::Override(DIR_APP_DATA, path);
}

void OverrideWinAppLogsPath() {
  std::string appName = GetApplicationName();
  std::string logPath = "%HOMEDRIVE%%HOMEPATH%\\AppData\\Roaming\\";
  std::string appLogPath = logPath + appName + "\\logs";

  int status = mkdir(appLogPath.c_str(), S_IRWXU | S_IRGRP | S_IROTH);

  PathService::Override(DIR_APP_LOGS, base::FilePath(appLogPath));
}

void OverrideLinuxAppLogsPath() {
  std::string appName = GetApplicationName();
  std::string homePath = std::string(getenv("HOME"));
  std::string appLogPath = homePath + "/.config/" + appName + "/logs";

  int status = mkdir(appLogPath.c_str(), S_IRWXU | S_IRGRP | S_IROTH);

  PathService::Override(DIR_APP_LOGS, base::FilePath(appLogPath));
  return;
}

int BrowserX11ErrorHandler(Display* d, XErrorEvent* error) {
  if (!g_in_x11_io_error_handler) {
    base::ThreadTaskRunnerHandle::Get()->PostTask(
        FROM_HERE, base::Bind(&ui::LogErrorEventDescription, d, *error));
  }
  return 0;
}

// This function is used to help us diagnose crash dumps that happen
// during the shutdown process.
NOINLINE void WaitingForUIThreadToHandleIOError() {
  // Ensure function isn't optimized away.
  asm("");
  sleep(kWaitForUIThreadSeconds);
}

int BrowserX11IOErrorHandler(Display* d) {
  if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
    // Wait for the UI thread (which has a different connection to the X server)
    // to get the error. We can't call shutdown from this thread without
    // tripping an error. Doing it through a function so that we'll be able
    // to see it in any crash dumps.
    WaitingForUIThreadToHandleIOError();
    return 0;
  }

  // If there's an IO error it likely means the X server has gone away.
  // If this CHECK fails, then that means SessionEnding() below triggered some
  // code that tried to talk to the X server, resulting in yet another error.
  CHECK(!g_in_x11_io_error_handler);

  g_in_x11_io_error_handler = true;
  LOG(ERROR) << "X IO error received (X server probably went away)";
  base::ThreadTaskRunnerHandle::Get()->PostTask(
      FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());

  return 0;
}

int X11EmptyErrorHandler(Display* d, XErrorEvent* error) {
  return 0;
}

int X11EmptyIOErrorHandler(Display* d) {
  return 0;
}
#endif

base::string16 MediaStringProvider(media::MessageId id) {
  switch (id) {
    case media::DEFAULT_AUDIO_DEVICE_NAME:
      return base::ASCIIToUTF16("Default");
#if defined(OS_WIN)
    case media::COMMUNICATIONS_AUDIO_DEVICE_NAME:
      return base::ASCIIToUTF16("Communications");
#endif
    default:
      return base::string16();
  }
}

}  // namespace

BrowserMainParts::BrowserMainParts() {
}

BrowserMainParts::~BrowserMainParts() {
}

void BrowserMainParts::PreEarlyInitialization() {
  std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList);
  feature_list->InitializeFromCommandLine("", "");
  base::FeatureList::SetInstance(std::move(feature_list));
#if defined(OS_MACOSX)
  OverrideMacAppLogsPath();
#endif
#if defined(OS_LINUX)
  OverrideLinuxAppLogsPath();
#endif
#if defined(OS_WIN)
  OverrideWinAppLogsPath();
#endif
#if defined(USE_X11)
  views::LinuxUI::SetInstance(BuildGtkUi());
  OverrideLinuxAppDataPath();

  // Installs the X11 error handlers for the browser process used during
  // startup. They simply print error messages and exit because
  // we can't shutdown properly while creating and initializing services.
  ui::SetX11ErrorHandlers(nullptr, nullptr);
#endif
}

void BrowserMainParts::ToolkitInitialized() {
  ui::MaterialDesignController::Initialize();

#if defined(USE_AURA) && defined(USE_X11)
  views::LinuxUI::instance()->Initialize();
#endif

#if defined(USE_AURA)
  wm_state_.reset(new wm::WMState);
#endif

#if defined(TOOLKIT_VIEWS)
  views_delegate_.reset(new ViewsDelegate);
#endif

#if defined(OS_WIN)
  gfx::PlatformFontWin::adjust_font_callback = &AdjustUIFont;
  gfx::PlatformFontWin::get_minimum_font_size_callback = &GetMinimumFontSize;

  wchar_t module_name[MAX_PATH] = { 0 };
  if (GetModuleFileName(NULL, module_name, MAX_PATH))
    ui::CursorLoaderWin::SetCursorResourceModule(module_name);
#endif
}

void BrowserMainParts::PreMainMessageLoopStart() {
#if defined(OS_MACOSX)
  l10n_util::OverrideLocaleWithCocoaLocale();
#endif
  InitializeResourceBundle("");
#if defined(OS_MACOSX)
  InitializeMainNib();
#endif
  media::SetLocalizedStringProvider(MediaStringProvider);
}

void BrowserMainParts::PreMainMessageLoopRun() {
  content::WebUIControllerFactory::RegisterFactory(
      WebUIControllerFactory::GetInstance());

  // --remote-debugging-port
  auto command_line = base::CommandLine::ForCurrentProcess();
  if (command_line->HasSwitch(switches::kRemoteDebuggingPort))
    DevToolsManagerDelegate::StartHttpHandler();
}

void BrowserMainParts::PostMainMessageLoopStart() {
#if defined(USE_X11)
  // Installs the X11 error handlers for the browser process after the
  // main message loop has started. This will allow us to exit cleanly
  // if X exits before us.
  ui::SetX11ErrorHandlers(BrowserX11ErrorHandler, BrowserX11IOErrorHandler);
#endif
#if defined(OS_LINUX)
  bluez::DBusBluezManagerWrapperLinux::Initialize();
#endif
}

void BrowserMainParts::PostMainMessageLoopRun() {
#if defined(USE_X11)
  // Unset the X11 error handlers. The X11 error handlers log the errors using a
  // |PostTask()| on the message-loop. But since the message-loop is in the
  // process of terminating, this can cause errors.
  ui::SetX11ErrorHandlers(X11EmptyErrorHandler, X11EmptyIOErrorHandler);
#endif
}

int BrowserMainParts::PreCreateThreads() {
#if defined(USE_AURA)
  display::Screen* screen = views::CreateDesktopScreen();
  display::Screen::SetScreenInstance(screen);
#if defined(USE_X11)
  views::LinuxUI::instance()->UpdateDeviceScaleFactor();
#endif
#endif

  if (!views::LayoutProvider::Get())
    layout_provider_.reset(new views::LayoutProvider());

  return 0;
}

void BrowserMainParts::PostDestroyThreads() {
#if defined(OS_LINUX)
  device::BluetoothAdapterFactory::Shutdown();
  bluez::DBusBluezManagerWrapperLinux::Shutdown();
#endif
}

}  // namespace brightray
<|endoftext|>