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

#include "chrome/service/service_process.h"

#include <algorithm>

#include "app/app_switches.h"
#include "app/resource_bundle.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/path_service.h"
#include "base/singleton.h"
#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/net/url_fetcher.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/service_process_util.h"
#include "chrome/service/cloud_print/cloud_print_proxy.h"
#include "chrome/service/service_ipc_server.h"
#include "chrome/service/service_process_prefs.h"
#include "net/base/network_change_notifier.h"

#if defined(ENABLE_REMOTING)
#include "chrome/service/remoting/chromoting_host_manager.h"
#endif  // defined(ENABLED_REMOTING)

ServiceProcess* g_service_process = NULL;

namespace {

// Delay in millseconds after the last service is disabled before we attempt
// a shutdown.
const int64 kShutdownDelay = 60000;

const char kDefaultServiceProcessLocale[] = "en-US";

class ServiceIOThread : public base::Thread {
 public:
  explicit ServiceIOThread(const char* name);
  virtual ~ServiceIOThread();

 protected:
  virtual void CleanUp();

 private:
  DISALLOW_COPY_AND_ASSIGN(ServiceIOThread);
};

ServiceIOThread::ServiceIOThread(const char* name) : base::Thread(name) {}
ServiceIOThread::~ServiceIOThread() {
  // We cannot rely on our base class to stop the thread since we want our
  // CleanUp function to run.
  Stop();
}

void ServiceIOThread::CleanUp() {
  URLFetcher::CancelAll();
}

}  // namespace

ServiceProcess::ServiceProcess()
  : shutdown_event_(true, false),
    main_message_loop_(NULL),
    enabled_services_(0),
    update_available_(false) {
  DCHECK(!g_service_process);
  g_service_process = this;
}

bool ServiceProcess::Initialize(MessageLoop* message_loop,
                                const CommandLine& command_line) {
  main_message_loop_ = message_loop;
  network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
  base::Thread::Options options;
  options.message_loop_type = MessageLoop::TYPE_IO;
  io_thread_.reset(new ServiceIOThread("ServiceProcess_IO"));
  file_thread_.reset(new base::Thread("ServiceProcess_File"));
  if (!io_thread_->StartWithOptions(options) ||
      !file_thread_->StartWithOptions(options)) {
    NOTREACHED();
    Teardown();
    return false;
  }

  // See if we have been suppiled an LSID in the command line. This LSID will
  // override the credentials we use for Cloud Print.
  std::string lsid = command_line.GetSwitchValueASCII(
          switches::kServiceAccountLsid);

  FilePath user_data_dir;
  PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
  FilePath pref_path = user_data_dir.Append(chrome::kServiceStateFileName);
  service_prefs_.reset(
      new ServiceProcessPrefs(pref_path, file_thread_->message_loop_proxy()));
  service_prefs_->ReadPrefs();

  // Check if a locale override has been specified on the command-line.
  std::string locale = command_line.GetSwitchValueASCII(switches::kLang);
  if (!locale.empty()) {
    service_prefs_->SetString(prefs::kApplicationLocale, locale);
    service_prefs_->WritePrefs();
  } else {
    // If no command-line value was specified, read the last used locale from
    // the prefs.
    service_prefs_->GetString(prefs::kApplicationLocale, &locale);
    // If no locale was specified anywhere, use the default one.
    if (locale.empty())
      locale = kDefaultServiceProcessLocale;
  }
  ResourceBundle::InitSharedInstance(locale);

#if defined(ENABLE_REMOTING)
  // Initialize chromoting host manager.
  remoting_host_manager_ = new remoting::ChromotingHostManager(this);
  remoting_host_manager_->Initialize(file_thread_->message_loop_proxy());
#endif

  // Enable Cloud Print if needed. First check the command-line.
  bool cloud_print_proxy_enabled =
      command_line.HasSwitch(switches::kEnableCloudPrintProxy);
  if (!cloud_print_proxy_enabled) {
    // Then check if the cloud print proxy was previously enabled.
    service_prefs_->GetBoolean(prefs::kCloudPrintProxyEnabled,
                               &cloud_print_proxy_enabled);
  }

  if (cloud_print_proxy_enabled) {
    GetCloudPrintProxy()->EnableForUser(lsid);
  }

  VLOG(1) << "Starting Service Process IPC Server";
  ipc_server_.reset(new ServiceIPCServer(GetServiceProcessChannelName()));
  ipc_server_->Init();

  // After the IPC server has started we signal that the service process is
  // ready.
  ServiceProcessState::GetInstance()->SignalReady(
      NewRunnableMethod(this, &ServiceProcess::Shutdown));

  // See if we need to stay running.
  ScheduleShutdownCheck();
  return true;
}

bool ServiceProcess::Teardown() {
  service_prefs_.reset();
  cloud_print_proxy_.reset();

#if defined(ENABLE_REMOTING)
  remoting_host_manager_->Teardown();
#endif

  ipc_server_.reset();
  // Signal this event before shutting down the service process. That way all
  // background threads can cleanup.
  shutdown_event_.Signal();
  io_thread_.reset();
  file_thread_.reset();
  // The NetworkChangeNotifier must be destroyed after all other threads that
  // might use it have been shut down.
  network_change_notifier_.reset();

  ServiceProcessState::GetInstance()->SignalStopped();
  return true;
}

void ServiceProcess::Shutdown() {
  // Quit the main message loop.
  main_message_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}

bool ServiceProcess::HandleClientDisconnect() {
  // If there are no enabled services or if there is an update available
  // we want to shutdown right away. Else we want to keep listening for
  // new connections.
  if (!enabled_services_ || update_available()) {
    Shutdown();
    return false;
  }
  return true;
}

CloudPrintProxy* ServiceProcess::GetCloudPrintProxy() {
  if (!cloud_print_proxy_.get()) {
    cloud_print_proxy_.reset(new CloudPrintProxy());
    cloud_print_proxy_->Initialize(service_prefs_.get(), this);
  }
  return cloud_print_proxy_.get();
}

void ServiceProcess::OnCloudPrintProxyEnabled(bool persist_state) {
  if (persist_state) {
    // Save the preference that we have enabled the cloud print proxy.
    service_prefs_->SetBoolean(prefs::kCloudPrintProxyEnabled, true);
    service_prefs_->WritePrefs();
  }
  OnServiceEnabled();
}

void ServiceProcess::OnCloudPrintProxyDisabled(bool persist_state) {
  if (persist_state) {
    // Save the preference that we have disabled the cloud print proxy.
    service_prefs_->SetBoolean(prefs::kCloudPrintProxyEnabled, false);
    service_prefs_->WritePrefs();
  }
  OnServiceDisabled();
}

void ServiceProcess::OnRemotingHostEnabled() {
  OnServiceEnabled();
}

void ServiceProcess::OnRemotingHostDisabled() {
  OnServiceDisabled();
}

void ServiceProcess::OnServiceEnabled() {
  enabled_services_++;
  if (1 == enabled_services_) {
    ServiceProcessState::GetInstance()->AddToAutoRun();
  }
}

void ServiceProcess::OnServiceDisabled() {
  DCHECK_NE(enabled_services_, 0);
  enabled_services_--;
  if (0 == enabled_services_) {
    ServiceProcessState::GetInstance()->RemoveFromAutoRun();
    // We will wait for some time to respond to IPCs before shutting down.
    ScheduleShutdownCheck();
  }
}

void ServiceProcess::ScheduleShutdownCheck() {
  MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      NewRunnableMethod(this, &ServiceProcess::ShutdownIfNeeded),
      kShutdownDelay);
}

void ServiceProcess::ShutdownIfNeeded() {
  if (0 == enabled_services_) {
    if (ipc_server_->is_client_connected()) {
      // If there is a client connected, we need to try again later.
      // Note that there is still a timing window here because a client may
      // decide to connect at this point.
      // TODO(sanjeevr): Fix this timing window.
      ScheduleShutdownCheck();
    } else {
      Shutdown();
    }
  }
}

