<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------

#include "cling/Interpreter/DynamicLibraryManager.h"
#include "cling/Interpreter/InvocationOptions.h"

#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"

#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <stdio.h>

#ifdef WIN32
#include <Windows.h>
#include <shlobj.h>
#else
#include <limits.h> /* PATH_MAX */
#include <dlfcn.h>
#endif

namespace cling {
  DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts)
    : m_Opts(Opts) { }

  DynamicLibraryManager::~DynamicLibraryManager() {}

  static bool isSharedLib(llvm::StringRef LibName, bool& exists) {
    using namespace llvm::sys::fs;
    file_magic Magic;
    llvm::error_code Error = identify_magic(LibName, Magic);
    exists = (Error == llvm::errc::success);
    return exists &&
#ifdef __APPLE__
        (Magic == file_magic::macho_fixed_virtual_memory_shared_lib
         || Magic == file_magic::macho_dynamically_linked_shared_lib
         || Magic == file_magic::macho_dynamically_linked_shared_lib_stub)
#elif defined(LLVM_ON_UNIX)
#ifdef __CYGWIN__
        Magic == file_magic::pecoff_executable
#else
        Magic == file_magic::elf_shared_object
#endif
#elif defined(LLVM_ON_WIN32)
		(Magic == file_magic::pecoff_executable)
#else
# error "Unsupported platform."
#endif
      ;
  }

  static void
  findSharedLibrary(llvm::StringRef fileStem,
                    const llvm::SmallVectorImpl<std::string>& Paths,
                    llvm::SmallString<512>& FoundDyLib,
                    bool& exists, bool& isDyLib) {
    for (llvm::SmallVectorImpl<std::string>::const_iterator
        IPath = Paths.begin(), EPath = Paths.end(); IPath != EPath; ++IPath) {
      llvm::SmallString<512> ThisPath(*IPath);
      llvm::sys::path::append(ThisPath, fileStem);
      isDyLib = isSharedLib(ThisPath.str(), exists);
      if (isDyLib)
        ThisPath.swap(FoundDyLib);
      if (exists)
        return;
    }
  }

#if defined(LLVM_ON_UNIX)
  static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {
    char* env_var = getenv("LD_LIBRARY_PATH");
#if __APPLE__
    if (!env_var)
      env_var = getenv("DYLD_LIBRARY_PATH");
    if (!env_var)
      env_var = getenv("DYLD_FALLBACK_LIBRARY_PATH");
#endif
    if (env_var != 0) {
      static const char PathSeparator = ':';
      const char* at = env_var;
      const char* delim = strchr(at, PathSeparator);
      while (delim != 0) {
        std::string tmp(at, size_t(delim-at));
        if (llvm::sys::fs::is_directory(tmp.c_str()))
            Paths.push_back(tmp);
        at = delim + 1;
        delim = strchr(at, PathSeparator);
      }

      if (*at != 0)
        if (llvm::sys::fs::is_directory(llvm::StringRef(at)))
          Paths.push_back(at);
    }
    static bool initialized = false;
    static std::vector<std::string> SysPaths;
    if (!initialized) {
      // trick to get the system search path
      std::string cmd("LD_DEBUG=libs LD_PRELOAD=DOESNOTEXIST ls 2>&1");
      FILE *pf = popen(cmd.c_str (), "r");
      std::string result = "";
      std::string sys_path = "";
      char buffer[128];
      while (!feof(pf)) {
         if (fgets(buffer, 128, pf) != NULL)
            result += buffer;
      }
      pclose(pf);
      std::size_t from = result.find("search path=", result.find("(LD_LIBRARY_PATH)"));
      std::size_t to = result.find("(system search path)");
      if (from != std::string::npos && to != std::string::npos) {
         from += 12;
         sys_path = result.substr(from, to-from);
         sys_path.erase(std::remove_if(sys_path.begin(), sys_path.end(), isspace), sys_path.end());
         sys_path += ':';
      }
      static const char PathSeparator = ':';
      const char* at = sys_path.c_str();
      const char* delim = strchr(at, PathSeparator);
      while (delim != 0) {
        std::string tmp(at, size_t(delim-at));
        if (llvm::sys::fs::is_directory(tmp.c_str()))
          SysPaths.push_back(tmp);
        at = delim + 1;
        delim = strchr(at, PathSeparator);
      }
      initialized = true;
    }
    std::vector<std::string>::const_iterator it = SysPaths.begin();
    while ((++it) != SysPaths.end()) {
      Paths.push_back((*it).c_str());
    }
#ifdef __APPLE__
    Paths.push_back("/usr/local/lib/");
    Paths.push_back("/usr/X11R6/lib/");
    Paths.push_back("/usr/lib/");
    Paths.push_back("/lib/");
#endif
  }
#elif defined(LLVM_ON_WIN32)
  static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {
    char buff[MAX_PATH];
    // Generic form of C:\Windows\System32
    HRESULT res =  SHGetFolderPathA(NULL,
                                    CSIDL_FLAG_CREATE | CSIDL_SYSTEM,
                                    NULL,
                                    SHGFP_TYPE_CURRENT,
                                    buff);
    if (res != S_OK) {
      assert(0 && "Failed to get system directory");
      return;
    }
    Paths.push_back(buff);

    // Reset buff.
    buff[0] = 0;
    // Generic form of C:\Windows
    res =  SHGetFolderPathA(NULL,
                            CSIDL_FLAG_CREATE | CSIDL_WINDOWS,
                            NULL,
                            SHGFP_TYPE_CURRENT,
                            buff);
    if (res != S_OK) {
      assert(0 && "Failed to get windows directory");
      return;
    }
    Paths.push_back(buff);
  }
#else
# error "Unsupported platform."
#endif

  DynamicLibraryManager::LoadLibResult
  DynamicLibraryManager::tryLinker(const std::string& filename, bool permanent,
                                   bool isAbsolute, bool& exists,
                                   bool& isDyLib) {
    using namespace llvm::sys;
    exists = false;
    isDyLib = false;

    llvm::SmallString<512> FoundDyLib;

    if (isAbsolute) {
      isDyLib = isSharedLib(filename, exists);
      if (isDyLib)
        FoundDyLib = filename;
    } else {
      llvm::SmallVector<std::string, 16>
        SearchPaths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end());
      GetSystemLibraryPaths(SearchPaths);
      SearchPaths.push_back("."); // search also in the current directory

      findSharedLibrary(filename, SearchPaths, FoundDyLib, exists, isDyLib);

      if (!exists) {
        // Add DyLib extension:
        llvm::SmallString<512> filenameWithExt(filename);
#if defined(LLVM_ON_UNIX)
#ifdef __APPLE__
        llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;
#endif
        static const char* DyLibExt = ".so";
#elif defined(LLVM_ON_WIN32)
        static const char* DyLibExt = ".dll";
#else
# error "Unsupported platform."
#endif
        filenameWithExt += DyLibExt;
        findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,
                          isDyLib);
#ifdef __APPLE__
        if (!exists) {
           filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());
           filenameWithExt += ".dylib";
           findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,
                             isDyLib);
        }
#endif
      }
    }

    if (!isDyLib)
      return kLoadLibError;

    assert(!FoundDyLib.empty() && "The shared lib exists but can't find it!");

    // get canonical path name and check if already loaded
#if defined(LLVM_ON_WIN32)
    llvm::SmallString<_MAX_PATH> FullPath("");
    char *res = _fullpath((char *)FullPath.data(), FoundDyLib.c_str(), _MAX_PATH);
#else
    llvm::SmallString<PATH_MAX+1> FullPath("");
    char *res = realpath(FoundDyLib.c_str(), (char *)FullPath.data());
#endif
    if (res == 0) {
      llvm::errs() << "cling::Interpreter::tryLinker(): error getting real (canonical) path\n";
      return kLoadLibError;
    }
    FullPath.set_size(strlen(res));
    if (m_loadedLibraries.find(FullPath) != m_loadedLibraries.end())
      return kLoadLibExists;

    std::string errMsg;
    // TODO: !permanent case
#if defined(LLVM_ON_WIN32)
    HMODULE dyLibHandle = LoadLibraryEx(FullPath.c_str(), NULL, DONT_RESOLVE_DLL_REFERENCES);
    errMsg = "LoadLibraryEx: GetLastError() returned ";
    errMsg += GetLastError();
#else
    const void* dyLibHandle = dlopen(FullPath.c_str(), RTLD_LAZY|RTLD_GLOBAL);
    if (const char* DyLibError = dlerror()) {
      errMsg = DyLibError;
    }
#endif
    if (!dyLibHandle) {
      llvm::errs() << "cling::Interpreter::tryLinker(): " << errMsg << '\n';
      return kLoadLibError;
    }
    std::pair<DyLibs::iterator, bool> insRes
      = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle,
                                                            FullPath.str()));
    if (!insRes.second)
      return kLoadLibExists;
    m_loadedLibraries.insert(FullPath);
    return kLoadLibSuccess;
  }

  DynamicLibraryManager::LoadLibResult
  DynamicLibraryManager::loadLibrary(const std::string& filename,
                                     bool permanent, bool* tryCode) {
    llvm::SmallString<128> Absolute((llvm::StringRef(filename)));
    llvm::sys::fs::make_absolute(Absolute);
    bool isAbsolute = filename == Absolute.c_str();
    bool exists = false;
    bool isDyLib = false;
    LoadLibResult res = tryLinker(filename, permanent, isAbsolute, exists,
                                  isDyLib);
    if (tryCode) {
      *tryCode = !isDyLib;
      if (isAbsolute)
        *tryCode &= exists;
    }
    if (exists)
      return res;

    if (!isAbsolute && filename.compare(0, 3, "lib")) {
      // try with "lib" prefix:
      res = tryLinker("lib" + filename, permanent, false, exists, isDyLib);
      if (tryCode) {
        *tryCode = !isDyLib;
        if (isAbsolute)
          *tryCode &= exists;
      }
      if (res != kLoadLibError)
        return res;
    }
    return kLoadLibError;
  }

  bool
  DynamicLibraryManager::isDynamicLibraryLoaded(llvm::StringRef fullPath) const {
    // get canonical path name and check if already loaded
#if defined(LLVM_ON_WIN32)
    char buf[_MAX_PATH];
    char *res = _fullpath(buf, fullPath.str().c_str(), _MAX_PATH);
#else
    char buf[PATH_MAX+1];
    char *res = realpath(fullPath.str().c_str(), buf);
#endif
    if (res == 0) {
      llvm::errs() << "cling::Interpreter::isDynamicLibraryLoaded(): error getting real (canonical) path\n";
      return false;
    }
    if (m_loadedLibraries.find(buf) != m_loadedLibraries.end()) return true;
    return false;
  }

  void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {
    llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle));
  }
} // end namespace cling
<commit_msg>Use hard-coded system library path on cygwin/gcc<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//------------------------------------------------------------------------------

