<commit_before>//===--- tools/extra/clang-tidy/ClangTidyMain.cpp - Clang tidy tool -------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
///  \file This file implements a clang-tidy tool.
///
///  This tool uses the Clang Tooling infrastructure, see
///    http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
///  for details on setting it up with LLVM source tree.
///
//===----------------------------------------------------------------------===//

#include "../ClangTidy.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "llvm/Support/Process.h"

using namespace clang::ast_matchers;
using namespace clang::driver;
using namespace clang::tooling;
using namespace llvm;

static cl::OptionCategory ClangTidyCategory("clang-tidy options");

static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
static cl::extrahelp ClangTidyHelp(
    "Configuration files:\n"
    "  clang-tidy attempts to read configuration for each source file from a\n"
    "  .clang-tidy file located in the closest parent directory of the source\n"
    "  file. If any configuration options have a corresponding command-line\n"
    "  option, command-line option takes precedence. The effective\n"
    "  configuration can be inspected using -dump-config:\n"
    "\n"
    "    $ clang-tidy -dump-config - --\n"
    "    ---\n"
    "    Checks:          '-*,some-check'\n"
    "    HeaderFilterRegex: ''\n"
    "    AnalyzeTemporaryDtors: false\n"
    "    User:            user\n"
    "    CheckOptions:    \n"
    "      - key:             some-check.SomeOption\n"
    "        value:           'some value'\n"
    "    ...\n"
    "\n\n");

const char DefaultChecks[] =  // Enable these checks:
    "clang-diagnostic-*,"     //   * compiler diagnostics
    "clang-analyzer-*,"       //   * Static Analyzer checks
    "-clang-analyzer-alpha*"; //   * but not alpha checks: many false positives

static cl::opt<std::string>
Checks("checks", cl::desc("Comma-separated list of globs with optional '-'\n"
                          "prefix. Globs are processed in order of appearance\n"
                          "in the list. Globs without '-' prefix add checks\n"
                          "with matching names to the set, globs with the '-'\n"
                          "prefix remove checks with matching names from the\n"
                          "set of enabled checks.\n"
                          "This option's value is appended to the value read\n"
                          "from a .clang-tidy file, if any."),
       cl::init(""), cl::cat(ClangTidyCategory));

static cl::opt<std::string>
HeaderFilter("header-filter",
             cl::desc("Regular expression matching the names of the\n"
                      "headers to output diagnostics from. Diagnostics\n"
                      "from the main file of each translation unit are\n"
                      "always displayed.\n"
                      "Can be used together with -line-filter.\n"
                      "This option overrides the value read from a\n"
                      ".clang-tidy file."),
             cl::init(""), cl::cat(ClangTidyCategory));

static cl::opt<bool>
    SystemHeaders("system-headers",
                  cl::desc("Display the errors from system headers."),
                  cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<std::string>
LineFilter("line-filter",
           cl::desc("List of files with line ranges to filter the\n"
                    "warnings. Can be used together with\n"
                    "-header-filter. The format of the list is a JSON\n"
                    "array of objects:\n"
                    "  [\n"
                    "    {\"name\":\"file1.cpp\",\"lines\":[[1,3],[5,7]]},\n"
                    "    {\"name\":\"file2.h\"}\n"
                    "  ]"),
           cl::init(""), cl::cat(ClangTidyCategory));

static cl::opt<bool>
    Fix("fix", cl::desc("Apply suggested fixes. Without -fix-errors\n"
                        "clang-tidy will bail out if any compilation\n"
                        "errors were found."),
        cl::init(false), cl::cat(ClangTidyCategory));

static cl::opt<bool>
    FixErrors("fix-errors",
              cl::desc("Apply suggested fixes even if compilation errors\n"
                       "were found. If compiler errors have attached\n"
                       "fix-its, clang-tidy will apply them as well."),
              cl::init(false), cl::cat(ClangTidyCategory));

static cl::opt<bool>
ListChecks("list-checks",
           cl::desc("List all enabled checks and exit. Use with\n"
                    "-checks='*' to list all available checks."),
           cl::init(false), cl::cat(ClangTidyCategory));

static cl::opt<std::string> Config(
    "config",
    cl::desc("Specifies a configuration in YAML/JSON format:\n"
             "  -config=\"{Checks: '*', CheckOptions: [{key: x, value: y}]}\"\n"
             "When the value is empty, clang-tidy will attempt to find\n"
             "a file named .clang-tidy for each source file in its parent\n"
             "directories."),
    cl::init(""), cl::cat(ClangTidyCategory));

static cl::opt<bool> DumpConfig(
    "dump-config",
    cl::desc("Dumps configuration in the YAML format to stdout. This option\n"
             "should be used along with a file name (and '--' if the file is\n"
             "outside of a project with configured compilation database). The\n"
             "configuration used for this file will be printed."),
    cl::init(false), cl::cat(ClangTidyCategory));

static cl::opt<bool> EnableCheckProfile(
    "enable-check-profile",
    cl::desc("Enable per-check timing profiles, and print a report to stderr."),
    cl::init(false), cl::cat(ClangTidyCategory));

static cl::opt<bool> AnalyzeTemporaryDtors(
    "analyze-temporary-dtors",
    cl::desc("Enable temporary destructor-aware analysis in\n"
             "clang-analyzer- checks.\n"
             "This option overrides the value read from a\n"
             ".clang-tidy file."),
    cl::init(false), cl::cat(ClangTidyCategory));

static cl::opt<std::string> ExportFixes(
    "export-fixes",
    cl::desc("YAML file to store suggested fixes in. The\n"
             "stored fixes can be applied to the input source\n"
             "code with clang-apply-replacements."),
    cl::value_desc("filename"), cl::cat(ClangTidyCategory));

namespace clang {
namespace tidy {

static void printStats(const ClangTidyStats &Stats) {
  if (Stats.errorsIgnored()) {
    llvm::errs() << "Suppressed " << Stats.errorsIgnored() << " warnings (";
    StringRef Separator = "";
    if (Stats.ErrorsIgnoredNonUserCode) {
      llvm::errs() << Stats.ErrorsIgnoredNonUserCode << " in non-user code";
      Separator = ", ";
    }
    if (Stats.ErrorsIgnoredLineFilter) {
      llvm::errs() << Separator << Stats.ErrorsIgnoredLineFilter
                   << " due to line filter";
      Separator = ", ";
    }
    if (Stats.ErrorsIgnoredNOLINT) {
      llvm::errs() << Separator << Stats.ErrorsIgnoredNOLINT << " NOLINT";
      Separator = ", ";
    }
    if (Stats.ErrorsIgnoredCheckFilter)
      llvm::errs() << Separator << Stats.ErrorsIgnoredCheckFilter
                   << " with check filters";
    llvm::errs() << ").\n";
    if (Stats.ErrorsIgnoredNonUserCode)
      llvm::errs() << "Use -header-filter='.*' to display errors from all "
                      "non-system headers.\n";
  }
}

static void printProfileData(const ProfileData &Profile,
                             llvm::raw_ostream &OS) {
  // Time is first to allow for sorting by it.
  std::vector<std::pair<llvm::TimeRecord, StringRef>> Timers;
  TimeRecord Total;

  for (const auto& P : Profile.Records) {
    Timers.emplace_back(P.getValue(), P.getKey());
    Total += P.getValue();
  }

  std::sort(Timers.begin(), Timers.end());

  std::string Line = "===" + std::string(73, '-') + "===\n";
  OS << Line;

  if (Total.getUserTime())
    OS << "   ---User Time---";
  if (Total.getSystemTime())
    OS << "   --System Time--";
  if (Total.getProcessTime())
    OS << "   --User+System--";
  OS << "   ---Wall Time---";
  if (Total.getMemUsed())
    OS << "  ---Mem---";
  OS << "  --- Name ---\n";

  // Loop through all of the timing data, printing it out.
  for (auto I = Timers.rbegin(), E = Timers.rend(); I != E; ++I) {
    I->first.print(Total, OS);
    OS << I->second << '\n';
  }

  Total.print(Total, OS);
  OS << "Total\n";
  OS << Line << "\n";
  OS.flush();
}

std::unique_ptr<ClangTidyOptionsProvider> createOptionsProvider() {
  ClangTidyGlobalOptions GlobalOptions;
  if (std::error_code Err = parseLineFilter(LineFilter, GlobalOptions)) {
    llvm::errs() << "Invalid LineFilter: " << Err.message() << "\n\nUsage:\n";
    llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
    return nullptr;
  }

  ClangTidyOptions DefaultOptions;
  DefaultOptions.Checks = DefaultChecks;
  DefaultOptions.HeaderFilterRegex = HeaderFilter;
  DefaultOptions.SystemHeaders = SystemHeaders;
  DefaultOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
  DefaultOptions.User = llvm::sys::Process::GetEnv("USER");
  // USERNAME is used on Windows.
  if (!DefaultOptions.User)
    DefaultOptions.User = llvm::sys::Process::GetEnv("USERNAME");

  ClangTidyOptions OverrideOptions;
  if (Checks.getNumOccurrences() > 0)
    OverrideOptions.Checks = Checks;
  if (HeaderFilter.getNumOccurrences() > 0)
    OverrideOptions.HeaderFilterRegex = HeaderFilter;
  if (SystemHeaders.getNumOccurrences() > 0)
    OverrideOptions.SystemHeaders = SystemHeaders;
  if (AnalyzeTemporaryDtors.getNumOccurrences() > 0)
    OverrideOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;

  if (!Config.empty()) {
    if (llvm::ErrorOr<ClangTidyOptions> ParsedConfig =
            parseConfiguration(Config)) {
      return llvm::make_unique<DefaultOptionsProvider>(
          GlobalOptions, ClangTidyOptions::getDefaults()
                             .mergeWith(DefaultOptions)
                             .mergeWith(*ParsedConfig)
                             .mergeWith(OverrideOptions));
    } else {
      llvm::errs() << "Error: invalid configuration specified.\n"
                   << ParsedConfig.getError().message() << "\n";
      return nullptr;
    }
  }
  return llvm::make_unique<FileOptionsProvider>(GlobalOptions, DefaultOptions,
                                                OverrideOptions);
}

int clangTidyMain(int argc, const char **argv) {
  CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory);

  auto OptionsProvider = createOptionsProvider();
  if (!OptionsProvider)
    return 1;

  std::string FileName = OptionsParser.getSourcePathList().front();
  ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FileName);
  std::vector<std::string> EnabledChecks = getCheckNames(EffectiveOptions);

  // FIXME: Allow using --list-checks without positional arguments.
  if (ListChecks) {
    llvm::outs() << "Enabled checks:";
    for (auto CheckName : EnabledChecks)
      llvm::outs() << "\n    " << CheckName;
    llvm::outs() << "\n\n";
    return 0;
  }

  if (DumpConfig) {
    EffectiveOptions.CheckOptions = getCheckOptions(EffectiveOptions);
    llvm::outs() << configurationAsText(ClangTidyOptions::getDefaults()
                                            .mergeWith(EffectiveOptions))
                 << "\n";
    return 0;
  }

  if (EnabledChecks.empty()) {
    llvm::errs() << "Error: no checks enabled.\n";
    llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
    return 1;
  }

  ProfileData Profile;

  std::vector<ClangTidyError> Errors;
  ClangTidyStats Stats =
      runClangTidy(std::move(OptionsProvider), OptionsParser.getCompilations(),
                   OptionsParser.getSourcePathList(), &Errors,
                   EnableCheckProfile ? &Profile : nullptr);
  bool FoundErrors =
      std::find_if(Errors.begin(), Errors.end(), [](const ClangTidyError &E) {
        return E.DiagLevel == ClangTidyError::Error;
      }) != Errors.end();

  const bool DisableFixes = Fix && FoundErrors && !FixErrors;

  // -fix-errors implies -fix.
  handleErrors(Errors, (FixErrors || Fix) && !DisableFixes);

  if (!ExportFixes.empty() && !Errors.empty()) {
    std::error_code EC;
    llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None);
    if (EC) {
      llvm::errs() << "Error opening output file: " << EC.message() << '\n';
      return 1;
    }
    exportReplacements(Errors, OS);
  }

  printStats(Stats);
  if (DisableFixes)
    llvm::errs() << "Found compiler errors, but -fix-error was not specified.\n"
                    "Fixes have NOT been applied.\n\n";

  if (EnableCheckProfile)
    printProfileData(Profile, llvm::errs());

  return 0;
}

