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

#include "chrome/common/pepper_plugin_registry.h"

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/native_library.h"
#include "base/path_service.h"
#include "base/string_split.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "remoting/client/plugin/pepper_entrypoints.h"

const char* PepperPluginRegistry::kPDFPluginName = "Chrome PDF Viewer";
const char* PepperPluginRegistry::kPDFPluginMimeType = "application/pdf";
const char* PepperPluginRegistry::kPDFPluginExtension = "pdf";
const char* PepperPluginRegistry::kPDFPluginDescription =
    "Portable Document Format";

const char* PepperPluginRegistry::kNaClPluginName = "Chrome NaCl";
const char* PepperPluginRegistry::kNaClPluginMimeType =
    "application/x-ppapi-nacl-srpc";
const char* PepperPluginRegistry::kNaClPluginExtension = "nexe";
const char* PepperPluginRegistry::kNaClPluginDescription =
    "Native Client Executable";

PepperPluginInfo::PepperPluginInfo()
    : is_internal(false),
      is_out_of_process(false) {
}

PepperPluginInfo::~PepperPluginInfo() {}

// static
PepperPluginRegistry* PepperPluginRegistry::GetInstance() {
  static PepperPluginRegistry* registry = NULL;
  // This object leaks.  It is a temporary hack to work around a crash.
  // http://code.google.com/p/chromium/issues/detail?id=63234
  if (!registry)
    registry = new PepperPluginRegistry;
  return registry;
}

// static
void PepperPluginRegistry::GetList(std::vector<PepperPluginInfo>* plugins) {
  InternalPluginInfoList internal_plugin_info;
  GetInternalPluginInfo(&internal_plugin_info);
  for (InternalPluginInfoList::const_iterator it =
         internal_plugin_info.begin();
       it != internal_plugin_info.end();
       ++it) {
    plugins->push_back(*it);
  }

  GetPluginInfoFromSwitch(plugins);
  GetExtraPlugins(plugins);
}

// static
void PepperPluginRegistry::PreloadModules() {
  std::vector<PepperPluginInfo> plugins;
  GetList(&plugins);
  for (size_t i = 0; i < plugins.size(); ++i) {
    if (!plugins[i].is_internal && !plugins[i].is_out_of_process) {
      base::NativeLibrary library = base::LoadNativeLibrary(plugins[i].path);
      LOG_IF(WARNING, !library) << "Unable to load plugin "
                                << plugins[i].path.value();
    }
  }
}

// static
void PepperPluginRegistry::GetPluginInfoFromSwitch(
    std::vector<PepperPluginInfo>* plugins) {
  const std::string value =
      CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
          switches::kRegisterPepperPlugins);
  if (value.empty())
    return;

  bool out_of_process =
      CommandLine::ForCurrentProcess()->HasSwitch(switches::kPpapiOutOfProcess);

  // FORMAT:
  // command-line = <plugin-entry> + *( LWS + "," + LWS + <plugin-entry> )
  // plugin-entry = <file-path> + ["#" + <name> + ["#" + <description>]] +
  //                *1( LWS + ";" + LWS + <mime-type> )

  std::vector<std::string> modules;
  base::SplitString(value, ',', &modules);
  for (size_t i = 0; i < modules.size(); ++i) {
    std::vector<std::string> parts;
    base::SplitString(modules[i], ';', &parts);
    if (parts.size() < 2) {
      DLOG(ERROR) << "Required mime-type not found";
      continue;
    }

    std::vector<std::string> name_parts;
    base::SplitString(parts[0], '#', &name_parts);

    PepperPluginInfo plugin;
    plugin.is_out_of_process = out_of_process;
#if defined(OS_WIN)
    // This means we can't provide plugins from non-ASCII paths, but
    // since this switch is only for development I don't think that's
    // too awful.
    plugin.path = FilePath(ASCIIToUTF16(name_parts[0]));
#else
    plugin.path = FilePath(name_parts[0]);
#endif
    if (name_parts.size() > 1)
      plugin.name = name_parts[1];
    if (name_parts.size() > 2)
      plugin.type_descriptions = name_parts[2];
    for (size_t j = 1; j < parts.size(); ++j)
      plugin.mime_types.push_back(parts[j]);

    plugins->push_back(plugin);
  }
}

// static
void PepperPluginRegistry::GetExtraPlugins(
    std::vector<PepperPluginInfo>* plugins) {
  // Once we're sandboxed, we can't know if the PDF plugin is
  // available or not; but (on Linux) this function is always called
  // once before we're sandboxed.  So the first time through test if
  // the file is available and then skip the check on subsequent calls
  // if yes.
  static bool skip_pdf_file_check = false;
  FilePath path;
  if (PathService::Get(chrome::FILE_PDF_PLUGIN, &path)) {
    if (skip_pdf_file_check || file_util::PathExists(path)) {
      PepperPluginInfo pdf;
      pdf.path = path;
      pdf.name = kPDFPluginName;
      pdf.mime_types.push_back(kPDFPluginMimeType);
      pdf.file_extensions = kPDFPluginExtension;
      pdf.type_descriptions = kPDFPluginDescription;
      plugins->push_back(pdf);

      skip_pdf_file_check = true;
    }
  }

  // Verify that we enable nacl on the command line.  The name of the
  // switch varies between the browser and renderer process.
  bool enable_nacl =
      CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableNaCl) ||
      CommandLine::ForCurrentProcess()->HasSwitch(switches::kInternalNaCl);

  static bool skip_nacl_file_check = false;
  if (enable_nacl && PathService::Get(chrome::FILE_NACL_PLUGIN, &path)) {
    if (skip_nacl_file_check || file_util::PathExists(path)) {
      PepperPluginInfo nacl;
      nacl.path = path;
      nacl.name = kNaClPluginName;
      nacl.mime_types.push_back(kNaClPluginMimeType);
      nacl.file_extensions = kNaClPluginExtension;
      nacl.type_descriptions = kNaClPluginDescription;
      plugins->push_back(nacl);

      skip_nacl_file_check = true;
    }
  }
}

PepperPluginRegistry::InternalPluginInfo::InternalPluginInfo() {
  is_internal = true;
}

// static
void PepperPluginRegistry::GetInternalPluginInfo(
    InternalPluginInfoList* plugin_info) {
  // Currently, to centralize the internal plugin registration logic, we
  // hardcode the list of plugins, mimetypes, and registration information
  // in this function.  This is gross, but because the GetList() function is
  // called from both the renderer and browser the other option is to force a
  // special register function for each plugin to be called by both
  // RendererMain() and BrowserMain().  This seemed like the better tradeoff.
  //
  // TODO(ajwong): Think up a better way to maintain the plugin registration
  // information. Perhaps by construction of a singly linked list of
  // plugin initializers that is built with static initializers?

#if defined(ENABLE_REMOTING)
  if (CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableRemoting)) {
    InternalPluginInfo info;
    // Add the chromoting plugin.
    DCHECK(info.is_internal);
    info.path =
        FilePath(FILE_PATH_LITERAL("internal-chromoting"));
    info.mime_types.push_back("pepper-application/x-chromoting");
    info.entry_points.get_interface = remoting::PPP_GetInterface;
    info.entry_points.initialize_module = remoting::PPP_InitializeModule;
    info.entry_points.shutdown_module = remoting::PPP_ShutdownModule;

    plugin_info->push_back(info);
  }
#endif
}

bool PepperPluginRegistry::RunOutOfProcessForPlugin(
    const FilePath& path) const {
  // TODO(brettw) don't recompute this every time. But since this Pepper
  // switch is only for development, it's OK for now.
  std::vector<PepperPluginInfo> plugins;
  GetList(&plugins);
  for (size_t i = 0; i < plugins.size(); ++i) {
    if (path == plugins[i].path)
      return plugins[i].is_out_of_process;
  }
  return false;
}

webkit::ppapi::PluginModule* PepperPluginRegistry::GetModule(
    const FilePath& path) {
  NonOwningModuleMap::iterator it = live_modules_.find(path);
  if (it == live_modules_.end())
    return NULL;
  return it->second;
}

void PepperPluginRegistry::AddLiveModule(const FilePath& path,
                                         webkit::ppapi::PluginModule* module) {
  DCHECK(live_modules_.find(path) == live_modules_.end());
  live_modules_[path] = module;
}

void PepperPluginRegistry::PluginModuleDestroyed(
    webkit::ppapi::PluginModule* destroyed_module) {
  // Modules aren't destroyed very often and there are normally at most a
  // couple of them. So for now we just do a brute-force search.
  for (NonOwningModuleMap::iterator i = live_modules_.begin();
       i != live_modules_.end(); ++i) {
    if (i->second == destroyed_module) {
      live_modules_.erase(i);
      return;
    }
  }
  NOTREACHED();  // Should have always found the module above.
}

PepperPluginRegistry::~PepperPluginRegistry() {
  // Explicitly clear all preloaded modules first. This will cause callbacks
  // to erase these modules from the live_modules_ list, and we don't want
  // that to happen implicitly out-of-order.
  preloaded_modules_.clear();

  DCHECK(live_modules_.empty());
}

PepperPluginRegistry::PepperPluginRegistry() {
  InternalPluginInfoList internal_plugin_info;
  GetInternalPluginInfo(&internal_plugin_info);

  // Register modules for these suckers.
  for (InternalPluginInfoList::const_iterator it =
         internal_plugin_info.begin();
       it != internal_plugin_info.end();
       ++it) {
    const FilePath& path = it->path;
    scoped_refptr<webkit::ppapi::PluginModule> module(
        new webkit::ppapi::PluginModule(this));
    if (!module->InitAsInternalPlugin(it->entry_points)) {
      DLOG(ERROR) << "Failed to load pepper module: " << path.value();
      continue;
    }
    module->set_name(it->name);
    preloaded_modules_[path] = module;
    AddLiveModule(path, module);
  }

  // Add the modules specified on the command line last so that they can
  // override the internal plugins.
  std::vector<PepperPluginInfo> plugins;
  GetPluginInfoFromSwitch(&plugins);
  GetExtraPlugins(&plugins);
  for (size_t i = 0; i < plugins.size(); ++i) {
    if (plugins[i].is_out_of_process)
      continue;  // Only preload in-process plugins.

    const FilePath& path = plugins[i].path;
    scoped_refptr<webkit::ppapi::PluginModule> module(
        new webkit::ppapi::PluginModule(this));
    if (!module->InitAsLibrary(path)) {
      DLOG(ERROR) << "Failed to load pepper module: " << path.value();
      continue;
    }
    module->set_name(plugins[i].name);
    preloaded_modules_[path] = module;
    AddLiveModule(path, module);
  }
}
<commit_msg>Adds the x-nacl to the MIME types recognized by the Pepper NaCl plug-in. Another CL will remove the old MIME type (x-ppapi-nacl-srpc) after the NaCl tree has been updated, to avoid a window where NaCl is broken. BUG=none TESTS=manual Review URL: http://codereview.chromium.org/6117005<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/common/pepper_plugin_registry.h"

#include "base/command_line.h"
#include "base/file_util.h"
#include "base/native_library.h"
#include "base/path_service.h"
#include "base/string_split.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "remoting/client/plugin/pepper_entrypoints.h"

const char* PepperPluginRegistry::kPDFPluginName = "Chrome PDF Viewer";
const char* PepperPluginRegistry::kPDFPluginMimeType = "application/pdf";
const char* PepperPluginRegistry::kPDFPluginExtension = "pdf";
const char* PepperPluginRegistry::kPDFPluginDescription =
    "Portable Document Format";

const char* PepperPluginRegistry::kNaClPluginName = "Chrome NaCl";
const char* PepperPluginRegistry::kNaClPluginMimeType =
    "application/x-nacl";
const char* PepperPluginRegistry::kNaClPluginExtension = "nexe";
const char* PepperPluginRegistry::kNaClPluginDescription =
    "Native Client Executable";

PepperPluginInfo::PepperPluginInfo()
    : is_internal(false),
      is_out_of_process(false) {
}

PepperPluginInfo::~PepperPluginInfo() {}