#include "cling/Interpreter/DynamicLibraryManager.h"
#include "cling/Interpreter/InvocationOptions.h"

#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"

#include <stdlib.h>
#include <algorithm>
#include <iostream>
#include <stdio.h>

#ifdef WIN32
#include <Windows.h>
#include <shlobj.h>
#else
#include <limits.h> /* PATH_MAX */
#include <dlfcn.h>
#endif

namespace cling {
  DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts)
    : m_Opts(Opts) { }

  DynamicLibraryManager::~DynamicLibraryManager() {}

  static bool isSharedLib(llvm::StringRef LibName, bool& exists) {
    using namespace llvm::sys::fs;
    file_magic Magic;
    llvm::error_code Error = identify_magic(LibName, Magic);
    exists = (Error == llvm::errc::success);
    return exists &&
#ifdef __APPLE__
        (Magic == file_magic::macho_fixed_virtual_memory_shared_lib
         || Magic == file_magic::macho_dynamically_linked_shared_lib
         || Magic == file_magic::macho_dynamically_linked_shared_lib_stub)
#elif defined(LLVM_ON_UNIX)
#ifdef __CYGWIN__
        Magic == file_magic::pecoff_executable
#else
        Magic == file_magic::elf_shared_object
#endif
#elif defined(LLVM_ON_WIN32)
		(Magic == file_magic::pecoff_executable)
#else
# error "Unsupported platform."
#endif
      ;
  }

  static void
  findSharedLibrary(llvm::StringRef fileStem,
                    const llvm::SmallVectorImpl<std::string>& Paths,
                    llvm::SmallString<512>& FoundDyLib,
                    bool& exists, bool& isDyLib) {
    for (llvm::SmallVectorImpl<std::string>::const_iterator
        IPath = Paths.begin(), EPath = Paths.end(); IPath != EPath; ++IPath) {
      llvm::SmallString<512> ThisPath(*IPath);
      llvm::sys::path::append(ThisPath, fileStem);
      isDyLib = isSharedLib(ThisPath.str(), exists);
      if (isDyLib)
        ThisPath.swap(FoundDyLib);
      if (exists)
        return;
    }
  }

#if defined(LLVM_ON_UNIX)
  static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {
    char* env_var = getenv("LD_LIBRARY_PATH");
#if __APPLE__
    if (!env_var)
      env_var = getenv("DYLD_LIBRARY_PATH");
    if (!env_var)
      env_var = getenv("DYLD_FALLBACK_LIBRARY_PATH");
#endif
    if (env_var != 0) {
      static const char PathSeparator = ':';
      const char* at = env_var;
      const char* delim = strchr(at, PathSeparator);
      while (delim != 0) {
        std::string tmp(at, size_t(delim-at));
        if (llvm::sys::fs::is_directory(tmp.c_str()))
            Paths.push_back(tmp);
        at = delim + 1;
        delim = strchr(at, PathSeparator);
      }

      if (*at != 0)
        if (llvm::sys::fs::is_directory(llvm::StringRef(at)))
          Paths.push_back(at);
    }
#ifndef __CYGWIN__
    static bool initialized = false;
    static std::vector<std::string> SysPaths;
    if (!initialized) {
      // trick to get the system search path
      std::string cmd("LD_DEBUG=libs LD_PRELOAD=DOESNOTEXIST ls 2>&1");
      FILE *pf = popen(cmd.c_str (), "r");
      std::string result = "";
      std::string sys_path = "";
      char buffer[128];
      while (!feof(pf)) {
         if (fgets(buffer, 128, pf) != NULL)
            result += buffer;
      }
      pclose(pf);
      std::size_t from = result.find("search path=", result.find("(LD_LIBRARY_PATH)"));
      std::size_t to = result.find("(system search path)");
      if (from != std::string::npos && to != std::string::npos) {
         from += 12;
         sys_path = result.substr(from, to-from);
         sys_path.erase(std::remove_if(sys_path.begin(), sys_path.end(), isspace), sys_path.end());
         sys_path += ':';
      }
      static const char PathSeparator = ':';
      const char* at = sys_path.c_str();
      const char* delim = strchr(at, PathSeparator);
      while (delim != 0) {
        std::string tmp(at, size_t(delim-at));
        if (llvm::sys::fs::is_directory(tmp.c_str()))
          SysPaths.push_back(tmp);
        at = delim + 1;
        delim = strchr(at, PathSeparator);
      }
      initialized = true;
    }
    std::vector<std::string>::const_iterator it = SysPaths.begin();
    while ((++it) != SysPaths.end()) {
      Paths.push_back((*it).c_str());
    }
#endif
#if defined(__APPLE__) || defined(__CYGWIN__)
    Paths.push_back("/usr/local/lib/");
    Paths.push_back("/usr/X11R6/lib/");
    Paths.push_back("/usr/lib/");
    Paths.push_back("/lib/");

    Paths.push_back("/lib/x86_64-linux-gnu/");
    Paths.push_back("/usr/local/lib64/");
    Paths.push_back("/usr/lib64/");
    Paths.push_back("/lib64/");
#endif
  }
#elif defined(LLVM_ON_WIN32)
  static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) {
    char buff[MAX_PATH];
    // Generic form of C:\Windows\System32
    HRESULT res =  SHGetFolderPathA(NULL,
                                    CSIDL_FLAG_CREATE | CSIDL_SYSTEM,
                                    NULL,
                                    SHGFP_TYPE_CURRENT,
                                    buff);
    if (res != S_OK) {
      assert(0 && "Failed to get system directory");
      return;
    }
    Paths.push_back(buff);

    // Reset buff.
    buff[0] = 0;
    // Generic form of C:\Windows
    res =  SHGetFolderPathA(NULL,
                            CSIDL_FLAG_CREATE | CSIDL_WINDOWS,
                            NULL,
                            SHGFP_TYPE_CURRENT,
                            buff);
    if (res != S_OK) {
      assert(0 && "Failed to get windows directory");
      return;
    }
    Paths.push_back(buff);
  }
#else
# error "Unsupported platform."
#endif

  DynamicLibraryManager::LoadLibResult
  DynamicLibraryManager::tryLinker(const std::string& filename, bool permanent,
                                   bool isAbsolute, bool& exists,
                                   bool& isDyLib) {
    using namespace llvm::sys;
    exists = false;
    isDyLib = false;

    llvm::SmallString<512> FoundDyLib;

    if (isAbsolute) {
      isDyLib = isSharedLib(filename, exists);
      if (isDyLib)
        FoundDyLib = filename;
    } else {
      llvm::SmallVector<std::string, 16>
        SearchPaths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end());
      GetSystemLibraryPaths(SearchPaths);
      SearchPaths.push_back("."); // search also in the current directory

      findSharedLibrary(filename, SearchPaths, FoundDyLib, exists, isDyLib);

      if (!exists) {
        // Add DyLib extension:
        llvm::SmallString<512> filenameWithExt(filename);
#if defined(LLVM_ON_UNIX)
#ifdef __APPLE__
        llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;
#endif
        static const char* DyLibExt = ".so";
#elif defined(LLVM_ON_WIN32)
        static const char* DyLibExt = ".dll";
#else
# error "Unsupported platform."
#endif
        filenameWithExt += DyLibExt;
        findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,
                          isDyLib);
#ifdef __APPLE__
        if (!exists) {
           filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());
           filenameWithExt += ".dylib";
           findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,
                             isDyLib);
        }
#endif
      }
    }

    if (!isDyLib)
      return kLoadLibError;

    assert(!FoundDyLib.empty() && "The shared lib exists but can't find it!");

    // get canonical path name and check if already loaded
#if defined(LLVM_ON_WIN32)
    llvm::SmallString<_MAX_PATH> FullPath("");
    char *res = _fullpath((char *)FullPath.data(), FoundDyLib.c_str(), _MAX_PATH);
#else
    llvm::SmallString<PATH_MAX+1> FullPath("");
    char *res = realpath(FoundDyLib.c_str(), (char *)FullPath.data());
#endif
    if (res == 0) {
      llvm::errs() << "cling::Interpreter::tryLinker(): error getting real (canonical) path\n";
      return kLoadLibError;
    }
    FullPath.set_size(strlen(res));
    if (m_loadedLibraries.find(FullPath) != m_loadedLibraries.end())
      return kLoadLibExists;

    std::string errMsg;
    // TODO: !permanent case
#if defined(LLVM_ON_WIN32)
    HMODULE dyLibHandle = LoadLibraryEx(FullPath.c_str(), NULL, DONT_RESOLVE_DLL_REFERENCES);
    errMsg = "LoadLibraryEx: GetLastError() returned ";
    errMsg += GetLastError();
#else
    const void* dyLibHandle = dlopen(FullPath.c_str(), RTLD_LAZY|RTLD_GLOBAL);
    if (const char* DyLibError = dlerror()) {
      errMsg = DyLibError;
    }