ServiceProcess::~ServiceProcess() {
  Teardown();
  g_service_process = NULL;
}

// Disable refcounting for runnable method because it is really not needed
// when we post tasks on the main message loop.
DISABLE_RUNNABLE_METHOD_REFCOUNT(ServiceProcess);
<commit_msg>Fix bustage by updating header includes.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/service/service_process.h"

#include <algorithm>

#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/path_service.h"
#include "base/singleton.h"
#include "base/string16.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/net/url_fetcher.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/service_process_util.h"
#include "chrome/service/cloud_print/cloud_print_proxy.h"
#include "chrome/service/service_ipc_server.h"
#include "chrome/service/service_process_prefs.h"
#include "net/base/network_change_notifier.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_switches.h"

#if defined(ENABLE_REMOTING)
#include "chrome/service/remoting/chromoting_host_manager.h"
#endif  // defined(ENABLED_REMOTING)

ServiceProcess* g_service_process = NULL;

namespace {

// Delay in millseconds after the last service is disabled before we attempt
// a shutdown.
const int64 kShutdownDelay = 60000;

const char kDefaultServiceProcessLocale[] = "en-US";

class ServiceIOThread : public base::Thread {
 public:
  explicit ServiceIOThread(const char* name);
  virtual ~ServiceIOThread();

 protected:
  virtual void CleanUp();

 private:
  DISALLOW_COPY_AND_ASSIGN(ServiceIOThread);
};

ServiceIOThread::ServiceIOThread(const char* name) : base::Thread(name) {}
ServiceIOThread::~ServiceIOThread() {
  // We cannot rely on our base class to stop the thread since we want our
  // CleanUp function to run.
  Stop();
}

void ServiceIOThread::CleanUp() {
  URLFetcher::CancelAll();
}

}  // namespace

ServiceProcess::ServiceProcess()
  : shutdown_event_(true, false),
    main_message_loop_(NULL),
    enabled_services_(0),
    update_available_(false) {
  DCHECK(!g_service_process);
  g_service_process = this;
}

bool ServiceProcess::Initialize(MessageLoop* message_loop,
                                const CommandLine& command_line) {
  main_message_loop_ = message_loop;
  network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
  base::Thread::Options options;
  options.message_loop_type = MessageLoop::TYPE_IO;
  io_thread_.reset(new ServiceIOThread("ServiceProcess_IO"));
  file_thread_.reset(new base::Thread("ServiceProcess_File"));
  if (!io_thread_->StartWithOptions(options) ||
      !file_thread_->StartWithOptions(options)) {
    NOTREACHED();
    Teardown();
    return false;
  }

  // See if we have been suppiled an LSID in the command line. This LSID will
  // override the credentials we use for Cloud Print.
  std::string lsid = command_line.GetSwitchValueASCII(
          switches::kServiceAccountLsid);

  FilePath user_data_dir;
  PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
  FilePath pref_path = user_data_dir.Append(chrome::kServiceStateFileName);
  service_prefs_.reset(
      new ServiceProcessPrefs(pref_path, file_thread_->message_loop_proxy()));
  service_prefs_->ReadPrefs();

  // Check if a locale override has been specified on the command-line.
  std::string locale = command_line.GetSwitchValueASCII(switches::kLang);
  if (!locale.empty()) {
    service_prefs_->SetString(prefs::kApplicationLocale, locale);
    service_prefs_->WritePrefs();
  } else {
    // If no command-line value was specified, read the last used locale from
    // the prefs.
    service_prefs_->GetString(prefs::kApplicationLocale, &locale);
    // If no locale was specified anywhere, use the default one.
    if (locale.empty())
      locale = kDefaultServiceProcessLocale;
  }
  ResourceBundle::InitSharedInstance(locale);

#if defined(ENABLE_REMOTING)
  // Initialize chromoting host manager.
  remoting_host_manager_ = new remoting::ChromotingHostManager(this);
  remoting_host_manager_->Initialize(file_thread_->message_loop_proxy());
#endif

  // Enable Cloud Print if needed. First check the command-line.
  bool cloud_print_proxy_enabled =
      command_line.HasSwitch(switches::kEnableCloudPrintProxy);
  if (!cloud_print_proxy_enabled) {
    // Then check if the cloud print proxy was previously enabled.
    service_prefs_->GetBoolean(prefs::kCloudPrintProxyEnabled,
                               &cloud_print_proxy_enabled);
  }

  if (cloud_print_proxy_enabled) {
    GetCloudPrintProxy()->EnableForUser(lsid);
  }

  VLOG(1) << "Starting Service Process IPC Server";
  ipc_server_.reset(new ServiceIPCServer(GetServiceProcessChannelName()));
  ipc_server_->Init();

  // After the IPC server has started we signal that the service process is
  // ready.
  ServiceProcessState::GetInstance()->SignalReady(
      NewRunnableMethod(this, &ServiceProcess::Shutdown));

  // See if we need to stay running.
  ScheduleShutdownCheck();
  return true;
}

bool ServiceProcess::Teardown() {
  service_prefs_.reset();
  cloud_print_proxy_.reset();

#if defined(ENABLE_REMOTING)
  remoting_host_manager_->Teardown();
#endif

  ipc_server_.reset();
  // Signal this event before shutting down the service process. That way all
  // background threads can cleanup.
  shutdown_event_.Signal();
  io_thread_.reset();
  file_thread_.reset();
  // The NetworkChangeNotifier must be destroyed after all other threads that
  // might use it have been shut down.
  network_change_notifier_.reset();

  ServiceProcessState::GetInstance()->SignalStopped();
  return true;
}

void ServiceProcess::Shutdown() {
  // Quit the main message loop.
  main_message_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask());
}

bool ServiceProcess::HandleClientDisconnect() {
  // If there are no enabled services or if there is an update available
  // we want to shutdown right away. Else we want to keep listening for
  // new connections.
  if (!enabled_services_ || update_available()) {
    Shutdown();
    return false;
  }
  return true;
}

CloudPrintProxy* ServiceProcess::GetCloudPrintProxy() {
  if (!cloud_print_proxy_.get()) {
    cloud_print_proxy_.reset(new CloudPrintProxy());
    cloud_print_proxy_->Initialize(service_prefs_.get(), this);
  }
  return cloud_print_proxy_.get();
}

void ServiceProcess::OnCloudPrintProxyEnabled(bool persist_state) {
  if (persist_state) {
    // Save the preference that we have enabled the cloud print proxy.
    service_prefs_->SetBoolean(prefs::kCloudPrintProxyEnabled, true);
    service_prefs_->WritePrefs();
  }
  OnServiceEnabled();
}

void ServiceProcess::OnCloudPrintProxyDisabled(bool persist_state) {
  if (persist_state) {
    // Save the preference that we have disabled the cloud print proxy.
    service_prefs_->SetBoolean(prefs::kCloudPrintProxyEnabled, false);
    service_prefs_->WritePrefs();
  }
  OnServiceDisabled();
}

void ServiceProcess::OnRemotingHostEnabled() {
  OnServiceEnabled();
}

void ServiceProcess::OnRemotingHostDisabled() {
  OnServiceDisabled();
}

void ServiceProcess::OnServiceEnabled() {
  enabled_services_++;
  if (1 == enabled_services_) {
    ServiceProcessState::GetInstance()->AddToAutoRun();
  }
}

void ServiceProcess::OnServiceDisabled() {
  DCHECK_NE(enabled_services_, 0);
  enabled_services_--;
  if (0 == enabled_services_) {
    ServiceProcessState::GetInstance()->RemoveFromAutoRun();
    // We will wait for some time to respond to IPCs before shutting down.
    ScheduleShutdownCheck();
  }
}

void ServiceProcess::ScheduleShutdownCheck() {
  MessageLoop::current()->PostDelayedTask(
      FROM_HERE,
      NewRunnableMethod(this, &ServiceProcess::ShutdownIfNeeded),
      kShutdownDelay);
}