// static
PepperPluginRegistry* PepperPluginRegistry::GetInstance() {
  static PepperPluginRegistry* registry = NULL;
  // This object leaks.  It is a temporary hack to work around a crash.
  // http://code.google.com/p/chromium/issues/detail?id=63234
  if (!registry)
    registry = new PepperPluginRegistry;
  return registry;
}

// static
void PepperPluginRegistry::GetList(std::vector<PepperPluginInfo>* plugins) {
  InternalPluginInfoList internal_plugin_info;
  GetInternalPluginInfo(&internal_plugin_info);
  for (InternalPluginInfoList::const_iterator it =
         internal_plugin_info.begin();
       it != internal_plugin_info.end();
       ++it) {
    plugins->push_back(*it);
  }

  GetPluginInfoFromSwitch(plugins);
  GetExtraPlugins(plugins);
}

// static
void PepperPluginRegistry::PreloadModules() {
  std::vector<PepperPluginInfo> plugins;
  GetList(&plugins);
  for (size_t i = 0; i < plugins.size(); ++i) {
    if (!plugins[i].is_internal && !plugins[i].is_out_of_process) {
      base::NativeLibrary library = base::LoadNativeLibrary(plugins[i].path);
      LOG_IF(WARNING, !library) << "Unable to load plugin "
                                << plugins[i].path.value();
    }
  }
}

// static
void PepperPluginRegistry::GetPluginInfoFromSwitch(
    std::vector<PepperPluginInfo>* plugins) {
  const std::string value =
      CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
          switches::kRegisterPepperPlugins);
  if (value.empty())
    return;

  bool out_of_process =
      CommandLine::ForCurrentProcess()->HasSwitch(switches::kPpapiOutOfProcess);

  // FORMAT:
  // command-line = <plugin-entry> + *( LWS + "," + LWS + <plugin-entry> )
  // plugin-entry = <file-path> + ["#" + <name> + ["#" + <description>]] +
  //                *1( LWS + ";" + LWS + <mime-type> )

  std::vector<std::string> modules;
  base::SplitString(value, ',', &modules);
  for (size_t i = 0; i < modules.size(); ++i) {
    std::vector<std::string> parts;
    base::SplitString(modules[i], ';', &parts);
    if (parts.size() < 2) {
      DLOG(ERROR) << "Required mime-type not found";
      continue;
    }

    std::vector<std::string> name_parts;
    base::SplitString(parts[0], '#', &name_parts);

    PepperPluginInfo plugin;
    plugin.is_out_of_process = out_of_process;
#if defined(OS_WIN)
    // This means we can't provide plugins from non-ASCII paths, but
    // since this switch is only for development I don't think that's
    // too awful.
    plugin.path = FilePath(ASCIIToUTF16(name_parts[0]));
#else
    plugin.path = FilePath(name_parts[0]);
#endif
    if (name_parts.size() > 1)
      plugin.name = name_parts[1];
    if (name_parts.size() > 2)
      plugin.type_descriptions = name_parts[2];
    for (size_t j = 1; j < parts.size(); ++j)
      plugin.mime_types.push_back(parts[j]);

    plugins->push_back(plugin);
  }
}

// static
void PepperPluginRegistry::GetExtraPlugins(
    std::vector<PepperPluginInfo>* plugins) {
  // Once we're sandboxed, we can't know if the PDF plugin is
  // available or not; but (on Linux) this function is always called
  // once before we're sandboxed.  So the first time through test if
  // the file is available and then skip the check on subsequent calls
  // if yes.
  static bool skip_pdf_file_check = false;
  FilePath path;
  if (PathService::Get(chrome::FILE_PDF_PLUGIN, &path)) {
    if (skip_pdf_file_check || file_util::PathExists(path)) {
      PepperPluginInfo pdf;
      pdf.path = path;
      pdf.name = kPDFPluginName;
      pdf.mime_types.push_back(kPDFPluginMimeType);
      pdf.file_extensions = kPDFPluginExtension;
      pdf.type_descriptions = kPDFPluginDescription;
      plugins->push_back(pdf);

      skip_pdf_file_check = true;
    }
  }

  // Verify that we enable nacl on the command line.  The name of the
  // switch varies between the browser and renderer process.
  bool enable_nacl =
      CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableNaCl) ||
      CommandLine::ForCurrentProcess()->HasSwitch(switches::kInternalNaCl);

  static bool skip_nacl_file_check = false;
  if (enable_nacl && PathService::Get(chrome::FILE_NACL_PLUGIN, &path)) {
    if (skip_nacl_file_check || file_util::PathExists(path)) {
      PepperPluginInfo nacl;
      nacl.path = path;
      nacl.name = kNaClPluginName;
      nacl.mime_types.push_back(kNaClPluginMimeType);

      // TODO(bbudge) Remove this mime type after NaCl tree has been updated.
      const char* kNaClPluginOldMimeType =
          "application/x-ppapi-nacl-srpc";
      nacl.mime_types.push_back(kNaClPluginOldMimeType);

      nacl.file_extensions = kNaClPluginExtension;
      nacl.type_descriptions = kNaClPluginDescription;
      plugins->push_back(nacl);

      skip_nacl_file_check = true;
    }
  }
}

PepperPluginRegistry::InternalPluginInfo::InternalPluginInfo() {
  is_internal = true;
}

// static
void PepperPluginRegistry::GetInternalPluginInfo(
    InternalPluginInfoList* plugin_info) {
  // Currently, to centralize the internal plugin registration logic, we
  // hardcode the list of plugins, mimetypes, and registration information
  // in this function.  This is gross, but because the GetList() function is
  // called from both the renderer and browser the other option is to force a
  // special register function for each plugin to be called by both
  // RendererMain() and BrowserMain().  This seemed like the better tradeoff.
  //
  // TODO(ajwong): Think up a better way to maintain the plugin registration
  // information. Perhaps by construction of a singly linked list of
  // plugin initializers that is built with static initializers?

#if defined(ENABLE_REMOTING)
  if (CommandLine::ForCurrentProcess()->HasSwitch(
      switches::kEnableRemoting)) {
    InternalPluginInfo info;
    // Add the chromoting plugin.
    DCHECK(info.is_internal);
    info.path =
        FilePath(FILE_PATH_LITERAL("internal-chromoting"));
    info.mime_types.push_back("pepper-application/x-chromoting");
    info.entry_points.get_interface = remoting::PPP_GetInterface;
    info.entry_points.initialize_module = remoting::PPP_InitializeModule;
    info.entry_points.shutdown_module = remoting::PPP_ShutdownModule;

    plugin_info->push_back(info);
  }
#endif
}

bool PepperPluginRegistry::RunOutOfProcessForPlugin(
    const FilePath& path) const {
  // TODO(brettw) don't recompute this every time. But since this Pepper
  // switch is only for development, it's OK for now.
  std::vector<PepperPluginInfo> plugins;
  GetList(&plugins);
  for (size_t i = 0; i < plugins.size(); ++i) {
    if (path == plugins[i].path)
      return plugins[i].is_out_of_process;
  }
  return false;
}

webkit::ppapi::PluginModule* PepperPluginRegistry::GetModule(
    const FilePath& path) {
  NonOwningModuleMap::iterator it = live_modules_.find(path);
  if (it == live_modules_.end())
    return NULL;
  return it->second;
}

void PepperPluginRegistry::AddLiveModule(const FilePath& path,
                                         webkit::ppapi::PluginModule* module) {
  DCHECK(live_modules_.find(path) == live_modules_.end());
  live_modules_[path] = module;
}

void PepperPluginRegistry::PluginModuleDestroyed(
    webkit::ppapi::PluginModule* destroyed_module) {
  // Modules aren't destroyed very often and there are normally at most a
  // couple of them. So for now we just do a brute-force search.
  for (NonOwningModuleMap::iterator i = live_modules_.begin();
       i != live_modules_.end(); ++i) {
    if (i->second == destroyed_module) {
      live_modules_.erase(i);
      return;
    }
  }
  NOTREACHED();  // Should have always found the module above.
}

PepperPluginRegistry::~PepperPluginRegistry() {
  // Explicitly clear all preloaded modules first. This will cause callbacks
  // to erase these modules from the live_modules_ list, and we don't want
  // that to happen implicitly out-of-order.
  preloaded_modules_.clear();

  DCHECK(live_modules_.empty());
}