#endif
    if (!dyLibHandle) {
      llvm::errs() << "cling::Interpreter::tryLinker(): " << errMsg << '\n';
      return kLoadLibError;
    }
    std::pair<DyLibs::iterator, bool> insRes
      = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle,
                                                            FullPath.str()));
    if (!insRes.second)
      return kLoadLibExists;
    m_loadedLibraries.insert(FullPath);
    return kLoadLibSuccess;
  }

  DynamicLibraryManager::LoadLibResult
  DynamicLibraryManager::loadLibrary(const std::string& filename,
                                     bool permanent, bool* tryCode) {
    llvm::SmallString<128> Absolute((llvm::StringRef(filename)));
    llvm::sys::fs::make_absolute(Absolute);
    bool isAbsolute = filename == Absolute.c_str();
    bool exists = false;
    bool isDyLib = false;
    LoadLibResult res = tryLinker(filename, permanent, isAbsolute, exists,
                                  isDyLib);
    if (tryCode) {
      *tryCode = !isDyLib;
      if (isAbsolute)
        *tryCode &= exists;
    }
    if (exists)
      return res;

    if (!isAbsolute && filename.compare(0, 3, "lib")) {
      // try with "lib" prefix:
      res = tryLinker("lib" + filename, permanent, false, exists, isDyLib);
      if (tryCode) {
        *tryCode = !isDyLib;
        if (isAbsolute)
          *tryCode &= exists;
      }
      if (res != kLoadLibError)
        return res;
    }
    return kLoadLibError;
  }

  bool
  DynamicLibraryManager::isDynamicLibraryLoaded(llvm::StringRef fullPath) const {
    // get canonical path name and check if already loaded
#if defined(LLVM_ON_WIN32)
    char buf[_MAX_PATH];
    char *res = _fullpath(buf, fullPath.str().c_str(), _MAX_PATH);
#else
    char buf[PATH_MAX+1];
    char *res = realpath(fullPath.str().c_str(), buf);
#endif
    if (res == 0) {
      llvm::errs() << "cling::Interpreter::isDynamicLibraryLoaded(): error getting real (canonical) path\n";
      return false;
    }
    if (m_loadedLibraries.find(buf) != m_loadedLibraries.end()) return true;
    return false;
  }

  void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {
    llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle));
  }
} // end namespace cling
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2016 Fondazione Istituto Italiano di Tecnologia
 * Authors: Silvio Traversaro
 * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT
 *
 */

#include <iDynTree/Core/EigenHelpers.h>
#include <iDynTree/Core/VectorFixSize.h>
#include <iDynTree/Core/Rotation.h>
#include <iDynTree/Core/Utils.h>
#include <iDynTree/Core/TestUtils.h>

#include <kdl_codyco/KDLConversions.h>
#include <kdl/frames.hpp>

#include <iDynTree/yarp/YARPConversions.h>

#include <yarp/sig/Matrix.h>
#include <yarp/math/Math.h>

#include <cstdlib>
#include <limits>
#include <iostream>
#include <sstream>

void getQuaternion(const iDynTree::Rotation & rot,
                   iDynTree::Vector4 & quat_idyntree,
                   iDynTree::Vector4 & quat_kdl,
                   iDynTree::Vector4 & quat_yarp)
{
    rot.getQuaternion(quat_idyntree);

    // Notice that KDL uses a imaginary/real serialization, while we use real/imaginary
    iDynTree::ToKDL(rot).GetQuaternion(quat_kdl(1),quat_kdl(2),quat_kdl(3),quat_kdl(0));

    yarp::sig::Matrix rotYarp(3,3);
    iDynTree::toYarp(rot,rotYarp);

    yarp::sig::Vector quat_yarp_yarp(4);

    quat_yarp_yarp = yarp::math::dcm2quat(rotYarp);

    iDynTree::toiDynTree(quat_yarp_yarp,quat_yarp);
}

void checkRotationToQuaternion(const iDynTree::Rotation randRot)
{
    iDynTree::Vector4 quat_idyntree, quat_kdl, quat_yarp;
    getQuaternion(randRot,quat_idyntree,quat_kdl,quat_yarp);

    std::cerr << "Quaternion converted by KDL: " << quat_kdl.toString() << " ( norm " << toEigen(quat_kdl).norm() <<  " ) " << std::endl;
    std::cerr << "Quaternion converted by YARP: " << quat_yarp.toString() << " ( norm " << toEigen(quat_yarp).norm() <<  " ) " << std::endl;
    std::cerr << "Quaternion converted by iDynTree: " << quat_idyntree.toString() << " ( norm " << toEigen(quat_idyntree).norm() <<  " ) " << std::endl;

    /*
    ASSERT_EQUAL_VECTOR(quat_kdl,quat_yarp);
    ASSERT_EQUAL_VECTOR(quat_idyntree,quat_kdl);
    ASSERT_EQUAL_VECTOR(quat_idyntree,quat_yarp);
    */

    // Check going back to a rotation
    iDynTree::Rotation randRotCheck = iDynTree::Rotation::RotationFromQuaternion(quat_idyntree);

    std::cerr << "Original rotation:\n" << randRot.toString() << std::endl;
    std::cerr << "Rotation converted back and forth from quaternion:\n" << randRotCheck.toString() << std::endl;

    //ASSERT_EQUAL_MATRIX(randRot,randRotCheck);
}

int main()
{
    std::cerr << "Quaternion Consistency check " << std::endl;

    // First we check an easy one for debugging
    checkRotationToQuaternion(iDynTree::Rotation::RPY(M_PI,0.0,0.0));

    // Then some random ones
    int nrOfTrials = 0;

    for(int i=0; i < nrOfTrials;i++)
    {
        // Create random rotation
        iDynTree::Rotation randRot = iDynTree::getRandomRotation();

        checkRotationToQuaternion(randRot);
    }

    return EXIT_SUCCESS;
}
<commit_msg>Added infrastructure for test of output ranges of component returned by getQuaternion<commit_after>/*
 * Copyright (C) 2016 Fondazione Istituto Italiano di Tecnologia
 * Authors: Silvio Traversaro
 * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT
 *
 */

#include <iDynTree/Core/EigenHelpers.h>
#include <iDynTree/Core/VectorFixSize.h>
#include <iDynTree/Core/Rotation.h>
#include <iDynTree/Core/Utils.h>
#include <iDynTree/Core/TestUtils.h>

#include <kdl_codyco/KDLConversions.h>
#include <kdl/frames.hpp>

#include <iDynTree/yarp/YARPConversions.h>

#include <yarp/sig/Matrix.h>
#include <yarp/math/Math.h>

#include <cstdlib>
#include <limits>
#include <iostream>
#include <sstream>

class MaxMin
{
public:
    double min;
    double max;

    MaxMin()
    {
        min = std::numeric_limits<double>::max();
        max = -std::numeric_limits<double>::max();
    }

    void update(const double newValue)
    {
        if( newValue > max )
        {
            max = newValue;
        }

        if( newValue < min )
        {
            min = newValue;
        }
    }
};

class QuaternionMaxMin
{
public:
    MaxMin help[4];

    void update(const iDynTree::Vector4 & quat)
    {
        help[0].update(quat(0));
        help[1].update(quat(1));
        help[2].update(quat(2));
        help[3].update(quat(3));
    }

    std::string toString()
    {
        std::stringstream ss;
        ss << "Real part is in (" << (help[0].min) << " , " << (help[0].max) << ")" << std::endl;
        ss << "Imag x    is in (" << (help[1].min) << " , " << (help[1].max) << ")" << std::endl;
        ss << "Imag y    is in (" << (help[2].min) << " , " << (help[2].max) << ")" << std::endl;
        ss << "Imag z    is in (" << (help[3].min) << " , " << (help[3].max) << ")" << std::endl;

        return ss.str();
    }
};

struct QuaternionMaxMinHelper
{
    QuaternionMaxMin idyntree;
    QuaternionMaxMin yarp;
    QuaternionMaxMin kdl;
};

void getQuaternion(const iDynTree::Rotation & rot,
                   iDynTree::Vector4 & quat_idyntree,
                   iDynTree::Vector4 & quat_kdl,
                   iDynTree::Vector4 & quat_yarp)
{
    rot.getQuaternion(quat_idyntree);

    // Notice that KDL uses a imaginary/real serialization, while we use real/imaginary
    iDynTree::ToKDL(rot).GetQuaternion(quat_kdl(1),quat_kdl(2),quat_kdl(3),quat_kdl(0));

    yarp::sig::Matrix rotYarp(3,3);
    iDynTree::toYarp(rot,rotYarp);

    yarp::sig::Vector quat_yarp_yarp(4);

    quat_yarp_yarp = yarp::math::dcm2quat(rotYarp);

    iDynTree::toiDynTree(quat_yarp_yarp,quat_yarp);
}

void checkRotationToQuaternion(const iDynTree::Rotation randRot, QuaternionMaxMinHelper & helper, bool verbose)
{
    iDynTree::Vector4 quat_idyntree, quat_kdl, quat_yarp;
    getQuaternion(randRot,quat_idyntree,quat_kdl,quat_yarp);

    if( verbose )
    {
        std::cerr << "Quaternion converted by KDL: " << quat_kdl.toString() << " ( norm " << toEigen(quat_kdl).norm() <<  " ) " << std::endl;
        std::cerr << "Quaternion converted by YARP: " << quat_yarp.toString() << " ( norm " << toEigen(quat_yarp).norm() <<  " ) " << std::endl;
        std::cerr << "Quaternion converted by iDynTree: " << quat_idyntree.toString() << " ( norm " << toEigen(quat_idyntree).norm() <<  " ) " << std::endl;
    }

    /*
    ASSERT_EQUAL_VECTOR(quat_kdl,quat_yarp);
    ASSERT_EQUAL_VECTOR(quat_idyntree,quat_kdl);
    ASSERT_EQUAL_VECTOR(quat_idyntree,quat_yarp);
    */

    // Check going back to a rotation
    iDynTree::Rotation randRotCheck = iDynTree::Rotation::RotationFromQuaternion(quat_idyntree);

    if( verbose )
    {
        std::cerr << "Original rotation:\n" << randRot.toString() << std::endl;
        std::cerr << "Rotation converted back and forth from quaternion:\n" << randRotCheck.toString() << std::endl;
    }

    //ASSERT_EQUAL_MATRIX(randRot,randRotCheck);

    // Check range
    helper.idyntree.update(quat_idyntree);
    helper.kdl.update(quat_kdl);
    helper.yarp.update(quat_yarp);
}