// This anchor is used to force the linker to link the LLVMModule.
extern volatile int LLVMModuleAnchorSource;
static int LLVMModuleAnchorDestination = LLVMModuleAnchorSource;

// This anchor is used to force the linker to link the GoogleModule.
extern volatile int GoogleModuleAnchorSource;
static int GoogleModuleAnchorDestination = GoogleModuleAnchorSource;

// This anchor is used to force the linker to link the MiscModule.
extern volatile int MiscModuleAnchorSource;
static int MiscModuleAnchorDestination = MiscModuleAnchorSource;

// This anchor is used to force the linker to link the ReadabilityModule.
extern volatile int ReadabilityModuleAnchorSource;
static int ReadabilityModuleAnchorDestination = ReadabilityModuleAnchorSource;

} // namespace tidy
} // namespace clang

int main(int argc, const char **argv) {
  return clang::tidy::clangTidyMain(argc, argv);
}
<commit_msg>[clang-tidy] Fix a typo.<commit_after>//===--- tools/extra/clang-tidy/ClangTidyMain.cpp - Clang tidy tool -------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
///  \file This file implements a clang-tidy tool.
///
///  This tool uses the Clang Tooling infrastructure, see
///    http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
///  for details on setting it up with LLVM source tree.
///
//===----------------------------------------------------------------------===//

#include "../ClangTidy.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "llvm/Support/Process.h"

using namespace clang::ast_matchers;
using namespace clang::driver;
using namespace clang::tooling;
using namespace llvm;

static cl::OptionCategory ClangTidyCategory("clang-tidy options");

static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
static cl::extrahelp ClangTidyHelp(
    "Configuration files:\n"
    "  clang-tidy attempts to read configuration for each source file from a\n"
    "  .clang-tidy file located in the closest parent directory of the source\n"
    "  file. If any configuration options have a corresponding command-line\n"
    "  option, command-line option takes precedence. The effective\n"
    "  configuration can be inspected using -dump-config:\n"
    "\n"
    "    $ clang-tidy -dump-config - --\n"
    "    ---\n"
    "    Checks:          '-*,some-check'\n"
    "    HeaderFilterRegex: ''\n"
    "    AnalyzeTemporaryDtors: false\n"
    "    User:            user\n"
    "    CheckOptions:    \n"
    "      - key:             some-check.SomeOption\n"
    "        value:           'some value'\n"
    "    ...\n"
    "\n\n");

const char DefaultChecks[] =  // Enable these checks:
    "clang-diagnostic-*,"     //   * compiler diagnostics
    "clang-analyzer-*,"       //   * Static Analyzer checks
    "-clang-analyzer-alpha*"; //   * but not alpha checks: many false positives

static cl::opt<std::string>
Checks("checks", cl::desc("Comma-separated list of globs with optional '-'\n"
                          "prefix. Globs are processed in order of appearance\n"
                          "in the list. Globs without '-' prefix add checks\n"
                          "with matching names to the set, globs with the '-'\n"
                          "prefix remove checks with matching names from the\n"
                          "set of enabled checks.\n"
                          "This option's value is appended to the value read\n"
                          "from a .clang-tidy file, if any."),
       cl::init(""), cl::cat(ClangTidyCategory));

static cl::opt<std::string>
HeaderFilter("header-filter",
             cl::desc("Regular expression matching the names of the\n"
                      "headers to output diagnostics from. Diagnostics\n"
                      "from the main file of each translation unit are\n"
                      "always displayed.\n"
                      "Can be used together with -line-filter.\n"
                      "This option overrides the value read from a\n"
                      ".clang-tidy file."),
             cl::init(""), cl::cat(ClangTidyCategory));

static cl::opt<bool>
    SystemHeaders("system-headers",
                  cl::desc("Display the errors from system headers."),
                  cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<std::string>
LineFilter("line-filter",
           cl::desc("List of files with line ranges to filter the\n"
                    "warnings. Can be used together with\n"
                    "-header-filter. The format of the list is a JSON\n"
                    "array of objects:\n"
                    "  [\n"
                    "    {\"name\":\"file1.cpp\",\"lines\":[[1,3],[5,7]]},\n"
                    "    {\"name\":\"file2.h\"}\n"
                    "  ]"),
           cl::init(""), cl::cat(ClangTidyCategory));

static cl::opt<bool>
    Fix("fix", cl::desc("Apply suggested fixes. Without -fix-errors\n"
                        "clang-tidy will bail out if any compilation\n"
                        "errors were found."),
        cl::init(false), cl::cat(ClangTidyCategory));

static cl::opt<bool>
    FixErrors("fix-errors",
              cl::desc("Apply suggested fixes even if compilation errors\n"
                       "were found. If compiler errors have attached\n"
                       "fix-its, clang-tidy will apply them as well."),
              cl::init(false), cl::cat(ClangTidyCategory));

static cl::opt<bool>
ListChecks("list-checks",
           cl::desc("List all enabled checks and exit. Use with\n"
                    "-checks='*' to list all available checks."),
           cl::init(false), cl::cat(ClangTidyCategory));

static cl::opt<std::string> Config(
    "config",
    cl::desc("Specifies a configuration in YAML/JSON format:\n"
             "  -config=\"{Checks: '*', CheckOptions: [{key: x, value: y}]}\"\n"
             "When the value is empty, clang-tidy will attempt to find\n"
             "a file named .clang-tidy for each source file in its parent\n"
             "directories."),
    cl::init(""), cl::cat(ClangTidyCategory));

static cl::opt<bool> DumpConfig(
    "dump-config",
    cl::desc("Dumps configuration in the YAML format to stdout. This option\n"
             "should be used along with a file name (and '--' if the file is\n"
             "outside of a project with configured compilation database). The\n"
             "configuration used for this file will be printed."),
    cl::init(false), cl::cat(ClangTidyCategory));

static cl::opt<bool> EnableCheckProfile(
    "enable-check-profile",
    cl::desc("Enable per-check timing profiles, and print a report to stderr."),
    cl::init(false), cl::cat(ClangTidyCategory));

static cl::opt<bool> AnalyzeTemporaryDtors(
    "analyze-temporary-dtors",
    cl::desc("Enable temporary destructor-aware analysis in\n"
             "clang-analyzer- checks.\n"
             "This option overrides the value read from a\n"
             ".clang-tidy file."),
    cl::init(false), cl::cat(ClangTidyCategory));

static cl::opt<std::string> ExportFixes(
    "export-fixes",
    cl::desc("YAML file to store suggested fixes in. The\n"
             "stored fixes can be applied to the input source\n"
             "code with clang-apply-replacements."),
    cl::value_desc("filename"), cl::cat(ClangTidyCategory));

namespace clang {
namespace tidy {

static void printStats(const ClangTidyStats &Stats) {
  if (Stats.errorsIgnored()) {
    llvm::errs() << "Suppressed " << Stats.errorsIgnored() << " warnings (";
    StringRef Separator = "";
    if (Stats.ErrorsIgnoredNonUserCode) {
      llvm::errs() << Stats.ErrorsIgnoredNonUserCode << " in non-user code";
      Separator = ", ";
    }
    if (Stats.ErrorsIgnoredLineFilter) {
      llvm::errs() << Separator << Stats.ErrorsIgnoredLineFilter
                   << " due to line filter";
      Separator = ", ";
    }
    if (Stats.ErrorsIgnoredNOLINT) {
      llvm::errs() << Separator << Stats.ErrorsIgnoredNOLINT << " NOLINT";
      Separator = ", ";
    }
    if (Stats.ErrorsIgnoredCheckFilter)
      llvm::errs() << Separator << Stats.ErrorsIgnoredCheckFilter
                   << " with check filters";
    llvm::errs() << ").\n";
    if (Stats.ErrorsIgnoredNonUserCode)
      llvm::errs() << "Use -header-filter='.*' to display errors from all "
                      "non-system headers.\n";
  }
}

static void printProfileData(const ProfileData &Profile,
                             llvm::raw_ostream &OS) {
  // Time is first to allow for sorting by it.
  std::vector<std::pair<llvm::TimeRecord, StringRef>> Timers;
  TimeRecord Total;

  for (const auto& P : Profile.Records) {
    Timers.emplace_back(P.getValue(), P.getKey());
    Total += P.getValue();
  }

  std::sort(Timers.begin(), Timers.end());

  std::string Line = "===" + std::string(73, '-') + "===\n";
  OS << Line;

  if (Total.getUserTime())
    OS << "   ---User Time---";
  if (Total.getSystemTime())
    OS << "   --System Time--";
  if (Total.getProcessTime())
    OS << "   --User+System--";
  OS << "   ---Wall Time---";
  if (Total.getMemUsed())
    OS << "  ---Mem---";
  OS << "  --- Name ---\n";

  // Loop through all of the timing data, printing it out.
  for (auto I = Timers.rbegin(), E = Timers.rend(); I != E; ++I) {
    I->first.print(Total, OS);
    OS << I->second << '\n';
  }

  Total.print(Total, OS);
  OS << "Total\n";
  OS << Line << "\n";
  OS.flush();
}

std::unique_ptr<ClangTidyOptionsProvider> createOptionsProvider() {
  ClangTidyGlobalOptions GlobalOptions;
  if (std::error_code Err = parseLineFilter(LineFilter, GlobalOptions)) {
    llvm::errs() << "Invalid LineFilter: " << Err.message() << "\n\nUsage:\n";
    llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
    return nullptr;
  }

  ClangTidyOptions DefaultOptions;
  DefaultOptions.Checks = DefaultChecks;
  DefaultOptions.HeaderFilterRegex = HeaderFilter;
  DefaultOptions.SystemHeaders = SystemHeaders;
  DefaultOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
  DefaultOptions.User = llvm::sys::Process::GetEnv("USER");
  // USERNAME is used on Windows.
  if (!DefaultOptions.User)
    DefaultOptions.User = llvm::sys::Process::GetEnv("USERNAME");

  ClangTidyOptions OverrideOptions;
  if (Checks.getNumOccurrences() > 0)
    OverrideOptions.Checks = Checks;
  if (HeaderFilter.getNumOccurrences() > 0)
    OverrideOptions.HeaderFilterRegex = HeaderFilter;
  if (SystemHeaders.getNumOccurrences() > 0)
    OverrideOptions.SystemHeaders = SystemHeaders;
  if (AnalyzeTemporaryDtors.getNumOccurrences() > 0)
    OverrideOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;

  if (!Config.empty()) {
    if (llvm::ErrorOr<ClangTidyOptions> ParsedConfig =
            parseConfiguration(Config)) {
      return llvm::make_unique<DefaultOptionsProvider>(
          GlobalOptions, ClangTidyOptions::getDefaults()
                             .mergeWith(DefaultOptions)
                             .mergeWith(*ParsedConfig)
                             .mergeWith(OverrideOptions));
    } else {
      llvm::errs() << "Error: invalid configuration specified.\n"
                   << ParsedConfig.getError().message() << "\n";
      return nullptr;
    }
  }
  return llvm::make_unique<FileOptionsProvider>(GlobalOptions, DefaultOptions,
                                                OverrideOptions);
}

int clangTidyMain(int argc, const char **argv) {
  CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory);

  auto OptionsProvider = createOptionsProvider();
  if (!OptionsProvider)
    return 1;

  std::string FileName = OptionsParser.getSourcePathList().front();
  ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FileName);
  std::vector<std::string> EnabledChecks = getCheckNames(EffectiveOptions);

  // FIXME: Allow using --list-checks without positional arguments.
  if (ListChecks) {
    llvm::outs() << "Enabled checks:";
    for (auto CheckName : EnabledChecks)
      llvm::outs() << "\n    " << CheckName;
    llvm::outs() << "\n\n";
    return 0;
  }

  if (DumpConfig) {
    EffectiveOptions.CheckOptions = getCheckOptions(EffectiveOptions);
    llvm::outs() << configurationAsText(ClangTidyOptions::getDefaults()
                                            .mergeWith(EffectiveOptions))
                 << "\n";
    return 0;
  }

  if (EnabledChecks.empty()) {
    llvm::errs() << "Error: no checks enabled.\n";
    llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
    return 1;
  }

  ProfileData Profile;

  std::vector<ClangTidyError> Errors;
  ClangTidyStats Stats =
      runClangTidy(std::move(OptionsProvider), OptionsParser.getCompilations(),
                   OptionsParser.getSourcePathList(), &Errors,
                   EnableCheckProfile ? &Profile : nullptr);
  bool FoundErrors =
      std::find_if(Errors.begin(), Errors.end(), [](const ClangTidyError &E) {
        return E.DiagLevel == ClangTidyError::Error;
      }) != Errors.end();

  const bool DisableFixes = Fix && FoundErrors && !FixErrors;

  // -fix-errors implies -fix.
  handleErrors(Errors, (FixErrors || Fix) && !DisableFixes);

  if (!ExportFixes.empty() && !Errors.empty()) {
    std::error_code EC;
    llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None);
    if (EC) {
      llvm::errs() << "Error opening output file: " << EC.message() << '\n';
      return 1;
    }
    exportReplacements(Errors, OS);
  }

  printStats(Stats);
  if (DisableFixes)
    llvm::errs()
        << "Found compiler errors, but -fix-errors was not specified.\n"
           "Fixes have NOT been applied.\n\n";

  if (EnableCheckProfile)
    printProfileData(Profile, llvm::errs());

  return 0;
}