PepperPluginRegistry::PepperPluginRegistry() {
  InternalPluginInfoList internal_plugin_info;
  GetInternalPluginInfo(&internal_plugin_info);

  // Register modules for these suckers.
  for (InternalPluginInfoList::const_iterator it =
         internal_plugin_info.begin();
       it != internal_plugin_info.end();
       ++it) {
    const FilePath& path = it->path;
    scoped_refptr<webkit::ppapi::PluginModule> module(
        new webkit::ppapi::PluginModule(this));
    if (!module->InitAsInternalPlugin(it->entry_points)) {
      DLOG(ERROR) << "Failed to load pepper module: " << path.value();
      continue;
    }
    module->set_name(it->name);
    preloaded_modules_[path] = module;
    AddLiveModule(path, module);
  }

  // Add the modules specified on the command line last so that they can
  // override the internal plugins.
  std::vector<PepperPluginInfo> plugins;
  GetPluginInfoFromSwitch(&plugins);
  GetExtraPlugins(&plugins);
  for (size_t i = 0; i < plugins.size(); ++i) {
    if (plugins[i].is_out_of_process)
      continue;  // Only preload in-process plugins.

    const FilePath& path = plugins[i].path;
    scoped_refptr<webkit::ppapi::PluginModule> module(
        new webkit::ppapi::PluginModule(this));
    if (!module->InitAsLibrary(path)) {
      DLOG(ERROR) << "Failed to load pepper module: " << path.value();
      continue;
    }
    module->set_name(plugins[i].name);
    preloaded_modules_[path] = module;
    AddLiveModule(path, module);
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright 2008 Blanton Black
 *
 * 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.
 */

/**
 * @file main.cpp
 * @brief main implementation
 */

#include <gas/fdio.h>

#include <stdio.h>
#include <fcntl.h>

#include <string>
#include <iostream>

using namespace std;

extern "C"
{
void gas_print (GASchunk* c);
}

int test_main (int argc, char **argv);

#if HAVE_QT4
int xml2gas_main (int argc, char **argv);
int qtedit_main (int argc, char **argv);
#endif

int gas2c (int argc, char **argv);

void print_gas_file (string fname)
{
    int fd;
    GASchunk *c;

    fd = open(fname.c_str(), O_RDONLY);
    gas_read_fd(fd, &c);
    close(fd);

    gas_print(c);

    gas_destroy(c);
}

void die (string msg)
{
    cerr << msg << endl;
    exit(1);
}

int main (int argc, char **argv)
{
    if (argc < 2) {
        die("invalid usage: command not given");
    }

    string cmd = argv[1];
    if (cmd == "print") {
        if (argc != 3) {
            die("file not given");
        }
        print_gas_file(argv[2]);
    } else if (cmd == "test") {
        test_main(argc-1, &argv[1]);
#if HAVE_QT4
    } else if (cmd == "xml2gas") {
        xml2gas_main(argc-1, &argv[1]);
    } else if (cmd == "edit") {
        qtedit_main(argc-1, &argv[1]);
#endif
    } else if (cmd == "gas2c") {
        gas2c(argc-1, &argv[1]);
    } else {
        die("invalid command");
    }
    return 0;
}

// vim: sw=4 fdm=marker
<commit_msg>gascan print reads to end of file<commit_after>/*
 * Copyright 2008 Blanton Black
 *
 * 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.
 */

/**
 * @file main.cpp
 * @brief main implementation
 */

#include <gas/fsio.h>

#include <stdio.h>
#include <fcntl.h>

#include <string>
#include <iostream>

using namespace std;

extern "C"
{
void gas_print (GASchunk* c);
}

int test_main (int argc, char **argv);

#if HAVE_QT4
int xml2gas_main (int argc, char **argv);
int qtedit_main (int argc, char **argv);
#endif

int gas2c (int argc, char **argv);

void print_gas_file (string fname)
{
    FILE* fs;
    GASchunk *c = NULL;

    fs = fopen(fname.c_str(), "r");
    if (fs == NULL) {
        fprintf(stderr, "file not found");
        return;
    }
    while (!feof(fs)) {
        gas_read_fs(fs, &c);
        gas_print(c);
        gas_destroy(c);
        c = NULL;
    }
    fclose(fs);
}

void die (string msg)
{
    cerr << msg << endl;
    exit(1);
}

int main (int argc, char **argv)
{
    if (argc < 2) {
        die("invalid usage: command not given");
    }

    string cmd = argv[1];
    if (cmd == "print") {
        if (argc != 3) {
            die("file not given");
        }
        print_gas_file(argv[2]);
    } else if (cmd == "test") {
        test_main(argc-1, &argv[1]);
#if HAVE_QT4
    } else if (cmd == "xml2gas") {
        xml2gas_main(argc-1, &argv[1]);
    } else if (cmd == "edit") {
        qtedit_main(argc-1, &argv[1]);
#endif
    } else if (cmd == "gas2c") {
        gas2c(argc-1, &argv[1]);
    } else {
        die("invalid command");
    }
    return 0;
}

// vim: sw=4 fdm=marker
<|endoftext|>


<commit_before>//******************************************************************
//
// Copyright 2015 Samsung Electronics All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// 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.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

#include <memory>

#include "ResourceEncapsulationTestSimulator.h"

#include "ResourceHosting.h"

using namespace testing;
using namespace OIC::Service;

namespace
{
    void onDiscoveryResource(RCSRemoteResourceObject::Ptr) { }
}

class ResourceHostingTest : public TestWithMock
{
public:
    std::mutex mutexForCondition;
    std::condition_variable responseCon;
    std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask;

protected:

    void SetUp()
    {
        TestWithMock::SetUp();
    }

    void TearDown()
    {
        TestWithMock::TearDown();

        if (ResourceHosting::getInstance())
        {
            ResourceHosting::getInstance()->stopHosting();
        }

    }

public:
    void waitForCondition(int waitingTime = 1000)
    {
        std::unique_lock< std::mutex > lock{ mutexForCondition };
        responseCon.wait_for(lock, std::chrono::milliseconds{ waitingTime });
    }

    void notifyCondition()
    {
        responseCon.notify_all();
    }

};

TEST(ResourceHostingSTATICMethodTest, getInstanceAllwaysSameReturnInstance)
{
    EXPECT_EQ(ResourceHosting::getInstance(), ResourceHosting::getInstance());
}

TEST_F(ResourceHostingTest, HostingFoundBeforeMakeOriginServer)
{
    ResourceEncapsulationTestSimulator::Ptr testObject
        = std::make_shared<ResourceEncapsulationTestSimulator>();
    testObject->createResource();

    ResourceHosting::getInstance()->startHosting();
    std::this_thread::sleep_for(std::chrono::milliseconds{1000});

    std::string uri = "";
    mocks.OnCallFunc(onDiscoveryResource).Do(
            [this, &uri, &testObject, &discoveryTask](RCSRemoteResourceObject::Ptr ptr)
            {
                if(ptr->getUri() == testObject->getHostedServerUri())
                {
                    uri = ptr->getUri();
                    discoveryTask->cancel();
                    notifyCondition();
                }
            });

    discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(
            RCSAddress::multicast(), "resource.hosting", onDiscoveryResource);
    waitForCondition(2000);

    std::string mirroredUri = { testObject->getHostedServerUri() };

    testObject->destroy();

    ASSERT_EQ(uri, mirroredUri);
}

TEST_F(ResourceHostingTest, startHosting)
{
    ResourceEncapsulationTestSimulator::Ptr testObject
        = std::make_shared<ResourceEncapsulationTestSimulator>();
    testObject->createResource();

    ResourceHosting::getInstance()->startHosting();
    std::this_thread::sleep_for(std::chrono::milliseconds{1000});

    testObject->destroy();
}

TEST_F(ResourceHostingTest, stopHosting)
{
    ResourceEncapsulationTestSimulator::Ptr testObject
        = std::make_shared<ResourceEncapsulationTestSimulator>();
    testObject->createResource();

    ResourceHosting::getInstance()->startHosting();
    std::this_thread::sleep_for(std::chrono::milliseconds{1000});

    testObject->destroy();

    ResourceHosting::getInstance()->stopHosting();
}
<commit_msg>Fixed code that would only compile on buggy compilers.<commit_after>//******************************************************************
//
// Copyright 2015 Samsung Electronics All Rights Reserved.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
//
// 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.
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

#include <memory>

#include "ResourceEncapsulationTestSimulator.h"

#include "ResourceHosting.h"

using namespace testing;
using namespace OIC::Service;

namespace
{
    void onDiscoveryResource(RCSRemoteResourceObject::Ptr) { }
}

class ResourceHostingTest : public TestWithMock
{
public:
    std::mutex mutexForCondition;
    std::condition_variable responseCon;
    std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask;

protected:

    void SetUp()
    {
        TestWithMock::SetUp();
    }

    void TearDown()
    {
        TestWithMock::TearDown();

        if (ResourceHosting::getInstance())
        {
            ResourceHosting::getInstance()->stopHosting();
        }

    }

public:
    void waitForCondition(int waitingTime = 1000)
    {
        std::unique_lock< std::mutex > lock{ mutexForCondition };
        responseCon.wait_for(lock, std::chrono::milliseconds{ waitingTime });
    }

    void notifyCondition()
    {
        responseCon.notify_all();
    }

};

TEST(ResourceHostingSTATICMethodTest, getInstanceAllwaysSameReturnInstance)
{
    EXPECT_EQ(ResourceHosting::getInstance(), ResourceHosting::getInstance());
}

TEST_F(ResourceHostingTest, HostingFoundBeforeMakeOriginServer)
{
    ResourceEncapsulationTestSimulator::Ptr testObject
        = std::make_shared<ResourceEncapsulationTestSimulator>();
    testObject->createResource();

    ResourceHosting::getInstance()->startHosting();
    std::this_thread::sleep_for(std::chrono::milliseconds{1000});

    std::string uri = "";
    mocks.OnCallFunc(onDiscoveryResource).Do(
            [this, &uri, &testObject](RCSRemoteResourceObject::Ptr ptr)
            {
                if(ptr->getUri() == testObject->getHostedServerUri())
                {
                    uri = ptr->getUri();
                    discoveryTask->cancel();
                    notifyCondition();
                }
            });

    discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(
            RCSAddress::multicast(), "resource.hosting", onDiscoveryResource);
    waitForCondition(2000);

    std::string mirroredUri = { testObject->getHostedServerUri() };

    testObject->destroy();

    ASSERT_EQ(mirroredUri, uri);
}

TEST_F(ResourceHostingTest, startHosting)
{
    ResourceEncapsulationTestSimulator::Ptr testObject
        = std::make_shared<ResourceEncapsulationTestSimulator>();
    testObject->createResource();

    ResourceHosting::getInstance()->startHosting();
    std::this_thread::sleep_for(std::chrono::milliseconds{1000});

    testObject->destroy();
}

TEST_F(ResourceHostingTest, stopHosting)
{
    ResourceEncapsulationTestSimulator::Ptr testObject
        = std::make_shared<ResourceEncapsulationTestSimulator>();
    testObject->createResource();

    ResourceHosting::getInstance()->startHosting();
    std::this_thread::sleep_for(std::chrono::milliseconds{1000});

    testObject->destroy();

    ResourceHosting::getInstance()->stopHosting();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: xmlFormatCondition.cxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#include "precompiled_reportdesign.hxx"
#include "xmlFormatCondition.hxx"
#include "xmlfilter.hxx"
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmlnmspe.hxx>
#include <xmloff/nmspmap.hxx>
#include <xmloff/xmluconv.hxx>
#include "xmlEnums.hxx"
#include "xmlHelper.hxx"
#include <com/sun/star/report/XReportControlFormat.hpp>
#include <comphelper/genericpropertyset.hxx>
#include <com/sun/star/awt/FontDescriptor.hpp>
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HXX_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef RPT_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#include "xmlStyleImport.hxx"
#include <tools/debug.hxx>

namespace rptxml
{
    using namespace ::comphelper;
    using namespace ::com::sun::star;
    using namespace ::com::sun::star::report;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::xml::sax;
    using namespace ::com::sun::star::beans;

DBG_NAME( rpt_OXMLFormatCondition )

OXMLFormatCondition::OXMLFormatCondition( ORptFilter& rImport,
                sal_uInt16 nPrfx, const ::rtl::OUString& rLName,
                const Reference< XAttributeList > & _xAttrList
                ,const Reference< XFormatCondition > & _xComponent ) :
    SvXMLImportContext( rImport, nPrfx, rLName )
,m_xComponent(_xComponent)
{
    DBG_CTOR( rpt_OXMLFormatCondition,NULL);

    OSL_ENSURE(m_xComponent.is(),"Component is NULL!");
    const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
    const SvXMLTokenMap& rTokenMap = rImport.GetFormatElemTokenMap();
    static const ::rtl::OUString s_sTRUE = ::xmloff::token::GetXMLToken(XML_TRUE);
    const sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0;
    try
    {
        for(sal_Int16 i = 0; i < nLength; ++i)
        {
         ::rtl::OUString sLocalName;
            const rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
            const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
            const rtl::OUString sValue = _xAttrList->getValueByIndex( i );

            switch( rTokenMap.Get( nPrefix, sLocalName ) )
            {
                case XML_TOK_ENABLED:
                    m_xComponent->setEnabled(sValue == s_sTRUE);
                    break;
                case XML_TOK_FORMULA:
                    m_xComponent->setFormula(ORptFilter::convertFormula(sValue));
                    break;
                case XML_TOK_FORMAT_STYLE_NAME:
                    m_sStyleName = sValue;
                    break;
                default:
                    break;
            }
        }
    }
    catch(Exception&)
    {
        OSL_ENSURE(0,"Exception catched while filling the report definition props");
    }
}
// -----------------------------------------------------------------------------

OXMLFormatCondition::~OXMLFormatCondition()
{

    DBG_DTOR( rpt_OXMLFormatCondition,NULL);
}
// -----------------------------------------------------------------------------
ORptFilter& OXMLFormatCondition::GetOwnImport()
{
    return static_cast<ORptFilter&>(GetImport());
}
// -----------------------------------------------------------------------------
void OXMLFormatCondition::EndElement()
{
    OXMLHelper::copyStyleElements(m_sStyleName,GetImport().GetAutoStyles(),m_xComponent.get());
}
//----------------------------------------------------------------------------
} // namespace rptxml
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS rptchart02 (1.4.52); FILE MERGED 2008/04/16 06:28:58 oj 1.4.52.2: RESYNC: (1.4-1.5); FILE MERGED 2008/04/03 06:35:19 oj 1.4.52.1: #i86343# remove unused code<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: xmlFormatCondition.cxx,v $
 * $Revision: 1.6 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#include "precompiled_reportdesign.hxx"
#include "xmlFormatCondition.hxx"
#include "xmlfilter.hxx"
#include <xmloff/xmltoken.hxx>
#include <xmloff/xmlnmspe.hxx>
#include <xmloff/nmspmap.hxx>
#include <xmloff/xmluconv.hxx>
#include "xmlEnums.hxx"
#include "xmlHelper.hxx"
#include <com/sun/star/report/XReportControlFormat.hpp>
#include <comphelper/genericpropertyset.hxx>
#include <com/sun/star/awt/FontDescriptor.hpp>
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HXX_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef RPT_SHARED_XMLSTRINGS_HRC
#include "xmlstrings.hrc"
#endif
#include "xmlStyleImport.hxx"
#include <tools/debug.hxx>

namespace rptxml
{
    using namespace ::comphelper;
    using namespace ::com::sun::star;
    using namespace ::com::sun::star::report;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::xml::sax;
    using namespace ::com::sun::star::beans;

DBG_NAME( rpt_OXMLFormatCondition )

OXMLFormatCondition::OXMLFormatCondition( ORptFilter& rImport,
                sal_uInt16 nPrfx, const ::rtl::OUString& rLName,
                const Reference< XAttributeList > & _xAttrList
                ,const Reference< XFormatCondition > & _xComponent ) :
    SvXMLImportContext( rImport, nPrfx, rLName )
,m_xComponent(_xComponent)
{
    DBG_CTOR( rpt_OXMLFormatCondition,NULL);

    OSL_ENSURE(m_xComponent.is(),"Component is NULL!");
    const SvXMLNamespaceMap& rMap = rImport.GetNamespaceMap();
    const SvXMLTokenMap& rTokenMap = rImport.GetFormatElemTokenMap();
    static const ::rtl::OUString s_sTRUE = ::xmloff::token::GetXMLToken(XML_TRUE);
    const sal_Int16 nLength = (_xAttrList.is()) ? _xAttrList->getLength() : 0;
    try
    {
        for(sal_Int16 i = 0; i < nLength; ++i)
        {
         ::rtl::OUString sLocalName;
            const rtl::OUString sAttrName = _xAttrList->getNameByIndex( i );
            const sal_uInt16 nPrefix = rMap.GetKeyByAttrName( sAttrName,&sLocalName );
            const rtl::OUString sValue = _xAttrList->getValueByIndex( i );

            switch( rTokenMap.Get( nPrefix, sLocalName ) )
            {
                case XML_TOK_ENABLED:
                    m_xComponent->setEnabled(sValue == s_sTRUE);
                    break;
                case XML_TOK_FORMULA:
                    m_xComponent->setFormula(ORptFilter::convertFormula(sValue));
                    break;
                case XML_TOK_FORMAT_STYLE_NAME:
                    m_sStyleName = sValue;
                    break;
                default:
                    break;
            }
        }
    }
    catch(Exception&)
    {
        OSL_ENSURE(0,"Exception catched while filling the report definition props");
    }
}
// -----------------------------------------------------------------------------

OXMLFormatCondition::~OXMLFormatCondition()
{

    DBG_DTOR( rpt_OXMLFormatCondition,NULL);
}
// -----------------------------------------------------------------------------
void OXMLFormatCondition::EndElement()
{
    OXMLHelper::copyStyleElements(m_sStyleName,GetImport().GetAutoStyles(),m_xComponent.get());
}
//----------------------------------------------------------------------------
} // namespace rptxml
// -----------------------------------------------------------------------------
<|endoftext|>


<commit_before>// Copyright (c) 2013 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/renderer/net/net_error_helper.h"

#include "chrome/common/render_messages.h"
#include "chrome/common/net/net_error_info.h"
#include "content/public/common/url_constants.h"
#include "content/public/renderer/render_view.h"
#include "googleurl/src/gurl.h"
#include "ipc/ipc_message.h"
#include "ipc/ipc_message_macros.h"
#include "net/base/net_errors.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebURL.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebURLError.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebURLRequest.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDataSource.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"

using chrome_common_net::DnsProbeResult;
using content::RenderView;
using content::RenderViewObserver;
using content::kUnreachableWebDataURL;

namespace {

GURL GetProvisionallyLoadingURLFromWebFrame(WebKit::WebFrame* frame) {
  return frame->provisionalDataSource()->request().url();
}

bool IsErrorPage(const GURL& url) {
  return (url.spec() == kUnreachableWebDataURL);
}

// Returns whether |net_error| is a DNS-related error (and therefore whether
// the tab helper should start a DNS probe after receiving it.)
bool IsDnsError(int net_error) {
  return net_error == net::ERR_NAME_NOT_RESOLVED ||
         net_error == net::ERR_NAME_RESOLUTION_FAILED;
}

NetErrorTracker::FrameType GetFrameType(WebKit::WebFrame* frame) {
  return frame->parent() ? NetErrorTracker::FRAME_SUB
                         : NetErrorTracker::FRAME_MAIN;
}

NetErrorTracker::PageType GetPageType(WebKit::WebFrame* frame) {
  bool error_page = IsErrorPage(GetProvisionallyLoadingURLFromWebFrame(frame));
  return error_page ? NetErrorTracker::PAGE_ERROR
                    : NetErrorTracker::PAGE_NORMAL;
}

NetErrorTracker::ErrorType GetErrorType(const WebKit::WebURLError& error) {
  return IsDnsError(error.reason) ? NetErrorTracker::ERROR_DNS
                                  : NetErrorTracker::ERROR_OTHER;
}

}  // namespace

NetErrorHelper::NetErrorHelper(RenderView* render_view)
    : RenderViewObserver(render_view),
      ALLOW_THIS_IN_INITIALIZER_LIST(tracker_(base::Bind(
          &NetErrorHelper::TrackerCallback,
          base::Unretained(this)))),
      dns_error_page_state_(NetErrorTracker::DNS_ERROR_PAGE_NONE),
      updated_error_page_(false) {
}

NetErrorHelper::~NetErrorHelper() {
}

void NetErrorHelper::DidStartProvisionalLoad(WebKit::WebFrame* frame) {
  tracker_.OnStartProvisionalLoad(GetFrameType(frame), GetPageType(frame));
}

void NetErrorHelper::DidFailProvisionalLoad(WebKit::WebFrame* frame,
                                            const WebKit::WebURLError& error) {
  tracker_.OnFailProvisionalLoad(GetFrameType(frame), GetErrorType(error));
}

void NetErrorHelper::DidCommitProvisionalLoad(WebKit::WebFrame* frame,
                                              bool is_new_navigation) {
  tracker_.OnCommitProvisionalLoad(GetFrameType(frame));
}

void NetErrorHelper::DidFinishLoad(WebKit::WebFrame* frame) {
  tracker_.OnFinishLoad(GetFrameType(frame));
}

bool NetErrorHelper::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;

  IPC_BEGIN_MESSAGE_MAP(NetErrorHelper, message)
    IPC_MESSAGE_HANDLER(ChromeViewMsg_NetErrorInfo, OnNetErrorInfo)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()

  return handled;
}

void NetErrorHelper::OnNetErrorInfo(int dns_probe_result) {
  DVLOG(1) << "Received DNS probe result " << dns_probe_result;

  if (dns_probe_result < 0 ||
      dns_probe_result >= chrome_common_net::DNS_PROBE_MAX) {
    DLOG(WARNING) << "Ignoring DNS probe result: invalid result "
                  << dns_probe_result;
    NOTREACHED();
    return;
  }

  if (dns_error_page_state_ != NetErrorTracker::DNS_ERROR_PAGE_LOADED) {
    DVLOG(1) << "Ignoring DNS probe result: not on DNS error page.";
    return;
  }

  if (updated_error_page_) {
    DVLOG(1) << "Ignoring DNS probe result: already updated error page.";
    return;
  }

  UpdateErrorPage(static_cast<DnsProbeResult>(dns_probe_result));
  updated_error_page_ = true;
}

void NetErrorHelper::TrackerCallback(
    NetErrorTracker::DnsErrorPageState state) {
  dns_error_page_state_ = state;

  if (state == NetErrorTracker::DNS_ERROR_PAGE_LOADED)
    updated_error_page_ = false;
}

void NetErrorHelper::UpdateErrorPage(DnsProbeResult dns_probe_result) {
  DVLOG(1) << "Updating error page with result " << dns_probe_result;
  // TODO(ttuttle): Update error page.
}
<commit_msg>Start of updating error pages on DNS probe results<commit_after>// Copyright (c) 2013 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/renderer/net/net_error_helper.h"

#include "base/values.h"
#include "chrome/common/localized_error.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/net/net_error_info.h"
#include "content/public/common/content_client.h"
#include "content/public/common/url_constants.h"
#include "content/public/renderer/content_renderer_client.h"
#include "content/public/renderer/render_thread.h"
#include "content/public/renderer/render_view.h"
#include "googleurl/src/gurl.h"
#include "ipc/ipc_message.h"
#include "ipc/ipc_message_macros.h"
#include "net/base/net_errors.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebURL.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebURLError.h"
#include "third_party/WebKit/Source/Platform/chromium/public/WebURLRequest.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebDataSource.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"

using base::DictionaryValue;
using chrome_common_net::DnsProbeResult;
using content::GetContentClient;
using content::RenderThread;
using content::RenderView;
using content::RenderViewObserver;
using content::kUnreachableWebDataURL;

namespace {

GURL GetProvisionallyLoadingURLFromWebFrame(WebKit::WebFrame* frame) {
  return frame->provisionalDataSource()->request().url();
}

bool IsErrorPage(const GURL& url) {
  return (url.spec() == kUnreachableWebDataURL);
}

// Returns whether |net_error| is a DNS-related error (and therefore whether
// the tab helper should start a DNS probe after receiving it.)
bool IsDnsError(int net_error) {
  return net_error == net::ERR_NAME_NOT_RESOLVED ||
         net_error == net::ERR_NAME_RESOLUTION_FAILED;
}

NetErrorTracker::FrameType GetFrameType(WebKit::WebFrame* frame) {
  return frame->parent() ? NetErrorTracker::FRAME_SUB
                         : NetErrorTracker::FRAME_MAIN;
}

NetErrorTracker::PageType GetPageType(WebKit::WebFrame* frame) {
  bool error_page = IsErrorPage(GetProvisionallyLoadingURLFromWebFrame(frame));
  return error_page ? NetErrorTracker::PAGE_ERROR
                    : NetErrorTracker::PAGE_NORMAL;
}

NetErrorTracker::ErrorType GetErrorType(const WebKit::WebURLError& error) {
  return IsDnsError(error.reason) ? NetErrorTracker::ERROR_DNS
                                  : NetErrorTracker::ERROR_OTHER;
}

// Converts a DNS probe result into a net error.  Returns OK if the error page
// should not be changed from the original DNS error.
int DnsProbeResultToNetError(DnsProbeResult result) {
  switch (result) {
  case chrome_common_net::DNS_PROBE_UNKNOWN:
    return net::OK;
  case chrome_common_net::DNS_PROBE_NO_INTERNET:
    // TODO(ttuttle): This is not the same error as when NCN returns this;
    // ideally we should have two separate error codes for "no network" and
    // "network with no internet".
    return net::ERR_INTERNET_DISCONNECTED;
  case chrome_common_net::DNS_PROBE_BAD_CONFIG:
    // This is unspecific enough that we should still show the full DNS error
    // page.
    return net::OK;
  case chrome_common_net::DNS_PROBE_NXDOMAIN:
    return net::ERR_NAME_NOT_RESOLVED;
  default:
    NOTREACHED();
    return net::OK;
  }
}

WebKit::WebURLError NetErrorToWebURLError(int net_error) {
  WebKit::WebURLError error;
  error.domain = WebKit::WebString::fromUTF8(net::kErrorDomain);
  error.reason = net_error;
  return error;
}

}  // namespace

NetErrorHelper::NetErrorHelper(RenderView* render_view)
    : RenderViewObserver(render_view),
      ALLOW_THIS_IN_INITIALIZER_LIST(tracker_(base::Bind(
          &NetErrorHelper::TrackerCallback,
          base::Unretained(this)))),
      dns_error_page_state_(NetErrorTracker::DNS_ERROR_PAGE_NONE),
      updated_error_page_(false) {
}

NetErrorHelper::~NetErrorHelper() {
}

void NetErrorHelper::DidStartProvisionalLoad(WebKit::WebFrame* frame) {
  tracker_.OnStartProvisionalLoad(GetFrameType(frame), GetPageType(frame));
}

void NetErrorHelper::DidFailProvisionalLoad(WebKit::WebFrame* frame,
                                            const WebKit::WebURLError& error) {
  tracker_.OnFailProvisionalLoad(GetFrameType(frame), GetErrorType(error));
}

void NetErrorHelper::DidCommitProvisionalLoad(WebKit::WebFrame* frame,
                                              bool is_new_navigation) {
  tracker_.OnCommitProvisionalLoad(GetFrameType(frame));
}

void NetErrorHelper::DidFinishLoad(WebKit::WebFrame* frame) {
  tracker_.OnFinishLoad(GetFrameType(frame));
}

bool NetErrorHelper::OnMessageReceived(const IPC::Message& message) {
  bool handled = true;

  IPC_BEGIN_MESSAGE_MAP(NetErrorHelper, message)
    IPC_MESSAGE_HANDLER(ChromeViewMsg_NetErrorInfo, OnNetErrorInfo)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()

  return handled;
}

void NetErrorHelper::OnNetErrorInfo(int dns_probe_result) {
  DVLOG(1) << "Received DNS probe result " << dns_probe_result;

  if (dns_probe_result < 0 ||
      dns_probe_result >= chrome_common_net::DNS_PROBE_MAX) {
    DLOG(WARNING) << "Ignoring DNS probe result: invalid result "
                  << dns_probe_result;
    NOTREACHED();
    return;
  }

  if (dns_error_page_state_ != NetErrorTracker::DNS_ERROR_PAGE_LOADED) {
    DVLOG(1) << "Ignoring DNS probe result: not on DNS error page.";
    return;
  }

  if (updated_error_page_) {
    DVLOG(1) << "Ignoring DNS probe result: already updated error page.";
    return;
  }

  UpdateErrorPage(static_cast<DnsProbeResult>(dns_probe_result));
  updated_error_page_ = true;
}

void NetErrorHelper::TrackerCallback(
    NetErrorTracker::DnsErrorPageState state) {
  dns_error_page_state_ = state;

  if (state == NetErrorTracker::DNS_ERROR_PAGE_LOADED)
    updated_error_page_ = false;
}

void NetErrorHelper::UpdateErrorPage(DnsProbeResult dns_probe_result) {
  DVLOG(1) << "Updating error page with result " << dns_probe_result;

  int net_error = DnsProbeResultToNetError(dns_probe_result);
  if (net_error == net::OK)
    return;

  DVLOG(1) << "net error code is " << net_error;

  DictionaryValue error_strings;
  LocalizedError::GetStrings(NetErrorToWebURLError(net_error),
                             &error_strings,
                             RenderThread::Get()->GetLocale());

  // TODO(ttuttle): Update error page with error_strings.
}
<|endoftext|>


<commit_before>/*
    kopeteonlinestatusmanager.cpp

    Copyright (c) 2004 by Olivier Goffart  <ogoffart @ tiscalinet . be>
    Copyright (c) 2003 by Will Stephenson <lists@stevello.free-online.co.uk>

    Kopete    (c) 2003-2004 by the Kopete developers  <kopete-devel@kde.org>

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

#include "kopeteonlinestatusmanager.h"

#include "kopeteawayaction.h"
#include "kopeteprotocol.h"
#include "kopeteaccount.h"
#include "kopetecontact.h"

#include <kiconloader.h>
#include <kiconeffect.h>
#include <kdebug.h>
#include <klocale.h>
#include <kstaticdeleter.h>
#include <kapplication.h>
#include <kcpuinfo.h> // for WORDS_BIGENDIAN

#include <algorithm> // for min

namespace Kopete {

class OnlineStatusManager::Private
{public:

	struct RegisteredStatusStruct
	{
		QString caption;
		unsigned int categories;
		unsigned int options;
	};

	typedef QMap< OnlineStatus , RegisteredStatusStruct >  ProtocolMap ;

	QPixmap *nullPixmap;
	QMap<Protocol* , ProtocolMap > registeredStatus;
	QDict< QPixmap > iconCache;
};

OnlineStatusManager *OnlineStatusManager::s_self=0L;

OnlineStatusManager *OnlineStatusManager::self()
{
	static KStaticDeleter<OnlineStatusManager> deleter;
	if(!s_self)
		deleter.setObject( s_self, new OnlineStatusManager() );
	return s_self;
}

OnlineStatusManager::OnlineStatusManager()
 : d( new Private )
{
	d->iconCache.setAutoDelete( true );
	d->nullPixmap = new QPixmap;
	connect( kapp, SIGNAL( iconChanged(int) ), this, SLOT( slotIconsChanged() ) );
}

OnlineStatusManager::~OnlineStatusManager()
{
	delete d->nullPixmap;
	delete d;
}

void OnlineStatusManager::slotIconsChanged()
{
	d->iconCache.clear();
	emit iconsChanged();
}

void OnlineStatusManager::registerOnlineStatus( const OnlineStatus &status, const QString & caption, unsigned int categories, unsigned int options)
{
	Private::RegisteredStatusStruct s;
	s.caption=caption;
	s.categories=categories;
	s.options=options;
	d->registeredStatus[status.protocol()].insert(status, s );
}

QString OnlineStatusManager::fingerprint( const OnlineStatus &statusFor, const QString& icon, int size, QColor color, bool idle)
{
	// create a 'fingerprint' to use as a hash key
	// fingerprint consists of description/icon name/color/overlay name/size/idle state
	return QString::fromLatin1("%1/%2/%3/%4/%5/%6")
	                           .arg( statusFor.description() )
	                           .arg( icon )
	                           .arg( color.name() )
	                           .arg( statusFor.overlayIcon())
	                           .arg( size )
	                           .arg( idle ? 'i' : 'a' );
}

QPixmap OnlineStatusManager::cacheLookupByObject( const OnlineStatus &statusFor, const QString& icon, int size, QColor color, bool idle)
{
	QString fp = fingerprint( statusFor, icon, size, color, idle );

	// look it up in the cache
	QPixmap *theIcon= d->iconCache.find( fp );
	if ( !theIcon  )
	{
		// cache miss
//		kdDebug(14010) << k_funcinfo << "Missed " << fingerprint << " in icon cache!" << endl;
		theIcon = renderIcon( statusFor, icon, size, color, idle);
		d->iconCache.insert( fp, theIcon );
	}
	return *theIcon;
}

QPixmap OnlineStatusManager::cacheLookupByMimeSource( const QString &mimeSource )
{
	// look it up in the cache
	const QPixmap *theIcon= d->iconCache.find( mimeSource );
	if ( !theIcon )
	{
		// need to return an invalid pixmap
		theIcon = d->nullPixmap;
	}
	return *theIcon;
}

// This code was forked from the broken KImageEffect::blendOnLower, but it's
// been so heavily fixed and rearranged it's hard to recognise that now.
static void blendOnLower( const QImage &upper_, QImage &lower )
{
	if ( upper_.width() <= 0 || upper_.height() <= 0 )
		return;
	if ( lower.width() <= 0 || lower.height() <= 0 )
		return;

	QImage upper = upper_;
	if ( upper.depth() != 32 )
		upper = upper.convertDepth( 32 );
	if ( lower.depth() != 32 )
		lower = lower.convertDepth( 32 );

	int cw = std::min( upper.width(), lower.width() ),
	    ch = std::min( upper.height(), lower.height() );
	const int m = 255;

	for ( int j = 0; j < ch; j++ )
	{
		QRgb *u = (QRgb*)upper.scanLine(j);
		QRgb *l = (QRgb*)lower.scanLine(j);

		for( int k = cw; k; ++u, ++l, --k )
		{
			int ua = qAlpha(*u);
			if ( !ua )
				continue;

			int la = qAlpha(*l);

			int   d =                       ua * m +              la * (m - ua);
			uchar r = uchar( (   qRed(*u) * ua * m +   qRed(*l) * la * (m - ua) ) / d );
			uchar g = uchar( ( qGreen(*u) * ua * m + qGreen(*l) * la * (m - ua) ) / d );
			uchar b = uchar( (  qBlue(*u) * ua * m +  qBlue(*l) * la * (m - ua) ) / d );
			uchar a = uchar( (         ua * ua * m +         la * la * (m - ua) ) / d );
			*l = qRgba( r, g, b, a );
		}
	}
}

QPixmap* OnlineStatusManager::renderIcon( const OnlineStatus &statusFor, const QString& baseIcon, int size, QColor color, bool idle) const
{
	// create an icon suiting the status from the base icon
	// use reasonable defaults if not provided or protocol not set

	if ( baseIcon == statusFor.overlayIcon() )
		kdWarning( 14010 ) << "Base and overlay icons are the same - icon effects will not be visible." << endl;

	QPixmap* basis = new QPixmap( SmallIcon( baseIcon ) );

	// Colorize
	if ( color.isValid() )
		*basis = KIconEffect().apply( *basis, KIconEffect::Colorize, 1, color, 0);

	// Apply standard Disabled effect to generate account-offline icons
	// Note that we do this before compositing the overlay, since we want
	// that to be colored in this case.
	if ( statusFor.internalStatus() == Kopete::OnlineStatus::AccountOffline )
		*basis = KIconEffect().apply( *basis, KIcon::Small, KIcon::DisabledState );

	//composite the iconOverlay for this status and the supplied baseIcon
	if ( !( statusFor.overlayIcon().isNull() ) ) // otherwise leave the basis as-is
	{
		KIconLoader *loader = KGlobal::instance()->iconLoader();
		QPixmap overlay = loader->loadIcon(statusFor.overlayIcon(), KIcon::Small, 0 ,  KIcon::DefaultState, 0L, /*canReturnNull=*/ true );

		if ( !overlay.isNull() )
		{
			// we want to preserve the alpha channels of both basis and overlay.
			// there's no way to do this in Qt. In fact, there's no way to do this
			// in KDE since KImageEffect is so badly broken.
			QImage basisImage = basis->convertToImage();
			blendOnLower( overlay.convertToImage(), basisImage );
			basis->convertFromImage( basisImage );
		}
	}

	// Apply standard Disabled effect to generate Offline icons
	// This will probably look crap on the Unknown icon
	// FIXME This won't return icons that are not installed using Martijn's
	// automake magic so we'd have to use UserIcon instead of SmallIcon
	if ( statusFor.status() == OnlineStatus::Offline )
		*basis = KIconEffect().apply( *basis, KIcon::Small, KIcon::DisabledState );

	// no need to scale if the icon is already of the required size (assuming height == width!)
	if ( basis->width() != size )
	{
		QImage scaledImg = basis->convertToImage().smoothScale( size, size );
		*basis = QPixmap( scaledImg );
	}

	// if idle, apply effects
	if ( idle )
		KIconEffect::semiTransparent( *basis );

	return basis;
}