int main()
{
    std::cerr << "Quaternion Consistency check " << std::endl;

    // Check ranges of the output quaternions
    QuaternionMaxMinHelper rangeHelper;

    // First we check an easy one for debugging
    checkRotationToQuaternion(iDynTree::Rotation::RPY(M_PI,0.0,0.0),rangeHelper,false);

    // Then we check two rotation, to see if any implementation suffer of the
    // discontinuities reported in http://it.mathworks.com/matlabcentral/answers/164746-bug-in-dcm2quat-function
    iDynTree::Rotation T_1059 = iDynTree::Rotation(0.4218,-0.3220,0.8475,
                                                   0.7299,-0.4339,-0.5282,
                                                   0.5378,0.8414,0.0520);

    iDynTree::Rotation T_1060 = iDynTree::Rotation(0.4312,-0.2603,0.8639,
                                                   0.7289,-0.4637,-0.5036,
                                                   0.5317,0.8469,-0.0102);

    checkRotationToQuaternion(T_1059,rangeHelper,true);
    checkRotationToQuaternion(T_1060,rangeHelper,true);

    // Then some random ones
    int nrOfTrials = 100000;

    for(int i=0; i < nrOfTrials;i++)
    {
        // Create random rotation
        iDynTree::Rotation randRot = iDynTree::getRandomRotation();

        checkRotationToQuaternion(randRot,rangeHelper,false);
    }

    std::cerr << "KDL quaternion ranges: " << std::endl;
    std::cerr << rangeHelper.kdl.toString();

    std::cerr << "YARP quaternion ranges: " << std::endl;
    std::cerr << rangeHelper.yarp.toString();

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <ostree.h>
#include <stdlib.h>

extern "C" OstreeDeployment *ostree_sysroot_get_booted_deployment(OstreeSysroot *self) {
  (void)self;
  const char *hash = getenv("OSTREE_HASH");
  return ostree_deployment_new(0, "dummy-os", hash, 1, hash, 1);
}

extern "C" const char *ostree_deployment_get_csum(OstreeDeployment *self) {
  (void)self;
  return getenv("OSTREE_HASH");
}
<commit_msg>aktualizr-lite: Fix mem leak in test code<commit_after>#include <ostree.h>
#include <stdlib.h>

extern "C" OstreeDeployment *ostree_sysroot_get_booted_deployment(OstreeSysroot *self) {
  (void)self;
  static OstreeDeployment *deployment;

  if (deployment != nullptr) {
    return deployment;
  }

  const char *hash = getenv("OSTREE_HASH");
  deployment = ostree_deployment_new(0, "dummy-os", hash, 1, hash, 1);
  return deployment;
}

extern "C" const char *ostree_deployment_get_csum(OstreeDeployment *self) {
  (void)self;
  return getenv("OSTREE_HASH");
}
<|endoftext|>


<commit_before>/** \file   generate_subscription_packets.cc
 *  \brief  Imports data from Zeder and writes a subscription packets defintion file.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *  \copyright 2020-2021 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <map>
#include <unordered_map>
#include <set>
#include "Compiler.h"
#include "FileUtil.h"
#include "IniFile.h"
#include "StringUtil.h"
#include "util.h"
#include "Zeder.h"

namespace {

[[noreturn]] void Usage() {
    ::Usage("packet_definition_config_file packet_subscriptions_output\n"
            "\tFor the documentation of the input config file, please see data/generate_subscription_packets.README.");
}

// Return true if an entry of "class_list" equals one of the vertical-bar-separated values of "expected_values_str."
bool FoundExpectedClassValue(const std::string &expected_values_str, const std::string &class_list_str) {
    std::vector<std::string> expected_values;
    StringUtil::Split(expected_values_str, '|', &expected_values);

    std::vector<std::string> class_list;
    StringUtil::SplitThenTrimWhite(class_list_str, ',', &class_list);

    for (const auto &class_str : class_list) {
        if (std::find_if(expected_values.cbegin(), expected_values.cend(),
                         [&class_str](auto &expected_value) { return ::strcasecmp(class_str.c_str(), expected_value.c_str()) == 0; }) != expected_values.cend())
            return true;
    }
    return false;
}

bool IncludeJournal(const Zeder::Entry &journal, const IniFile::Section &filter_section) {
    for (const auto &entry : filter_section) {
        if (entry.name_.empty() or entry.name_ == "description")
            continue;

        const std::string &zeder_column_name(entry.name_);
        const auto column_value(StringUtil::TrimWhite(journal.lookup(zeder_column_name == "except_class" ? "class" : zeder_column_name)));
        if (column_value.empty())
        {
            LOG_INFO("\tcolumn " + zeder_column_name + " was empty!");
            return false;

        }

        const bool found_it(FoundExpectedClassValue(entry.value_, column_value));
        if (zeder_column_name == "except_class") {
            if (found_it)
                return false;
        } else if (not found_it)
            return false;
    }

    return true;
}

// Please note that Zeder PPN entries are separated by spaces and, unlike what the column names "print_ppn" and
// "online_ppn" imply may in rare cases contain space-separated lists of PPN's.
void ProcessPPNs(const std::string &ppns, std::set<std::string> * const bundle_ppns) {
    std::vector<std::string> individual_ppns;
    StringUtil::Split(ppns, ' ', &individual_ppns);
    bundle_ppns->insert(individual_ppns.cbegin(), individual_ppns.cend());
}

std::string EscapeDoubleQuotes(const std::string &s) {
    std::string escaped_s;
    escaped_s.reserve(s.size());

    for (const char ch : s) {
        if (ch == '"' or ch == '\\')
            escaped_s += '\\';
        escaped_s += ch;
    }

    return escaped_s;
}

void GenerateBundleDefinition(const Zeder::SimpleZeder &zeder, const std::string &bundle_instances,
                              const IniFile::Section &section, File * const output_file)
{
    unsigned included_journal_count(0);
    std::set<std::string> bundle_ppns; // We use a std::set because it is automatically being sorted for us.
    bool contains_print(false);
    bool contains_online(false);
    for (const auto &journal : zeder) {
        if (journal.empty() or not IncludeJournal(journal, section))
            continue;

        ++included_journal_count;
        const auto print_ppns(journal.lookup("pppn"));
        const auto online_ppns(journal.lookup("eppn"));

        if (print_ppns.empty() and online_ppns.empty()) {
            --included_journal_count;
            LOG_WARNING("Zeder entry #" + std::to_string(journal.getId()) + " is missing print and online PPN's!");
            continue;
        }

        // Prefer online journals to print journals:
        // At the moment the logic is electronic over print
        // in discussion if this should be changed (if so, publication year range has to be considered)
        if (not online_ppns.empty()) {
            ProcessPPNs(online_ppns, &bundle_ppns);
            contains_online = true;
        } else {
            ProcessPPNs(print_ppns, &bundle_ppns);
            contains_print = true;
        }
    }

    if (bundle_ppns.empty())
        LOG_WARNING("No bundle generated for \"" + section.getSectionName() + "\" because there were no matching entries in Zeder!");
    else {
        (*output_file) << '[' << section.getSectionName() << "]\n";
        (*output_file) << "display_name = \"" << EscapeDoubleQuotes(section.getSectionName()) << "\"\n";
        const auto description(section.find("description"));
        if (description != section.end())
            (*output_file) << "description  = \"" << EscapeDoubleQuotes(description->value_) << "\"\n";
        (*output_file) << "instances    = \"" << bundle_instances << "\"\n";
        std::string media_type;
        if (contains_online)
            if (contains_print)
                media_type = "online_and_print";
            else
                media_type = "online";
        else
            media_type = "print";
        (*output_file) << "media_type   = \"" << media_type << "\"\n";
        (*output_file) << "ppns         = " << StringUtil::Join(bundle_ppns, ',') << '\n';
        (*output_file) << '\n';
    }

    LOG_INFO("included " + std::to_string(included_journal_count) + " journal(s) with " + std::to_string(bundle_ppns.size())
             + " PPN's in the bundle for \"" + section.getSectionName() + "\".");
}

} // unnamed namespace

int Main(int argc, char *argv[]) {
    if (argc != 3)
        Usage();

    const IniFile packet_definitions_ini_file(argv[1]);
    const auto zeder_instance(packet_definitions_ini_file.getString("", "zeder_instance"));
    if (zeder_instance != "ixtheo" and zeder_instance != "relbib")
        LOG_ERROR("zeder_instance in \"" + packet_definitions_ini_file.getFilename()
                  + "\" must be either \"ixtheo\" or \"relbib\"!");

    const Zeder::SimpleZeder zeder(zeder_instance == "ixtheo" ? Zeder::IXTHEO : Zeder::KRIMDOK);
    if (not zeder)
        LOG_ERROR("can't connect to the Zeder MySQL server!");
    if (unlikely(zeder.empty()))
        LOG_ERROR("found no Zeder entries matching any of our requested columns!"
                  " (This *should* not happen as we included the column ID!)");

    const auto bundle_instances(packet_definitions_ini_file.getString("", "bundle_instances"));

    const auto bundle_definitions_output_file(FileUtil::OpenOutputFileOrDie(argv[2]));
    for (const auto &section : packet_definitions_ini_file) {
        if (section.getSectionName().empty())
            continue; // Skip the global section.
        GenerateBundleDefinition(zeder, bundle_instances, section, bundle_definitions_output_file.get());
    }

    return EXIT_SUCCESS;
}
<commit_msg>generate_subscription_packets.cc: Change error message related to Zeder connection<commit_after>/** \file   generate_subscription_packets.cc
 *  \brief  Imports data from Zeder and writes a subscription packets defintion file.
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *  \copyright 2020-2021 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <map>
#include <unordered_map>
#include <set>
#include "Compiler.h"
#include "FileUtil.h"
#include "IniFile.h"
#include "StringUtil.h"
#include "util.h"
#include "Zeder.h"

namespace {

[[noreturn]] void Usage() {
    ::Usage("packet_definition_config_file packet_subscriptions_output\n"
            "\tFor the documentation of the input config file, please see data/generate_subscription_packets.README.");
}

// Return true if an entry of "class_list" equals one of the vertical-bar-separated values of "expected_values_str."
bool FoundExpectedClassValue(const std::string &expected_values_str, const std::string &class_list_str) {
    std::vector<std::string> expected_values;
    StringUtil::Split(expected_values_str, '|', &expected_values);

    std::vector<std::string> class_list;
    StringUtil::SplitThenTrimWhite(class_list_str, ',', &class_list);

    for (const auto &class_str : class_list) {
        if (std::find_if(expected_values.cbegin(), expected_values.cend(),
                         [&class_str](auto &expected_value) { return ::strcasecmp(class_str.c_str(), expected_value.c_str()) == 0; }) != expected_values.cend())
            return true;
    }
    return false;
}

bool IncludeJournal(const Zeder::Entry &journal, const IniFile::Section &filter_section) {
    for (const auto &entry : filter_section) {
        if (entry.name_.empty() or entry.name_ == "description")
            continue;

        const std::string &zeder_column_name(entry.name_);
        const auto column_value(StringUtil::TrimWhite(journal.lookup(zeder_column_name == "except_class" ? "class" : zeder_column_name)));
        if (column_value.empty())
        {
            LOG_INFO("\tcolumn " + zeder_column_name + " was empty!");
            return false;

        }

        const bool found_it(FoundExpectedClassValue(entry.value_, column_value));
        if (zeder_column_name == "except_class") {
            if (found_it)
                return false;
        } else if (not found_it)
            return false;
    }

    return true;
}

// Please note that Zeder PPN entries are separated by spaces and, unlike what the column names "print_ppn" and
// "online_ppn" imply may in rare cases contain space-separated lists of PPN's.
void ProcessPPNs(const std::string &ppns, std::set<std::string> * const bundle_ppns) {
    std::vector<std::string> individual_ppns;
    StringUtil::Split(ppns, ' ', &individual_ppns);
    bundle_ppns->insert(individual_ppns.cbegin(), individual_ppns.cend());
}

std::string EscapeDoubleQuotes(const std::string &s) {
    std::string escaped_s;
    escaped_s.reserve(s.size());

    for (const char ch : s) {
        if (ch == '"' or ch == '\\')
            escaped_s += '\\';
        escaped_s += ch;
    }

    return escaped_s;
}

void GenerateBundleDefinition(const Zeder::SimpleZeder &zeder, const std::string &bundle_instances,
                              const IniFile::Section &section, File * const output_file)
{
    unsigned included_journal_count(0);
    std::set<std::string> bundle_ppns; // We use a std::set because it is automatically being sorted for us.
    bool contains_print(false);
    bool contains_online(false);
    for (const auto &journal : zeder) {
        if (journal.empty() or not IncludeJournal(journal, section))
            continue;

        ++included_journal_count;
        const auto print_ppns(journal.lookup("pppn"));
        const auto online_ppns(journal.lookup("eppn"));

        if (print_ppns.empty() and online_ppns.empty()) {
            --included_journal_count;
            LOG_WARNING("Zeder entry #" + std::to_string(journal.getId()) + " is missing print and online PPN's!");
            continue;
        }

        // Prefer online journals to print journals:
        // At the moment the logic is electronic over print
        // in discussion if this should be changed (if so, publication year range has to be considered)
        if (not online_ppns.empty()) {
            ProcessPPNs(online_ppns, &bundle_ppns);
            contains_online = true;
        } else {
            ProcessPPNs(print_ppns, &bundle_ppns);
            contains_print = true;
        }
    }

    if (bundle_ppns.empty())
        LOG_WARNING("No bundle generated for \"" + section.getSectionName() + "\" because there were no matching entries in Zeder!");
    else {
        (*output_file) << '[' << section.getSectionName() << "]\n";
        (*output_file) << "display_name = \"" << EscapeDoubleQuotes(section.getSectionName()) << "\"\n";
        const auto description(section.find("description"));
        if (description != section.end())
            (*output_file) << "description  = \"" << EscapeDoubleQuotes(description->value_) << "\"\n";
        (*output_file) << "instances    = \"" << bundle_instances << "\"\n";
        std::string media_type;
        if (contains_online)
            if (contains_print)
                media_type = "online_and_print";
            else
                media_type = "online";
        else
            media_type = "print";
        (*output_file) << "media_type   = \"" << media_type << "\"\n";
        (*output_file) << "ppns         = " << StringUtil::Join(bundle_ppns, ',') << '\n';
        (*output_file) << '\n';
    }

    LOG_INFO("included " + std::to_string(included_journal_count) + " journal(s) with " + std::to_string(bundle_ppns.size())
             + " PPN's in the bundle for \"" + section.getSectionName() + "\".");
}

} // unnamed namespace

int Main(int argc, char *argv[]) {
    if (argc != 3)
        Usage();

    const IniFile packet_definitions_ini_file(argv[1]);
    const auto zeder_instance(packet_definitions_ini_file.getString("", "zeder_instance"));
    if (zeder_instance != "ixtheo" and zeder_instance != "relbib")
        LOG_ERROR("zeder_instance in \"" + packet_definitions_ini_file.getFilename()
                  + "\" must be either \"ixtheo\" or \"relbib\"!");

    const Zeder::SimpleZeder zeder(zeder_instance == "ixtheo" ? Zeder::IXTHEO : Zeder::KRIMDOK);
    if (not zeder)
        LOG_ERROR("can't connect to Zeder!");
    if (unlikely(zeder.empty()))
        LOG_ERROR("found no Zeder entries matching any of our requested columns!"
                  " (This *should* not happen as we included the column ID!)");

    const auto bundle_instances(packet_definitions_ini_file.getString("", "bundle_instances"));

    const auto bundle_definitions_output_file(FileUtil::OpenOutputFileOrDie(argv[2]));
    for (const auto &section : packet_definitions_ini_file) {
        if (section.getSectionName().empty())
            continue; // Skip the global section.
        GenerateBundleDefinition(zeder, bundle_instances, section, bundle_definitions_output_file.get());
    }

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "setupwizard_cli.h"

WARNINGS_DISABLE
#include <QFileDialog>
#include <QMessageBox>
#include <QObject>
#include <QStandardPaths>

#include "ui_setupwizard_cli.h"
WARNINGS_ENABLE

#include <TSettings.h>
#include <TWizardPage.h>

#include "tasks-defs.h"
#include "taskstatus.h"
#include "utils.h"

CliPage::CliPage(QWidget *parent)
    : TWizardPage(parent), _ui(new Ui::CliPage), _problemOccurred(false)
{
    _ui->setupUi(this);

    // We only want to expand the widget if there's a problem.
    _ui->cliAdvancedWidget->hide();
    _ui->cliAdvancedButton->setChecked(false);

    // Basic operation on this page.
    connect(_ui->cliAdvancedButton, &QPushButton::toggled,
            _ui->cliAdvancedWidget, &QWidget::setVisible);

    // A config field changed.
    connect(_ui->cliPathLineBrowse, &PathLineBrowse::textChanged, this,
            &CliPage::tarsnapPathChanged);
    connect(_ui->cachePathLineBrowse, &PathLineBrowse::textChanged, this,
            &CliPage::tarsnapCacheChanged);
    connect(_ui->appdataPathLineBrowse, &PathLineBrowse::textChanged, this,
            &CliPage::appDataDirChanged);
}

CliPage::~CliPage()
{
    delete _ui;
}

void CliPage::initializePage()
{
    TWizardPage::initializePage();

    // CLI path.
    QString tarsnapPath = Utils::findTarsnapClientInPath("", true);
    _ui->cliPathLineBrowse->setText(tarsnapPath);
    if(tarsnapPath.isEmpty())
    {
        // Trigger this manually, because the automatic connection
        // won't trigger it's blank.
        tarsnapPathChanged(tarsnapPath);
    }

    /// Cache dir.
    QString tarsnapCacheDir =
        QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
    if(ensureDirExists(tarsnapCacheDir))
        _ui->cachePathLineBrowse->setText(tarsnapCacheDir);

    // App Data dir.
    QString appDataDir = QStandardPaths::writableLocation(APPDATA);
    if(ensureDirExists(appDataDir))
        _ui->appdataPathLineBrowse->setText(appDataDir);
}

bool CliPage::checkComplete()
{
    // Check the remaining items.
    TSettings settings;

    // Do we have a valid version number?  (This is the last piece of config.)
    if(!settings.contains("tarsnap/version"))
        return setProceedButton(false);

    // Do we have everything else?  (Double-check; almost certainly not needed.)
    if((!settings.contains("tarsnap/path"))
       || (!settings.contains("tarsnap/cache"))
       || (!settings.contains("app/app_data")))
        return setProceedButton(false);

    _problemOccurred = false;
    _ui->cliValidationLabel->clear();
    return setProceedButton(true);
}

void CliPage::reportError(const QString &text)
{
    _ui->cliValidationLabel->messageError(text);
    _ui->cliAdvancedButton->setChecked(true);
    setProceedButton(false);
    _problemOccurred = true;
}

void CliPage::tarsnapCacheChanged(const QString &text)
{
    // Clear previous setting.
    TSettings settings;
    settings.remove("tarsnap/cache");

    if(text.isEmpty())
    {
        reportError(tr("Empty Tarsnap cache directory set."));
        return;
    }

    QString tarsnapCacheDir = Utils::validateTarsnapCache(text);
    if(tarsnapCacheDir.isEmpty())
    {
        reportError(tr("Invalid Tarsnap cache directory set."));
        return;
    }

    // We're ok
    settings.setValue("tarsnap/cache", tarsnapCacheDir);
    checkComplete();
}

void CliPage::appDataDirChanged(const QString &text)
{
    // Clear previous setting.
    TSettings settings;
    settings.remove("app/app_data");

    if(text.isEmpty())
    {
        reportError(tr("Empty App data directory set."));
        return;
    }

    QString appDataDir = Utils::validateAppDataDir(text);
    if(appDataDir.isEmpty())
    {
        reportError(tr("Invalid App data directory set."));
        return;
    }

    // We're ok
    settings.setValue("app/app_data", appDataDir);
    checkComplete();
}

void CliPage::tarsnapPathChanged(const QString &text)
{
    // Clear previous settings.
    TSettings settings;
    settings.remove("tarsnap/path");
    settings.remove("tarsnap/version");

    if(text.isEmpty())
    {
        reportError(tr("Empty Tarsnap directory set."));
        return;
    }

    QString tarsnapDir = Utils::findTarsnapClientInPath(text, true);
    if(tarsnapDir.isEmpty())
    {
        reportError(tr("Tarsnap utilities not found. Visit "
                       "tarsnap.com"
                       " for help with acquiring them."));
        return;
    }

    // We're ok
    settings.setValue("tarsnap/path", tarsnapDir);
    emit tarsnapVersionRequested();
    checkComplete();
}

void CliPage::tarsnapVersionResponse(TaskStatus status, QString versionString)
{
    TSettings settings;

    // Sanity check.
    if(versionString.isEmpty())
        status = TaskStatus::Failed;

    // Handle response.
    switch(status)
    {
    case TaskStatus::Completed:
        // Record value
        settings.setValue("tarsnap/version", versionString);
        // Auto-focus on "Next" if the user isn't manually changing things.
        if(checkComplete() && !_problemOccurred)
            _ui->nextButton->setFocus();
        // Display message (after checkComplete, which can clear the label).
        _ui->cliValidationLabel->messageNormal(
            tr("Tarsnap CLI version ") + versionString + tr(" detected.  ✔"));
        break;
    case TaskStatus::VersionTooLow:
        // Don't record the too-low version number.
        reportError(
            tr("Tarsnap CLI version ") + versionString
            + tr(" too low; must be at least %1").arg(TARSNAP_MIN_VERSION));
        break;
    case TaskStatus::Failed:
        reportError(tr("Error retrieving Tarsnap CLI verison"));
        break;
    default:
        break;
    }
}

bool CliPage::ensureDirExists(const QString &dirname)
{
    // Create directory (if needed).
    if(QDir().mkpath(dirname))
        return true;
    else
    {
        QMessageBox::critical(this, tr("Could not create directory"),
                              tr("Could not create directory") + ": "
                                  + dirname);
        return false;
    }
}
<commit_msg>SetupWizard CLI: better message for missing binaries<commit_after>#include "setupwizard_cli.h"

WARNINGS_DISABLE
#include <QFileDialog>
#include <QMessageBox>
#include <QObject>
#include <QStandardPaths>

#include "ui_setupwizard_cli.h"
WARNINGS_ENABLE

#include <TSettings.h>
#include <TWizardPage.h>

#include "tasks-defs.h"
#include "taskstatus.h"
#include "utils.h"

CliPage::CliPage(QWidget *parent)
    : TWizardPage(parent), _ui(new Ui::CliPage), _problemOccurred(false)
{
    _ui->setupUi(this);

    // We only want to expand the widget if there's a problem.
    _ui->cliAdvancedWidget->hide();
    _ui->cliAdvancedButton->setChecked(false);

    // Basic operation on this page.
    connect(_ui->cliAdvancedButton, &QPushButton::toggled,
            _ui->cliAdvancedWidget, &QWidget::setVisible);

    // A config field changed.
    connect(_ui->cliPathLineBrowse, &PathLineBrowse::textChanged, this,
            &CliPage::tarsnapPathChanged);
    connect(_ui->cachePathLineBrowse, &PathLineBrowse::textChanged, this,
            &CliPage::tarsnapCacheChanged);
    connect(_ui->appdataPathLineBrowse, &PathLineBrowse::textChanged, this,
            &CliPage::appDataDirChanged);
}

CliPage::~CliPage()
{
    delete _ui;
}

void CliPage::initializePage()
{
    TWizardPage::initializePage();

    // CLI path.
    QString tarsnapPath = Utils::findTarsnapClientInPath("", true);
    _ui->cliPathLineBrowse->setText(tarsnapPath);
    if(tarsnapPath.isEmpty())
    {
        // Trigger this manually, because the automatic connection
        // won't trigger it's blank.
        tarsnapPathChanged(tarsnapPath);
    }

    /// Cache dir.
    QString tarsnapCacheDir =
        QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
    if(ensureDirExists(tarsnapCacheDir))
        _ui->cachePathLineBrowse->setText(tarsnapCacheDir);

    // App Data dir.
    QString appDataDir = QStandardPaths::writableLocation(APPDATA);
    if(ensureDirExists(appDataDir))
        _ui->appdataPathLineBrowse->setText(appDataDir);
}

bool CliPage::checkComplete()
{
    // Check the remaining items.
    TSettings settings;

    // Do we have a valid version number?  (This is the last piece of config.)
    if(!settings.contains("tarsnap/version"))
        return setProceedButton(false);

    // Do we have everything else?  (Double-check; almost certainly not needed.)
    if((!settings.contains("tarsnap/path"))
       || (!settings.contains("tarsnap/cache"))
       || (!settings.contains("app/app_data")))
        return setProceedButton(false);

    _problemOccurred = false;
    _ui->cliValidationLabel->clear();
    return setProceedButton(true);
}

void CliPage::reportError(const QString &text)
{
    _ui->cliValidationLabel->messageError(text);
    _ui->cliAdvancedButton->setChecked(true);
    setProceedButton(false);
    _problemOccurred = true;
}

void CliPage::tarsnapCacheChanged(const QString &text)
{
    // Clear previous setting.
    TSettings settings;
    settings.remove("tarsnap/cache");

    if(text.isEmpty())
    {
        reportError(tr("Empty Tarsnap cache directory set."));
        return;
    }

    QString tarsnapCacheDir = Utils::validateTarsnapCache(text);
    if(tarsnapCacheDir.isEmpty())
    {
        reportError(tr("Invalid Tarsnap cache directory set."));
        return;
    }

    // We're ok
    settings.setValue("tarsnap/cache", tarsnapCacheDir);
    checkComplete();
}

void CliPage::appDataDirChanged(const QString &text)
{
    // Clear previous setting.
    TSettings settings;
    settings.remove("app/app_data");

    if(text.isEmpty())
    {
        reportError(tr("Empty App data directory set."));
        return;
    }

    QString appDataDir = Utils::validateAppDataDir(text);
    if(appDataDir.isEmpty())
    {
        reportError(tr("Invalid App data directory set."));
        return;
    }

    // We're ok
    settings.setValue("app/app_data", appDataDir);
    checkComplete();
}

void CliPage::tarsnapPathChanged(const QString &text)
{
    // Clear previous settings.
    TSettings settings;
    settings.remove("tarsnap/path");
    settings.remove("tarsnap/version");

    // Don't check for an empty dir here, because we want users to see the
    // "visit tarsnap.com" message if they don't have the binaries.

    QString tarsnapDir = Utils::findTarsnapClientInPath(text, true);
    if(tarsnapDir.isEmpty())
    {
        reportError(tr("Tarsnap utilities not found. Visit "
                       "tarsnap.com"
                       " for help with acquiring them."));
        return;
    }

    // We're ok
    settings.setValue("tarsnap/path", tarsnapDir);
    emit tarsnapVersionRequested();
    checkComplete();
}

void CliPage::tarsnapVersionResponse(TaskStatus status, QString versionString)
{
    TSettings settings;

    // Sanity check.
    if(versionString.isEmpty())
        status = TaskStatus::Failed;

    // Handle response.
    switch(status)
    {
    case TaskStatus::Completed:
        // Record value
        settings.setValue("tarsnap/version", versionString);
        // Auto-focus on "Next" if the user isn't manually changing things.
        if(checkComplete() && !_problemOccurred)
            _ui->nextButton->setFocus();
        // Display message (after checkComplete, which can clear the label).
        _ui->cliValidationLabel->messageNormal(
            tr("Tarsnap CLI version ") + versionString + tr(" detected.  ✔"));
        break;
    case TaskStatus::VersionTooLow:
        // Don't record the too-low version number.
        reportError(
            tr("Tarsnap CLI version ") + versionString
            + tr(" too low; must be at least %1").arg(TARSNAP_MIN_VERSION));
        break;
    case TaskStatus::Failed:
        reportError(tr("Error retrieving Tarsnap CLI verison"));
        break;
    default:
        break;
    }
}

bool CliPage::ensureDirExists(const QString &dirname)
{
    // Create directory (if needed).
    if(QDir().mkpath(dirname))
        return true;
    else
    {
        QMessageBox::critical(this, tr("Could not create directory"),
                              tr("Could not create directory") + ": "
                                  + dirname);
        return false;
    }
}
<|endoftext|>


<commit_before>// KMail startup and initialize code
// Author: Stefan Taferner <taferner@alpin.or.at>

#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

#ifdef HAVE_PATHS_H
#include <paths.h>
#endif

#include <kuniqueapp.h>
#include <klocale.h>
#include <kglobal.h>
#include <dcopclient.h>
#include <kcrash.h>

#include "kmkernel.h" //control center

#undef Status // stupid X headers
#include "kmailIface_stub.h" // to call control center of master kmail

#include <kaboutdata.h>
#include <kdebug.h>

#include "kmversion.h"

// OLD about text.  This is horrbly outdated.
/*const char* aboutText =
    "KMail [" KMAIL_VERSION "] by\n\n"
    "Stefan Taferner <taferner@kde.org>,\n"
    "Markus Wbben <markus.wuebben@kde.org>\n\n"
    "based on the work of:\n"
    "Lynx <lynx@topaz.hknet.com>,\n"
    "Stephan Meyer <Stephan.Meyer@pobox.com>,\n"
    "and the above authors.\n\n"
    "This program is covered by the GPL.\n\n"
    "Please send bugreports to taferner@kde.org";
*/
const char *aboutText =
  "KMail [" KMAIL_VERSION "] by\n\n"
  "Stefan Taferner <taferner@kde.org>,\n"
  "Don Sanders <don@sanders.org>,\n"
  "Waldo Bastian <bastian@kde.org>,\n"
  "Andreas Gungl <Andreas.Gungle@osp-dd.de>,\n"
  "Lars Knoll <knoll@mpi-hd.mpg.de>,\n"
  "J. Nick Koston <bdraco@darkorb.net>,\n"
  "Daniel Naber <dnaber@mini.gt.owl.de>,\n"
  "Sven Radej <radej@kde.org>,\n"
  "Espen Sand <espen@kde.org>,\n"
  "George Staikos <staikos@kde.org>,\n"
  "Mario Weilguni <mweilguni@sime.com>,\n"
  "Robert D. Williams <rwilliams@kde.org>\n\n"
  "based on the work of:\n"
  "Lynx <lynx@topaz.hknet.com>,\n"
  "Stephan Meyer <Stephan.Meyer@pobox.com>\n"
  "and the above authors.\n\n"
  "Please send bugreports to kmail@kde.org";

//static const char *description = I18N_NOOP("A KDE E-Mail client.");
static const char *description = aboutText;

static KCmdLineOptions kmoptions[] =
{
  { "s", 0 , 0 },
  { "subject <subject>",	I18N_NOOP("Set subject of msg."), 0 },
  { "c", 0 , 0 },
  { "cc <address>",		I18N_NOOP("Send CC: to 'address'."), 0 },
  { "b", 0 , 0 },
  { "bcc <address>",		I18N_NOOP("Send BCC: to 'addres'."), 0 },
  { "h", 0 , 0 },
  { "header <header>",		I18N_NOOP("Add 'header' to msg."), 0 },
  { "msg <file>",		I18N_NOOP("Read msg-body from 'file'."), 0 },
  { "check",			I18N_NOOP("Check for new mail only."), 0 },
  { "composer",			I18N_NOOP("Open only composer window."), 0 },
  { "+[address]",		I18N_NOOP("Send msg to 'address'."), 0 },
//  { "+[file]",                  I18N_NOOP("Show message from file 'file'."), 0 },
  { 0, 0, 0}
};

static void signalHandler(int sigId);
static void setSignalHandler(void (*handler)(int));

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

// Crash recovery signal handler
static void signalHandler(int sigId)
{
  setSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId);
  // try to cleanup all windows
  kernel->dumpDeadLetters();
  ::exit(-1); //
}