// This anchor is used to force the linker to link the LLVMModule.
extern volatile int LLVMModuleAnchorSource;
static int LLVMModuleAnchorDestination = LLVMModuleAnchorSource;

// This anchor is used to force the linker to link the GoogleModule.
extern volatile int GoogleModuleAnchorSource;
static int GoogleModuleAnchorDestination = GoogleModuleAnchorSource;

// This anchor is used to force the linker to link the MiscModule.
extern volatile int MiscModuleAnchorSource;
static int MiscModuleAnchorDestination = MiscModuleAnchorSource;

// This anchor is used to force the linker to link the ReadabilityModule.
extern volatile int ReadabilityModuleAnchorSource;
static int ReadabilityModuleAnchorDestination = ReadabilityModuleAnchorSource;

} // namespace tidy
} // namespace clang

int main(int argc, const char **argv) {
  return clang::tidy::clangTidyMain(argc, argv);
}
<|endoftext|>


<commit_before>#include "Mesh.h"
#include "DefaultRenderTypes.h"
#include "DefaultShaders.h"
#include "MeshManager.h"
#include "Utility.hpp"

using namespace Device;
using namespace Rendering;
using namespace Rendering::Geometry;
using namespace Rendering::Shader;
using namespace Rendering::Manager;
using namespace Rendering::Buffer;
using namespace Core;
using namespace Utility;
using namespace Math;
using namespace Intersection;

void Mesh::Initialize(Device::DirectX& dx, BufferManager& bufferMgr, const CreateFuncArguments& args)
{
	uint vertexCount	= args.vertices.count;
	uint indexCount		= args.indices.size();

	uint vbKey = Utility::String::MakeKey({ args.fileName, std::to_string(args.vbUserHashKey) });

	if (bufferMgr.GetPool<VertexBuffer>().Has(vbKey) == false)
	{
		VertexBuffer::Desc param;
		{
			param.stride		= args.vertices.byteWidth;
			param.vertexCount	= args.vertices.count;
		}

		VertexBuffer vb;
		vb.Initialize(dx, param, args.vertices.data, args.useDynamicVB, args.semanticInfos);

		bufferMgr.GetPool<VertexBuffer>().Add(vbKey, vb);
		_vbKey = vbKey;
	}

	uint ibKey = String::MakeKey({ args.fileName, args.ibPartID });
	if (bufferMgr.GetPool<IndexBuffer>().Has(ibKey) == false)
	{
		IndexBuffer ib;
		ib.Initialize(dx, args.indices, vbKey, args.useDynamicIB);

		bufferMgr.GetPool<IndexBuffer>().Add(ibKey, ib);
		_ibKey = ibKey;
	}

	_bufferFlag = ComputeBufferFlag(args.semanticInfos);

	_transformCB.Initialize(dx);
}

void Mesh::Initialize(DirectX& dx, const VertexBuffer::Semantics& semantics, BaseBuffer::Key vbKey, BaseBuffer::Key ibKey)
{
	_vbKey = vbKey;
	_ibKey = ibKey;

	_bufferFlag = ComputeBufferFlag(semantics);

	_transformCB.Initialize(dx);
}

uint Mesh::ComputeBufferFlag(const std::vector<VertexShader::SemanticInfo>& semantics, uint maxRecognizeBoneCount) const
{
	uint flag = 0;
	for (auto iter = semantics.begin(); iter != semantics.end(); ++iter)
	{
		const auto& semantic = *iter;

		if (semantic.name == "POSITION")		continue;
		else if (semantic.name == "TEXCOORD")
		{
			if (semantic.semanticIndex > 1)
				flag |= static_cast<uint>(DefaultVertexInputTypeFlag::USERS);
			else
				flag |= static_cast<uint>(DefaultVertexInputTypeFlag::UV0) << semantic.semanticIndex;
		}
		else if (semantic.name == "NORMAL")
			flag |= static_cast<uint>(DefaultVertexInputTypeFlag::NORMAL);
		else if (semantic.name == "TANGENT")
			flag |= static_cast<uint>(DefaultVertexInputTypeFlag::TANGENT);
		else if (semantic.name == "COLOR")
			flag |= static_cast<uint>(DefaultVertexInputTypeFlag::COLOR);
		else if (semantic.name == "BONEWEIGHT")
		{
			if (semantic.semanticIndex + 1 >= maxRecognizeBoneCount)
				flag |= static_cast<uint>(DefaultVertexInputTypeFlag::BONE) << semantic.semanticIndex;
			else
				flag |= static_cast<uint>(DefaultVertexInputTypeFlag::USERS);
		}
		else
		{
			flag |= static_cast<uint>(DefaultVertexInputTypeFlag::USERS);
		}
	}

	// Error, You use undefined semantic in RenderManager::DefaultVertexInputTypeFlag.
	assert((flag & static_cast<uint>(DefaultVertexInputTypeFlag::USERS)) == 0);

	return flag;
}

void Mesh::CalcWorldSize(Math::Vector3& worldMin, Math::Vector3& worldMax, const Core::Transform& transform) const
{
	Vector3 extents		= _boundBox.GetExtents();
	Vector3 boxCenter	= _boundBox.GetCenter();

	const Matrix& worldMat	= transform.GetWorldMatrix();
	Vector3 worldPos		= Vector3(worldMat._41, worldMat._42, worldMat._43) + boxCenter;

	Vector3 worldScale = transform.GetWorldScale();

	Vector3 minPos = worldPos - (extents * worldScale);
	Vector3 maxPos = worldPos + (extents * worldScale);

	if (worldMin.x > minPos.x) worldMin.x = minPos.x;
	if (worldMin.y > minPos.y) worldMin.y = minPos.y;
	if (worldMin.z > minPos.z) worldMin.z = minPos.z;

	if (worldMax.x < maxPos.x) worldMax.x = maxPos.x;
	if (worldMax.y < maxPos.y) worldMax.y = maxPos.y;
	if (worldMax.z < maxPos.z) worldMax.z = maxPos.z;
}

void Mesh::UpdateTransformCB(DirectX& dx, const Transform& transform)
{
	assert(transform.GetObjectID() == _objectID);

	if(transform.GetDirty())
		_tfChangeState = TransformCB::ChangeState::HasChanged;

	assert(_tfChangeState != TransformCB::ChangeState::No);

	const Matrix& worldMat = transform.GetWorldMatrix();

	TransformCB tfCB;
	tfCB.world				= Matrix::Transpose(worldMat);
	tfCB.prevWorld			= Matrix::Transpose(_prevWorldMat);
	tfCB.worldInvTranspose	= Matrix::Inverse(tfCB.world);
	_transformCB.UpdateSubResource(dx, tfCB);

	_prevWorldMat = worldMat;
	_tfChangeState = TransformCB::ChangeState((static_cast<uint>(_tfChangeState) + 1) % static_cast<uint>(TransformCB::ChangeState::MAX));
}
<commit_msg>Mesh - worldInvTranspose가 제대로 계산되지 않고 constant buffer로 넘어가던 문제 수정 -_-..<commit_after>#include "Mesh.h"
#include "DefaultRenderTypes.h"
#include "DefaultShaders.h"
#include "MeshManager.h"
#include "Utility.hpp"

using namespace Device;
using namespace Rendering;
using namespace Rendering::Geometry;
using namespace Rendering::Shader;
using namespace Rendering::Manager;
using namespace Rendering::Buffer;
using namespace Core;
using namespace Utility;
using namespace Math;
using namespace Intersection;

void Mesh::Initialize(Device::DirectX& dx, BufferManager& bufferMgr, const CreateFuncArguments& args)
{
	uint vertexCount	= args.vertices.count;
	uint indexCount		= args.indices.size();

	uint vbKey = Utility::String::MakeKey({ args.fileName, std::to_string(args.vbUserHashKey) });

	if (bufferMgr.GetPool<VertexBuffer>().Has(vbKey) == false)
	{
		VertexBuffer::Desc param;
		{
			param.stride		= args.vertices.byteWidth;
			param.vertexCount	= args.vertices.count;
		}

		VertexBuffer vb;
		vb.Initialize(dx, param, args.vertices.data, args.useDynamicVB, args.semanticInfos);

		bufferMgr.GetPool<VertexBuffer>().Add(vbKey, vb);
		_vbKey = vbKey;
	}

	uint ibKey = String::MakeKey({ args.fileName, args.ibPartID });
	if (bufferMgr.GetPool<IndexBuffer>().Has(ibKey) == false)
	{
		IndexBuffer ib;
		ib.Initialize(dx, args.indices, vbKey, args.useDynamicIB);

		bufferMgr.GetPool<IndexBuffer>().Add(ibKey, ib);
		_ibKey = ibKey;
	}

	_bufferFlag = ComputeBufferFlag(args.semanticInfos);

	_transformCB.Initialize(dx);
}

void Mesh::Initialize(DirectX& dx, const VertexBuffer::Semantics& semantics, BaseBuffer::Key vbKey, BaseBuffer::Key ibKey)
{
	_vbKey = vbKey;
	_ibKey = ibKey;

	_bufferFlag = ComputeBufferFlag(semantics);

	_transformCB.Initialize(dx);
}

uint Mesh::ComputeBufferFlag(const std::vector<VertexShader::SemanticInfo>& semantics, uint maxRecognizeBoneCount) const
{
	uint flag = 0;
	for (auto iter = semantics.begin(); iter != semantics.end(); ++iter)
	{
		const auto& semantic = *iter;

		if (semantic.name == "POSITION")		continue;
		else if (semantic.name == "TEXCOORD")
		{
			if (semantic.semanticIndex > 1)
				flag |= static_cast<uint>(DefaultVertexInputTypeFlag::USERS);
			else
				flag |= static_cast<uint>(DefaultVertexInputTypeFlag::UV0) << semantic.semanticIndex;
		}
		else if (semantic.name == "NORMAL")
			flag |= static_cast<uint>(DefaultVertexInputTypeFlag::NORMAL);
		else if (semantic.name == "TANGENT")
			flag |= static_cast<uint>(DefaultVertexInputTypeFlag::TANGENT);
		else if (semantic.name == "COLOR")
			flag |= static_cast<uint>(DefaultVertexInputTypeFlag::COLOR);
		else if (semantic.name == "BONEWEIGHT")
		{
			if (semantic.semanticIndex + 1 >= maxRecognizeBoneCount)
				flag |= static_cast<uint>(DefaultVertexInputTypeFlag::BONE) << semantic.semanticIndex;
			else
				flag |= static_cast<uint>(DefaultVertexInputTypeFlag::USERS);
		}
		else
		{
			flag |= static_cast<uint>(DefaultVertexInputTypeFlag::USERS);
		}
	}

	// Error, You use undefined semantic in RenderManager::DefaultVertexInputTypeFlag.
	assert((flag & static_cast<uint>(DefaultVertexInputTypeFlag::USERS)) == 0);

	return flag;
}