void OnlineStatusManager::createAccountStatusActions( Account *account , KActionMenu *parent)
{
	Private::ProtocolMap protocolMap=d->registeredStatus[account->protocol()];
	Private::ProtocolMap::Iterator it;
	for ( it = --protocolMap.end(); it != protocolMap.end(); --it )
	{
		unsigned int options=it.data().options;
		if(options & OnlineStatusManager::HideFromMenu)
			continue;

		OnlineStatus status=it.key();
		QString caption=it.data().caption;
		KAction *action;
		if(options & OnlineStatusManager::HasAwayMessage)
		{
			action = new AwayAction( status, caption, status.iconFor(account), 0, account,
					SLOT( setOnlineStatus( const Kopete::OnlineStatus&, const QString& ) ),
					account );
		}
		else
		{
			action=new OnlineStatusAction( status, caption, status.iconFor(account) , parent  );
			connect(action,SIGNAL(activated(const Kopete::OnlineStatus&)) , account, SLOT(setOnlineStatus(const Kopete::OnlineStatus&)));
		}

		if(options & OnlineStatusManager::DisabledIfOffline  && !account->isConnected())
			action->setEnabled(false);

		if(parent)
			parent->insert(action);

	}
}

OnlineStatusAction::OnlineStatusAction( const OnlineStatus& status, const QString &text, const QIconSet &pix, QObject *parent, const char *name)
		: KAction( text, pix, KShortcut() , parent, name) , m_status(status)
{
	connect(this,SIGNAL(activated()),this,SLOT(slotActivated()));
}