void ServiceProcess::ShutdownIfNeeded() {
  if (0 == enabled_services_) {
    if (ipc_server_->is_client_connected()) {
      // If there is a client connected, we need to try again later.
      // Note that there is still a timing window here because a client may
      // decide to connect at this point.
      // TODO(sanjeevr): Fix this timing window.
      ScheduleShutdownCheck();
    } else {
      Shutdown();
    }
  }
}

ServiceProcess::~ServiceProcess() {
  Teardown();
  g_service_process = NULL;
}

// Disable refcounting for runnable method because it is really not needed
// when we post tasks on the main message loop.
DISABLE_RUNNABLE_METHOD_REFCOUNT(ServiceProcess);
<|endoftext|>


<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"

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");

const char DefaultChecks[] =
    "*,"                       // Enable all checks, except these:
    "-clang-analyzer-alpha*,"  // Too many false positives.
    "-llvm-include-order,"     // Not implemented yet.
    "-google-*,";              // Doesn't apply to LLVM.

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<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("Fix detected errors if possible."),
                         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<bool>
DumpConfig("dump-config",
           cl::desc("Dumps configuration in the YAML format to stdout."),
           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));

static void printStats(const clang::tidy::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";
  }
}

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

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

  clang::tidy::ClangTidyOptions FallbackOptions;
  FallbackOptions.Checks = DefaultChecks;
  FallbackOptions.HeaderFilterRegex = HeaderFilter;
  FallbackOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;

  clang::tidy::ClangTidyOptions OverrideOptions;
  if (Checks.getNumOccurrences() > 0)
    OverrideOptions.Checks = Checks;
  if (HeaderFilter.getNumOccurrences() > 0)
    OverrideOptions.HeaderFilterRegex = HeaderFilter;
  if (AnalyzeTemporaryDtors.getNumOccurrences() > 0)
    OverrideOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;

  auto OptionsProvider = llvm::make_unique<clang::tidy::FileOptionsProvider>(
      GlobalOptions, FallbackOptions, OverrideOptions);

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

  // 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) {
    llvm::outs() << clang::tidy::configurationAsText(
                        clang::tidy::ClangTidyOptions::getDefaults()
                            .mergeWith(OptionsProvider->getOptions(FileName)))
                 << "\n";
    return 0;
  }

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

  std::vector<clang::tidy::ClangTidyError> Errors;
  clang::tidy::ClangTidyStats Stats = clang::tidy::runClangTidy(
      std::move(OptionsProvider), OptionsParser.getCompilations(),
      OptionsParser.getSourcePathList(), &Errors);
  clang::tidy::handleErrors(Errors, Fix);

  if (!ExportFixes.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;
    }
    clang::tidy::exportReplacements(Errors, OS);
  }

  printStats(Stats);
  return 0;
}

namespace clang {
namespace tidy {

// 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;

} // namespace tidy
} // namespace clang
<commit_msg>Don't write files with no fixes.<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"

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");

const char DefaultChecks[] =
    "*,"                       // Enable all checks, except these:
    "-clang-analyzer-alpha*,"  // Too many false positives.
    "-llvm-include-order,"     // Not implemented yet.
    "-google-*,";              // Doesn't apply to LLVM.

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<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("Fix detected errors if possible."),
                         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<bool>
DumpConfig("dump-config",
           cl::desc("Dumps configuration in the YAML format to stdout."),
           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));

static void printStats(const clang::tidy::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";
  }
}

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

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

  clang::tidy::ClangTidyOptions FallbackOptions;
  FallbackOptions.Checks = DefaultChecks;
  FallbackOptions.HeaderFilterRegex = HeaderFilter;
  FallbackOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;

  clang::tidy::ClangTidyOptions OverrideOptions;
  if (Checks.getNumOccurrences() > 0)
    OverrideOptions.Checks = Checks;
  if (HeaderFilter.getNumOccurrences() > 0)
    OverrideOptions.HeaderFilterRegex = HeaderFilter;
  if (AnalyzeTemporaryDtors.getNumOccurrences() > 0)
    OverrideOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;

  auto OptionsProvider = llvm::make_unique<clang::tidy::FileOptionsProvider>(
      GlobalOptions, FallbackOptions, OverrideOptions);

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

  // 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) {
    llvm::outs() << clang::tidy::configurationAsText(
                        clang::tidy::ClangTidyOptions::getDefaults()
                            .mergeWith(OptionsProvider->getOptions(FileName)))
                 << "\n";
    return 0;
  }

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

  std::vector<clang::tidy::ClangTidyError> Errors;
  clang::tidy::ClangTidyStats Stats = clang::tidy::runClangTidy(
      std::move(OptionsProvider), OptionsParser.getCompilations(),
      OptionsParser.getSourcePathList(), &Errors);
  clang::tidy::handleErrors(Errors, Fix);

  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;
    }
    clang::tidy::exportReplacements(Errors, OS);
  }

  printStats(Stats);
  return 0;
}

namespace clang {
namespace tidy {

// 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;

} // namespace tidy
} // namespace clang
<|endoftext|>


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

// EXTERNAL INCLUDES

// INTERNAL INCLUDES
#include "shared/view.h"

#include <dali-toolkit/dali-toolkit.h>
#include <dali-toolkit/devel-api/controls/magnifier/magnifier.h>
using namespace Dali;

namespace
{
const char* BACKGROUND_IMAGE( DALI_IMAGE_DIR "background-magnifier.jpg" );
const char* TOOLBAR_IMAGE( DALI_IMAGE_DIR "top-bar.png" );
const char* APPLICATION_TITLE( "Magnifier Example" );
const Vector3 MAGNIFIER_SIZE(0.25f, 0.25f, 0.0f);       ///< Magnifier sides should be 25% of the width of the stage
const float ANIMATION_DURATION(60.0f);                  ///< Run animation for a minute before repeating.
const float MAGNIFIER_DISPLAY_DURATION(0.125f);         ///< Duration in seconds for show/hide manual magnifier animation

const float MAGNIFICATION_FACTOR(2.0f);                 ///< Amount to magnify by.
const float MAGNIFIER_INDENT(10.0f);                    ///< Indentation around edge of stage to define where magnifiers may move.
const float FINGER_RADIUS_INCHES(0.25f);                ///< Average finger radius in inches from the center of index finger to edge.

/**
 * MagnifierPathConstraint
 * This constraint governs the position of the
 * animating magnifier in a swirly pattern around
 * the stage.
 */
struct MagnifierPathConstraint
{
  /**
   * Constraint constructor
   * @param[in] stageSize The stage size so that the constraint can create a path
   * within stage bounds.
   */
  MagnifierPathConstraint(const Vector3& stageSize,
                          Vector3 offset = Vector3::ZERO)
  : mStageSize(stageSize),
    mOffset(offset)
  {
  }

  void operator()( Vector3& current, const PropertyInputContainer& inputs )
  {
    float time = inputs[1]->GetFloat();
    const Vector3& size = inputs[0]->GetVector3();

    current = mOffset;

    Vector3 range( mStageSize - size - Vector3::ONE * MAGNIFIER_INDENT * 2.0f );
    current.x += 0.5f * sinf(time * 0.471f) * range.width;
    current.y += 0.5f * sinf(time * 0.8739f) * range.height;
  }