void Mesh::CalcWorldSize(Math::Vector3& worldMin, Math::Vector3& worldMax, const Core::Transform& transform) const
{
	Vector3 extents		= _boundBox.GetExtents();
	Vector3 boxCenter	= _boundBox.GetCenter();

	const Matrix& worldMat	= transform.GetWorldMatrix();
	Vector3 worldPos		= Vector3(worldMat._41, worldMat._42, worldMat._43) + boxCenter;

	Vector3 worldScale = transform.GetWorldScale();

	Vector3 minPos = worldPos - (extents * worldScale);
	Vector3 maxPos = worldPos + (extents * worldScale);

	if (worldMin.x > minPos.x) worldMin.x = minPos.x;
	if (worldMin.y > minPos.y) worldMin.y = minPos.y;
	if (worldMin.z > minPos.z) worldMin.z = minPos.z;

	if (worldMax.x < maxPos.x) worldMax.x = maxPos.x;
	if (worldMax.y < maxPos.y) worldMax.y = maxPos.y;
	if (worldMax.z < maxPos.z) worldMax.z = maxPos.z;
}

void Mesh::UpdateTransformCB(DirectX& dx, const Transform& transform)
{
	assert(transform.GetObjectID() == _objectID);

	if(transform.GetDirty())
		_tfChangeState = TransformCB::ChangeState::HasChanged;

	assert(_tfChangeState != TransformCB::ChangeState::No);

	const Matrix& worldMat = transform.GetWorldMatrix();

	TransformCB tfCB;
	tfCB.world				= Matrix::Transpose(worldMat);
	tfCB.prevWorld			= Matrix::Transpose(_prevWorldMat);
	tfCB.worldInvTranspose	= Matrix::Inverse(worldMat);
	_transformCB.UpdateSubResource(dx, tfCB);

	_prevWorldMat = worldMat;
	_tfChangeState = TransformCB::ChangeState((static_cast<uint>(_tfChangeState) + 1) % static_cast<uint>(TransformCB::ChangeState::MAX));
}
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org

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

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

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

#include "OgreRay.h"

using namespace Ogre;
using namespace OgreBites;
using namespace Ogre::Volume;

void Sample_VolumeTerrain::setupContent(void)
{
    setupControls();

    // Skydome
    mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8);

    // Light
    Light* directionalLight0 = mSceneMgr->createLight("directionalLight0");
    directionalLight0->setType(Light::LT_DIRECTIONAL);
    directionalLight0->setDirection(Vector3((Real)1, (Real)-1, (Real)1));
    directionalLight0->setDiffuseColour((Real)1, (Real)0.98, (Real)0.73);
    directionalLight0->setSpecularColour((Real)0.1, (Real)0.1, (Real)0.1);

    // Volume
    mVolumeRoot = OGRE_NEW Chunk();
    SceneNode *volumeRootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("VolumeParent");
    mVolumeRoot->load(volumeRootNode, mSceneMgr, "volumeTerrain.cfg", &mSource);

    // Camera
    mCamera->setPosition((Real)(2560 - 384), (Real)2000, (Real)(2560 - 384));
    mCamera->lookAt((Real)0, (Real)100, (Real)0);
    mCamera->setNearClipDistance((Real)0.5);

}

//-----------------------------------------------------------------------

void Sample_VolumeTerrain::setupControls(void)
{
    mTrayMgr->showCursor();
#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS
        setDragLook(true);
#endif
    mCameraMan->setTopSpeed((Real)100.0);
    // make room for the volume
    mTrayMgr->showLogo(TL_TOPRIGHT);
    mTrayMgr->showFrameStats(TL_TOPRIGHT);
    mTrayMgr->toggleAdvancedFrameStats();

    mTrayMgr->createTextBox(TL_TOPLEFT, "VolumeTerrainHelp", "Usage:\n\nHold the left mouse button,\n press wasd for movement\nand move the mouse for\n the direction.\nYou can place white spheres\nwith the middle mouse\nbutton like in an ego-shooter.", 265, 160);
}

//-----------------------------------------------------------------------

void Sample_VolumeTerrain::cleanupContent(void)
{
    OGRE_DELETE mVolumeRoot;
    delete mSource;
    mVolumeRoot = 0;
}

//-----------------------------------------------------------------------

Sample_VolumeTerrain::Sample_VolumeTerrain(void) : mVolumeRoot(0), mHideAll(false)
{
    mInfo["Title"] = "Volume Terrain";
    mInfo["Description"] = "Demonstrates a volumetric terrain defined by an 3D texture and ray intersection with a volume.";
    mInfo["Thumbnail"] = "thumb_volumeterrain.png";
    mInfo["Category"] = "Geometry";
}

//-----------------------------------------------------------------------

bool Sample_VolumeTerrain::keyPressed(const OIS::KeyEvent& evt)
{
    if (evt.key == OIS::KC_F10)
    {
        mVolumeRoot->setVolumeVisible(!mVolumeRoot->getVolumeVisible());
    }
    if (evt.key == OIS::KC_F11)
    {
        mVolumeRoot->setOctreeVisible(!mVolumeRoot->getOctreeVisible());
    }
    if (evt.key == OIS::KC_F12)
    {
        mVolumeRoot->setDualGridVisible(!mVolumeRoot->getDualGridVisible());
    }
    if (evt.key == OIS::KC_H)
    {
        if (mHideAll)
        {
            mTrayMgr->showAll();
        }
        else
        {
            mTrayMgr->hideAll();
        }
        mHideAll = !mHideAll;
    }
    return SdkSample::keyPressed(evt);
}

//-----------------------------------------------------------------------

void Sample_VolumeTerrain::shootRay(Ray ray)
{
        Vector3 intersection;
        bool intersects = mSource->getFirstRayIntersection(ray, intersection);
        static int intersectionName = 0;
        if (intersects)
        {
            intersectionName++;
            SceneNode *n = mSceneMgr->getRootSceneNode()->createChildSceneNode();
            n->translate(intersection * mVolumeRoot->getScale());
            n->scale(Vector3((Real)0.05));
            Entity * mcSphere = mSceneMgr->createEntity("intersection" + StringConverter::toString(intersectionName), "sphere.mesh");
            n->attachObject(mcSphere);
        }
}

//-----------------------------------------------------------------------

bool Sample_VolumeTerrain::mousePressed(const OIS::MouseEvent& evt, OIS::MouseButtonID id)
{

    if (id == OIS::MB_Middle)
    {
            LogManager::getSingleton().stream() << "SCALE: " << mVolumeRoot->getScale();
        Ray ray(mCamera->getPosition() / mVolumeRoot->getScale(), -mCamera->getOrientation().zAxis());
        shootRay(ray);
    }

    return SdkSample::mousePressed(evt, id);
}

//-----------------------------------------------------------------------

#ifndef OGRE_STATIC_LIB

SamplePlugin* sp;
Sample* s;

//-----------------------------------------------------------------------

extern "C" _OgreSampleExport void dllStartPlugin()
{
    s = new Sample_VolumeTerrain();
    sp = OGRE_NEW SamplePlugin(s->getInfo()["Title"] + " Sample");
    sp->addSample(s);
    Root::getSingleton().installPlugin(sp);
}

//-----------------------------------------------------------------------

extern "C" _OgreSampleExport void dllStopPlugin()
{
    Root::getSingleton().uninstallPlugin(sp);
    OGRE_DELETE sp;
    delete s;
}

#endif
<commit_msg>Volume Rendering: removed debug log<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org

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

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

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

#include "OgreRay.h"

using namespace Ogre;
using namespace OgreBites;
using namespace Ogre::Volume;

void Sample_VolumeTerrain::setupContent(void)
{
    setupControls();

    // Skydome
    mSceneMgr->setSkyDome(true, "Examples/CloudySky", 5, 8);

    // Light
    Light* directionalLight0 = mSceneMgr->createLight("directionalLight0");
    directionalLight0->setType(Light::LT_DIRECTIONAL);
    directionalLight0->setDirection(Vector3((Real)1, (Real)-1, (Real)1));
    directionalLight0->setDiffuseColour((Real)1, (Real)0.98, (Real)0.73);
    directionalLight0->setSpecularColour((Real)0.1, (Real)0.1, (Real)0.1);

    // Volume
    mVolumeRoot = OGRE_NEW Chunk();
    SceneNode *volumeRootNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("VolumeParent");
    mVolumeRoot->load(volumeRootNode, mSceneMgr, "volumeTerrain.cfg", &mSource);

    // Camera
    mCamera->setPosition((Real)(2560 - 384), (Real)2000, (Real)(2560 - 384));
    mCamera->lookAt((Real)0, (Real)100, (Real)0);
    mCamera->setNearClipDistance((Real)0.5);

}

//-----------------------------------------------------------------------

void Sample_VolumeTerrain::setupControls(void)
{
    mTrayMgr->showCursor();
#if OGRE_PLATFORM != OGRE_PLATFORM_APPLE_IOS
        setDragLook(true);
#endif
    mCameraMan->setTopSpeed((Real)100.0);
    // make room for the volume
    mTrayMgr->showLogo(TL_TOPRIGHT);
    mTrayMgr->showFrameStats(TL_TOPRIGHT);
    mTrayMgr->toggleAdvancedFrameStats();

    mTrayMgr->createTextBox(TL_TOPLEFT, "VolumeTerrainHelp", "Usage:\n\nHold the left mouse button,\n press wasd for movement\nand move the mouse for\n the direction.\nYou can place white spheres\nwith the middle mouse\nbutton like in an ego-shooter.", 265, 160);
}

//-----------------------------------------------------------------------

void Sample_VolumeTerrain::cleanupContent(void)
{
    OGRE_DELETE mVolumeRoot;
    delete mSource;
    mVolumeRoot = 0;
}

//-----------------------------------------------------------------------

Sample_VolumeTerrain::Sample_VolumeTerrain(void) : mVolumeRoot(0), mHideAll(false)
{
    mInfo["Title"] = "Volume Terrain";
    mInfo["Description"] = "Demonstrates a volumetric terrain defined by an 3D texture and ray intersection with a volume.";
    mInfo["Thumbnail"] = "thumb_volumeterrain.png";
    mInfo["Category"] = "Geometry";
}

//-----------------------------------------------------------------------

bool Sample_VolumeTerrain::keyPressed(const OIS::KeyEvent& evt)
{
    if (evt.key == OIS::KC_F10)
    {
        mVolumeRoot->setVolumeVisible(!mVolumeRoot->getVolumeVisible());
    }
    if (evt.key == OIS::KC_F11)
    {
        mVolumeRoot->setOctreeVisible(!mVolumeRoot->getOctreeVisible());
    }
    if (evt.key == OIS::KC_F12)
    {
        mVolumeRoot->setDualGridVisible(!mVolumeRoot->getDualGridVisible());
    }
    if (evt.key == OIS::KC_H)
    {
        if (mHideAll)
        {
            mTrayMgr->showAll();
        }
        else
        {
            mTrayMgr->hideAll();
        }
        mHideAll = !mHideAll;
    }
    return SdkSample::keyPressed(evt);
}

//-----------------------------------------------------------------------

void Sample_VolumeTerrain::shootRay(Ray ray)
{
        Vector3 intersection;
        bool intersects = mSource->getFirstRayIntersection(ray, intersection);
        static int intersectionName = 0;
        if (intersects)
        {
            intersectionName++;
            SceneNode *n = mSceneMgr->getRootSceneNode()->createChildSceneNode();
            n->translate(intersection * mVolumeRoot->getScale());
            n->scale(Vector3((Real)0.05));
            Entity * mcSphere = mSceneMgr->createEntity("intersection" + StringConverter::toString(intersectionName), "sphere.mesh");
            n->attachObject(mcSphere);
        }
}

//-----------------------------------------------------------------------

bool Sample_VolumeTerrain::mousePressed(const OIS::MouseEvent& evt, OIS::MouseButtonID id)
{

    if (id == OIS::MB_Middle)
    {
        Ray ray(mCamera->getPosition() / mVolumeRoot->getScale(), -mCamera->getOrientation().zAxis());
        shootRay(ray);
    }

    return SdkSample::mousePressed(evt, id);
}

//-----------------------------------------------------------------------

#ifndef OGRE_STATIC_LIB

SamplePlugin* sp;
Sample* s;

//-----------------------------------------------------------------------

extern "C" _OgreSampleExport void dllStartPlugin()
{
    s = new Sample_VolumeTerrain();
    sp = OGRE_NEW SamplePlugin(s->getInfo()["Title"] + " Sample");
    sp->addSample(s);
    Root::getSingleton().installPlugin(sp);
}

//-----------------------------------------------------------------------