void OnlineStatusAction::slotActivated()
{
	emit activated(m_status);
}

} //END namespace Kopete

#include "kopeteonlinestatusmanager.moc"

// vim: set noet ts=4 sts=4 sw=4:

<commit_msg>Reuse account status awayactions, instead of leaking them.  If your protocol doesn't use autogenerated account menus yet, this is another reason to make the move.<commit_after>/*
    kopeteonlinestatusmanager.cpp

    Copyright (c) 2004 by Olivier Goffart  <ogoffart @ tiscalinet . be>
    Copyright (c) 2003 by Will Stephenson <lists@stevello.free-online.co.uk>

    Kopete    (c) 2003-2004 by the Kopete developers  <kopete-devel@kde.org>

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

#include "kopeteonlinestatusmanager.h"

#include "kopeteawayaction.h"
#include "kopeteprotocol.h"
#include "kopeteaccount.h"
#include "kopetecontact.h"

#include <kiconloader.h>
#include <kiconeffect.h>
#include <kdebug.h>
#include <klocale.h>
#include <kstaticdeleter.h>
#include <kapplication.h>
#include <kcpuinfo.h> // for WORDS_BIGENDIAN

#include <algorithm> // for min

namespace Kopete {

class OnlineStatusManager::Private
{public:

	struct RegisteredStatusStruct
	{
		QString caption;
		unsigned int categories;
		unsigned int options;
	};