  Vector3 mStageSize;     ///< Keep track of the stage size for determining path within stage bounds
  Vector3 mOffset;        ///< Amount to offset magnifier path
};

/**
 * Confine Actor to boundaries of reference actor (e.g. Parent)
 * Actor bounds (top-left position + size) are confined to reference Actor's
 * bounds.
 */
struct ConfinementConstraint
{
  /**
   * Confinement constraint constructor.
   * @param[in] offsetOrigin (optional) Whether to offset the parent origin or not.
   * @param[in] topLeftMargin (optional) Top-Left margins (defaults to 0.0f, 0.0f)
   * @param[in] bottomRightMargin (optional) Bottom-Right margins (defaults to 0.0f, 0.0f)
   * @param[in] flipHorizontal (optional) whether to flip Actor to the other side X if near edge, and by
   * how much (defaults to 0.0f i.e. no flip)
   * @param[in] flipVertical (optional) whether to flip Actor to the other side Y if near edge, and by
   * how much (defaults to 0.0f i.e. no flip)
   */
  ConfinementConstraint(Vector3 offsetOrigin = Vector3::ZERO, Vector2 topLeftMargin = Vector2::ZERO, Vector2 bottomRightMargin = Vector2::ZERO, bool flipHorizontal = false, bool flipVertical = false)
  : mOffsetOrigin(offsetOrigin),
    mMinIndent(topLeftMargin),
    mMaxIndent(bottomRightMargin),
    mFlipHorizontal(flipHorizontal),
    mFlipVertical(flipVertical)
  {
  }

  void operator()( Vector3& current, const PropertyInputContainer& inputs )
  {
    const Vector3& size = inputs[0]->GetVector3();
    const Vector3 origin = inputs[1]->GetVector3();
    const Vector3& anchor = inputs[2]->GetVector3();
    const Vector3& referenceSize = inputs[3]->GetVector3();

    Vector3 offset(mOffsetOrigin * referenceSize);

    // Get actual position of Actor relative to parent's Top-Left.
    Vector3 position(current + offset + origin * referenceSize);

    current += offset;

    // if top-left corner is outside of Top-Left bounds, then push back in screen.
    Vector3 corner(position - size * anchor - mMinIndent);

    if(mFlipHorizontal && corner.x < 0.0f)
    {
      corner.x = 0.0f;
      current.x += size.width;
    }

    if(mFlipVertical && corner.y < 0.0f)
    {
      corner.y = 0.0f;
      current.y += size.height;
    }

    current.x -= std::min(corner.x, 0.0f);
    current.y -= std::min(corner.y, 0.0f);

    // if bottom-right corner is outside of Bottom-Right bounds, then push back in screen.
    corner += size - referenceSize + mMinIndent + mMaxIndent;

    if(mFlipHorizontal && corner.x > 0.0f)
    {
      corner.x = 0.0f;
      current.x -= size.width;
    }

    if(mFlipVertical && corner.y > 0.0f)
    {
      corner.y = 0.0f;
      current.y -= size.height;
    }

    current.x -= std::max(corner.x, 0.0f);
    current.y -= std::max(corner.y, 0.0f);
  }

  Vector3 mOffsetOrigin;                                ///< Manual Parent Offset Origin.
  Vector3 mMinIndent;                                   ///< Top-Left Margin
  Vector3 mMaxIndent;                                   ///< Bottom-Right Margin.
  bool mFlipHorizontal;                                 ///< Whether to flip actor's position if exceeds horizontal screen bounds
  bool mFlipVertical;                                   ///< Whether to flip actor's position if exceeds vertical screen bounds
};

}

// This example shows how to use the Magnifier component.
//
class ExampleController : public ConnectionTracker
{
public:

  /**
   * The example controller constructor.
   * @param[in] application The application instance
   */
  ExampleController( Application& application )
  : mApplication( application ),
    mView(),
    mAnimationTime(0.0f),
    mMagnifierShown(false)
  {
    // Connect to the Application's Init signal
    mApplication.InitSignal().Connect( this, &ExampleController::Create );
  }

  /**
   * The example controller destructor
   */
  ~ExampleController()
  {
    // Nothing to do here;
  }

  /**
   * Invoked upon creation of application
   * @param[in] application The application instance
   */
  void Create( Application& application )
  {
    Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleController::OnKeyEvent);

    mStageSize = Stage::GetCurrent().GetSize();

    // The Init signal is received once (only) during the Application lifetime

    // Hide the indicator bar
    application.GetWindow().ShowIndicator( Dali::Window::INVISIBLE );

    // Creates a default view with a default tool bar.
    // The view is added to the stage.
    Toolkit::ToolBar toolBar;
    mContent = DemoHelper::CreateView( application,
                                       mView,
                                       toolBar,
                                       BACKGROUND_IMAGE,
                                       TOOLBAR_IMAGE,
                                       APPLICATION_TITLE );

    mContent.SetLeaveRequired(true);
    mContent.TouchedSignal().Connect( this, &ExampleController::OnTouched );

    // Create magnifier (controlled by human touch)
    Layer overlay = Layer::New();
    overlay.SetSensitive(false);
    overlay.SetParentOrigin( ParentOrigin::CENTER );
    overlay.SetSize(mStageSize);
    Stage::GetCurrent().Add(overlay);

    mMagnifier = Toolkit::Magnifier::New();
    mMagnifier.SetSourceActor( mView.GetChildAt( 0 ) );
    mMagnifier.SetSize( MAGNIFIER_SIZE * mStageSize.width );  // Size of magnifier is in relation to stage width
    mMagnifier.SetMagnificationFactor( MAGNIFICATION_FACTOR );
    mMagnifier.SetScale(Vector3::ZERO);
    overlay.Add( mMagnifier );

    // Apply constraint to animate the position of the magnifier.
    Constraint constraint = Constraint::New<Vector3>( mMagnifier, Actor::Property::POSITION, ConfinementConstraint(Vector3( 0.5f, 0.5f, 0.0f ), Vector2::ONE * MAGNIFIER_INDENT, Vector2::ONE * MAGNIFIER_INDENT) );
    constraint.AddSource( LocalSource(Actor::Property::SIZE) );
    constraint.AddSource( LocalSource(Actor::Property::PARENT_ORIGIN) );
    constraint.AddSource( LocalSource(Actor::Property::ANCHOR_POINT) );
    constraint.AddSource( ParentSource(Actor::Property::SIZE) );
    constraint.SetRemoveAction(Constraint::Discard);
    constraint.Apply();

    // Create bouncing magnifier automatically bounces around screen.
    mBouncingMagnifier = Toolkit::Magnifier::New();
    mBouncingMagnifier.SetSourceActor( mView.GetChildAt( 0 ) );
    mBouncingMagnifier.SetSize( MAGNIFIER_SIZE * mStageSize.width ); // Size of magnifier is in relation to stage width
    mBouncingMagnifier.SetMagnificationFactor( MAGNIFICATION_FACTOR );
    overlay.Add( mBouncingMagnifier );

    mAnimationTimeProperty = mBouncingMagnifier.RegisterProperty("animation-time", 0.0f);
    ContinueAnimation();

    // Apply constraint to animate the position of the magnifier.
    constraint = Constraint::New<Vector3>( mBouncingMagnifier, Actor::Property::POSITION, MagnifierPathConstraint(mStageSize, mStageSize * 0.5f) );
    constraint.AddSource( LocalSource(Actor::Property::SIZE) );
    constraint.AddSource( LocalSource(mAnimationTimeProperty) );
    constraint.Apply();