// Crash recovery signal handler
static void crashHandler(int sigId)
{
  setSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId);
  // try to cleanup all windows
  kernel->dumpDeadLetters();
  // Return to DrKonqi.
}
//-----------------------------------------------------------------------------

static void setSignalHandler(void (*handler)(int))
{
  signal(SIGKILL, handler);
  signal(SIGTERM, handler);
  signal(SIGHUP,  handler);
  KCrash::setEmergencySaveFunction(crashHandler);
}
//-----------------------------------------------------------------------------

class KMailApplication : public KUniqueApplication
{
public:
  KMailApplication() : KUniqueApplication() { };

  virtual int newInstance();
};

int KMailApplication::newInstance()
{
  QString to, cc, bcc, subj;
  KURL messageFile = QString::null;
  bool mailto = false;
  bool checkMail = false;
  //bool viewOnly = false;

  // process args:
  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
  if (args->getOption("subject"))
  {
     mailto = true;
     subj = args->getOption("subject");
  }

  if (args->getOption("cc"))
  {
     mailto = true;
     cc = args->getOption("cc");
  }

  if (args->getOption("bcc"))
  {
     mailto = true;
     bcc = args->getOption("bcc");
  }

  if (args->isSet("composer"))
    mailto = true;

  if (args->isSet("check"))
    checkMail = true;

  for(int i= 0; i < args->count(); i++)
  {
    if (!to.isEmpty())
      to += ", ";
     if (strncasecmp(args->arg(i),"mailto:",7)==0)
       to += args->arg(i);
     else
       to += args->arg(i);
     mailto = true;
  }

  args->clear();

  kernel->action (mailto, checkMail, to, cc, bcc, subj, messageFile);
  return 0;
}