	typedef QMap< OnlineStatus , RegisteredStatusStruct >  ProtocolMap ;

	QPixmap *nullPixmap;
	QMap<Protocol* , ProtocolMap > registeredStatus;
	QDict< QPixmap > iconCache;
};

OnlineStatusManager *OnlineStatusManager::s_self=0L;

OnlineStatusManager *OnlineStatusManager::self()
{
	static KStaticDeleter<OnlineStatusManager> deleter;
	if(!s_self)
		deleter.setObject( s_self, new OnlineStatusManager() );
	return s_self;
}

OnlineStatusManager::OnlineStatusManager()
 : d( new Private )
{
	d->iconCache.setAutoDelete( true );
	d->nullPixmap = new QPixmap;
	connect( kapp, SIGNAL( iconChanged(int) ), this, SLOT( slotIconsChanged() ) );
}

OnlineStatusManager::~OnlineStatusManager()
{
	delete d->nullPixmap;
	delete d;
}

void OnlineStatusManager::slotIconsChanged()
{
	d->iconCache.clear();
	emit iconsChanged();
}

void OnlineStatusManager::registerOnlineStatus( const OnlineStatus &status, const QString & caption, unsigned int categories, unsigned int options)
{
	Private::RegisteredStatusStruct s;
	s.caption=caption;
	s.categories=categories;
	s.options=options;
	d->registeredStatus[status.protocol()].insert(status, s );
}

QString OnlineStatusManager::fingerprint( const OnlineStatus &statusFor, const QString& icon, int size, QColor color, bool idle)
{
	// create a 'fingerprint' to use as a hash key
	// fingerprint consists of description/icon name/color/overlay name/size/idle state
	return QString::fromLatin1("%1/%2/%3/%4/%5/%6")
	                           .arg( statusFor.description() )
	                           .arg( icon )
	                           .arg( color.name() )
	                           .arg( statusFor.overlayIcon())
	                           .arg( size )
	                           .arg( idle ? 'i' : 'a' );
}

QPixmap OnlineStatusManager::cacheLookupByObject( const OnlineStatus &statusFor, const QString& icon, int size, QColor color, bool idle)
{
	QString fp = fingerprint( statusFor, icon, size, color, idle );

	// look it up in the cache
	QPixmap *theIcon= d->iconCache.find( fp );
	if ( !theIcon  )
	{
		// cache miss
//		kdDebug(14010) << k_funcinfo << "Missed " << fingerprint << " in icon cache!" << endl;
		theIcon = renderIcon( statusFor, icon, size, color, idle);
		d->iconCache.insert( fp, theIcon );
	}
	return *theIcon;
}

QPixmap OnlineStatusManager::cacheLookupByMimeSource( const QString &mimeSource )
{
	// look it up in the cache
	const QPixmap *theIcon= d->iconCache.find( mimeSource );
	if ( !theIcon )
	{
		// need to return an invalid pixmap
		theIcon = d->nullPixmap;
	}
	return *theIcon;
}

// This code was forked from the broken KImageEffect::blendOnLower, but it's
// been so heavily fixed and rearranged it's hard to recognise that now.
static void blendOnLower( const QImage &upper_, QImage &lower )
{
	if ( upper_.width() <= 0 || upper_.height() <= 0 )
		return;
	if ( lower.width() <= 0 || lower.height() <= 0 )
		return;

	QImage upper = upper_;
	if ( upper.depth() != 32 )
		upper = upper.convertDepth( 32 );
	if ( lower.depth() != 32 )
		lower = lower.convertDepth( 32 );

	int cw = std::min( upper.width(), lower.width() ),
	    ch = std::min( upper.height(), lower.height() );
	const int m = 255;

	for ( int j = 0; j < ch; j++ )
	{
		QRgb *u = (QRgb*)upper.scanLine(j);
		QRgb *l = (QRgb*)lower.scanLine(j);

		for( int k = cw; k; ++u, ++l, --k )
		{
			int ua = qAlpha(*u);
			if ( !ua )
				continue;

			int la = qAlpha(*l);

			int   d =                       ua * m +              la * (m - ua);
			uchar r = uchar( (   qRed(*u) * ua * m +   qRed(*l) * la * (m - ua) ) / d );
			uchar g = uchar( ( qGreen(*u) * ua * m + qGreen(*l) * la * (m - ua) ) / d );
			uchar b = uchar( (  qBlue(*u) * ua * m +  qBlue(*l) * la * (m - ua) ) / d );
			uchar a = uchar( (         ua * ua * m +         la * la * (m - ua) ) / d );
			*l = qRgba( r, g, b, a );
		}
	}
}

QPixmap* OnlineStatusManager::renderIcon( const OnlineStatus &statusFor, const QString& baseIcon, int size, QColor color, bool idle) const
{
	// create an icon suiting the status from the base icon
	// use reasonable defaults if not provided or protocol not set

	if ( baseIcon == statusFor.overlayIcon() )
		kdWarning( 14010 ) << "Base and overlay icons are the same - icon effects will not be visible." << endl;

	QPixmap* basis = new QPixmap( SmallIcon( baseIcon ) );

	// Colorize
	if ( color.isValid() )
		*basis = KIconEffect().apply( *basis, KIconEffect::Colorize, 1, color, 0);

	// Apply standard Disabled effect to generate account-offline icons
	// Note that we do this before compositing the overlay, since we want
	// that to be colored in this case.
	if ( statusFor.internalStatus() == Kopete::OnlineStatus::AccountOffline )
		*basis = KIconEffect().apply( *basis, KIcon::Small, KIcon::DisabledState );

	//composite the iconOverlay for this status and the supplied baseIcon
	if ( !( statusFor.overlayIcon().isNull() ) ) // otherwise leave the basis as-is
	{
		KIconLoader *loader = KGlobal::instance()->iconLoader();
		QPixmap overlay = loader->loadIcon(statusFor.overlayIcon(), KIcon::Small, 0 ,  KIcon::DefaultState, 0L, /*canReturnNull=*/ true );

		if ( !overlay.isNull() )
		{
			// we want to preserve the alpha channels of both basis and overlay.
			// there's no way to do this in Qt. In fact, there's no way to do this
			// in KDE since KImageEffect is so badly broken.
			QImage basisImage = basis->convertToImage();
			blendOnLower( overlay.convertToImage(), basisImage );
			basis->convertFromImage( basisImage );
		}
	}

	// Apply standard Disabled effect to generate Offline icons
	// This will probably look crap on the Unknown icon
	// FIXME This won't return icons that are not installed using Martijn's
	// automake magic so we'd have to use UserIcon instead of SmallIcon
	if ( statusFor.status() == OnlineStatus::Offline )
		*basis = KIconEffect().apply( *basis, KIcon::Small, KIcon::DisabledState );

	// no need to scale if the icon is already of the required size (assuming height == width!)
	if ( basis->width() != size )
	{
		QImage scaledImg = basis->convertToImage().smoothScale( size, size );
		*basis = QPixmap( scaledImg );
	}

	// if idle, apply effects
	if ( idle )
		KIconEffect::semiTransparent( *basis );

	return basis;
}

void OnlineStatusManager::createAccountStatusActions( Account *account , KActionMenu *parent)
{
	Private::ProtocolMap protocolMap=d->registeredStatus[account->protocol()];
	Private::ProtocolMap::Iterator it;
	for ( it = --protocolMap.end(); it != protocolMap.end(); --it )
	{
		unsigned int options=it.data().options;
		if(options & OnlineStatusManager::HideFromMenu)
			continue;

		OnlineStatus status=it.key();
		QString caption=it.data().caption;
		KAction *action;

		// Any existing actions owned by the account are reused by recovering them
		// from the parent's child list.
		// The description of the onlinestatus is used as the qobject name
		// This is safe as long as OnlineStatus are immutable
		QCString actionName = status.description().ascii();
		if ( !( action = static_cast<KAction*>( account->child( actionName ) ) ) )
		{
			if(options & OnlineStatusManager::HasAwayMessage)
			{
				action = new AwayAction( status, caption, status.iconFor(account), 0, account,
						SLOT( setOnlineStatus( const Kopete::OnlineStatus&, const QString& ) ),
						account, actionName );
			}
			else
			{
				action=new OnlineStatusAction( status, caption, status.iconFor(account) , account, actionName );
				connect(action,SIGNAL(activated(const Kopete::OnlineStatus&)) ,
						account, SLOT(setOnlineStatus(const Kopete::OnlineStatus&)));
			}
		}

		if(options & OnlineStatusManager::DisabledIfOffline  && !account->isConnected())
			action->setEnabled(false);

		if(parent)
			parent->insert(action);

	}
}

OnlineStatusAction::OnlineStatusAction( const OnlineStatus& status, const QString &text, const QIconSet &pix, QObject *parent, const char *name)
		: KAction( text, pix, KShortcut() , parent, name) , m_status(status)
{
	connect(this,SIGNAL(activated()),this,SLOT(slotActivated()));
}

void OnlineStatusAction::slotActivated()
{
	emit activated(m_status);
}

} //END namespace Kopete

#include "kopeteonlinestatusmanager.moc"

// vim: set noet ts=4 sts=4 sw=4:

<|endoftext|>


<commit_before>/*
 * File:   FieldDetector.cpp
 * Author: Heinrich Mellmann
 *
 */

#include "FieldDetector.h"

#include <Tools/Math/ConvexHull.h>

using namespace std;

FieldDetector::FieldDetector()
:
  cameraID(CameraInfo::Bottom)
{
  DEBUG_REQUEST_REGISTER("Vision:FieldDetector:mark_field_polygon", "mark polygonal boundary of the detected field on the image", false);
  DEBUG_REQUEST_REGISTER("Vision:FieldDetector:mark_corrected_field_polygon", "mark polygonal boundary of the detected field cutted by horizon on the image", false);
  DEBUG_REQUEST_REGISTER("Vision:FieldDetector:setHoleImageAsField", "mark hole image as if field were detected", false);
  DEBUG_REQUEST_REGISTER("Vision:FieldDetector:mark_field_polygon_old", "mark polygonal boundary of the detected field before outlier detection", false);
  DEBUG_REQUEST_REGISTER("Vision:FieldDetector:mark_field_polygon_new", "mark new polygonal boundary of the detected field after outlier detection", false);

  getDebugParameterList().add(&theParameters);
}

FieldDetector::~FieldDetector()
{}