    // Apply constraint to animate the source of the magnifier.
    constraint = Constraint::New<Vector3>( mBouncingMagnifier, mBouncingMagnifier.GetPropertyIndex( Toolkit::Magnifier::SOURCE_POSITION_PROPERTY_NAME ), MagnifierPathConstraint(mStageSize) );
    constraint.AddSource( LocalSource(Actor::Property::SIZE) );
    constraint.AddSource( LocalSource(mAnimationTimeProperty) );
    constraint.Apply();
  }

  /**
   * Invoked whenever the animation finishes (every 60 seconds)
   * @param[in] animation The animation
   */
  void OnAnimationFinished( Animation& animation )
  {
    animation.FinishedSignal().Disconnect(this, &ExampleController::OnAnimationFinished);
    animation.Clear();
    ContinueAnimation();
  }

  /**
   * Resumes animation for another ANIMATION_DURATION seconds.
   */
  void ContinueAnimation()
  {
    Animation animation = Animation::New(ANIMATION_DURATION);
    mAnimationTime += ANIMATION_DURATION;
    animation.AnimateTo( Property(mBouncingMagnifier, mAnimationTimeProperty), mAnimationTime );
    animation.Play();
    animation.FinishedSignal().Connect(this, &ExampleController::OnAnimationFinished);
  }

  /**
   * Invoked whenever the quit button is clicked
   * @param[in] button the quit button
   */
  bool OnQuitButtonClicked( Toolkit::Button button )
  {
    // quit the application
    mApplication.Quit();
    return true;
  }

  /**
   * Invoked whenever the content (screen) is touched
   * @param[in] actor The actor that received the touch
   * @param[in] event The touch-event information
   */
  bool OnTouched( Actor actor, const TouchEvent& event )
  {
    if(event.GetPointCount() > 0)
    {
      const TouchPoint& point = event.GetPoint(0);
      switch(point.state)
      {
        case TouchPoint::Down:
        case TouchPoint::Motion:
        {
          ShowMagnifier();
          break;
        }
        case TouchPoint::Up:
        case TouchPoint::Leave:
        case TouchPoint::Interrupted:
        {
          HideMagnifier();
          break;
        }
        default:
        {
          break;
        }
      } // end switch

      Vector3 touchPoint(point.screen);

      SetMagnifierPosition(touchPoint - mStageSize * 0.5f);
    }

    return false;
  }

  /**
   * Shows the magnifier
   */
  void ShowMagnifier()
  {
    if(!mMagnifierShown)
    {
      Animation animation = Animation::New(MAGNIFIER_DISPLAY_DURATION);
      animation.AnimateTo(Property(mMagnifier, Actor::Property::SCALE), Vector3::ONE, AlphaFunction::EASE_IN);
      animation.Play();
      mMagnifierShown = true;
    }
  }

  /**
   * Hides the magnifier
   */
  void HideMagnifier()
  {
    if(mMagnifierShown)
    {
      Animation animation = Animation::New(MAGNIFIER_DISPLAY_DURATION);
      animation.AnimateTo(Property(mMagnifier, Actor::Property::SCALE), Vector3::ZERO, AlphaFunction::EASE_OUT);
      animation.Play();
      mMagnifierShown = false;
    }
  }

  /**
   * Manually sets the magnifier position
   * @param[in] position The magnifier's position relative to center of stage
   */
  void SetMagnifierPosition(const Vector3 position)
  {
    mMagnifier.SetSourcePosition( position );

    // position magnifier glass such that bottom edge is touching/near top of finger.
    Vector3 glassPosition(position);
    glassPosition.y -= mStageSize.width * MAGNIFIER_SIZE.height * 0.5f + Stage::GetCurrent().GetDpi().height * FINGER_RADIUS_INCHES;

    mMagnifier.SetPosition( glassPosition );
  }

  void OnKeyEvent(const KeyEvent& event)
  {
    if(event.state == KeyEvent::Down)
    {
      if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
      {
        mApplication.Quit();
      }
    }
  }

private:

  Application&  mApplication;                             ///< Application instance
  Toolkit::Control mView;                                 ///< The view
  Layer mContent;                                         ///< The content layer
  Toolkit::Magnifier mMagnifier;                          ///< The manually controlled magnifier
  Toolkit::Magnifier mBouncingMagnifier;                  ///< The animating magnifier (swirly animation)
  Vector3 mStageSize;                                     ///< The size of the stage
  float mAnimationTime;                                   ///< Keep track of start animation time.
  Property::Index mAnimationTimeProperty;                 ///< Animation time property (responsible for swirly animation)
  bool mMagnifierShown;                                   ///< Flag indicating whether the magnifier is being shown or not.

};

void RunTest( Application& application )
{
  ExampleController test( application );

  application.MainLoop();
}