extern "C" _OgreSampleExport void dllStopPlugin()
{
    Root::getSingleton().uninstallPlugin(sp);
    OGRE_DELETE sp;
    delete s;
}

#endif
<|endoftext|>


<commit_before>#include "heating.h"

char target_temperature = 25;
bool heating_active = false;

long int resistors_time = 0;

void init_heating(){
    pinMode(heating, OUTPUT);
}

void change_temperature_target(){

        long int button_press = 0;
        bool target_temperature_changed = true;

        while(digitalRead(button_3) == LOW){

            if(digitalRead(button_1) == HIGH && millis() - button_press > 200){
                button_press = millis();
                lower_target_temperature();
                target_temperature_changed = true;
            }
            else if(digitalRead(button_2) == HIGH && millis() - button_press > 200){
                button_press = millis();
                raise_target_temperature();
                target_temperature_changed = true;
            }

            if(target_temperature > 30){
                target_temperature = 30;
            }

            if(target_temperature_changed){
                get_lcd()->clear();
                get_lcd()->setCursor(0,0);
                get_lcd()->print("Set target temp:");
                get_lcd()->setCursor(13,1);
                get_lcd()->print((int)target_temperature);
                get_lcd()->print((char)223);
                get_lcd()->print("C");
                target_temperature_changed = false;
            }

            delay(50);

        }
}

void raise_target_temperature(){
    target_temperature++;
    check_temperature();
}

void lower_target_temperature(){
    target_temperature--;
    check_temperature();
}

void check_temperature(){

    if(get_sensor_values().temperature < target_temperature){

        if(millis() - resistors_time > 90000){
            digitalWrite(heating, HIGH);
            resistors_time = millis();
        }
        else if(millis() - resistors_time < 90000 && millis() - resistors_time > 60000){
            digitalWrite(heating, LOW);
        }

    }
    else{
        digitalWrite(heating, LOW);
    }

}
<commit_msg>Made the heating go on for longer periods of time<commit_after>#include "heating.h"

char target_temperature = 25;
bool heating_active = false;

long int resistors_time = 0;

void init_heating(){
    pinMode(heating, OUTPUT);
}

void change_temperature_target(){

        long int button_press = 0;
        bool target_temperature_changed = true;

        while(digitalRead(button_3) == LOW){

            if(digitalRead(button_1) == HIGH && millis() - button_press > 200){
                button_press = millis();
                lower_target_temperature();
                target_temperature_changed = true;
            }
            else if(digitalRead(button_2) == HIGH && millis() - button_press > 200){
                button_press = millis();
                raise_target_temperature();
                target_temperature_changed = true;
            }

            if(target_temperature > 30){
                target_temperature = 30;
            }

            if(target_temperature_changed){
                get_lcd()->clear();
                get_lcd()->setCursor(0,0);
                get_lcd()->print("Set target temp:");
                get_lcd()->setCursor(13,1);
                get_lcd()->print((int)target_temperature);
                get_lcd()->print((char)223);
                get_lcd()->print("C");
                target_temperature_changed = false;
            }

            delay(50);

        }
}

void raise_target_temperature(){
    target_temperature++;
    check_temperature();
}

void lower_target_temperature(){
    target_temperature--;
    check_temperature();
}

void check_temperature(){

    if(get_sensor_values().temperature < target_temperature){

        if(millis() - resistors_time < 60*1000*3){
            digitalWrite(heating, HIGH);
        }
        else if(millis() - resistors_time > 60*1000*3 + 30000){
            resistors_time = millis();
        }
        else{
            digitalWrite(heating, LOW);
        }

    }
    else{
        digitalWrite(heating, LOW);
    }

}
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// QUESO - a library to support the Quantification of Uncertainty
// for Estimation, Simulation and Optimization
//
// Copyright (C) 2008,2009,2010,2011,2012,2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-
//
// $Id$
//
//--------------------------------------------------------------------------

#include <queso/MpiComm.h>
#include <queso/Environment.h>

namespace QUESO {

// Default constructor ------------------------------
MpiComm::MpiComm()
  :
  m_env( *(new EmptyEnvironment()) )
{
  UQ_FATAL_TEST_MACRO(true,
                      UQ_UNAVAILABLE_RANK,
                      "MpiComm::constructor()",
                      "should not be called");
}
// QUESO MpiComm MPI Constructor ------------------
MpiComm::MpiComm(const BaseEnvironment& env, RawType_MPI_Comm inputRawComm)
  :
  m_env          (env),
#ifdef QUESO_HAS_TRILINOS
  m_epetraMpiComm( new Epetra_MpiComm(inputRawComm) ),
#endif
  m_rawComm      (inputRawComm),
  m_worldRank    (-1),
  m_myPid        (-1),
  m_numProc      (-1)
{
#ifdef QUESO_HAS_MPI
  int mpiRC = MPI_Comm_rank(MPI_COMM_WORLD,&m_worldRank);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      UQ_UNAVAILABLE_RANK,
                      "MpiComm::constructor()",
                      "failed MPI_Comm_rank() on MPI_COMM_WORLD");

  mpiRC = MPI_Comm_rank(inputRawComm,&m_myPid);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      m_worldRank,
                      "MpiComm::constructor()",
                      "failed MPI_Comm_rank() on inputRawComm");

  mpiRC = MPI_Comm_size(inputRawComm,&m_numProc);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      m_worldRank,
                      "MpiComm::constructor()",
                      "failed MPI_Comm_size() on inputRawComm");
#else
  m_worldRank = 0;
  m_myPid     = 0;
  m_numProc   = 1;
#endif
}

// Copy constructor ---------------------------------
MpiComm::MpiComm(const MpiComm& src)
  :
  m_env          (src.m_env)
#ifdef QUESO_HAS_TRILINOS
  ,
  m_epetraMpiComm(NULL)
#endif
{
  this->copy(src);
}

// Destructor ---------------------------------------
MpiComm::~MpiComm()
{
#ifdef QUESO_HAS_TRILINOS
  delete m_epetraMpiComm;
  m_epetraMpiComm = NULL;
#endif
}

// --------------------------------------------------
// Set methodos -------------------------------------
MpiComm&
MpiComm::operator=(const MpiComm& rhs)
{
  this->copy(rhs);
  return *this;
}

// Attribute access methods -------------------------
RawType_MPI_Comm
MpiComm::Comm() const
{
#ifdef QUESO_HAS_TRILINOS
  return m_epetraMpiComm->Comm();
#endif
  return m_rawComm;
}
// --------------------------------------------------
int
MpiComm::MyPID() const
{
#ifdef QUESO_HAS_TRILINOS
  return m_epetraMpiComm->MyPID();
#endif
  return m_myPid;
}
// --------------------------------------------------
int
MpiComm::NumProc() const
{
#ifdef QUESO_HAS_TRILINOS
  return m_epetraMpiComm->NumProc();
#endif
  return m_numProc;
}
// Methods overridden from Comm ---------------------

void
MpiComm::Allreduce(void* sendbuf, void* recvbuf, int count, RawType_MPI_Datatype datatype, RawType_MPI_Op op, const char* whereMsg, const char* whatMsg) const
{
#ifdef QUESO_HAS_MPI
  int mpiRC = MPI_Allreduce(sendbuf, recvbuf, count, datatype, op, m_rawComm);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
#else
  size_t dataTypeSize = sizeOfDataType(datatype, whereMsg, whatMsg);
  size_t dataTotal = dataTypeSize*count;
  memcpy(recvbuf, sendbuf, dataTotal);
#endif

  return;
}
//--------------------------------------------------
void
MpiComm::Barrier() const // const char* whereMsg, const char* whatMsg) const
{
#ifdef QUESO_HAS_TRILINOS
  return m_epetraMpiComm->Barrier();
#endif
#ifdef QUESO_HAS_MPI
  int mpiRC = MPI_Barrier(m_rawComm);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      m_worldRank,
                      "MPIComm::Barrier()", // whereMsg,
                      "mpiRC indicates failure");  // whatMsg);
#else
  // Nothing needs to be done