void FieldDetector::execute(CameraInfo::CameraID id)
{
  cameraID = id;

  bool simulateField = false;

  DEBUG_REQUEST("Vision:FieldDetector:setHoleImageAsField",
    simulateField = true;
  );

  if(simulateField)
  {
    vector<Vector2i > result;
    result.push_back(Vector2i(0,0));
    result.push_back(Vector2i(0,getImage().height()-1));
    result.push_back(Vector2i(getImage().width()-1, getImage().height()-0));
    result.push_back(Vector2i(getImage().width()-1,0));
    result.push_back(Vector2i(0,0));

    // create the polygon
    FieldPercept::FieldPoly fieldPoly;
    for(size_t i = 0; i < result.size(); i++)
    {
      fieldPoly.add(result[i]);
    }
    Math::LineSegment horizon(Vector2i(0, 0), Vector2i(getImage().width() - 1, 0));

    getFieldPercept().setField(fieldPoly, horizon);
    if(fieldPoly.getArea() >= 5600)
    {
      getFieldPercept().valid = true;
    }

    DEBUG_REQUEST( "Vision:FieldDetector:mark_field_polygon",
      size_t idx = 0;
      ColorClasses::Color color = getFieldPercept().valid ? ColorClasses::green : ColorClasses::red;
      for(size_t i = 1; i < result.size(); i++)
      {
        LINE_PX(color, result[idx].x, result[idx].y, result[i].x, result[i].y);
        idx = i;
      }
    );
  }
  else if(getScanLineEdgelPercept().endPoints.size() > 0)
  {
    vector<Vector2i > points;//(getScanLineEdgelPercept().endPoints.size());

    for(size_t i = 0; i < getScanLineEdgelPercept().endPoints.size(); i++)
    {
      const Vector2i& p = getScanLineEdgelPercept().endPoints[i].posInImage;
      if(p.y < (int) getImage().height() - 6)
      {
        points.push_back(p);
      }
      //points[i] = getScanLineEdgelPercept().endPoints[i].posInImage;
    }

    // move the outer points
    //points.front().x = 0;
    //points.back().x = getImage().width()-1;

    // lower image points
    //points.push_back(Vector2i(0,getImage().height()-1));
    //points.push_back(Vector2i(getImage().width()-1, getImage().height()-1));

    if(points.size() > 1)
    {
      Vector2i p1 = points.front();
      p1.y = getImage().height() - 1;
      Vector2i p2 = points.back();
      p2.y = getImage().height() - 1;

      points.push_back(p1);
      points.push_back(p2);

      if(getScanLineEdgelPercept().endPoints.front().posInImage.y < (int) getImage().height() - 6)
      {
        points.push_back(Vector2i(0, getScanLineEdgelPercept().endPoints.front().posInImage.y));
        points.push_back(Vector2i(0, getImage().height() - 1));
      }

      if(getScanLineEdgelPercept().endPoints.back().posInImage.y < (int) getImage().height() - 6)
      {
        points.push_back(Vector2i(getImage().width() - 1, getScanLineEdgelPercept().endPoints.back().posInImage.y));
        points.push_back(Vector2i(getImage().width() - 1, getImage().height() - 1));
      }

    }
    // calculate the convex hull
    vector<Vector2i> result = ConvexHull::convexHull(points);

    // create the polygon
    FieldPercept::FieldPoly fieldPoly;

    for(size_t i = 0; i < result.size(); i++)
    {
      fieldPoly.add(result[i]);
    }
    DEBUG_REQUEST("Vision:FieldDetector:mark_field_polygon_old",
      int idx = 0;
      for(int i = 1; i < fieldPoly.length; i++)
      {
        LINE_PX(ColorClasses::red, fieldPoly[idx].x, fieldPoly[idx].y, fieldPoly[i].x, fieldPoly[i].y);
        idx = i;
      }
    );

    // sort points by x value
    sort(points.begin(), points.end(), this->myVecCompareX);

    // remove points on the edge of the BodyContour
    std::vector<size_t> badPoints;
    for(size_t i = 2; i+2 < points.size(); i++)
    {
      if(points[i].y > 0)
      {
        Vector2i dummyPoint = points[i];
        dummyPoint.y += 6;
        if(getBodyContour().isOccupied(dummyPoint))
        {
          badPoints.push_back(i);
        }
      }
    }
    if(badPoints.size() > 0)
    {
      for(size_t i = 0; i < badPoints.size(); i++)
      {
        // badPoints are ordered so the small indices are removed first
        points.erase(points.begin() + badPoints[i] - i);
      }
    }
    // check outliers but keep first and last point in any case
    for(size_t nLoop = 0; nLoop < 5; nLoop++)
    {
      badPoints.clear();
      for(size_t i = 2; i+2 < points.size(); i++)
      {
        std::vector<Vector2i> pointsCheck = points;
        pointsCheck.erase(pointsCheck.begin()+i);

        vector<Vector2i> resultCheck = ConvexHull::convexHull(pointsCheck);

        FieldPercept::FieldPoly fieldPolyCheck;
        for(size_t j = 0; j < resultCheck.size(); j++)
        {
          fieldPolyCheck.add(resultCheck[j]);
        }
        if(fieldPolyCheck.getArea() / fieldPoly.getArea() < theParameters.pruneThresholdArea)
        {
          badPoints.push_back(i);
        }
      }
      // remove outliers
      if(badPoints.size() > 0)
      {
        for(size_t i = 0; i < badPoints.size(); i++)
        {
          // badPoints are ordered so the small indices are removed first
          points.erase(points.begin() + badPoints[i] - i);
        }
        result = ConvexHull::convexHull(points);
        // clear old polygon
        fieldPoly = FieldPercept::FieldPoly();
        for(size_t i = 0; i < result.size(); i++)
        {
          fieldPoly.add(result[i]);
        }
      } else
      {
        break;
      }
    }
    DEBUG_REQUEST("Vision:FieldDetector:mark_field_polygon_new",
      int idx = 0;
      for(int i = 1; i < fieldPoly.length; i++)
      {
        LINE_PX(ColorClasses::green, fieldPoly[idx].x, fieldPoly[idx].y, fieldPoly[i].x, fieldPoly[i].y);
        idx = i;
      }
    );

    // add field to percept
    getFieldPercept().setField(fieldPoly, getArtificialHorizon());
    // check result
    if(fieldPoly.getArea() >= 5600)
    {
      getFieldPercept().valid = true;
    }
    else
    {
      getFieldPercept().valid = false;
    }

    DEBUG_REQUEST( "Vision:FieldDetector:mark_field_polygon",
      size_t idx = 0;
      ColorClasses::Color color = getFieldPercept().valid ? ColorClasses::black : ColorClasses::red;
      for(size_t i = 1; i < result.size(); i++)
      {
        LINE_PX(color, result[idx].x, result[idx].y, result[i].x, result[i].y);
        idx = i;
      }
    );

    DEBUG_REQUEST( "Vision:FieldDetector:mark_corrected_field_polygon",
      int idx = 0;
      ColorClasses::Color color = getFieldPercept().valid ? ColorClasses::green : ColorClasses::red;
      const FieldPercept::FieldPoly& fieldpoly = getFieldPercept().getValidField();
      for(int i = 1; i < fieldpoly.length; i++)
      {
        LINE_PX(color, fieldpoly[idx].x, fieldpoly[idx].y, fieldpoly[i].x, fieldpoly[i].y);
        idx = i;
      }
    );
  }
}//end execute

bool FieldDetector::myVecCompareX(const Vector2i &first, const Vector2i &second)
{
  return (first.x<second.x);
}
<commit_msg>bugfix: sometimes precedence matters ;)<commit_after>/*
 * File:   FieldDetector.cpp
 * Author: Heinrich Mellmann
 *
 */

#include "FieldDetector.h"

#include <Tools/Math/ConvexHull.h>

using namespace std;

FieldDetector::FieldDetector()
:
  cameraID(CameraInfo::Bottom)
{
  DEBUG_REQUEST_REGISTER("Vision:FieldDetector:mark_field_polygon", "mark polygonal boundary of the detected field on the image", false);
  DEBUG_REQUEST_REGISTER("Vision:FieldDetector:mark_corrected_field_polygon", "mark polygonal boundary of the detected field cutted by horizon on the image", false);
  DEBUG_REQUEST_REGISTER("Vision:FieldDetector:setHoleImageAsField", "mark hole image as if field were detected", false);
  DEBUG_REQUEST_REGISTER("Vision:FieldDetector:mark_field_polygon_old", "mark polygonal boundary of the detected field before outlier detection", false);
  DEBUG_REQUEST_REGISTER("Vision:FieldDetector:mark_field_polygon_new", "mark new polygonal boundary of the detected field after outlier detection", false);

  getDebugParameterList().add(&theParameters);
}

FieldDetector::~FieldDetector()
{}

void FieldDetector::execute(CameraInfo::CameraID id)
{
  cameraID = id;

  bool simulateField = false;

  DEBUG_REQUEST("Vision:FieldDetector:setHoleImageAsField",
    simulateField = true;
  );

  if(simulateField)
  {
    vector<Vector2i > result;
    result.push_back(Vector2i(0,0));
    result.push_back(Vector2i(0,getImage().height()-1));
    result.push_back(Vector2i(getImage().width()-1, getImage().height()-0));
    result.push_back(Vector2i(getImage().width()-1,0));
    result.push_back(Vector2i(0,0));

    // create the polygon
    FieldPercept::FieldPoly fieldPoly;
    for(size_t i = 0; i < result.size(); i++)
    {
      fieldPoly.add(result[i]);
    }
    Math::LineSegment horizon(Vector2i(0, 0), Vector2i(getImage().width() - 1, 0));

    getFieldPercept().setField(fieldPoly, horizon);
    if(fieldPoly.getArea() >= 5600)
    {
      getFieldPercept().valid = true;
    }

    DEBUG_REQUEST( "Vision:FieldDetector:mark_field_polygon",
      size_t idx = 0;
      ColorClasses::Color color = getFieldPercept().valid ? ColorClasses::green : ColorClasses::red;
      for(size_t i = 1; i < result.size(); i++)
      {
        LINE_PX(color, result[idx].x, result[idx].y, result[i].x, result[i].y);
        idx = i;
      }
    );
  }
  else if(getScanLineEdgelPercept().endPoints.size() > 0)
  {
    vector<Vector2i > points;//(getScanLineEdgelPercept().endPoints.size());

    for(size_t i = 0; i < getScanLineEdgelPercept().endPoints.size(); i++)
    {
      const Vector2i& p = getScanLineEdgelPercept().endPoints[i].posInImage;
      if(p.y < (int) getImage().height() - 6)
      {
        points.push_back(p);
      }
      //points[i] = getScanLineEdgelPercept().endPoints[i].posInImage;
    }

    // move the outer points
    //points.front().x = 0;
    //points.back().x = getImage().width()-1;

    // lower image points
    //points.push_back(Vector2i(0,getImage().height()-1));
    //points.push_back(Vector2i(getImage().width()-1, getImage().height()-1));

    if(points.size() > 1)
    {
      Vector2i p1 = points.front();
      p1.y = getImage().height() - 1;
      Vector2i p2 = points.back();
      p2.y = getImage().height() - 1;

      points.push_back(p1);
      points.push_back(p2);

      if(getScanLineEdgelPercept().endPoints.front().posInImage.y < (int) getImage().height() - 6)
      {
        points.push_back(Vector2i(0, getScanLineEdgelPercept().endPoints.front().posInImage.y));
        points.push_back(Vector2i(0, getImage().height() - 1));
      }

      if(getScanLineEdgelPercept().endPoints.back().posInImage.y < (int) getImage().height() - 6)
      {
        points.push_back(Vector2i(getImage().width() - 1, getScanLineEdgelPercept().endPoints.back().posInImage.y));
        points.push_back(Vector2i(getImage().width() - 1, getImage().height() - 1));
      }

    }
    // calculate the convex hull
    vector<Vector2i> result = ConvexHull::convexHull(points);

    // create the polygon
    FieldPercept::FieldPoly fieldPoly;

    for(size_t i = 0; i < result.size(); i++)
    {
      fieldPoly.add(result[i]);
    }
    DEBUG_REQUEST("Vision:FieldDetector:mark_field_polygon_old",
      int idx = 0;
      for(int i = 1; i < fieldPoly.length; i++)
      {
        LINE_PX(ColorClasses::red, fieldPoly[idx].x, fieldPoly[idx].y, fieldPoly[i].x, fieldPoly[i].y);
        idx = i;
      }
    );

    // sort points by x value
    sort(points.begin(), points.end(), this->myVecCompareX);

    // remove points on the edge of the BodyContour
    std::vector<size_t> badPoints;
    for(size_t i = 2; i+2 < points.size(); i++)
    {
      if(points[i].y > 0)
      {
        Vector2i dummyPoint = points[i];
        dummyPoint.y += 6;
        if(getBodyContour().isOccupied(dummyPoint))
        {
          badPoints.push_back(i);
        }
      }
    }
    if(badPoints.size() > 0)
    {
      for(size_t i = 0; i < badPoints.size(); i++)
      {
        // badPoints are ordered so the small indices are removed first
        points.erase(points.begin() + (badPoints[i] - i));
      }
    }
    // check outliers but keep first and last point in any case
    for(size_t nLoop = 0; nLoop < 5; nLoop++)
    {
      badPoints.clear();
      for(size_t i = 2; i+2 < points.size(); i++)
      {
        std::vector<Vector2i> pointsCheck = points;
        pointsCheck.erase(pointsCheck.begin()+i);

        vector<Vector2i> resultCheck = ConvexHull::convexHull(pointsCheck);

        FieldPercept::FieldPoly fieldPolyCheck;
        for(size_t j = 0; j < resultCheck.size(); j++)
        {
          fieldPolyCheck.add(resultCheck[j]);
        }
        if(fieldPolyCheck.getArea() / fieldPoly.getArea() < theParameters.pruneThresholdArea)
        {
          badPoints.push_back(i);
        }
      }
      // remove outliers
      if(badPoints.size() > 0)
      {
        for(size_t i = 0; i < badPoints.size(); i++)
        {
          // badPoints are ordered so the small indices are removed first
          points.erase(points.begin() + badPoints[i] - i);
        }
        result = ConvexHull::convexHull(points);
        // clear old polygon
        fieldPoly = FieldPercept::FieldPoly();
        for(size_t i = 0; i < result.size(); i++)
        {
          fieldPoly.add(result[i]);
        }
      } else
      {
        break;
      }
    }
    DEBUG_REQUEST("Vision:FieldDetector:mark_field_polygon_new",
      int idx = 0;
      for(int i = 1; i < fieldPoly.length; i++)
      {
        LINE_PX(ColorClasses::green, fieldPoly[idx].x, fieldPoly[idx].y, fieldPoly[i].x, fieldPoly[i].y);
        idx = i;
      }
    );

    // add field to percept
    getFieldPercept().setField(fieldPoly, getArtificialHorizon());
    // check result
    if(fieldPoly.getArea() >= 5600)
    {
      getFieldPercept().valid = true;
    }
    else
    {
      getFieldPercept().valid = false;
    }

    DEBUG_REQUEST( "Vision:FieldDetector:mark_field_polygon",
      size_t idx = 0;
      ColorClasses::Color color = getFieldPercept().valid ? ColorClasses::black : ColorClasses::red;
      for(size_t i = 1; i < result.size(); i++)
      {
        LINE_PX(color, result[idx].x, result[idx].y, result[i].x, result[i].y);
        idx = i;
      }
    );

    DEBUG_REQUEST( "Vision:FieldDetector:mark_corrected_field_polygon",
      int idx = 0;
      ColorClasses::Color color = getFieldPercept().valid ? ColorClasses::green : ColorClasses::red;
      const FieldPercept::FieldPoly& fieldpoly = getFieldPercept().getValidField();
      for(int i = 1; i < fieldpoly.length; i++)
      {
        LINE_PX(color, fieldpoly[idx].x, fieldpoly[idx].y, fieldpoly[i].x, fieldpoly[i].y);
        idx = i;
      }
    );
  }
}//end execute