// Entry point for Linux & Tizen applications
//
int main( int argc, char **argv )
{
  Application application = Application::New( &argc, &argv, DALI_DEMO_THEME_PATH );

  RunTest( application );

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

// EXTERNAL INCLUDES

// INTERNAL INCLUDES
#include "shared/view.h"

#include <dali-toolkit/dali-toolkit.h>
#include <dali-toolkit/devel-api/controls/magnifier/magnifier.h>
using namespace Dali;

namespace
{
const char* BACKGROUND_IMAGE( DALI_IMAGE_DIR "background-magnifier.jpg" );
const char* TOOLBAR_IMAGE( DALI_IMAGE_DIR "top-bar.png" );
const char* APPLICATION_TITLE( "Magnifier Example" );
const Vector3 MAGNIFIER_SIZE(0.25f, 0.25f, 0.0f);       ///< Magnifier sides should be 25% of the width of the stage
const float ANIMATION_DURATION(60.0f);                  ///< Run animation for a minute before repeating.
const float MAGNIFIER_DISPLAY_DURATION(0.125f);         ///< Duration in seconds for show/hide manual magnifier animation

const float MAGNIFICATION_FACTOR(2.0f);                 ///< Amount to magnify by.
const float MAGNIFIER_INDENT(10.0f);                    ///< Indentation around edge of stage to define where magnifiers may move.
const float FINGER_RADIUS_INCHES(0.25f);                ///< Average finger radius in inches from the center of index finger to edge.

/**
 * MagnifierPathConstraint
 * This constraint governs the position of the
 * animating magnifier in a swirly pattern around
 * the stage.
 */
struct MagnifierPathConstraint
{
  /**
   * Constraint constructor
   * @param[in] stageSize The stage size so that the constraint can create a path
   * within stage bounds.
   */
  MagnifierPathConstraint(const Vector3& stageSize,
                          Vector3 offset = Vector3::ZERO)
  : mStageSize(stageSize),
    mOffset(offset)
  {
  }

  void operator()( Vector3& current, const PropertyInputContainer& inputs )
  {
    float time = inputs[1]->GetFloat();
    const Vector3& size = inputs[0]->GetVector3();

    current = mOffset;

    Vector3 range( mStageSize - size - Vector3::ONE * MAGNIFIER_INDENT * 2.0f );
    current.x += 0.5f * sinf(time * 0.471f) * range.width;
    current.y += 0.5f * sinf(time * 0.8739f) * range.height;
  }

  Vector3 mStageSize;     ///< Keep track of the stage size for determining path within stage bounds
  Vector3 mOffset;        ///< Amount to offset magnifier path
};

/**
 * Confine Actor to boundaries of reference actor (e.g. Parent)
 * Actor bounds (top-left position + size) are confined to reference Actor's
 * bounds.
 */
struct ConfinementConstraint
{
  /**
   * Confinement constraint constructor.
   * @param[in] offsetOrigin (optional) Whether to offset the parent origin or not.
   * @param[in] topLeftMargin (optional) Top-Left margins (defaults to 0.0f, 0.0f)
   * @param[in] bottomRightMargin (optional) Bottom-Right margins (defaults to 0.0f, 0.0f)
   * @param[in] flipHorizontal (optional) whether to flip Actor to the other side X if near edge, and by
   * how much (defaults to 0.0f i.e. no flip)
   * @param[in] flipVertical (optional) whether to flip Actor to the other side Y if near edge, and by
   * how much (defaults to 0.0f i.e. no flip)
   */
  ConfinementConstraint(Vector3 offsetOrigin = Vector3::ZERO, Vector2 topLeftMargin = Vector2::ZERO, Vector2 bottomRightMargin = Vector2::ZERO, bool flipHorizontal = false, bool flipVertical = false)
  : mOffsetOrigin(offsetOrigin),
    mMinIndent(topLeftMargin),
    mMaxIndent(bottomRightMargin),
    mFlipHorizontal(flipHorizontal),
    mFlipVertical(flipVertical)
  {
  }

  void operator()( Vector3& current, const PropertyInputContainer& inputs )
  {
    const Vector3& size = inputs[0]->GetVector3();
    const Vector3 origin = inputs[1]->GetVector3();
    const Vector3& anchor = inputs[2]->GetVector3();
    const Vector3& referenceSize = inputs[3]->GetVector3();

    Vector3 offset(mOffsetOrigin * referenceSize);

    // Get actual position of Actor relative to parent's Top-Left.
    Vector3 position(current + offset + origin * referenceSize);

    current += offset;

    // if top-left corner is outside of Top-Left bounds, then push back in screen.
    Vector3 corner(position - size * anchor - mMinIndent);

    if(mFlipHorizontal && corner.x < 0.0f)
    {
      corner.x = 0.0f;
      current.x += size.width;
    }

    if(mFlipVertical && corner.y < 0.0f)
    {
      corner.y = 0.0f;
      current.y += size.height;
    }

    current.x -= std::min(corner.x, 0.0f);
    current.y -= std::min(corner.y, 0.0f);

    // if bottom-right corner is outside of Bottom-Right bounds, then push back in screen.
    corner += size - referenceSize + mMinIndent + mMaxIndent;

    if(mFlipHorizontal && corner.x > 0.0f)
    {
      corner.x = 0.0f;
      current.x -= size.width;
    }

    if(mFlipVertical && corner.y > 0.0f)
    {
      corner.y = 0.0f;
      current.y -= size.height;
    }

    current.x -= std::max(corner.x, 0.0f);
    current.y -= std::max(corner.y, 0.0f);
  }

  Vector3 mOffsetOrigin;                                ///< Manual Parent Offset Origin.
  Vector3 mMinIndent;                                   ///< Top-Left Margin
  Vector3 mMaxIndent;                                   ///< Bottom-Right Margin.
  bool mFlipHorizontal;                                 ///< Whether to flip actor's position if exceeds horizontal screen bounds
  bool mFlipVertical;                                   ///< Whether to flip actor's position if exceeds vertical screen bounds
};

}

// This example shows how to use the Magnifier component.
//
class ExampleController : public ConnectionTracker
{
public:

  /**
   * The example controller constructor.
   * @param[in] application The application instance
   */
  ExampleController( Application& application )
  : mApplication( application ),
    mView(),
    mAnimationTime(0.0f),
    mMagnifierShown(false)
  {
    // Connect to the Application's Init signal
    mApplication.InitSignal().Connect( this, &ExampleController::Create );
  }

  /**
   * The example controller destructor
   */
  ~ExampleController()
  {
    // Nothing to do here;
  }

  /**
   * Invoked upon creation of application
   * @param[in] application The application instance
   */
  void Create( Application& application )
  {
    Stage::GetCurrent().KeyEventSignal().Connect(this, &ExampleController::OnKeyEvent);

    mStageSize = Stage::GetCurrent().GetSize();

    // The Init signal is received once (only) during the Application lifetime

    // Hide the indicator bar
    application.GetWindow().ShowIndicator( Dali::Window::INVISIBLE );

    // Creates a default view with a default tool bar.
    // The view is added to the stage.
    Toolkit::ToolBar toolBar;
    mContent = DemoHelper::CreateView( application,
                                       mView,
                                       toolBar,
                                       BACKGROUND_IMAGE,
                                       TOOLBAR_IMAGE,
                                       APPLICATION_TITLE );

    mContent.SetLeaveRequired(true);
    mContent.TouchedSignal().Connect( this, &ExampleController::OnTouched );

    // Create magnifier (controlled by human touch)
    Layer overlay = Layer::New();
    overlay.SetSensitive(false);
    overlay.SetParentOrigin( ParentOrigin::CENTER );
    overlay.SetSize(mStageSize);
    Stage::GetCurrent().Add(overlay);

    mMagnifier = Toolkit::Magnifier::New();
    mMagnifier.SetSourceActor( mView.GetChildAt( 0 ) );
    mMagnifier.SetSize( MAGNIFIER_SIZE * mStageSize.width );  // Size of magnifier is in relation to stage width
    mMagnifier.SetProperty( Toolkit::Magnifier::Property::MAGNIFICATION_FACTOR, MAGNIFICATION_FACTOR );
    mMagnifier.SetScale(Vector3::ZERO);
    overlay.Add( mMagnifier );

    // Apply constraint to animate the position of the magnifier.
    Constraint constraint = Constraint::New<Vector3>( mMagnifier, Actor::Property::POSITION, ConfinementConstraint(Vector3( 0.5f, 0.5f, 0.0f ), Vector2::ONE * MAGNIFIER_INDENT, Vector2::ONE * MAGNIFIER_INDENT) );
    constraint.AddSource( LocalSource(Actor::Property::SIZE) );
    constraint.AddSource( LocalSource(Actor::Property::PARENT_ORIGIN) );
    constraint.AddSource( LocalSource(Actor::Property::ANCHOR_POINT) );
    constraint.AddSource( ParentSource(Actor::Property::SIZE) );
    constraint.SetRemoveAction(Constraint::Discard);
    constraint.Apply();

    // Create bouncing magnifier automatically bounces around screen.
    mBouncingMagnifier = Toolkit::Magnifier::New();
    mBouncingMagnifier.SetSourceActor( mView.GetChildAt( 0 ) );
    mBouncingMagnifier.SetSize( MAGNIFIER_SIZE * mStageSize.width ); // Size of magnifier is in relation to stage width
    mBouncingMagnifier.SetProperty( Toolkit::Magnifier::Property::MAGNIFICATION_FACTOR, MAGNIFICATION_FACTOR );
    overlay.Add( mBouncingMagnifier );

    mAnimationTimeProperty = mBouncingMagnifier.RegisterProperty("animation-time", 0.0f);
    ContinueAnimation();

    // Apply constraint to animate the position of the magnifier.
    constraint = Constraint::New<Vector3>( mBouncingMagnifier, Actor::Property::POSITION, MagnifierPathConstraint(mStageSize, mStageSize * 0.5f) );
    constraint.AddSource( LocalSource(Actor::Property::SIZE) );
    constraint.AddSource( LocalSource(mAnimationTimeProperty) );
    constraint.Apply();

    // Apply constraint to animate the source of the magnifier.
    constraint = Constraint::New<Vector3>( mBouncingMagnifier, Toolkit::Magnifier::Property::SOURCE_POSITION, MagnifierPathConstraint(mStageSize) );
    constraint.AddSource( LocalSource(Actor::Property::SIZE) );
    constraint.AddSource( LocalSource(mAnimationTimeProperty) );
    constraint.Apply();
  }

  /**
   * Invoked whenever the animation finishes (every 60 seconds)
   * @param[in] animation The animation
   */
  void OnAnimationFinished( Animation& animation )
  {
    animation.FinishedSignal().Disconnect(this, &ExampleController::OnAnimationFinished);
    animation.Clear();
    ContinueAnimation();
  }

  /**
   * Resumes animation for another ANIMATION_DURATION seconds.
   */
  void ContinueAnimation()
  {
    Animation animation = Animation::New(ANIMATION_DURATION);
    mAnimationTime += ANIMATION_DURATION;
    animation.AnimateTo( Property(mBouncingMagnifier, mAnimationTimeProperty), mAnimationTime );
    animation.Play();
    animation.FinishedSignal().Connect(this, &ExampleController::OnAnimationFinished);
  }

  /**
   * Invoked whenever the quit button is clicked
   * @param[in] button the quit button
   */
  bool OnQuitButtonClicked( Toolkit::Button button )
  {
    // quit the application
    mApplication.Quit();
    return true;
  }

  /**
   * Invoked whenever the content (screen) is touched
   * @param[in] actor The actor that received the touch
   * @param[in] event The touch-event information
   */
  bool OnTouched( Actor actor, const TouchEvent& event )
  {
    if(event.GetPointCount() > 0)
    {
      const TouchPoint& point = event.GetPoint(0);
      switch(point.state)
      {
        case TouchPoint::Down:
        case TouchPoint::Motion:
        {
          ShowMagnifier();
          break;
        }
        case TouchPoint::Up:
        case TouchPoint::Leave:
        case TouchPoint::Interrupted:
        {
          HideMagnifier();
          break;
        }
        default:
        {
          break;
        }
      } // end switch

      Vector3 touchPoint(point.screen);

      SetMagnifierPosition(touchPoint - mStageSize * 0.5f);
    }

    return false;
  }

  /**
   * Shows the magnifier
   */
  void ShowMagnifier()
  {
    if(!mMagnifierShown)
    {
      Animation animation = Animation::New(MAGNIFIER_DISPLAY_DURATION);
      animation.AnimateTo(Property(mMagnifier, Actor::Property::SCALE), Vector3::ONE, AlphaFunction::EASE_IN);
      animation.Play();
      mMagnifierShown = true;
    }
  }

  /**
   * Hides the magnifier
   */
  void HideMagnifier()
  {
    if(mMagnifierShown)
    {
      Animation animation = Animation::New(MAGNIFIER_DISPLAY_DURATION);
      animation.AnimateTo(Property(mMagnifier, Actor::Property::SCALE), Vector3::ZERO, AlphaFunction::EASE_OUT);
      animation.Play();
      mMagnifierShown = false;
    }
  }

  /**
   * Manually sets the magnifier position
   * @param[in] position The magnifier's position relative to center of stage
   */
  void SetMagnifierPosition(const Vector3 position)
  {
    mMagnifier.SetProperty( Toolkit::Magnifier::Property::SOURCE_POSITION, position );

    // position magnifier glass such that bottom edge is touching/near top of finger.
    Vector3 glassPosition(position);
    glassPosition.y -= mStageSize.width * MAGNIFIER_SIZE.height * 0.5f + Stage::GetCurrent().GetDpi().height * FINGER_RADIUS_INCHES;

    mMagnifier.SetPosition( glassPosition );
  }

  void OnKeyEvent(const KeyEvent& event)
  {
    if(event.state == KeyEvent::Down)
    {
      if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
      {
        mApplication.Quit();
      }
    }
  }

private:

  Application&  mApplication;                             ///< Application instance
  Toolkit::Control mView;                                 ///< The view
  Layer mContent;                                         ///< The content layer
  Toolkit::Magnifier mMagnifier;                          ///< The manually controlled magnifier
  Toolkit::Magnifier mBouncingMagnifier;                  ///< The animating magnifier (swirly animation)
  Vector3 mStageSize;                                     ///< The size of the stage
  float mAnimationTime;                                   ///< Keep track of start animation time.
  Property::Index mAnimationTimeProperty;                 ///< Animation time property (responsible for swirly animation)
  bool mMagnifierShown;                                   ///< Flag indicating whether the magnifier is being shown or not.

};

void RunTest( Application& application )
{
  ExampleController test( application );

  application.MainLoop();
}

// Entry point for Linux & Tizen applications
//
int main( int argc, char **argv )
{
  Application application = Application::New( &argc, &argv, DALI_DEMO_THEME_PATH );

  RunTest( application );

  return 0;
}
<|endoftext|>


<commit_before>#include <gmi_null.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <apf.h>
#include <apfShape.h>
#include <PCU.h>

namespace {

apf::Vector3 points[4] =
{apf::Vector3(0,0,0),
 apf::Vector3(1,0,0),
 apf::Vector3(0,1,0),
 apf::Vector3(0,1,2)};

apf::Mesh2* createMesh()
{
  gmi_model* model = gmi_load(".null");
  return apf::makeEmptyMdsMesh(model,3,false);
}

apf::MeshElement* createTet(apf::Mesh2* m, apf::Vector3 const* points)
{
  apf::MeshEntity* e = apf::buildOneElement(
      m,m->findModelEntity(3,0),apf::Mesh::TET,points);
  return apf::createMeshElement(m,e);
}

void setFieldValues(apf::Field* f, int dim, double v)
{
  apf::Mesh* m = apf::getMesh(f);
  apf::MeshEntity* e;
  apf::MeshIterator* it = m->begin(dim);
  while ((e = m->iterate(it)))
    apf::setScalar(f,e,0,v);
}

apf::Field* createTestField(apf::Mesh2* m)
{
  apf::Field* f = apf::createHierarchicField(m,"test",apf::SCALAR,2);
  for (int d=0; d < 2; ++d)
    setFieldValues(f,d,1.0);
  return f;
}

void testInterpolation(apf::Element* e)
{
  double v = 0.350480947161671;
  apf::Vector3 p(0.25,0.25,0.25);
  assert( (apf::getScalar(e,p) - v) < 1e-12 );
}

void testShapeGrads(apf::Element* e)
{
  apf::Vector3 p(0.25,0.25,0.25);
  apf::NewArray<apf::Vector3> grads;
  apf::getShapeGrads(e,p,grads);
}

void testHierarchic(apf::Mesh2* m)
{
  apf::MeshElement* me = createTet(m,points);
  apf::Field* f = createTestField(m);
  apf::Element* e = apf::createElement(f,me);
  testInterpolation(e);
  testShapeGrads(e);
  apf::destroyField(f);
}

}

int main(int argc, char** argv)
{
  MPI_Init(&argc,&argv);
  PCU_Comm_Init();
  PCU_Protect();
  gmi_register_null();
  apf::Mesh2* m = createMesh();
  testHierarchic(m);
  apf::destroyMesh(m);
  PCU_Comm_Free();
  MPI_Finalize();
}

<commit_msg>fixing hierarchic test error<commit_after>#include <gmi_null.h>
#include <apfMDS.h>
#include <apfMesh2.h>
#include <apf.h>
#include <apfShape.h>
#include <PCU.h>

namespace {

apf::Vector3 points[4] =
{apf::Vector3(0,0,0),
 apf::Vector3(1,0,0),
 apf::Vector3(0,1,0),
 apf::Vector3(0,1,2)};

apf::Mesh2* createMesh()
{
  gmi_model* model = gmi_load(".null");
  return apf::makeEmptyMdsMesh(model,3,false);
}

apf::MeshElement* createTet(apf::Mesh2* m, apf::Vector3 const* points)
{
  apf::MeshEntity* e = apf::buildOneElement(
      m,m->findModelEntity(3,0),apf::Mesh::TET,points);
  return apf::createMeshElement(m,e);
}

void setFieldValues(apf::Field* f, int dim, double v)
{
  apf::Mesh* m = apf::getMesh(f);
  apf::MeshEntity* e;
  apf::MeshIterator* it = m->begin(dim);
  while ((e = m->iterate(it)))
    apf::setScalar(f,e,0,v);
}

apf::Field* createTestField(apf::Mesh2* m)
{
  apf::Field* f = apf::createHierarchicField(m,"test",apf::SCALAR);
  for (int d=0; d < 2; ++d)
    setFieldValues(f,d,1.0);
  return f;
}

void testInterpolation(apf::Element* e)
{
  double v = 0.350480947161671;
  apf::Vector3 p(0.25,0.25,0.25);
  assert( (apf::getScalar(e,p) - v) < 1e-12 );
}

void testShapeGrads(apf::Element* e)
{
  apf::Vector3 p(0.25,0.25,0.25);
  apf::NewArray<apf::Vector3> grads;
  apf::getShapeGrads(e,p,grads);
}

void testHierarchic(apf::Mesh2* m)
{
  apf::MeshElement* me = createTet(m,points);
  apf::Field* f = createTestField(m);
  apf::Element* e = apf::createElement(f,me);
  testInterpolation(e);
  testShapeGrads(e);
  apf::destroyField(f);
}

}

int main(int argc, char** argv)
{
  MPI_Init(&argc,&argv);
  PCU_Comm_Init();
  PCU_Protect();
  gmi_register_null();
  apf::Mesh2* m = createMesh();
  testHierarchic(m);
  apf::destroyMesh(m);
  PCU_Comm_Free();
  MPI_Finalize();
}

<|endoftext|>


<commit_before>/* vcal-setup.cc                        KPilot
**
** Copyright (C) 2002-2003 Reinhold Kainhofer
** Copyright (C) 2001 by Dan Pilone
**
** This file defines the setup dialog for the vcal-conduit plugin.
*/

/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program 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 in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/

#include "options.h"

#include <qtabwidget.h>
#include <qcheckbox.h>
#include <qbuttongroup.h>
#include <qcombobox.h>

#include <kconfig.h>
#include <kurlrequester.h>

#include "korganizerConduit.h"
#include "vcal-factory.h"
#include "vcal-setup.h"

VCalWidgetSetupBase::VCalWidgetSetupBase(QWidget *w, const char *n) :
	ConduitConfigBase(w,n),
	fConfigWidget(new VCalWidget(w))
{
	FUNCTIONSETUP;
	fWidget=fConfigWidget;

	fConfigWidget->fCalendarFile->setMode( KFile::File | KFile::LocalOnly );
	fConfigWidget->fCalendarFile->setFilter("*.vcs *.ics|ICalendars\n*.*|All Files (*.*)");

#define CM(a,b) connect(fConfigWidget->a,b,this,SLOT(modified()));
	CM(fSyncDestination,SIGNAL(clicked(int)));
	CM(fCalendarFile,SIGNAL(textChanged(const QString &)));
	CM(fArchive,SIGNAL(toggled(bool)));
	CM(fConflictResolution,SIGNAL(activated(int)));
#undef CM
}

VCalWidgetSetupBase::~VCalWidgetSetupBase()
{
	FUNCTIONSETUP;
}

/* virtual */ void VCalWidgetSetupBase::commit(KConfig *fConfig)
{
	FUNCTIONSETUP;
	if (!fConfig) return;
	KConfigGroupSaver s(fConfig,configGroup());
	// General page
	fConfig->writeEntry(VCalConduitFactoryBase::calendarType,
		fConfigWidget->fSyncDestination->id(
			fConfigWidget->fSyncDestination->selected()));
	fConfig->writePathEntry(VCalConduitFactoryBase::calendarFile,
		fConfigWidget->fCalendarFile->url());

	fConfig->writeEntry(VCalConduitFactoryBase::archive,
		fConfigWidget->fArchive->isChecked());

	// Conflicts page
	fConfig->writeEntry(VCalConduitFactoryBase::conflictResolution,
		fConfigWidget->fConflictResolution->currentItem()+SyncAction::eCROffset);

	unmodified();
}

/* virtual */ void VCalWidgetSetupBase::load(KConfig *fConfig)
{
	FUNCTIONSETUP;

	if (!fConfig) return;
	KConfigGroupSaver s(fConfig, configGroup());

	// General page
	fConfigWidget->fSyncDestination->setButton(
		fConfig->readNumEntry(VCalConduitFactoryBase::calendarType, 0));
	fConfigWidget->fCalendarFile->setURL( fConfig->readPathEntry(
		VCalConduitFactoryBase::calendarFile));

	fConfigWidget->fArchive->setChecked(
		fConfig->readBoolEntry(VCalConduitFactoryBase::archive, true));

	// Conflicts page
	fConfigWidget->fConflictResolution->setCurrentItem(
		fConfig->readNumEntry(VCalConduitFactoryBase::conflictResolution,
		SyncAction::eUseGlobalSetting)-SyncAction::eCROffset);

	unmodified();
}

VCalWidgetSetup::VCalWidgetSetup(QWidget *w, const char *n) :
	VCalWidgetSetupBase(w,n)
{
	UIDialog::addAboutPage(fConfigWidget->tabWidget,VCalConduitFactory::about());
	fConfigWidget->fSyncDestination->setTitle(i18n("Calendar Destination"));
	fConduitName=i18n("Calendar");
	fGroupName=QString::fromLatin1(VCalConduitFactory::group);

}

/* static */ ConduitConfigBase *VCalWidgetSetup::create(QWidget *w,const char *n)
{
	return new VCalWidgetSetup(w,n);
}

<commit_msg>Make unsermake happy (complains if not all moc files are included, and the same source file is included in multiple targets)<commit_after>/* vcal-setup.cc                        KPilot
**
** Copyright (C) 2002-2003 Reinhold Kainhofer
** Copyright (C) 2001 by Dan Pilone
**
** This file defines the setup dialog for the vcal-conduit plugin.
*/

/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program 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 in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/

#include "options.h"

#include <qtabwidget.h>
#include <qcheckbox.h>
#include <qbuttongroup.h>
#include <qcombobox.h>

#include <kconfig.h>
#include <kurlrequester.h>

#include "korganizerConduit.h"
#include "vcal-factory.h"
#include "vcal-setup.h"

VCalWidgetSetupBase::VCalWidgetSetupBase(QWidget *w, const char *n) :
	ConduitConfigBase(w,n),
	fConfigWidget(new VCalWidget(w))
{
	FUNCTIONSETUP;
	fWidget=fConfigWidget;

	fConfigWidget->fCalendarFile->setMode( KFile::File | KFile::LocalOnly );
	fConfigWidget->fCalendarFile->setFilter("*.vcs *.ics|ICalendars\n*.*|All Files (*.*)");

#define CM(a,b) connect(fConfigWidget->a,b,this,SLOT(modified()));
	CM(fSyncDestination,SIGNAL(clicked(int)));
	CM(fCalendarFile,SIGNAL(textChanged(const QString &)));
	CM(fArchive,SIGNAL(toggled(bool)));
	CM(fConflictResolution,SIGNAL(activated(int)));
#undef CM
}

VCalWidgetSetupBase::~VCalWidgetSetupBase()
{
	FUNCTIONSETUP;
}

/* virtual */ void VCalWidgetSetupBase::commit(KConfig *fConfig)
{
	FUNCTIONSETUP;
	if (!fConfig) return;
	KConfigGroupSaver s(fConfig,configGroup());
	// General page
	fConfig->writeEntry(VCalConduitFactoryBase::calendarType,
		fConfigWidget->fSyncDestination->id(
			fConfigWidget->fSyncDestination->selected()));
	fConfig->writePathEntry(VCalConduitFactoryBase::calendarFile,
		fConfigWidget->fCalendarFile->url());

	fConfig->writeEntry(VCalConduitFactoryBase::archive,
		fConfigWidget->fArchive->isChecked());

	// Conflicts page
	fConfig->writeEntry(VCalConduitFactoryBase::conflictResolution,
		fConfigWidget->fConflictResolution->currentItem()+SyncAction::eCROffset);

	unmodified();
}

/* virtual */ void VCalWidgetSetupBase::load(KConfig *fConfig)
{
	FUNCTIONSETUP;

	if (!fConfig) return;
	KConfigGroupSaver s(fConfig, configGroup());

	// General page
	fConfigWidget->fSyncDestination->setButton(
		fConfig->readNumEntry(VCalConduitFactoryBase::calendarType, 0));
	fConfigWidget->fCalendarFile->setURL( fConfig->readPathEntry(
		VCalConduitFactoryBase::calendarFile));

	fConfigWidget->fArchive->setChecked(
		fConfig->readBoolEntry(VCalConduitFactoryBase::archive, true));

	// Conflicts page
	fConfigWidget->fConflictResolution->setCurrentItem(
		fConfig->readNumEntry(VCalConduitFactoryBase::conflictResolution,
		SyncAction::eUseGlobalSetting)-SyncAction::eCROffset);

	unmodified();
}

VCalWidgetSetup::VCalWidgetSetup(QWidget *w, const char *n) :
	VCalWidgetSetupBase(w,n)
{
	UIDialog::addAboutPage(fConfigWidget->tabWidget,VCalConduitFactory::about());
	fConfigWidget->fSyncDestination->setTitle(i18n("Calendar Destination"));
	fConduitName=i18n("Calendar");
	fGroupName=QString::fromLatin1(VCalConduitFactory::group);

}

/* static */ ConduitConfigBase *VCalWidgetSetup::create(QWidget *w,const char *n)
{
	return new VCalWidgetSetup(w,n);
}

#include "vcal-setup.moc"
<|endoftext|>