#endif
  return;
}
//--------------------------------------------------
void
MpiComm::Bcast(void* buffer, int count, RawType_MPI_Datatype datatype, int root, const char* whereMsg, const char* whatMsg) const
{
#ifdef QUESO_HAS_MPI
  int mpiRC = MPI_Bcast(buffer, count, datatype, root, m_rawComm);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
#else
  // Nothing needs to be done
#endif
  return;
}
//--------------------------------------------------
void
MpiComm::Gather(
  void* sendbuf, int sendcnt, RawType_MPI_Datatype sendtype,
  void* recvbuf, int recvcount, RawType_MPI_Datatype recvtype,
  int root,
  const char* whereMsg, const char* whatMsg) const
{
  //int MPI_Gather (void *sendbuf, int sendcnt, MPI_Datatype sendtype,
  //                void *recvbuf, int recvcount, MPI_Datatype recvtype,
  //                int root, MPI_Comm comm )
#ifdef QUESO_HAS_MPI
  int mpiRC = MPI_Gather(sendbuf, sendcnt, sendtype,
                         recvbuf, recvcount, recvtype,
                         root, m_rawComm);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
#else
  size_t sendDataTypeSize = sizeOfDataType(sendtype, whereMsg, whatMsg);
  size_t recvDataTypeSize = sizeOfDataType(recvtype, whereMsg, whatMsg);
  size_t sendTotal = sendDataTypeSize*sendcnt;
  size_t recvTotal = recvDataTypeSize*recvcount;
  if (sendTotal != recvTotal) {
    std::cerr << "MpiComm::Gather()"
              << ": sendTotal != recvTotal"
              << std::endl;
  }
  UQ_FATAL_TEST_MACRO(sendTotal != recvTotal,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
  memcpy(recvbuf, sendbuf, sendTotal);
#endif
  return;
}
//--------------------------------------------------
void
MpiComm::Gatherv(
  void* sendbuf, int sendcnt, RawType_MPI_Datatype sendtype,
  void* recvbuf, int* recvcnts, int* displs, RawType_MPI_Datatype recvtype,
  int root,
  const char* whereMsg, const char* whatMsg) const
{
  //int MPI_Gatherv(void *sendbuf, int sendcnt, MPI_Datatype sendtype,
  //                void *recvbuf, int *recvcnts, int *displs, MPI_Datatype recvtype,
  //                int root, MPI_Comm comm )
#ifdef QUESO_HAS_MPI
  int mpiRC = MPI_Gatherv(sendbuf, sendcnt, sendtype,
                          recvbuf, recvcnts, displs, recvtype,
                          root, m_rawComm);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
#else
  size_t sendDataTypeSize = sizeOfDataType(sendtype, whereMsg, whatMsg);
  size_t recvDataTypeSize = sizeOfDataType(recvtype, whereMsg, whatMsg);
  size_t sendTotal = sendDataTypeSize*sendcnt;
  size_t recvTotal = recvDataTypeSize*recvcnts[0];
  if (sendTotal != recvTotal) {
    std::cerr << "MpiComm::Gatherv()"
              << ": sendTotal != recvTotal"
              << std::endl;
  }
  UQ_FATAL_TEST_MACRO(sendTotal != recvTotal,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
  memcpy(recvbuf, sendbuf, sendTotal);
#endif
  return;
}
//--------------------------------------------------
void
MpiComm::Recv(
  void* buf, int count, RawType_MPI_Datatype datatype, int source, int tag, RawType_MPI_Status* status,
  const char* whereMsg, const char* whatMsg) const
{
#ifdef QUESO_HAS_MPI
  int mpiRC = MPI_Recv(buf, count, datatype, source, tag, m_rawComm, status);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
#else
  std::cerr << "MpiComm::Recv()"
            << ": should note be used if there is no 'mpi'"
            << std::endl;
  UQ_FATAL_TEST_MACRO(true,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
#endif
  return;
}
//--------------------------------------------------
void
MpiComm::Send(
  void* buf, int count, RawType_MPI_Datatype datatype, int dest, int tag,
  const char* whereMsg, const char* whatMsg) const
{
#ifdef QUESO_HAS_MPI
  int mpiRC = MPI_Send(buf, count, datatype, dest, tag, m_rawComm);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
#else
  std::cerr << "MpiComm::Send()"
            << ": should note be used if there is no 'mpi'"
            << std::endl;
  UQ_FATAL_TEST_MACRO(true,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
#endif
  return;
}
// Misc methods ------------------------------------
void
MpiComm::syncPrintDebugMsg(const char* msg, unsigned int msgVerbosity, unsigned int numUSecs) const
{
  if (m_env.syncVerbosity() >= msgVerbosity) {
    this->Barrier();
    for (int i = 0; i < this->NumProc(); ++i) {
      if (i == this->MyPID()) {
        std::cout << msg
                  << ": fullRank "       << m_env.fullRank()
                  << ", subEnvironment " << m_env.subId()
                  << ", subRank "        << m_env.subRank()
                  << ", inter0Rank "     << m_env.inter0Rank()
                  << std::endl;
      }
      usleep(numUSecs);
      this->Barrier();
    }
    //if (this->fullRank() == 0) std::cout << "Sleeping " << numUSecs << " microseconds..."
    //                                     << std::endl;
    //usleep(numUSecs);
    this->Barrier();
  }

  return;
}
// -------------------------------------------------
#ifdef QUESO_HAS_TRILINOS
const Epetra_MpiComm&
MpiComm::epetraMpiComm() const
{
  return *m_epetraMpiComm;
}
#endif

// Private methods----------------------------------
void
MpiComm::copy(const MpiComm& src)
{
#ifdef QUESO_HAS_TRILINOS
  delete m_epetraMpiComm;
  m_epetraMpiComm = new Epetra_MpiComm(*src.m_epetraMpiComm);
#endif
  m_rawComm   = src.m_rawComm;
  m_worldRank = src.m_worldRank;
  m_myPid     = src.m_myPid;
  m_numProc   = src.m_numProc;

  return;
}
// -------------------------------------------------
#ifdef QUESO_HAS_MPI
#else
size_t
MpiComm::sizeOfDataType(RawType_MPI_Datatype datatype, const char* whereMsg, const char* whatMsg) const
{
  size_t dataTypeSize = 0;

  switch (datatype) {
    case RawValue_MPI_CHAR:
      dataTypeSize = sizeof(char);
    break;

    case RawValue_MPI_INT:
      dataTypeSize = sizeof(int);
    break;

    case RawValue_MPI_DOUBLE:
      dataTypeSize = sizeof(double);
    break;

    case RawValue_MPI_UNSIGNED:
      dataTypeSize = sizeof(unsigned int);
    break;

    default:
      std::cerr << "MpiComm::Allreduce()"
                << ": datatype not supported yet"
                << std::endl;
      UQ_FATAL_TEST_MACRO(true,
                          m_worldRank,
                          whereMsg,
                          whatMsg);
    break;
  }

  return dataTypeSize;
}
#endif

}  // End namespace QUESO
<commit_msg>[queso]: replacing references to MPI_COMM_WORLD with communicator passed to queso.<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// QUESO - a library to support the Quantification of Uncertainty
// for Estimation, Simulation and Optimization
//
// Copyright (C) 2008,2009,2010,2011,2012,2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-
//
// $Id$
//
//--------------------------------------------------------------------------

#include <queso/MpiComm.h>
#include <queso/Environment.h>

namespace QUESO {

// Default constructor ------------------------------
MpiComm::MpiComm()
  :
  m_env( *(new EmptyEnvironment()) )
{
  UQ_FATAL_TEST_MACRO(true,
                      UQ_UNAVAILABLE_RANK,
                      "MpiComm::constructor()",
                      "should not be called");
}
// QUESO MpiComm MPI Constructor ------------------
MpiComm::MpiComm(const BaseEnvironment& env, RawType_MPI_Comm inputRawComm)
  :
  m_env          (env),
#ifdef QUESO_HAS_TRILINOS
  m_epetraMpiComm( new Epetra_MpiComm(inputRawComm) ),
#endif
  m_rawComm      (inputRawComm),
  m_worldRank    (-1),
  m_myPid        (-1),
  m_numProc      (-1)
{
#ifdef QUESO_HAS_MPI
  int mpiRC = MPI_Comm_rank(inputRawComm,&m_worldRank);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      UQ_UNAVAILABLE_RANK,
                      "MpiComm::constructor()",
                      "failed MPI_Comm_rank() on full rank");

  mpiRC = MPI_Comm_rank(inputRawComm,&m_myPid);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      m_worldRank,
                      "MpiComm::constructor()",
                      "failed MPI_Comm_rank() on inputRawComm");

  mpiRC = MPI_Comm_size(inputRawComm,&m_numProc);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      m_worldRank,
                      "MpiComm::constructor()",
                      "failed MPI_Comm_size() on inputRawComm");
#else
  m_worldRank = 0;
  m_myPid     = 0;
  m_numProc   = 1;
#endif
}

// Copy constructor ---------------------------------
MpiComm::MpiComm(const MpiComm& src)
  :
  m_env          (src.m_env)
#ifdef QUESO_HAS_TRILINOS
  ,
  m_epetraMpiComm(NULL)
#endif
{
  this->copy(src);
}

// Destructor ---------------------------------------
MpiComm::~MpiComm()
{
#ifdef QUESO_HAS_TRILINOS
  delete m_epetraMpiComm;
  m_epetraMpiComm = NULL;
#endif
}

// --------------------------------------------------
// Set methodos -------------------------------------
MpiComm&
MpiComm::operator=(const MpiComm& rhs)
{
  this->copy(rhs);
  return *this;
}

// Attribute access methods -------------------------
RawType_MPI_Comm
MpiComm::Comm() const
{
#ifdef QUESO_HAS_TRILINOS
  return m_epetraMpiComm->Comm();
#endif
  return m_rawComm;
}
// --------------------------------------------------
int
MpiComm::MyPID() const
{
#ifdef QUESO_HAS_TRILINOS
  return m_epetraMpiComm->MyPID();
#endif
  return m_myPid;
}
// --------------------------------------------------
int
MpiComm::NumProc() const
{
#ifdef QUESO_HAS_TRILINOS
  return m_epetraMpiComm->NumProc();
#endif
  return m_numProc;
}
// Methods overridden from Comm ---------------------

void
MpiComm::Allreduce(void* sendbuf, void* recvbuf, int count, RawType_MPI_Datatype datatype, RawType_MPI_Op op, const char* whereMsg, const char* whatMsg) const
{
#ifdef QUESO_HAS_MPI
  int mpiRC = MPI_Allreduce(sendbuf, recvbuf, count, datatype, op, m_rawComm);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
#else
  size_t dataTypeSize = sizeOfDataType(datatype, whereMsg, whatMsg);
  size_t dataTotal = dataTypeSize*count;
  memcpy(recvbuf, sendbuf, dataTotal);
#endif

  return;
}
//--------------------------------------------------
void
MpiComm::Barrier() const // const char* whereMsg, const char* whatMsg) const
{
#ifdef QUESO_HAS_TRILINOS
  return m_epetraMpiComm->Barrier();
#endif
#ifdef QUESO_HAS_MPI
  int mpiRC = MPI_Barrier(m_rawComm);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      m_worldRank,
                      "MPIComm::Barrier()", // whereMsg,
                      "mpiRC indicates failure");  // whatMsg);
#else
  // Nothing needs to be done
#endif
  return;
}
//--------------------------------------------------
void
MpiComm::Bcast(void* buffer, int count, RawType_MPI_Datatype datatype, int root, const char* whereMsg, const char* whatMsg) const
{
#ifdef QUESO_HAS_MPI
  int mpiRC = MPI_Bcast(buffer, count, datatype, root, m_rawComm);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
#else
  // Nothing needs to be done
#endif
  return;
}
//--------------------------------------------------
void
MpiComm::Gather(
  void* sendbuf, int sendcnt, RawType_MPI_Datatype sendtype,
  void* recvbuf, int recvcount, RawType_MPI_Datatype recvtype,
  int root,
  const char* whereMsg, const char* whatMsg) const
{
  //int MPI_Gather (void *sendbuf, int sendcnt, MPI_Datatype sendtype,
  //                void *recvbuf, int recvcount, MPI_Datatype recvtype,
  //                int root, MPI_Comm comm )
#ifdef QUESO_HAS_MPI
  int mpiRC = MPI_Gather(sendbuf, sendcnt, sendtype,
                         recvbuf, recvcount, recvtype,
                         root, m_rawComm);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
#else
  size_t sendDataTypeSize = sizeOfDataType(sendtype, whereMsg, whatMsg);
  size_t recvDataTypeSize = sizeOfDataType(recvtype, whereMsg, whatMsg);
  size_t sendTotal = sendDataTypeSize*sendcnt;
  size_t recvTotal = recvDataTypeSize*recvcount;
  if (sendTotal != recvTotal) {
    std::cerr << "MpiComm::Gather()"
              << ": sendTotal != recvTotal"
              << std::endl;
  }
  UQ_FATAL_TEST_MACRO(sendTotal != recvTotal,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
  memcpy(recvbuf, sendbuf, sendTotal);
#endif
  return;
}
//--------------------------------------------------
void
MpiComm::Gatherv(
  void* sendbuf, int sendcnt, RawType_MPI_Datatype sendtype,
  void* recvbuf, int* recvcnts, int* displs, RawType_MPI_Datatype recvtype,
  int root,
  const char* whereMsg, const char* whatMsg) const
{
  //int MPI_Gatherv(void *sendbuf, int sendcnt, MPI_Datatype sendtype,
  //                void *recvbuf, int *recvcnts, int *displs, MPI_Datatype recvtype,
  //                int root, MPI_Comm comm )
#ifdef QUESO_HAS_MPI
  int mpiRC = MPI_Gatherv(sendbuf, sendcnt, sendtype,
                          recvbuf, recvcnts, displs, recvtype,
                          root, m_rawComm);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
#else
  size_t sendDataTypeSize = sizeOfDataType(sendtype, whereMsg, whatMsg);
  size_t recvDataTypeSize = sizeOfDataType(recvtype, whereMsg, whatMsg);
  size_t sendTotal = sendDataTypeSize*sendcnt;
  size_t recvTotal = recvDataTypeSize*recvcnts[0];
  if (sendTotal != recvTotal) {
    std::cerr << "MpiComm::Gatherv()"
              << ": sendTotal != recvTotal"
              << std::endl;
  }
  UQ_FATAL_TEST_MACRO(sendTotal != recvTotal,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
  memcpy(recvbuf, sendbuf, sendTotal);
#endif
  return;
}
//--------------------------------------------------
void
MpiComm::Recv(
  void* buf, int count, RawType_MPI_Datatype datatype, int source, int tag, RawType_MPI_Status* status,
  const char* whereMsg, const char* whatMsg) const
{
#ifdef QUESO_HAS_MPI
  int mpiRC = MPI_Recv(buf, count, datatype, source, tag, m_rawComm, status);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
#else
  std::cerr << "MpiComm::Recv()"
            << ": should note be used if there is no 'mpi'"
            << std::endl;
  UQ_FATAL_TEST_MACRO(true,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
#endif
  return;
}
//--------------------------------------------------
void
MpiComm::Send(
  void* buf, int count, RawType_MPI_Datatype datatype, int dest, int tag,
  const char* whereMsg, const char* whatMsg) const
{
#ifdef QUESO_HAS_MPI
  int mpiRC = MPI_Send(buf, count, datatype, dest, tag, m_rawComm);
  UQ_FATAL_TEST_MACRO(mpiRC != MPI_SUCCESS,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
#else
  std::cerr << "MpiComm::Send()"
            << ": should note be used if there is no 'mpi'"
            << std::endl;
  UQ_FATAL_TEST_MACRO(true,
                      m_worldRank,
                      whereMsg,
                      whatMsg);
#endif
  return;
}
// Misc methods ------------------------------------
void
MpiComm::syncPrintDebugMsg(const char* msg, unsigned int msgVerbosity, unsigned int numUSecs) const
{
  if (m_env.syncVerbosity() >= msgVerbosity) {
    this->Barrier();
    for (int i = 0; i < this->NumProc(); ++i) {
      if (i == this->MyPID()) {
        std::cout << msg
                  << ": fullRank "       << m_env.fullRank()
                  << ", subEnvironment " << m_env.subId()
                  << ", subRank "        << m_env.subRank()
                  << ", inter0Rank "     << m_env.inter0Rank()
                  << std::endl;
      }
      usleep(numUSecs);
      this->Barrier();
    }
    //if (this->fullRank() == 0) std::cout << "Sleeping " << numUSecs << " microseconds..."
    //                                     << std::endl;
    //usleep(numUSecs);
    this->Barrier();
  }

  return;
}
// -------------------------------------------------
#ifdef QUESO_HAS_TRILINOS
const Epetra_MpiComm&
MpiComm::epetraMpiComm() const
{
  return *m_epetraMpiComm;
}
#endif

// Private methods----------------------------------
void
MpiComm::copy(const MpiComm& src)
{
#ifdef QUESO_HAS_TRILINOS
  delete m_epetraMpiComm;
  m_epetraMpiComm = new Epetra_MpiComm(*src.m_epetraMpiComm);
#endif
  m_rawComm   = src.m_rawComm;
  m_worldRank = src.m_worldRank;
  m_myPid     = src.m_myPid;
  m_numProc   = src.m_numProc;

  return;
}
// -------------------------------------------------
#ifdef QUESO_HAS_MPI
#else
size_t
MpiComm::sizeOfDataType(RawType_MPI_Datatype datatype, const char* whereMsg, const char* whatMsg) const
{
  size_t dataTypeSize = 0;

  switch (datatype) {
    case RawValue_MPI_CHAR:
      dataTypeSize = sizeof(char);
    break;

    case RawValue_MPI_INT:
      dataTypeSize = sizeof(int);
    break;

    case RawValue_MPI_DOUBLE:
      dataTypeSize = sizeof(double);
    break;

    case RawValue_MPI_UNSIGNED:
      dataTypeSize = sizeof(unsigned int);
    break;

    default:
      std::cerr << "MpiComm::Allreduce()"
                << ": datatype not supported yet"
                << std::endl;
      UQ_FATAL_TEST_MACRO(true,
                          m_worldRank,
                          whereMsg,
                          whatMsg);
    break;
  }

  return dataTypeSize;
}
#endif

}  // End namespace QUESO
<|endoftext|>


<commit_before>/*  -*- c++ -*-
    bodypartformatter.cpp

    This file is part of KMail, the KDE mail client.
    Copyright (c) 2003 Marc Mutz <mutz@kde.org>

    KMail is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

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

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "bodypartformatter.h"
#include "bodypartformatterfactory_p.h"
#include "interfaces/bodypartformatter.h"

#include "objecttreeparser.h"
#include "partNode.h"

#include <mimelib/enum.h>
#include <mimelib/string.h>
#include <mimelib/utility.h>

#include <kdebug.h>

namespace {
  class AnyTypeBodyPartFormatter
    : public KMail::BodyPartFormatter,
      public KMail::Interface::BodyPartFormatter {
    static const AnyTypeBodyPartFormatter * self;
  public:
    Result format( KMail::Interface::BodyPart *, KMail::Interface::HtmlWriter * ) const {
      kdDebug(5006) << "AnyTypeBodyPartFormatter::format() acting as a KMail::Interface::BodyPartFormatter!" << endl;
      return AsIcon;
    }

    bool process( KMail::ObjectTreeParser *, partNode *, KMail::ProcessResult & result ) const {
      result.setNeverDisplayInline( true );
      return false;
    }
    static const KMail::BodyPartFormatter * create() {
      if ( !self )
	self = new AnyTypeBodyPartFormatter();
      return self;
    }
  };

  const AnyTypeBodyPartFormatter * AnyTypeBodyPartFormatter::self = 0;

  class ImageTypeBodyPartFormatter : public KMail::BodyPartFormatter {
    static const ImageTypeBodyPartFormatter * self;
  public:
    bool process( KMail::ObjectTreeParser *, partNode *, KMail::ProcessResult & result ) const {
      result.setIsImage( true );
      return false;
    }
    static const KMail::BodyPartFormatter * create() {
      if ( !self )
	self = new ImageTypeBodyPartFormatter();
      return self;
    }
  };

  const ImageTypeBodyPartFormatter * ImageTypeBodyPartFormatter::self = 0;

#define CREATE_BODY_PART_FORMATTER(subtype) \
  class subtype##BodyPartFormatter : public KMail::BodyPartFormatter { \
    static const subtype##BodyPartFormatter * self; \
  public: \
    bool process( KMail::ObjectTreeParser *, partNode *, KMail::ProcessResult & ) const; \
    static const KMail::BodyPartFormatter * create() { \
      if ( !self ) \
	self = new subtype##BodyPartFormatter(); \
      return self; \
    } \
  }; \
  \
  const subtype##BodyPartFormatter * subtype##BodyPartFormatter::self; \
  \
  bool subtype##BodyPartFormatter::process( KMail::ObjectTreeParser * otp, partNode * node, KMail::ProcessResult & result ) const { \
    return otp->process##subtype##Subtype( node, result ); \
  }

  CREATE_BODY_PART_FORMATTER(TextPlain)
  CREATE_BODY_PART_FORMATTER(TextHtml)
  //CREATE_BODY_PART_FORMATTER(TextEnriched)

  CREATE_BODY_PART_FORMATTER(ApplicationOctetStream)
  CREATE_BODY_PART_FORMATTER(ApplicationPkcs7Mime)
  //CREATE_BODY_PART_FORMATTER(ApplicationPgp)

  CREATE_BODY_PART_FORMATTER(MessageRfc822)

  CREATE_BODY_PART_FORMATTER(MultiPartMixed)
  CREATE_BODY_PART_FORMATTER(MultiPartAlternative)
  CREATE_BODY_PART_FORMATTER(MultiPartSigned)
  CREATE_BODY_PART_FORMATTER(MultiPartEncrypted)

  typedef TextPlainBodyPartFormatter ApplicationPgpBodyPartFormatter;

#undef CREATE_BODY_PART_FORMATTER
} // anon namespace

// FIXME: port some more KMail::BodyPartFormatters to KMail::Interface::BodyPartFormatters
void KMail::BodyPartFormatterFactoryPrivate::kmail_create_builtin_bodypart_formatters( KMail::BodyPartFormatterFactoryPrivate::TypeRegistry * reg ) {
  if ( !reg ) return;
  (*reg)["application"]["octet-stream"] = new AnyTypeBodyPartFormatter();
}

typedef const KMail::BodyPartFormatter * (*BodyPartFormatterCreator)();

struct SubtypeBuiltin {
  const char * subtype;
  BodyPartFormatterCreator create;
};

static const SubtypeBuiltin applicationSubtypeBuiltins[] = {
  { "octet-stream", &ApplicationOctetStreamBodyPartFormatter::create },
  { "pkcs7-mime", &ApplicationPkcs7MimeBodyPartFormatter::create },
  { "x-pkcs7-mime", &ApplicationPkcs7MimeBodyPartFormatter::create },
  { "pgp", &ApplicationPgpBodyPartFormatter::create },
};

static const SubtypeBuiltin textSubtypeBuiltins[] = {
  { "html", &TextHtmlBodyPartFormatter::create },
  //{ "enriched", &TextEnrichedBodyPartFormatter::create },
  { "x-vcard", &AnyTypeBodyPartFormatter::create },
  { "vcard", &AnyTypeBodyPartFormatter::create },
  { "rtf", &AnyTypeBodyPartFormatter::create },
  { "*", &TextPlainBodyPartFormatter::create },
};

static const SubtypeBuiltin multipartSubtypeBuiltins[] = {
  { "mixed", &MultiPartMixedBodyPartFormatter::create },
  { "alternative", &MultiPartAlternativeBodyPartFormatter::create },
  //{ "digest", &MultiPartDigestFormatter::create },
  //{ "parallel", &MultiPartParallelFormatter::create },
  //{ "related", &MultiPartRelatedFormatter::create },
  { "signed", &MultiPartSignedBodyPartFormatter::create },
  { "encrypted", &MultiPartEncryptedBodyPartFormatter::create },
  //{ "report", &MultiPartReportFormatter::create },
};

static const SubtypeBuiltin messageSubtypeBuiltins[] = {
  { "rfc822", &MessageRfc822BodyPartFormatter::create },
};

static const SubtypeBuiltin imageSubtypeBuiltins[] = {
  { "*", &ImageTypeBodyPartFormatter::create },
};

static const SubtypeBuiltin anySubtypeBuiltins[] = {
  { "*", &AnyTypeBodyPartFormatter::create },
};

#ifdef DIM
#undef DIM
#endif
#define DIM(x) sizeof(x) / sizeof(*x)

static const struct {
  const char * type;
  const SubtypeBuiltin * subtypes;
  unsigned int num_subtypes;
} builtins[] = {
  { "application", applicationSubtypeBuiltins, DIM(applicationSubtypeBuiltins) },
  { "text", textSubtypeBuiltins, DIM(textSubtypeBuiltins) },
  { "multipart", multipartSubtypeBuiltins, DIM(multipartSubtypeBuiltins) },
  { "message", messageSubtypeBuiltins, DIM(messageSubtypeBuiltins) },
  { "image", imageSubtypeBuiltins, DIM(imageSubtypeBuiltins) },
  //{ "audio", audioSubtypeBuiltins, DIM(audioSubtypeBuiltins) },
  //{ "model", modelSubtypeBuiltins, DIM(modelSubtypeBuiltins) },
  //{ "video", videoSubtypeBuiltins, DIM(videoSubtypeBuiltins) },
  { "*", anySubtypeBuiltins, DIM(anySubtypeBuiltins) },
};

#undef DIM

const KMail::BodyPartFormatter * KMail::BodyPartFormatter::createFor( int type, int subtype ) {
  DwString t, st;
  DwTypeEnumToStr( type, t );
  DwSubtypeEnumToStr( subtype, st );
  return createFor( t.c_str(), st.c_str() );
}

static const KMail::BodyPartFormatter * createForText( const char * subtype ) {
  if ( subtype && *subtype )
    switch ( subtype[0] ) {
    case 'h':
    case 'H':
      if ( qstricmp( subtype, "html" ) == 0 )
	return TextHtmlBodyPartFormatter::create();
      break;
    case 'r':
    case 'R':
      if ( qstricmp( subtype, "rtf" ) == 0 )
	return AnyTypeBodyPartFormatter::create();
      break;
    case 'x':
    case 'X':
    case 'v':
    case 'V':
      if ( qstricmp( subtype, "x-vcard" ) == 0 ||
	   qstricmp( subtype, "vcard" ) == 0 )
	return AnyTypeBodyPartFormatter::create();
      break;
    }

  return TextPlainBodyPartFormatter::create();
}

static const KMail::BodyPartFormatter * createForImage( const char * ) {
  return ImageTypeBodyPartFormatter::create();
}

static const KMail::BodyPartFormatter * createForMessage( const char * subtype ) {
  if ( qstricmp( subtype, "rfc822" ) == 0 )
    return MessageRfc822BodyPartFormatter::create();
  return AnyTypeBodyPartFormatter::create();
}

static const KMail::BodyPartFormatter * createForMultiPart( const char * subtype ) {
  if ( subtype && *subtype )
    switch ( subtype[0] ) {
    case 'a':
    case 'A':
      if ( qstricmp( subtype, "alternative" ) == 0 )
	return MultiPartAlternativeBodyPartFormatter::create();
      break;
    case 'e':
    case 'E':
      if ( qstricmp( subtype, "encrypted" ) == 0 )
	return MultiPartEncryptedBodyPartFormatter::create();
      break;
    case 's':
    case 'S':
      if ( qstricmp( subtype, "signed" ) == 0 )
	return MultiPartSignedBodyPartFormatter::create();
      break;
    }

  return MultiPartMixedBodyPartFormatter::create();
}

static const KMail::BodyPartFormatter * createForApplication( const char * subtype ) {
  if ( subtype && *subtype )
    switch ( subtype[0] ) {
    case 'p':
    case 'P':
      if ( qstricmp( subtype, "pgp" ) == 0 )
	return ApplicationPgpBodyPartFormatter::create();
      // fall through
    case 'x':
    case 'X':
      if ( qstricmp( subtype, "pkcs7-mime" ) == 0 ||
	   qstricmp( subtype, "x-pkcs7-mime" ) == 0 )
	return ApplicationPkcs7MimeBodyPartFormatter::create();
      break;
    case 'm':
    case 'M':
      //if ( qstricmp( subtype, "ms-tnef" ) == 0 )
      //  return ApplicationMsTnefBodyPartFormatter::create();
      break;
    }

  return AnyTypeBodyPartFormatter::create();
}

// OK, replace this with a factory with plugin support later on...
const KMail::BodyPartFormatter * KMail::BodyPartFormatter::createFor( const char * type, const char * subtype ) {
  if ( type && *type )
    switch ( type[0] ) {
    case 'a': // application
    case 'A':
      if ( qstricmp( type, "application" ) == 0 )
	return createForApplication( subtype );
      break;
    case 'i': // image
    case 'I':
      if ( qstricmp( type, "image" ) == 0 )
	return createForImage( subtype );
      break;
    case 'm': // multipart / message
    case 'M':
      if ( qstricmp( type, "multipart" ) == 0 )
	return createForMultiPart( subtype );
      else if ( qstricmp( type, "message" ) == 0 )
	return createForMessage( subtype );
      break;
    case 't': // text
    case 'T':
      if ( qstricmp( type, "text" ) == 0 )
	return createForText( subtype );
      break;
    }

  return AnyTypeBodyPartFormatter::create();
}

<commit_msg>unbreak compilation<commit_after>/*  -*- c++ -*-
    bodypartformatter.cpp

    This file is part of KMail, the KDE mail client.
    Copyright (c) 2003 Marc Mutz <mutz@kde.org>

    KMail is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License, version 2, as
    published by the Free Software Foundation.

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

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

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "bodypartformatter.h"
#include "bodypartformatterfactory_p.h"
#include "interfaces/bodypartformatter.h"

#include "objecttreeparser.h"
#include "partNode.h"

#include <mimelib/enum.h>
#include <mimelib/string.h>
#include <mimelib/utility.h>

#include <kdebug.h>

namespace {
  class AnyTypeBodyPartFormatter
    : public KMail::BodyPartFormatter,
      public KMail::Interface::BodyPartFormatter {
    static const AnyTypeBodyPartFormatter * self;
  public:
    Result format( KMail::Interface::BodyPart *, KMail::HtmlWriter * ) const {
      kdDebug(5006) << "AnyTypeBodyPartFormatter::format() acting as a KMail::Interface::BodyPartFormatter!" << endl;
      return AsIcon;
    }

    bool process( KMail::ObjectTreeParser *, partNode *, KMail::ProcessResult & result ) const {
      result.setNeverDisplayInline( true );
      return false;
    }
    static const KMail::BodyPartFormatter * create() {
      if ( !self )
	self = new AnyTypeBodyPartFormatter();
      return self;
    }
  };

  const AnyTypeBodyPartFormatter * AnyTypeBodyPartFormatter::self = 0;

  class ImageTypeBodyPartFormatter : public KMail::BodyPartFormatter {
    static const ImageTypeBodyPartFormatter * self;
  public:
    bool process( KMail::ObjectTreeParser *, partNode *, KMail::ProcessResult & result ) const {
      result.setIsImage( true );
      return false;
    }
    static const KMail::BodyPartFormatter * create() {
      if ( !self )
	self = new ImageTypeBodyPartFormatter();
      return self;
    }
  };

  const ImageTypeBodyPartFormatter * ImageTypeBodyPartFormatter::self = 0;

#define CREATE_BODY_PART_FORMATTER(subtype) \
  class subtype##BodyPartFormatter : public KMail::BodyPartFormatter { \
    static const subtype##BodyPartFormatter * self; \
  public: \
    bool process( KMail::ObjectTreeParser *, partNode *, KMail::ProcessResult & ) const; \
    static const KMail::BodyPartFormatter * create() { \
      if ( !self ) \
	self = new subtype##BodyPartFormatter(); \
      return self; \
    } \
  }; \
  \
  const subtype##BodyPartFormatter * subtype##BodyPartFormatter::self; \
  \
  bool subtype##BodyPartFormatter::process( KMail::ObjectTreeParser * otp, partNode * node, KMail::ProcessResult & result ) const { \
    return otp->process##subtype##Subtype( node, result ); \
  }

  CREATE_BODY_PART_FORMATTER(TextPlain)
  CREATE_BODY_PART_FORMATTER(TextHtml)
  //CREATE_BODY_PART_FORMATTER(TextEnriched)

  CREATE_BODY_PART_FORMATTER(ApplicationOctetStream)
  CREATE_BODY_PART_FORMATTER(ApplicationPkcs7Mime)
  //CREATE_BODY_PART_FORMATTER(ApplicationPgp)

  CREATE_BODY_PART_FORMATTER(MessageRfc822)

  CREATE_BODY_PART_FORMATTER(MultiPartMixed)
  CREATE_BODY_PART_FORMATTER(MultiPartAlternative)
  CREATE_BODY_PART_FORMATTER(MultiPartSigned)
  CREATE_BODY_PART_FORMATTER(MultiPartEncrypted)

  typedef TextPlainBodyPartFormatter ApplicationPgpBodyPartFormatter;

#undef CREATE_BODY_PART_FORMATTER
} // anon namespace

// FIXME: port some more KMail::BodyPartFormatters to KMail::Interface::BodyPartFormatters
void KMail::BodyPartFormatterFactoryPrivate::kmail_create_builtin_bodypart_formatters( KMail::BodyPartFormatterFactoryPrivate::TypeRegistry * reg ) {
  if ( !reg ) return;
  (*reg)["application"]["octet-stream"] = new AnyTypeBodyPartFormatter();
}

typedef const KMail::BodyPartFormatter * (*BodyPartFormatterCreator)();

struct SubtypeBuiltin {
  const char * subtype;
  BodyPartFormatterCreator create;
};

static const SubtypeBuiltin applicationSubtypeBuiltins[] = {
  { "octet-stream", &ApplicationOctetStreamBodyPartFormatter::create },
  { "pkcs7-mime", &ApplicationPkcs7MimeBodyPartFormatter::create },
  { "x-pkcs7-mime", &ApplicationPkcs7MimeBodyPartFormatter::create },
  { "pgp", &ApplicationPgpBodyPartFormatter::create },
};

static const SubtypeBuiltin textSubtypeBuiltins[] = {
  { "html", &TextHtmlBodyPartFormatter::create },
  //{ "enriched", &TextEnrichedBodyPartFormatter::create },
  { "x-vcard", &AnyTypeBodyPartFormatter::create },
  { "vcard", &AnyTypeBodyPartFormatter::create },
  { "rtf", &AnyTypeBodyPartFormatter::create },
  { "*", &TextPlainBodyPartFormatter::create },
};

static const SubtypeBuiltin multipartSubtypeBuiltins[] = {
  { "mixed", &MultiPartMixedBodyPartFormatter::create },
  { "alternative", &MultiPartAlternativeBodyPartFormatter::create },
  //{ "digest", &MultiPartDigestFormatter::create },
  //{ "parallel", &MultiPartParallelFormatter::create },
  //{ "related", &MultiPartRelatedFormatter::create },
  { "signed", &MultiPartSignedBodyPartFormatter::create },
  { "encrypted", &MultiPartEncryptedBodyPartFormatter::create },
  //{ "report", &MultiPartReportFormatter::create },
};

static const SubtypeBuiltin messageSubtypeBuiltins[] = {
  { "rfc822", &MessageRfc822BodyPartFormatter::create },
};

static const SubtypeBuiltin imageSubtypeBuiltins[] = {
  { "*", &ImageTypeBodyPartFormatter::create },
};

static const SubtypeBuiltin anySubtypeBuiltins[] = {
  { "*", &AnyTypeBodyPartFormatter::create },
};

#ifdef DIM
#undef DIM
#endif
#define DIM(x) sizeof(x) / sizeof(*x)

static const struct {
  const char * type;
  const SubtypeBuiltin * subtypes;
  unsigned int num_subtypes;
} builtins[] = {
  { "application", applicationSubtypeBuiltins, DIM(applicationSubtypeBuiltins) },
  { "text", textSubtypeBuiltins, DIM(textSubtypeBuiltins) },
  { "multipart", multipartSubtypeBuiltins, DIM(multipartSubtypeBuiltins) },
  { "message", messageSubtypeBuiltins, DIM(messageSubtypeBuiltins) },
  { "image", imageSubtypeBuiltins, DIM(imageSubtypeBuiltins) },
  //{ "audio", audioSubtypeBuiltins, DIM(audioSubtypeBuiltins) },
  //{ "model", modelSubtypeBuiltins, DIM(modelSubtypeBuiltins) },
  //{ "video", videoSubtypeBuiltins, DIM(videoSubtypeBuiltins) },
  { "*", anySubtypeBuiltins, DIM(anySubtypeBuiltins) },
};

#undef DIM

const KMail::BodyPartFormatter * KMail::BodyPartFormatter::createFor( int type, int subtype ) {
  DwString t, st;
  DwTypeEnumToStr( type, t );
  DwSubtypeEnumToStr( subtype, st );
  return createFor( t.c_str(), st.c_str() );
}

static const KMail::BodyPartFormatter * createForText( const char * subtype ) {
  if ( subtype && *subtype )
    switch ( subtype[0] ) {
    case 'h':
    case 'H':
      if ( qstricmp( subtype, "html" ) == 0 )
	return TextHtmlBodyPartFormatter::create();
      break;
    case 'r':
    case 'R':
      if ( qstricmp( subtype, "rtf" ) == 0 )
	return AnyTypeBodyPartFormatter::create();
      break;
    case 'x':
    case 'X':
    case 'v':
    case 'V':
      if ( qstricmp( subtype, "x-vcard" ) == 0 ||
	   qstricmp( subtype, "vcard" ) == 0 )
	return AnyTypeBodyPartFormatter::create();
      break;
    }

  return TextPlainBodyPartFormatter::create();
}

static const KMail::BodyPartFormatter * createForImage( const char * ) {
  return ImageTypeBodyPartFormatter::create();
}

static const KMail::BodyPartFormatter * createForMessage( const char * subtype ) {
  if ( qstricmp( subtype, "rfc822" ) == 0 )
    return MessageRfc822BodyPartFormatter::create();
  return AnyTypeBodyPartFormatter::create();
}

static const KMail::BodyPartFormatter * createForMultiPart( const char * subtype ) {
  if ( subtype && *subtype )
    switch ( subtype[0] ) {
    case 'a':
    case 'A':
      if ( qstricmp( subtype, "alternative" ) == 0 )
	return MultiPartAlternativeBodyPartFormatter::create();
      break;
    case 'e':
    case 'E':
      if ( qstricmp( subtype, "encrypted" ) == 0 )
	return MultiPartEncryptedBodyPartFormatter::create();
      break;
    case 's':
    case 'S':
      if ( qstricmp( subtype, "signed" ) == 0 )
	return MultiPartSignedBodyPartFormatter::create();
      break;
    }

  return MultiPartMixedBodyPartFormatter::create();
}

static const KMail::BodyPartFormatter * createForApplication( const char * subtype ) {
  if ( subtype && *subtype )
    switch ( subtype[0] ) {
    case 'p':
    case 'P':
      if ( qstricmp( subtype, "pgp" ) == 0 )
	return ApplicationPgpBodyPartFormatter::create();
      // fall through
    case 'x':
    case 'X':
      if ( qstricmp( subtype, "pkcs7-mime" ) == 0 ||
	   qstricmp( subtype, "x-pkcs7-mime" ) == 0 )
	return ApplicationPkcs7MimeBodyPartFormatter::create();
      break;
    case 'm':
    case 'M':
      //if ( qstricmp( subtype, "ms-tnef" ) == 0 )
      //  return ApplicationMsTnefBodyPartFormatter::create();
      break;
    }

  return AnyTypeBodyPartFormatter::create();
}

// OK, replace this with a factory with plugin support later on...
const KMail::BodyPartFormatter * KMail::BodyPartFormatter::createFor( const char * type, const char * subtype ) {
  if ( type && *type )
    switch ( type[0] ) {
    case 'a': // application
    case 'A':
      if ( qstricmp( type, "application" ) == 0 )
	return createForApplication( subtype );
      break;
    case 'i': // image
    case 'I':
      if ( qstricmp( type, "image" ) == 0 )
	return createForImage( subtype );
      break;
    case 'm': // multipart / message
    case 'M':
      if ( qstricmp( type, "multipart" ) == 0 )
	return createForMultiPart( subtype );
      else if ( qstricmp( type, "message" ) == 0 )
	return createForMessage( subtype );
      break;
    case 't': // text
    case 'T':
      if ( qstricmp( type, "text" ) == 0 )
	return createForText( subtype );
      break;
    }

  return AnyTypeBodyPartFormatter::create();
}

<|endoftext|>