bool FieldDetector::myVecCompareX(const Vector2i &first, const Vector2i &second)
{
  return (first.x<second.x);
}
<|endoftext|>


<commit_before>//
// Description: Widget for configuring build targets
//
// Copyright (C) 2011-2014 Kåre Särs <kare.sars@iki.fi>
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Library General Public
//  License version 2 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
//  Library General Public License for more details.
//
//  You should have received a copy of the GNU Library General Public License
//  along with this library; see the file COPYING.LIB.  If not, write to
//  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
//  Boston, MA 02110-1301, USA.

#include "targets.h"
#include "targets.moc"
#include <klocale.h>
#include <QIcon>
#include <QEvent>
#include <QKeyEvent>
#include <QDebug>

TargetsUi::TargetsUi(QWidget *parent):
QWidget(parent)
{
    targetLabel = new QLabel(i18n("Active target-set:"));
    targetCombo = new QComboBox(this);
    targetCombo->setToolTip(i18n("Select active target set"));
    targetCombo->setModel(&targetsModel);
    targetLabel->setBuddy(targetCombo);

    newTarget = new QToolButton(this);
    newTarget->setToolTip(i18n("Create new set of targets"));
    newTarget->setIcon(QIcon::fromTheme(QStringLiteral("document-new")));

    copyTarget = new QToolButton(this);
    copyTarget->setToolTip(i18n("Copy command or target set"));
    copyTarget->setIcon(QIcon::fromTheme(QStringLiteral("edit-copy")));

    deleteTarget = new QToolButton(this);
    deleteTarget->setToolTip(i18n("Delete current set of targets"));
    deleteTarget->setIcon(QIcon::fromTheme(QStringLiteral("edit-delete")));

    addButton = new QToolButton(this);
    addButton->setIcon(QIcon::fromTheme(QStringLiteral("list-add")));
    addButton->setToolTip(i18n("Add new target"));

    buildButton = new QToolButton(this);
    buildButton->setIcon(QIcon::fromTheme(QStringLiteral("dialog-ok")));
    buildButton->setToolTip(i18n("Build selected target"));

    targetsView = new QTreeView(this);
    targetsView->setAlternatingRowColors(true);

    targetsView->setModel(&targetsModel);
    m_delegate = new TargetHtmlDelegate(targetsView);
    targetsView->setItemDelegate(m_delegate);
    targetsView->setSelectionBehavior(QAbstractItemView::SelectItems);
    targetsView->setEditTriggers(QAbstractItemView::AnyKeyPressed | QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed);

    QHBoxLayout* tLayout = new QHBoxLayout();

    tLayout->addWidget(targetLabel);
    tLayout->addWidget(targetCombo);
    tLayout->addStretch(40);
    tLayout->addWidget(buildButton);
    tLayout->addSpacing(addButton->sizeHint().width());
    tLayout->addWidget(addButton);
    tLayout->addWidget(newTarget);
    tLayout->addWidget(copyTarget);
    tLayout->addWidget(deleteTarget);
    tLayout->setContentsMargins(0,0,0,0);

    QVBoxLayout* layout = new QVBoxLayout(this);
    layout->addLayout(tLayout);
    layout->addWidget(targetsView);

    connect(targetCombo, SIGNAL(activated(int)), this, SLOT(targetSetSelected(int)));
    connect(targetsView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(targetActivated(QModelIndex)));
    //connect(targetsView, SIGNAL(clicked(QModelIndex)), this, SLOT(targetActivated(QModelIndex)));

    targetsView->installEventFilter(this);
}

void TargetsUi::targetSetSelected(int index)
{
    //qDebug() << index;
    targetsView->collapseAll();
    QModelIndex rootItem = targetsModel.index(index, 0);

    targetsView->setExpanded(rootItem, true);
    targetsView->setCurrentIndex(rootItem.child(0,0));
}

void TargetsUi::targetActivated(const QModelIndex &index)
{
    //qDebug() << index;
    if (!index.isValid()) return;
    QModelIndex rootItem = index;
    if (rootItem.parent().isValid()) {
        rootItem = rootItem.parent();
    }

    targetCombo->setCurrentIndex(rootItem.row());
}

bool TargetsUi::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type()==QEvent::KeyPress) {
        QKeyEvent *keyEvent=static_cast<QKeyEvent*>(event);
        if (obj==targetsView) {
            if (((keyEvent->key()==Qt::Key_Return)
                || (keyEvent->key()==Qt::Key_Enter)) && m_delegate && !m_delegate->isEditing())
            {
                emit enterPressed();
                return true;
            }
        }
    }
    return QWidget::eventFilter(obj, event);
}
<commit_msg>Fix compile: includes<commit_after>//
// Description: Widget for configuring build targets
//
// Copyright (C) 2011-2014 Kåre Särs <kare.sars@iki.fi>
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Library General Public
//  License version 2 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
//  Library General Public License for more details.
//
//  You should have received a copy of the GNU Library General Public License
//  along with this library; see the file COPYING.LIB.  If not, write to
//  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
//  Boston, MA 02110-1301, USA.

#include "targets.h"
#include "targets.moc"
#include <klocalizedstring.h>
#include <QIcon>
#include <QEvent>
#include <QKeyEvent>
#include <QDebug>

TargetsUi::TargetsUi(QWidget *parent):
QWidget(parent)
{
    targetLabel = new QLabel(i18n("Active target-set:"));
    targetCombo = new QComboBox(this);
    targetCombo->setToolTip(i18n("Select active target set"));
    targetCombo->setModel(&targetsModel);
    targetLabel->setBuddy(targetCombo);

    newTarget = new QToolButton(this);
    newTarget->setToolTip(i18n("Create new set of targets"));
    newTarget->setIcon(QIcon::fromTheme(QStringLiteral("document-new")));

    copyTarget = new QToolButton(this);
    copyTarget->setToolTip(i18n("Copy command or target set"));
    copyTarget->setIcon(QIcon::fromTheme(QStringLiteral("edit-copy")));

    deleteTarget = new QToolButton(this);
    deleteTarget->setToolTip(i18n("Delete current set of targets"));
    deleteTarget->setIcon(QIcon::fromTheme(QStringLiteral("edit-delete")));

    addButton = new QToolButton(this);
    addButton->setIcon(QIcon::fromTheme(QStringLiteral("list-add")));
    addButton->setToolTip(i18n("Add new target"));

    buildButton = new QToolButton(this);
    buildButton->setIcon(QIcon::fromTheme(QStringLiteral("dialog-ok")));
    buildButton->setToolTip(i18n("Build selected target"));

    targetsView = new QTreeView(this);
    targetsView->setAlternatingRowColors(true);

    targetsView->setModel(&targetsModel);
    m_delegate = new TargetHtmlDelegate(targetsView);
    targetsView->setItemDelegate(m_delegate);
    targetsView->setSelectionBehavior(QAbstractItemView::SelectItems);
    targetsView->setEditTriggers(QAbstractItemView::AnyKeyPressed | QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed);

    QHBoxLayout* tLayout = new QHBoxLayout();

    tLayout->addWidget(targetLabel);
    tLayout->addWidget(targetCombo);
    tLayout->addStretch(40);
    tLayout->addWidget(buildButton);
    tLayout->addSpacing(addButton->sizeHint().width());
    tLayout->addWidget(addButton);
    tLayout->addWidget(newTarget);
    tLayout->addWidget(copyTarget);
    tLayout->addWidget(deleteTarget);
    tLayout->setContentsMargins(0,0,0,0);

    QVBoxLayout* layout = new QVBoxLayout(this);
    layout->addLayout(tLayout);
    layout->addWidget(targetsView);

    connect(targetCombo, SIGNAL(activated(int)), this, SLOT(targetSetSelected(int)));
    connect(targetsView->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(targetActivated(QModelIndex)));
    //connect(targetsView, SIGNAL(clicked(QModelIndex)), this, SLOT(targetActivated(QModelIndex)));

    targetsView->installEventFilter(this);
}

void TargetsUi::targetSetSelected(int index)
{
    //qDebug() << index;
    targetsView->collapseAll();
    QModelIndex rootItem = targetsModel.index(index, 0);

    targetsView->setExpanded(rootItem, true);
    targetsView->setCurrentIndex(rootItem.child(0,0));
}

void TargetsUi::targetActivated(const QModelIndex &index)
{
    //qDebug() << index;
    if (!index.isValid()) return;
    QModelIndex rootItem = index;
    if (rootItem.parent().isValid()) {
        rootItem = rootItem.parent();
    }

    targetCombo->setCurrentIndex(rootItem.row());
}

bool TargetsUi::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type()==QEvent::KeyPress) {
        QKeyEvent *keyEvent=static_cast<QKeyEvent*>(event);
        if (obj==targetsView) {
            if (((keyEvent->key()==Qt::Key_Return)
                || (keyEvent->key()==Qt::Key_Enter)) && m_delegate && !m_delegate->isEditing())
            {
                emit enterPressed();
                return true;
            }
        }
    }
    return QWidget::eventFilter(obj, event);
}
<|endoftext|>