int main(int argc, char *argv[])
{
  // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging
  // a bit harder: You should pass --nofork as commandline argument when using
  // a debugger. In gdb you can do this by typing "set args --nofork" before
  // typing "run".

  KAboutData about("kmail", I18N_NOOP("KMail"),
                   KMAIL_VERSION,
                   description,
		   KAboutData::License_GPL,
                   "(c) 1997-2000, The KMail developers" );

  KCmdLineArgs::init(argc, argv, &about);
  KCmdLineArgs::addCmdLineOptions( kmoptions ); // Add kmail options

  if (!KMailApplication::start())
     exit(0);

  KMailApplication app;

  //local, do the init
  KMKernel kmailKernel;
  kmailKernel.init();

  // and session management
  kmailKernel.doSessionManagement();

  // any dead letters?
  kmailKernel.recoverDeadLetters();

  setSignalHandler(signalHandler);

  // Go!
  kapp->exec();

  // clean up
  kmailKernel.cleanup();
}

<commit_msg>WABA: Fix BR6454, you need to update kdelibs/dcop for this!!<commit_after>// KMail startup and initialize code
// Author: Stefan Taferner <taferner@alpin.or.at>

#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

#ifdef HAVE_PATHS_H
#include <paths.h>
#endif

#include <kuniqueapp.h>
#include <klocale.h>
#include <kglobal.h>
#include <dcopclient.h>
#include <kcrash.h>

#include "kmkernel.h" //control center

#undef Status // stupid X headers
#include "kmailIface_stub.h" // to call control center of master kmail

#include <kaboutdata.h>
#include <kdebug.h>

#include "kmversion.h"

// OLD about text.  This is horrbly outdated.
/*const char* aboutText =
    "KMail [" KMAIL_VERSION "] by\n\n"
    "Stefan Taferner <taferner@kde.org>,\n"
    "Markus Wbben <markus.wuebben@kde.org>\n\n"
    "based on the work of:\n"
    "Lynx <lynx@topaz.hknet.com>,\n"
    "Stephan Meyer <Stephan.Meyer@pobox.com>,\n"
    "and the above authors.\n\n"
    "This program is covered by the GPL.\n\n"
    "Please send bugreports to taferner@kde.org";
*/
const char *aboutText =
  "KMail [" KMAIL_VERSION "] by\n\n"
  "Stefan Taferner <taferner@kde.org>,\n"
  "Don Sanders <don@sanders.org>,\n"
  "Waldo Bastian <bastian@kde.org>,\n"
  "Andreas Gungl <Andreas.Gungle@osp-dd.de>,\n"
  "Lars Knoll <knoll@mpi-hd.mpg.de>,\n"
  "J. Nick Koston <bdraco@darkorb.net>,\n"
  "Daniel Naber <dnaber@mini.gt.owl.de>,\n"
  "Sven Radej <radej@kde.org>,\n"
  "Espen Sand <espen@kde.org>,\n"
  "George Staikos <staikos@kde.org>,\n"
  "Mario Weilguni <mweilguni@sime.com>,\n"
  "Robert D. Williams <rwilliams@kde.org>\n\n"
  "based on the work of:\n"
  "Lynx <lynx@topaz.hknet.com>,\n"
  "Stephan Meyer <Stephan.Meyer@pobox.com>\n"
  "and the above authors.\n\n"
  "Please send bugreports to kmail@kde.org";

//static const char *description = I18N_NOOP("A KDE E-Mail client.");
static const char *description = aboutText;

static KCmdLineOptions kmoptions[] =
{
  { "s", 0 , 0 },
  { "subject <subject>",	I18N_NOOP("Set subject of msg."), 0 },
  { "c", 0 , 0 },
  { "cc <address>",		I18N_NOOP("Send CC: to 'address'."), 0 },
  { "b", 0 , 0 },
  { "bcc <address>",		I18N_NOOP("Send BCC: to 'addres'."), 0 },
  { "h", 0 , 0 },
  { "header <header>",		I18N_NOOP("Add 'header' to msg."), 0 },
  { "msg <file>",		I18N_NOOP("Read msg-body from 'file'."), 0 },
  { "check",			I18N_NOOP("Check for new mail only."), 0 },
  { "composer",			I18N_NOOP("Open only composer window."), 0 },
  { "+[address]",		I18N_NOOP("Send msg to 'address'."), 0 },
//  { "+[file]",                  I18N_NOOP("Show message from file 'file'."), 0 },
  { 0, 0, 0}
};

static void signalHandler(int sigId);
static void setSignalHandler(void (*handler)(int));

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

// Crash recovery signal handler
static void signalHandler(int sigId)
{
  setSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Exiting)\n", sigId);
  // try to cleanup all windows
  kernel->dumpDeadLetters();
  ::exit(-1); //
}

// Crash recovery signal handler
static void crashHandler(int sigId)
{
  setSignalHandler(SIG_DFL);
  fprintf(stderr, "*** KMail got signal %d (Crashing)\n", sigId);
  // try to cleanup all windows
  kernel->dumpDeadLetters();
  // Return to DrKonqi.
}
//-----------------------------------------------------------------------------

static void setSignalHandler(void (*handler)(int))
{
  signal(SIGKILL, handler);
  signal(SIGTERM, handler);
  signal(SIGHUP,  handler);
  KCrash::setEmergencySaveFunction(crashHandler);
}
//-----------------------------------------------------------------------------

class KMailApplication : public KUniqueApplication
{
public:
  KMailApplication() : KUniqueApplication() { };

  virtual int newInstance();
};

int KMailApplication::newInstance()
{
  QString to, cc, bcc, subj;
  KURL messageFile = QString::null;
  bool mailto = false;
  bool checkMail = false;
  //bool viewOnly = false;

  // process args:
  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
  if (args->getOption("subject"))
  {
     mailto = true;
     subj = args->getOption("subject");
  }

  if (args->getOption("cc"))
  {
     mailto = true;
     cc = args->getOption("cc");
  }

  if (args->getOption("bcc"))
  {
     mailto = true;
     bcc = args->getOption("bcc");
  }

  if (args->isSet("composer"))
    mailto = true;

  if (args->isSet("check"))
    checkMail = true;

  for(int i= 0; i < args->count(); i++)
  {
    if (!to.isEmpty())
      to += ", ";
     if (strncasecmp(args->arg(i),"mailto:",7)==0)
       to += args->arg(i);
     else
       to += args->arg(i);
     mailto = true;
  }

  args->clear();

  kernel->action (mailto, checkMail, to, cc, bcc, subj, messageFile);
  return 0;
}

int main(int argc, char *argv[])
{
  // WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging
  // a bit harder: You should pass --nofork as commandline argument when using
  // a debugger. In gdb you can do this by typing "set args --nofork" before
  // typing "run".

  KAboutData about("kmail", I18N_NOOP("KMail"),
                   KMAIL_VERSION,
                   description,
		   KAboutData::License_GPL,
                   "(c) 1997-2000, The KMail developers" );

  KCmdLineArgs::init(argc, argv, &about);
  KCmdLineArgs::addCmdLineOptions( kmoptions ); // Add kmail options

  if (!KMailApplication::start())
     exit(0);

  KMailApplication app;
  kapp->dcopClient()->suspend(); // Don't handle DCOP requests yet

  //local, do the init
  KMKernel kmailKernel;
  kmailKernel.init();

  // and session management
  kmailKernel.doSessionManagement();

  // any dead letters?
  kmailKernel.recoverDeadLetters();

  setSignalHandler(signalHandler);

  kapp->dcopClient()->resume(); // Ok. We are ready for DCOP requests.
  // Go!
  kapp->exec();

  // clean up
  kmailKernel.cleanup();
}

<|endoftext|>


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

#include "chrome/browser/extensions/extension_view.h"

#include "chrome/browser/extensions/extension.h"
#include "chrome/browser/extensions/extension_message_service.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/common/resource_bundle.h"

#include "grit/browser_resources.h"
#include "grit/generated_resources.h"

ExtensionView::ExtensionView(
    Extension* extension, const GURL& url, Profile* profile) :
    HWNDHtmlView(url, this, false), extension_(extension), profile_(profile) {
  // TODO(mpcomplete): query this from the renderer somehow?
  set_preferred_size(gfx::Size(100, 100));
}

void ExtensionView::CreatingRenderer() {
  render_view_host()->AllowExtensionBindings();
}

void ExtensionView::RenderViewCreated(RenderViewHost* render_view_host) {
  ExtensionMessageService::GetInstance()->RegisterExtensionView(this);
}

WebPreferences ExtensionView::GetWebkitPrefs() {
  // TODO(mpcomplete): return some reasonable prefs.
  return WebPreferences();
}

void ExtensionView::RunJavaScriptMessage(
    const std::wstring& message,
    const std::wstring& default_prompt,
    const GURL& frame_url,
    const int flags,
    IPC::Message* reply_msg,
    bool* did_suppress_message) {
  // Automatically cancel the javascript alert (otherwise the renderer hangs
  // indefinitely).
  *did_suppress_message = true;
  render_view_host()->JavaScriptMessageBoxClosed(reply_msg, true, L"");
}

void ExtensionView::DidStartLoading(RenderViewHost* render_view_host,
                                    int32 page_id) {
  static const StringPiece toolstrip_css(
      ResourceBundle::GetSharedInstance().GetRawDataResource(
          IDR_EXTENSIONS_TOOLSTRIP_CSS));
  render_view_host->InsertCSSInWebFrame(L"", toolstrip_css.as_string());
}
<commit_msg>OCD fixing of style for the initializer list of ExtensionView. Review URL: http://codereview.chromium.org/56113<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/extension_view.h"

#include "chrome/browser/extensions/extension.h"
#include "chrome/browser/extensions/extension_message_service.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/common/resource_bundle.h"

#include "grit/browser_resources.h"
#include "grit/generated_resources.h"

ExtensionView::ExtensionView(Extension* extension,
                             const GURL& url,
                             Profile* profile)
    : HWNDHtmlView(url, this, false),
      extension_(extension),
      profile_(profile) {
  // TODO(mpcomplete): query this from the renderer somehow?
  set_preferred_size(gfx::Size(100, 100));
}

void ExtensionView::CreatingRenderer() {
  render_view_host()->AllowExtensionBindings();
}

void ExtensionView::RenderViewCreated(RenderViewHost* render_view_host) {
  ExtensionMessageService::GetInstance()->RegisterExtensionView(this);
}

WebPreferences ExtensionView::GetWebkitPrefs() {
  // TODO(mpcomplete): return some reasonable prefs.
  return WebPreferences();
}

void ExtensionView::RunJavaScriptMessage(
    const std::wstring& message,
    const std::wstring& default_prompt,
    const GURL& frame_url,
    const int flags,
    IPC::Message* reply_msg,
    bool* did_suppress_message) {
  // Automatically cancel the javascript alert (otherwise the renderer hangs
  // indefinitely).
  *did_suppress_message = true;
  render_view_host()->JavaScriptMessageBoxClosed(reply_msg, true, L"");
}

void ExtensionView::DidStartLoading(RenderViewHost* render_view_host,
                                    int32 page_id) {
  static const StringPiece toolstrip_css(
      ResourceBundle::GetSharedInstance().GetRawDataResource(
          IDR_EXTENSIONS_TOOLSTRIP_CSS));
  render_view_host->InsertCSSInWebFrame(L"", toolstrip_css.as_string());
}
<|endoftext|>


<commit_before>#include <cstring>
#include <fstream>
#include <ostream>
#include <string>
#include <sys/time.h>
#include <vector>

template <typename T>
void print_graph(const char *filename, const Graph<T>& graph) {
    if (filename == NULL || strlen(filename) == 0) {
        return;
    }

    std::ostream *stream;
    std::ofstream *file_stream;

    std::string mpi_filename = std::string("mpi-output-") + std::to_string(GraphPad::global_myrank);
    file_stream = new std::ofstream(mpi_filename.c_str());
    stream = file_stream;

    for (size_t i = 0; i < graph.nvertices; i++) {
        if (graph.vertexproperty.node_owner(i+1)) {
            (*stream) << i + 1 << " " << graph.getVertexproperty(i+1) << std::endl;
        }
    }

    if (file_stream != NULL) {
        if (!file_stream->good()) {
            std::cerr << "failed to write output to file" << endl;
        }

        file_stream->flush();
        file_stream->close();
        delete file_stream;
    }

    MPI_Barrier(MPI_COMM_WORLD);
    if (GraphPad::global_myrank == 0) {
        std::ostream *stream_all;
        std::ofstream *file_stream_all;
        std::ifstream *mpi_stream;
        int mpi_comm_size;
        MPI_Comm_size(MPI_COMM_WORLD, &mpi_comm_size);
        if (strcmp(filename, "-") != 0) {
            file_stream_all = new std::ofstream(filename);
            stream_all = file_stream_all;
        } else {
            file_stream_all = NULL;
            stream_all = &std::cout;
        }
        for (int i = 0; i < mpi_comm_size; i++) {
            char buffer[1024];
            mpi_filename = std::string("mpi-output-") + std::to_string(i);
            mpi_stream = new std::ifstream(mpi_filename.c_str());
            while (!(*mpi_stream).eof()) {
                (*mpi_stream).getline(buffer, 1024);
                (*stream_all) << buffer << std::endl;
            }
            mpi_stream->close();
            delete mpi_stream;
            std::remove(mpi_filename.c_str());
        }
        if (file_stream_all != NULL) {
            if (!file_stream_all->good()) {
                std::cerr << "failed to write output to file" << endl;
            }
            file_stream_all->flush();
            file_stream_all->close();
            delete file_stream_all;
        }
    }
}

bool get_bit(size_t idx, char* vec) {
    size_t offset = idx >> 3;
    size_t bit = idx & 0x7;
    char mask = 1 << bit;
    return (vec[offset] & mask) != 0;
}

bool set_bit(size_t idx, char* vec) {
    size_t offset = idx >> 3;
    size_t bit = idx & 0x7;
    char mask = 1 << bit;
    char val = vec[offset];

    if (!(val & mask)) {
        vec[offset] = val | mask;
        return true;
    }

    return false;
}

double timer() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec + tv.tv_usec / 1000000.0;
}

static std::vector<std::pair<std::string, double>> timers;

void timer_start() {
    timers.clear();
}

void timer_next(std::string name) {
    timers.push_back(std::make_pair(name, timer()));
}

void timer_end() {
    timer_next("end");

    std::cerr << "Timing results:" << std::endl;

    for (size_t i = 0; i < timers.size() - 1; i++) {
        std::string &name = timers[i].first;
        double time = timers[i + 1].second - timers[i].second;

        std::cerr << " - "  << name << ": " << time << " sec" <<  std::endl;
    }

    timers.clear();
}
<commit_msg>Fix emply line in output<commit_after>#include <cstring>
#include <fstream>
#include <ostream>
#include <string>
#include <sys/time.h>
#include <vector>

template <typename T>
void print_graph(const char *filename, const Graph<T>& graph) {
    if (filename == NULL || strlen(filename) == 0) {
        return;
    }

    std::ostream *stream;
    std::ofstream *file_stream;

    std::string mpi_filename = std::string("mpi-output-") + std::to_string(GraphPad::global_myrank);
    file_stream = new std::ofstream(mpi_filename.c_str());
    stream = file_stream;

    for (size_t i = 0; i < graph.nvertices; i++) {
        if (graph.vertexproperty.node_owner(i+1)) {
            (*stream) << i + 1 << " " << graph.getVertexproperty(i+1) << std::endl;
        }
    }

    if (file_stream != NULL) {
        if (!file_stream->good()) {
            std::cerr << "failed to write output to file" << endl;
        }

        file_stream->flush();
        file_stream->close();
        delete file_stream;
    }

    MPI_Barrier(MPI_COMM_WORLD);
    if (GraphPad::global_myrank == 0) {
        std::ostream *stream_all;
        std::ofstream *file_stream_all;
        std::ifstream *mpi_stream;
        int mpi_comm_size;
        MPI_Comm_size(MPI_COMM_WORLD, &mpi_comm_size);
        if (strcmp(filename, "-") != 0) {
            file_stream_all = new std::ofstream(filename);
            stream_all = file_stream_all;
        } else {
            file_stream_all = NULL;
            stream_all = &std::cout;
        }
        for (int i = 0; i < mpi_comm_size; i++) {
            char buffer[1024];
            mpi_filename = std::string("mpi-output-") + std::to_string(i);
            mpi_stream = new std::ifstream(mpi_filename.c_str());
            (*mpi_stream).getline(buffer, 1024);
            while (!(*mpi_stream).eof()) {
                (*stream_all) << buffer << std::endl;
                (*mpi_stream).getline(buffer, 1024);
            }
            mpi_stream->close();
            delete mpi_stream;
            std::remove(mpi_filename.c_str());
        }
        if (file_stream_all != NULL) {
            if (!file_stream_all->good()) {
                std::cerr << "failed to write output to file" << endl;
            }
            file_stream_all->flush();
            file_stream_all->close();
            delete file_stream_all;
        }
    }
}

bool get_bit(size_t idx, char* vec) {
    size_t offset = idx >> 3;
    size_t bit = idx & 0x7;
    char mask = 1 << bit;
    return (vec[offset] & mask) != 0;
}

bool set_bit(size_t idx, char* vec) {
    size_t offset = idx >> 3;
    size_t bit = idx & 0x7;
    char mask = 1 << bit;
    char val = vec[offset];

    if (!(val & mask)) {
        vec[offset] = val | mask;
        return true;
    }

    return false;
}

double timer() {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec + tv.tv_usec / 1000000.0;
}

static std::vector<std::pair<std::string, double>> timers;

void timer_start() {
    timers.clear();
}

void timer_next(std::string name) {
    timers.push_back(std::make_pair(name, timer()));
}

void timer_end() {
    timer_next("end");

    std::cerr << "Timing results:" << std::endl;

    for (size_t i = 0; i < timers.size() - 1; i++) {
        std::string &name = timers[i].first;
        double time = timers[i + 1].second - timers[i].second;

        std::cerr << " - "  << name << ": " << time << " sec" <<  std::endl;
    }

    timers.clear();
}
<|endoftext|>