<commit_before>
#include "ufs_file.h"

#ifndef BOOST_MSVC
 #include <unistd.h>
 #include <fcntl.h>
#endif

__STXXL_BEGIN_NAMESPACE

int ufs_file_base::get_file_des() const
{
    return file_des;
}

void ufs_file_base::lock()
{
#ifdef BOOST_MSVC
    // not yet implemented
#else
    flock lock_struct;
    lock_struct.l_type = F_RDLCK | F_WRLCK;
    lock_struct.l_whence = SEEK_SET;
    lock_struct.l_start = 0;
    lock_struct.l_len = 0; // lock all bytes
    stxxl_ifcheck_i ((::fcntl (file_des, F_SETLK, &lock_struct)),
                     "Filedescriptor=" << file_des, io_error)
#endif
}

ufs_request_base::ufs_request_base (
    ufs_file_base * f,
    void * buf,
    stxxl::int64 off,
    size_t b,
    request_type t,
    completion_handler on_cmpl) :
    request (on_cmpl, f, buf, off, b, t),
    /*		file (f),
                    buffer (buf),
                    offset (off),
                    bytes (b),
                    type(t), */
    _state (OP)
{
#ifdef STXXL_CHECK_BLOCK_ALIGNING
    // Direct I/O requires filsystem block size alighnment for file offsets,
    // memory buffer adresses, and transfer(buffer) size must be multiple
    // of the filesystem block size
    check_aligning ();
#endif
}

bool ufs_request_base::add_waiter (onoff_switch * sw)
{
#ifdef STXXL_BOOST_THREADS
    boost::mutex::scoped_lock Lock(waiters_mutex);
#else
    waiters_mutex.lock ();
#endif

    if (poll ())                     // request already finished
    {
#ifndef STXXL_BOOST_THREADS
        waiters_mutex.unlock ();
#endif
        return true;
    }

    waiters.insert (sw);
#ifndef STXXL_BOOST_THREADS
    waiters_mutex.unlock ();
#endif

    return false;
}

void ufs_request_base::delete_waiter (onoff_switch * sw)
{
#ifdef STXXL_BOOST_THREADS
    boost::mutex::scoped_lock Lock(waiters_mutex);
    waiters.erase (sw);
#else
    waiters_mutex.lock ();
    waiters.erase (sw);
    waiters_mutex.unlock ();
#endif
}
int ufs_request_base::nwaiters ()                 // returns number of waiters
{
#ifdef STXXL_BOOST_THREADS
    boost::mutex::scoped_lock Lock(waiters_mutex);
    return waiters.size();
#else
    waiters_mutex.lock ();
    int size = waiters.size ();
    waiters_mutex.unlock ();
    return size;
#endif
}

void ufs_request_base::check_aligning ()
{
    if (offset % BLOCK_ALIGN)
        STXXL_ERRMSG ("Offset is not aligned: modulo "
                                              << BLOCK_ALIGN << " = " <<
                      offset % BLOCK_ALIGN);

    if (bytes % BLOCK_ALIGN)
        STXXL_ERRMSG ("Size is multiple of " <<
                      BLOCK_ALIGN << ", = " << bytes % BLOCK_ALIGN);

    if (long (buffer) % BLOCK_ALIGN)
        STXXL_ERRMSG ("Buffer is not aligned: modulo "
                                              << BLOCK_ALIGN << " = " <<
                      long (buffer) % BLOCK_ALIGN << " (" <<
                      std::hex << buffer << std::dec << ")");

}

ufs_request_base::~ufs_request_base ()
{
    STXXL_VERBOSE3("ufs_request_base " << unsigned (this) << ": deletion, cnt: " << ref_cnt)

    assert(_state() == DONE || _state() == READY2DIE);

    // if(_state() != DONE && _state()!= READY2DIE )
    //	STXXL_ERRMSG("WARNING: serious stxxl error requiest being deleted while I/O did not finish "<<
    //		"! Please report it to the stxxl author(s) <dementiev@mpi-sb.mpg.de>")

    // _state.wait_for (READY2DIE); // does not make sense ?
}

void ufs_request_base::wait ()
{
    STXXL_VERBOSE3("ufs_request_base : " << unsigned (this) << " wait ")

    START_COUNT_WAIT_TIME

#ifdef NO_OVERLAPPING
    enqueue();
#endif

    _state.wait_for (READY2DIE);

    END_COUNT_WAIT_TIME

    check_errors();
}
bool ufs_request_base::poll()
{
#ifdef NO_OVERLAPPING
    /*if(_state () < DONE)*/ wait();
#endif

    bool s = _state() >= DONE;

    check_errors();

    return s;
};
const char * ufs_request_base::io_type ()
{
    return "ufs_base";
}

ufs_file_base::ufs_file_base (
    const std::string & filename,
    int mode,
    int disk) : file (disk), file_des (-1), mode_(mode)
{
    int fmode = 0;
#ifndef STXXL_DIRECT_IO_OFF
 #ifndef BOOST_MSVC
    if (mode & DIRECT)
        fmode |= O_SYNC | O_RSYNC | O_DSYNC | O_DIRECT;

 #endif
#endif
    if (mode & RDONLY)
        fmode |= O_RDONLY;

    if (mode & WRONLY)
        fmode |= O_WRONLY;

    if (mode & RDWR)
        fmode |= O_RDWR;

    if (mode & CREAT)
        fmode |= O_CREAT;

    if (mode & TRUNC)
        fmode |= O_TRUNC;

#ifdef BOOST_MSVC
    fmode |= O_BINARY;                     // the default in MS is TEXT mode
#endif

#ifdef BOOST_MSVC
    stxxl_ifcheck_i ((file_des = ::open (filename.c_str(), fmode,
                                         S_IREAD | S_IWRITE )),
                     "Filedescriptor=" << file_des << " filename=" << filename << " fmode=" << fmode, io_error);
#else
    stxxl_ifcheck_i ((file_des = ::open (filename.c_str(), fmode,
                                         S_IREAD | S_IWRITE | S_IRGRP | S_IWGRP)),
                     "Filedescriptor=" << file_des << " filename=" << filename << " fmode=" << fmode, io_error)
#endif
}
ufs_file_base::~ufs_file_base ()
{
    int res = ::close (file_des);

    // if successful, reset file descriptor
    if (res >= 0)
        file_des = -1;

    else
        stxxl_function_error(io_error);

}
stxxl::int64 ufs_file_base::size ()
{
    struct stat st;
    stxxl_ifcheck (fstat (file_des, &st), io_error);
    return st.st_size;
}
void ufs_file_base::set_size (stxxl::int64 newsize)
{
    stxxl::int64 cur_size = size();

#ifdef BOOST_MSVC
    // FIXME: ADD TRUNCATION HERE, CURRENTLY NO SUITABLE FUNCTION FOUND
#else
    if (!(mode_ & RDONLY)) stxxl_ifcheck(::ftruncate(file_des, newsize), io_error);

#endif

    if (newsize > cur_size)
    {
        stxxl_ifcheck (::lseek (file_des, newsize - 1, SEEK_SET), io_error);
    }
}

__STXXL_END_NAMESPACE

<commit_msg>small fix for a mac system<commit_after>
#include "ufs_file.h"

#ifndef BOOST_MSVC
 #include <unistd.h>
 #include <fcntl.h>
#endif

__STXXL_BEGIN_NAMESPACE

int ufs_file_base::get_file_des() const
{
    return file_des;
}

void ufs_file_base::lock()
{
#ifdef BOOST_MSVC
    // not yet implemented
#else
    struct flock lock_struct;
    lock_struct.l_type = F_RDLCK | F_WRLCK;
    lock_struct.l_whence = SEEK_SET;
    lock_struct.l_start = 0;
    lock_struct.l_len = 0; // lock all bytes
    stxxl_ifcheck_i ((::fcntl (file_des, F_SETLK, &lock_struct)),
                     "Filedescriptor=" << file_des, io_error)
#endif
}

ufs_request_base::ufs_request_base (
    ufs_file_base * f,
    void * buf,
    stxxl::int64 off,
    size_t b,
    request_type t,
    completion_handler on_cmpl) :
    request (on_cmpl, f, buf, off, b, t),
    /*		file (f),
                    buffer (buf),
                    offset (off),
                    bytes (b),
                    type(t), */
    _state (OP)
{
#ifdef STXXL_CHECK_BLOCK_ALIGNING
    // Direct I/O requires filsystem block size alighnment for file offsets,
    // memory buffer adresses, and transfer(buffer) size must be multiple
    // of the filesystem block size
    check_aligning ();
#endif
}

bool ufs_request_base::add_waiter (onoff_switch * sw)
{
#ifdef STXXL_BOOST_THREADS
    boost::mutex::scoped_lock Lock(waiters_mutex);
#else
    waiters_mutex.lock ();
#endif

    if (poll ())                     // request already finished
    {
#ifndef STXXL_BOOST_THREADS
        waiters_mutex.unlock ();
#endif
        return true;
    }

    waiters.insert (sw);
#ifndef STXXL_BOOST_THREADS
    waiters_mutex.unlock ();
#endif

    return false;
}

void ufs_request_base::delete_waiter (onoff_switch * sw)
{
#ifdef STXXL_BOOST_THREADS
    boost::mutex::scoped_lock Lock(waiters_mutex);
    waiters.erase (sw);
#else
    waiters_mutex.lock ();
    waiters.erase (sw);
    waiters_mutex.unlock ();
#endif
}
int ufs_request_base::nwaiters ()                 // returns number of waiters
{
#ifdef STXXL_BOOST_THREADS
    boost::mutex::scoped_lock Lock(waiters_mutex);
    return waiters.size();
#else
    waiters_mutex.lock ();
    int size = waiters.size ();
    waiters_mutex.unlock ();
    return size;
#endif
}

void ufs_request_base::check_aligning ()
{
    if (offset % BLOCK_ALIGN)
        STXXL_ERRMSG ("Offset is not aligned: modulo "
                                              << BLOCK_ALIGN << " = " <<
                      offset % BLOCK_ALIGN);

    if (bytes % BLOCK_ALIGN)
        STXXL_ERRMSG ("Size is multiple of " <<
                      BLOCK_ALIGN << ", = " << bytes % BLOCK_ALIGN);

    if (long (buffer) % BLOCK_ALIGN)
        STXXL_ERRMSG ("Buffer is not aligned: modulo "
                                              << BLOCK_ALIGN << " = " <<
                      long (buffer) % BLOCK_ALIGN << " (" <<
                      std::hex << buffer << std::dec << ")");

}

ufs_request_base::~ufs_request_base ()
{
    STXXL_VERBOSE3("ufs_request_base " << unsigned (this) << ": deletion, cnt: " << ref_cnt)

    assert(_state() == DONE || _state() == READY2DIE);

    // if(_state() != DONE && _state()!= READY2DIE )
    //	STXXL_ERRMSG("WARNING: serious stxxl error requiest being deleted while I/O did not finish "<<
    //		"! Please report it to the stxxl author(s) <dementiev@mpi-sb.mpg.de>")

    // _state.wait_for (READY2DIE); // does not make sense ?
}

void ufs_request_base::wait ()
{
    STXXL_VERBOSE3("ufs_request_base : " << unsigned (this) << " wait ")

    START_COUNT_WAIT_TIME

#ifdef NO_OVERLAPPING
    enqueue();
#endif

    _state.wait_for (READY2DIE);

    END_COUNT_WAIT_TIME

    check_errors();
}
bool ufs_request_base::poll()
{
#ifdef NO_OVERLAPPING
    /*if(_state () < DONE)*/ wait();
#endif

    bool s = _state() >= DONE;

    check_errors();

    return s;
};
const char * ufs_request_base::io_type ()
{
    return "ufs_base";
}

ufs_file_base::ufs_file_base (
    const std::string & filename,
    int mode,
    int disk) : file (disk), file_des (-1), mode_(mode)
{
    int fmode = 0;
#ifndef STXXL_DIRECT_IO_OFF
 #ifndef BOOST_MSVC
    if (mode & DIRECT)
        fmode |= O_SYNC | O_RSYNC | O_DSYNC | O_DIRECT;

 #endif
#endif
    if (mode & RDONLY)
        fmode |= O_RDONLY;

    if (mode & WRONLY)
        fmode |= O_WRONLY;

    if (mode & RDWR)
        fmode |= O_RDWR;

    if (mode & CREAT)
        fmode |= O_CREAT;

    if (mode & TRUNC)
        fmode |= O_TRUNC;

#ifdef BOOST_MSVC
    fmode |= O_BINARY;                     // the default in MS is TEXT mode
#endif

#ifdef BOOST_MSVC
    stxxl_ifcheck_i ((file_des = ::open (filename.c_str(), fmode,
                                         S_IREAD | S_IWRITE )),
                     "Filedescriptor=" << file_des << " filename=" << filename << " fmode=" << fmode, io_error);
#else
    stxxl_ifcheck_i ((file_des = ::open (filename.c_str(), fmode,
                                         S_IREAD | S_IWRITE | S_IRGRP | S_IWGRP)),
                     "Filedescriptor=" << file_des << " filename=" << filename << " fmode=" << fmode, io_error)
#endif
}
ufs_file_base::~ufs_file_base ()
{
    int res = ::close (file_des);

    // if successful, reset file descriptor
    if (res >= 0)
        file_des = -1;

    else
        stxxl_function_error(io_error);

}
stxxl::int64 ufs_file_base::size ()
{
    struct stat st;
    stxxl_ifcheck (fstat (file_des, &st), io_error);
    return st.st_size;
}
void ufs_file_base::set_size (stxxl::int64 newsize)
{
    stxxl::int64 cur_size = size();

#ifdef BOOST_MSVC
    // FIXME: ADD TRUNCATION HERE, CURRENTLY NO SUITABLE FUNCTION FOUND
#else
    if (!(mode_ & RDONLY)) stxxl_ifcheck(::ftruncate(file_des, newsize), io_error);

#endif

    if (newsize > cur_size)
    {
        stxxl_ifcheck (::lseek (file_des, newsize - 1, SEEK_SET), io_error);
    }
}

__STXXL_END_NAMESPACE

<|endoftext|>


<commit_before>//===-- CFGPrinter.cpp - CFG printer pass ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines external functions that can be called to explicitly
// instantiate the CFG printer.
//
//===----------------------------------------------------------------------===//

#include "swift/SILPasses/Passes.h"
#include "swift/SILPasses/Transforms.h"
#include "swift/SIL/CFG.h"
#include "swift/SIL/SILBasicBlock.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILFunction.h"
#include "llvm/Support/GraphWriter.h"

using namespace swift;

template<typename InstTy, typename CaseValueTy>
inline CaseValueTy getCaseValueForBB(const InstTy *Inst,
                                     const SILBasicBlock *BB) {
  for (unsigned i = 0, e = Inst->getNumCases(); i != e; ++i) {
    auto P = Inst->getCase(i);
    if (P.second != BB)
      continue;
    return P.first;
  }
  llvm_unreachable("Error! should never pass in BB that is not a successor");
}

namespace llvm {
template<>
struct DOTGraphTraits<SILFunction *> : public DefaultDOTGraphTraits {

  DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}

  static std::string getGraphName(const SILFunction *F) {
    return "CFG for '" + F->getName().str() + "' function";
  }

  static std::string getSimpleNodeLabel(const SILBasicBlock *Node,
                                        const SILFunction *F) {
    std::string OutStr;
    raw_string_ostream OSS(OutStr);
    const_cast<SILBasicBlock *>(Node)->printAsOperand(OSS, false);
    return OSS.str();
  }

  static std::string getCompleteNodeLabel(const SILBasicBlock *Node,
                                          const SILFunction *F) {
    enum { MaxColumns = 80 };
    std::string Str;
    raw_string_ostream OS(Str);

    OS << *Node;
    std::string OutStr = OS.str();
    if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());

    // Process string output to make it nicer...
    unsigned ColNum = 0;
    unsigned LastSpace = 0;
    for (unsigned i = 0; i != OutStr.length(); ++i) {
      if (OutStr[i] == '\n') {                            // Left justify
        OutStr[i] = '\\';
        OutStr.insert(OutStr.begin()+i+1, 'l');
        ColNum = 0;
        LastSpace = 0;
      } else if (OutStr[i] == ';') {                      // Delete comments!
        unsigned Idx = OutStr.find('\n', i+1);            // Find end of line
        OutStr.erase(OutStr.begin()+i, OutStr.begin()+Idx);
        --i;
      } else if (ColNum == MaxColumns) {                  // Wrap lines.
        if (LastSpace) {
          OutStr.insert(LastSpace, "\\l...");
          ColNum = i - LastSpace;
          LastSpace = 0;
          i += 3; // The loop will advance 'i' again.
        }
        // Else keep trying to find a space.
      }
      else
        ++ColNum;
      if (OutStr[i] == ' ')
        LastSpace = i;
    }
    return OutStr;
  }

  std::string getNodeLabel(const SILBasicBlock *Node,
                           const SILFunction *Graph) {
    if (isSimple())
      return getSimpleNodeLabel(Node, Graph);
    else
      return getCompleteNodeLabel(Node, Graph);
  }

  static std::string getEdgeSourceLabel(const SILBasicBlock *Node,
                                        SILBasicBlock::const_succ_iterator I) {
    SILBasicBlock *Succ = I->getBB();
    const TermInst *Term = Node->getTerminator();

    // Label source of conditional branches with "T" or "F"
    if (auto *CBI = dyn_cast<CondBranchInst>(Term))
        return (Succ == CBI->getTrueBB()) ? "T" : "F";

    // Label source of switch edges with the associated value.
    if (auto *SI = dyn_cast<SwitchIntInst>(Term)) {
      if (SI->hasDefault() && SI->getDefaultBB() == Succ)
        return "def";

      std::string Str;
      raw_string_ostream OS(Str);

      APInt I = getCaseValueForBB<SwitchIntInst, APInt>(SI, Succ);
      OS << I;
      return OS.str();
    }

    if (auto *SEIB = dyn_cast<SwitchEnumInst>(Term)) {
      std::string Str;
      raw_string_ostream OS(Str);

      EnumElementDecl *E =
        getCaseValueForBB<SwitchEnumInst, EnumElementDecl *>(SEIB, Succ);
      OS << E->getFullName();
      return OS.str();
    }

    if (auto *SEIB = dyn_cast<SwitchEnumAddrInst>(Term)) {
      std::string Str;
      raw_string_ostream OS(Str);

      EnumElementDecl *E =
        getCaseValueForBB<SwitchEnumAddrInst, EnumElementDecl *>(SEIB, Succ);
      OS << E->getFullName();
      return OS.str();
    }

    if (auto *DMBI = dyn_cast<DynamicMethodBranchInst>(Term))
        return (Succ == DMBI->getHasMethodBB()) ? "T" : "F";

    if (auto *CCBI = dyn_cast<CheckedCastBranchInst>(Term))
        return (Succ == CCBI->getSuccessBB()) ? "T" : "F";

    if (auto *CCBI = dyn_cast<CheckedCastAddrBranchInst>(Term))
        return (Succ == CCBI->getSuccessBB()) ? "T" : "F";

    return "";
  }
};
} // end llvm namespace

//===----------------------------------------------------------------------===//
//                              Top Level Driver
//===----------------------------------------------------------------------===//

namespace {
class SILCFGPrinter : public SILFunctionTransform {
  StringRef getName() override { return "SIL CFG Printer"; }

  /// The entry point to the transformation.
  void run() override {
    SILFunction *F = getFunction();
    ViewGraph(F, "cfg" + F->getName().str());
  }
};
} // end anonymous namespace

SILTransform *swift::createSILCFGPrinter() {
  return new SILCFGPrinter();
}
<commit_msg>[cfg-printer] Add an option to only dump the CFG of a specific function.<commit_after>//===-- CFGPrinter.cpp - CFG printer pass ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines external functions that can be called to explicitly
// instantiate the CFG printer.
//
//===----------------------------------------------------------------------===//

#include "swift/SILPasses/Passes.h"
#include "swift/SILPasses/Transforms.h"
#include "swift/SIL/CFG.h"
#include "swift/SIL/SILBasicBlock.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILFunction.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Support/CommandLine.h"

using namespace swift;

template<typename InstTy, typename CaseValueTy>
inline CaseValueTy getCaseValueForBB(const InstTy *Inst,
                                     const SILBasicBlock *BB) {
  for (unsigned i = 0, e = Inst->getNumCases(); i != e; ++i) {
    auto P = Inst->getCase(i);
    if (P.second != BB)
      continue;
    return P.first;
  }
  llvm_unreachable("Error! should never pass in BB that is not a successor");
}

namespace llvm {
template<>
struct DOTGraphTraits<SILFunction *> : public DefaultDOTGraphTraits {

  DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {}

  static std::string getGraphName(const SILFunction *F) {
    return "CFG for '" + F->getName().str() + "' function";
  }

  static std::string getSimpleNodeLabel(const SILBasicBlock *Node,
                                        const SILFunction *F) {
    std::string OutStr;
    raw_string_ostream OSS(OutStr);
    const_cast<SILBasicBlock *>(Node)->printAsOperand(OSS, false);
    return OSS.str();
  }

  static std::string getCompleteNodeLabel(const SILBasicBlock *Node,
                                          const SILFunction *F) {
    enum { MaxColumns = 80 };
    std::string Str;
    raw_string_ostream OS(Str);

    OS << *Node;
    std::string OutStr = OS.str();
    if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());

    // Process string output to make it nicer...
    unsigned ColNum = 0;
    unsigned LastSpace = 0;
    for (unsigned i = 0; i != OutStr.length(); ++i) {
      if (OutStr[i] == '\n') {                            // Left justify
        OutStr[i] = '\\';
        OutStr.insert(OutStr.begin()+i+1, 'l');
        ColNum = 0;
        LastSpace = 0;
      } else if (OutStr[i] == ';') {                      // Delete comments!
        unsigned Idx = OutStr.find('\n', i+1);            // Find end of line
        OutStr.erase(OutStr.begin()+i, OutStr.begin()+Idx);
        --i;
      } else if (ColNum == MaxColumns) {                  // Wrap lines.
        if (LastSpace) {
          OutStr.insert(LastSpace, "\\l...");
          ColNum = i - LastSpace;
          LastSpace = 0;
          i += 3; // The loop will advance 'i' again.
        }
        // Else keep trying to find a space.
      }
      else
        ++ColNum;
      if (OutStr[i] == ' ')
        LastSpace = i;
    }
    return OutStr;
  }

  std::string getNodeLabel(const SILBasicBlock *Node,
                           const SILFunction *Graph) {
    if (isSimple())
      return getSimpleNodeLabel(Node, Graph);
    else
      return getCompleteNodeLabel(Node, Graph);
  }

  static std::string getEdgeSourceLabel(const SILBasicBlock *Node,
                                        SILBasicBlock::const_succ_iterator I) {
    SILBasicBlock *Succ = I->getBB();
    const TermInst *Term = Node->getTerminator();

    // Label source of conditional branches with "T" or "F"
    if (auto *CBI = dyn_cast<CondBranchInst>(Term))
        return (Succ == CBI->getTrueBB()) ? "T" : "F";

    // Label source of switch edges with the associated value.
    if (auto *SI = dyn_cast<SwitchIntInst>(Term)) {
      if (SI->hasDefault() && SI->getDefaultBB() == Succ)
        return "def";

      std::string Str;
      raw_string_ostream OS(Str);

      APInt I = getCaseValueForBB<SwitchIntInst, APInt>(SI, Succ);
      OS << I;
      return OS.str();
    }

    if (auto *SEIB = dyn_cast<SwitchEnumInst>(Term)) {
      std::string Str;
      raw_string_ostream OS(Str);

      EnumElementDecl *E =
        getCaseValueForBB<SwitchEnumInst, EnumElementDecl *>(SEIB, Succ);
      OS << E->getFullName();
      return OS.str();
    }

    if (auto *SEIB = dyn_cast<SwitchEnumAddrInst>(Term)) {
      std::string Str;
      raw_string_ostream OS(Str);

      EnumElementDecl *E =
        getCaseValueForBB<SwitchEnumAddrInst, EnumElementDecl *>(SEIB, Succ);
      OS << E->getFullName();
      return OS.str();
    }

    if (auto *DMBI = dyn_cast<DynamicMethodBranchInst>(Term))
        return (Succ == DMBI->getHasMethodBB()) ? "T" : "F";

    if (auto *CCBI = dyn_cast<CheckedCastBranchInst>(Term))
        return (Succ == CCBI->getSuccessBB()) ? "T" : "F";

    if (auto *CCBI = dyn_cast<CheckedCastAddrBranchInst>(Term))
        return (Succ == CCBI->getSuccessBB()) ? "T" : "F";

    return "";
  }
};
} // end llvm namespace

llvm::cl::opt<std::string>
TargetFunction("view-cfg-only-for-function", llvm::cl::init(""),
               llvm::cl::desc("Only print out the cfg for this function"));

//===----------------------------------------------------------------------===//
//                              Top Level Driver
//===----------------------------------------------------------------------===//

namespace {
class SILCFGPrinter : public SILFunctionTransform {
  StringRef getName() override { return "SIL CFG Printer"; }

  /// The entry point to the transformation.
  void run() override {
    SILFunction *F = getFunction();

    // If we have a target function, only print that function out.
    if (!TargetFunction.empty() && !(F->getName().str() == TargetFunction))
      return;

    ViewGraph(F, "cfg" + F->getName().str());
  }
};
} // end anonymous namespace

SILTransform *swift::createSILCFGPrinter() {
  return new SILCFGPrinter();
}
<|endoftext|>


<commit_before>#include <ros/ros.h>
#include <std_msgs/String.h>
#include <geometry_msgs/PoseArray.h>
#include <geometry_msgs/Accel.h>
#include <geometry_msgs/Pose.h>
#include <nav_msgs/Odometry.h>
#include <consai_msgs/VisionObservations.h>
#include <consai_msgs/VisionRobotPackets.h>
#include <consai_msgs/VisionPacket.h>
#include <tf/transform_datatypes.h>
#include <tf/transform_broadcaster.h>
#include <sensor_msgs/PointCloud.h>
#include <sstream>

#include <world_observer/estimator.hpp>
#include <world_observer/enemy_estimator.hpp>
#include <world_observer/ball_estimator.hpp>

class Observer
{
public:
  Observer(ros::NodeHandle& nh, std::string poses_source) :
    sub_vision(nh.subscribe(poses_source, 1000, &Observer::visionCallBack, this)),
    observation_refreshed(false)
  {
  }

  void update() {
    nav_msgs::Odometry  odom;

    if (observation_refreshed) {
      odom  = estimator->estimate(accel_, last_observation.poses);
      observation_refreshed = false;
    } else {
      odom  = estimator->estimate();
      ROS_DEBUG("No Observation received!");
    }

    publish(odom);
  }

protected:
  Estimator* estimator;
  ros::Subscriber sub_vision;
  geometry_msgs::PoseArray  last_observation;
  geometry_msgs::Accel  accel_;
  bool  observation_refreshed;

  virtual void publish(nav_msgs::Odometry odom) = 0;
  virtual void visionCallBackProcess(consai_msgs::VisionObservations msg) = 0;

  void visionCallBack(const consai_msgs::VisionObservations::ConstPtr& msg)
  {
    visionCallBackProcess(*msg);
//    last_observation  = *msg;
    observation_refreshed = true;
  }

  bool doSkip(const geometry_msgs::Pose& pose){
      bool skipFlag = false;
      double posX = pose.position.x;

      // if (posX < 0){
      //     skipFlag= true;
      // }

      return skipFlag;
  }

};

class FriendObserver :public Observer
{
public:
  FriendObserver(ros::NodeHandle& nh, std::string poses_source, int robot_id) :
    Observer(nh, poses_source),
    pub_odom(nh_odom.advertise<nav_msgs::Odometry>("odom", 1000)),
    sub_accel(nh_odom.subscribe<geometry_msgs::Accel>("accel_world", 1000, &FriendObserver::accelCallBack, this)),
    _robot_id(robot_id)
  {
    estimator = new EnemyEstimator(0.016);
  }

protected:
  int   _robot_id;
  ros::NodeHandle nh_odom;
  ros::Publisher  pub_odom;
  tf::TransformBroadcaster odom_broadcaster;
  ros::Subscriber sub_accel;

  void publish(nav_msgs::Odometry odom)
  {
    ros::Time current_time = ros::Time::now();

    odom.header.stamp = current_time;

    /* make transform */
    geometry_msgs::TransformStamped odom_trans;
    std::stringstream odom_name, base_link_name;

    odom_name   << "friend_" << _robot_id << "/odom";
    base_link_name << "friend_" << _robot_id << "/base_link";

    odom_trans.header.frame_id = odom_name.str();
    odom_trans.child_frame_id = base_link_name.str();
    odom_trans.header.stamp = current_time;

    odom_trans.transform.translation.x = odom.pose.pose.position.x;
    odom_trans.transform.translation.y = odom.pose.pose.position.y;
    odom_trans.transform.rotation = odom.pose.pose.orientation;

    odom_broadcaster.sendTransform(odom_trans);
    pub_odom.publish(odom);
  }

  void  visionCallBackProcess(consai_msgs::VisionObservations msg)
  {
      geometry_msgs::PoseArray  pose_array;

      vector<consai_msgs::VisionRobotPackets>::iterator it;

      it = msg.friends.begin();

      for (it = msg.friends.begin() ; it != msg.friends.end(); ++it) {
          // search desired robot id
          if (it->robot_id == _robot_id) {
              for (vector<consai_msgs::VisionPacket>::iterator it_pack = it->packets.begin(); it_pack != it->packets.end(); ++it_pack) {
                  if (doSkip(it_pack->pose) ){
                      continue;
                  }
                  pose_array.header=msg.header;
                  pose_array.poses.push_back(it_pack->pose);
              }
          }
      }

      last_observation  = pose_array;
  }

  void  accelCallBack(const geometry_msgs::AccelConstPtr& msg)
  {
     accel_ = *msg;
  }
};

class EnemyObserver :public Observer
{
public:
  EnemyObserver(ros::NodeHandle& nh, std::string poses_source, int robot_id) :
    Observer(nh, poses_source),
    pub_odom(nh_odom.advertise<nav_msgs::Odometry>("odom", 1000)),
    _robot_id(robot_id)
  {
    estimator = new EnemyEstimator(0.016);
  }

protected:
  int   _robot_id;
  ros::NodeHandle nh_odom;
  ros::Publisher  pub_odom;
  tf::TransformBroadcaster odom_broadcaster;

  void publish(nav_msgs::Odometry odom)
  {
    ros::Time current_time = ros::Time::now();

    odom.header.stamp = current_time;

    /* make transform */
    geometry_msgs::TransformStamped odom_trans;
    std::stringstream odom_name, base_link_name;

    odom_name   << "enemy_" << _robot_id << "/odom";
    base_link_name << "enemy_" << _robot_id << "/base_link";

    odom_trans.header.frame_id = odom_name.str();
    odom_trans.child_frame_id = base_link_name.str();
    odom_trans.header.stamp = current_time;

    odom_trans.transform.translation.x = odom.pose.pose.position.x;
    odom_trans.transform.translation.y = odom.pose.pose.position.y;
    odom_trans.transform.rotation = odom.pose.pose.orientation;

    odom_broadcaster.sendTransform(odom_trans);
    pub_odom.publish(odom);
  }

  void  visionCallBackProcess(consai_msgs::VisionObservations msg)
  {
      geometry_msgs::PoseArray  pose_array;

      vector<consai_msgs::VisionRobotPackets>::iterator it;

      it = msg.enemies.begin();

      for (it = msg.enemies.begin() ; it != msg.enemies.end(); ++it) {
          // search desired robot id
          if (it->robot_id == _robot_id) {
              for (vector<consai_msgs::VisionPacket>::iterator it_pack = it->packets.begin(); it_pack != it->packets.end(); ++it_pack) {
                  if (doSkip(it_pack->pose) ){
                      continue;
                  }
                  pose_array.header=msg.header;
                  pose_array.poses.push_back(it_pack->pose);
              }
          }
      }

      last_observation  = pose_array;
  }
};

class BallObserver :public Observer
{
public:
  BallObserver(ros::NodeHandle& nh, std::string poses_source) :
    Observer(nh, poses_source),
    pub_odom(nh.advertise<nav_msgs::Odometry>("estimation", 1000))
  {
    estimator = new BallEstimator(0.016);
  }

protected:
  ros::Publisher  pub_odom;
  tf::TransformBroadcaster odom_broadcaster;

  void publish(nav_msgs::Odometry odom)
  {
    ros::Time current_time = ros::Time::now();

    odom.header.stamp = current_time;

    /* make transform */
    geometry_msgs::TransformStamped odom_trans;

    odom_trans.header.frame_id = "map";
    odom_trans.child_frame_id = "ball";
    odom_trans.header.stamp = current_time;

    odom_trans.transform.translation.x = odom.pose.pose.position.x;
    odom_trans.transform.translation.y = odom.pose.pose.position.y;

    odom_trans.transform.rotation.x = 0.0;
    odom_trans.transform.rotation.y = 0.0;
    odom_trans.transform.rotation.z = 0.0;
    odom_trans.transform.rotation.w = 1.0;

    odom_broadcaster.sendTransform(odom_trans);
    pub_odom.publish(odom);
  }

  void  visionCallBackProcess(consai_msgs::VisionObservations msg)
  {
      geometry_msgs::PoseArray  pose_array;

      for (vector<consai_msgs::VisionPacket>::iterator it_pack = msg.ball.begin(); it_pack != msg.ball.end(); ++it_pack) {
          if (doSkip(it_pack->pose) ){
              continue;
          }
          pose_array.header=msg.header;
          pose_array.poses.push_back(it_pack->pose);
      }

      last_observation  = pose_array;
  }
};

int main(int argc, char **argv)
{
  const std::string node_name = "observer";

  ros::init(argc, argv, node_name);
  ros::NodeHandle nh("~");

  std::string poses_source;
  nh.param<std::string>("poses_source", poses_source, "/vision_observations");

  std::string observe_target;
  if (!nh.getParam("observe_target", observe_target)) {
      ROS_ERROR("observe target is not set");
      return 0;
  }

  int   observe_target_id;
  if (observe_target != "Ball") {
      if (!nh.getParam("observe_target_id", observe_target_id)) {
          ROS_ERROR("observe target id is not set");
          return 0;
      }
  }

  Observer*  obs;
  if (observe_target == "Ball") {
    obs = new BallObserver(nh, poses_source);
  } else if (observe_target == "Friend") {
    obs = new FriendObserver(nh, poses_source, observe_target_id);
  } else {
    obs = new EnemyObserver(nh, poses_source, observe_target_id);
  }

  ros::Rate loop_rate(60);

/********************************************/

  while (ros::ok()) {
    obs->update();

    ros::spinOnce();
    loop_rate.sleep();
  }

  return 0;

}
<commit_msg> #11 calcurate velocity norm in world_observer.cpp<commit_after>#include <ros/ros.h>
#include <std_msgs/String.h>
#include <std_msgs/Float64.h>
#include <geometry_msgs/PoseArray.h>
#include <geometry_msgs/Accel.h>
#include <geometry_msgs/Pose.h>
#include <nav_msgs/Odometry.h>
#include <consai_msgs/VisionObservations.h>
#include <consai_msgs/VisionRobotPackets.h>
#include <consai_msgs/VisionPacket.h>
#include <tf/transform_datatypes.h>
#include <tf/transform_broadcaster.h>
#include <sensor_msgs/PointCloud.h>
#include <sstream>
#include <cmath>

#include <world_observer/estimator.hpp>
#include <world_observer/enemy_estimator.hpp>
#include <world_observer/ball_estimator.hpp>

class Observer
{
    public:
        Observer(ros::NodeHandle& nh, std::string poses_source) :
            sub_vision(nh.subscribe(poses_source, 1000, &Observer::visionCallBack, this)),
            observation_refreshed(false){}

        void update() {
            nav_msgs::Odometry odom;

            if (observation_refreshed) {
                odom = estimator->estimate(accel_, last_observation.poses);
                observation_refreshed = false;
            } else {
                odom = estimator->estimate();
                ROS_DEBUG("No Observation received!");
            }

            publish(odom);
        }

    protected:
        Estimator* estimator;
        ros::Subscriber sub_vision;
        geometry_msgs::PoseArray last_observation;
        geometry_msgs::Accel accel_;
        bool observation_refreshed;

        virtual void publish(nav_msgs::Odometry odom) = 0;
        virtual void visionCallBackProcess(consai_msgs::VisionObservations msg) = 0;

        void visionCallBack(const consai_msgs::VisionObservations::ConstPtr& msg)
        {
            visionCallBackProcess(*msg);
            //    last_observation  = *msg;
            observation_refreshed = true;
        }

        // フィールドの右半分/左半分だけを使って練習するときに使用する。
        bool doSkip(const geometry_msgs::Pose& pose){
            bool skipFlag = false;

            // double posX = pose.position.x;
            // double posY = pose.position.y;
            //
            // Skip left side positions
            // if (posX < 0){
            //     skipFlag = true;
            // }
            //
            // Skip lower side positions
            // if (posY < 0){
            //     skipFlag = true;
            // }

            return skipFlag;
        }

};

class FriendObserver :public Observer
{
    public:
        FriendObserver(ros::NodeHandle& nh, std::string poses_source, int robot_id) :
            Observer(nh, poses_source),
            pub_odom(nh_odom.advertise<nav_msgs::Odometry>("odom", 1000)),
            pub_vel_norm(nh_odom.advertise<std_msgs::Float64>("vel_norm", 1000)),
            sub_accel(nh_odom.subscribe<geometry_msgs::Accel>("accel_world", 1000, &FriendObserver::accelCallBack, this)),
            _robot_id(robot_id)
    {
        estimator = new EnemyEstimator(0.016);
    }

    protected:
        int _robot_id;
        ros::NodeHandle nh_odom;
        ros::Publisher pub_odom;
        ros::Publisher pub_vel_norm;
        tf::TransformBroadcaster odom_broadcaster;
        ros::Subscriber sub_accel;

        void publish(nav_msgs::Odometry odom)
        {
            ros::Time current_time = ros::Time::now();

            odom.header.stamp = current_time;

            /* make transform */
            geometry_msgs::TransformStamped odom_trans;
            std::stringstream odom_name, base_link_name;

            odom_name   << "friend_" << _robot_id << "/odom";
            base_link_name << "friend_" << _robot_id << "/base_link";

            odom_trans.header.frame_id = odom_name.str();
            odom_trans.child_frame_id = base_link_name.str();
            odom_trans.header.stamp = current_time;

            odom_trans.transform.translation.x = odom.pose.pose.position.x;
            odom_trans.transform.translation.y = odom.pose.pose.position.y;
            odom_trans.transform.rotation = odom.pose.pose.orientation;

            odom_broadcaster.sendTransform(odom_trans);
            pub_odom.publish(odom);

            double velX = odom.twist.twist.linear.x;
            double velY = odom.twist.twist.linear.y;

            std_msgs::Float64 vel_norm;
            vel_norm.data = std::sqrt(velX*velX + velY*velY);
            pub_vel_norm.publish(vel_norm);
        }

        void visionCallBackProcess(consai_msgs::VisionObservations msg)
        {
            geometry_msgs::PoseArray pose_array;

            vector<consai_msgs::VisionRobotPackets>::iterator it;

            it = msg.friends.begin();

            for (it = msg.friends.begin() ; it != msg.friends.end(); ++it) {
                // search desired robot id
                if (it->robot_id == _robot_id) {
                    for (vector<consai_msgs::VisionPacket>::iterator it_pack = it->packets.begin(); it_pack != it->packets.end(); ++it_pack) {
                        if (doSkip(it_pack->pose) ){
                            continue;
                        }
                        pose_array.header=msg.header;
                        pose_array.poses.push_back(it_pack->pose);
                    }
                }
            }

            last_observation  = pose_array;
        }

        void accelCallBack(const geometry_msgs::AccelConstPtr& msg)
        {
            accel_ = *msg;
        }
};

class EnemyObserver :public Observer
{
    public:
        EnemyObserver(ros::NodeHandle& nh, std::string poses_source, int robot_id) :
            Observer(nh, poses_source),
            pub_odom(nh_odom.advertise<nav_msgs::Odometry>("odom", 1000)),
            pub_vel_norm(nh_odom.advertise<std_msgs::Float64>("vel_norm", 1000)),
            _robot_id(robot_id)
    {
        estimator = new EnemyEstimator(0.016);
    }

    protected:
        int _robot_id;
        ros::NodeHandle nh_odom;
        ros::Publisher pub_odom;
        ros::Publisher pub_vel_norm;
        tf::TransformBroadcaster odom_broadcaster;

        void publish(nav_msgs::Odometry odom)
        {
            ros::Time current_time = ros::Time::now();

            odom.header.stamp = current_time;

            /* make transform */
            geometry_msgs::TransformStamped odom_trans;
            std::stringstream odom_name, base_link_name;

            odom_name   << "enemy_" << _robot_id << "/odom";
            base_link_name << "enemy_" << _robot_id << "/base_link";

            odom_trans.header.frame_id = odom_name.str();
            odom_trans.child_frame_id = base_link_name.str();
            odom_trans.header.stamp = current_time;

            odom_trans.transform.translation.x = odom.pose.pose.position.x;
            odom_trans.transform.translation.y = odom.pose.pose.position.y;
            odom_trans.transform.rotation = odom.pose.pose.orientation;

            odom_broadcaster.sendTransform(odom_trans);
            pub_odom.publish(odom);

            double velX = odom.twist.twist.linear.x;
            double velY = odom.twist.twist.linear.y;

            std_msgs::Float64 vel_norm;
            vel_norm.data = std::sqrt(velX*velX + velY*velY);
            pub_vel_norm.publish(vel_norm);
        }

        void visionCallBackProcess(consai_msgs::VisionObservations msg)
        {
            geometry_msgs::PoseArray pose_array;

            vector<consai_msgs::VisionRobotPackets>::iterator it;

            it = msg.enemies.begin();

            for (it = msg.enemies.begin() ; it != msg.enemies.end(); ++it) {
                // search desired robot id
                if (it->robot_id == _robot_id) {
                    for (vector<consai_msgs::VisionPacket>::iterator it_pack = it->packets.begin(); it_pack != it->packets.end(); ++it_pack) {
                        if (doSkip(it_pack->pose) ){
                            continue;
                        }
                        pose_array.header=msg.header;
                        pose_array.poses.push_back(it_pack->pose);
                    }
                }
            }

            last_observation  = pose_array;
        }
};

class BallObserver :public Observer
{
    public:
        BallObserver(ros::NodeHandle& nh, std::string poses_source) :
            Observer(nh, poses_source),
            pub_odom(nh.advertise<nav_msgs::Odometry>("estimation", 1000)),
            pub_vel_norm(nh.advertise<std_msgs::Float64>("vel_norm", 1000))
    {
        estimator = new BallEstimator(0.016);
    }

    protected:
        ros::Publisher pub_odom;
        ros::Publisher pub_vel_norm;
        tf::TransformBroadcaster odom_broadcaster;

        void publish(nav_msgs::Odometry odom)
        {
            ros::Time current_time = ros::Time::now();

            odom.header.stamp = current_time;

            /* make transform */
            geometry_msgs::TransformStamped odom_trans;

            odom_trans.header.frame_id = "map";
            odom_trans.child_frame_id = "ball";
            odom_trans.header.stamp = current_time;

            odom_trans.transform.translation.x = odom.pose.pose.position.x;
            odom_trans.transform.translation.y = odom.pose.pose.position.y;

            odom_trans.transform.rotation.x = 0.0;
            odom_trans.transform.rotation.y = 0.0;
            odom_trans.transform.rotation.z = 0.0;
            odom_trans.transform.rotation.w = 1.0;

            odom_broadcaster.sendTransform(odom_trans);
            pub_odom.publish(odom);

            double velX = odom.twist.twist.linear.x;
            double velY = odom.twist.twist.linear.y;

            std_msgs::Float64 vel_norm;
            vel_norm.data = std::sqrt(velX*velX + velY*velY);
            pub_vel_norm.publish(vel_norm);
        }

        void visionCallBackProcess(consai_msgs::VisionObservations msg)
        {
            geometry_msgs::PoseArray  pose_array;

            for (vector<consai_msgs::VisionPacket>::iterator it_pack = msg.ball.begin(); it_pack != msg.ball.end(); ++it_pack) {
                if (doSkip(it_pack->pose) ){
                    continue;
                }
                pose_array.header=msg.header;
                pose_array.poses.push_back(it_pack->pose);
            }

            last_observation = pose_array;
        }
};

int main(int argc, char **argv)
{
    const std::string node_name = "observer";

    ros::init(argc, argv, node_name);
    ros::NodeHandle nh("~");

    std::string poses_source;
    nh.param<std::string>("poses_source", poses_source, "/vision_observations");

    std::string observe_target;
    if (!nh.getParam("observe_target", observe_target)) {
        ROS_ERROR("observe target is not set");
        return 0;
    }

    int observe_target_id;
    if (observe_target != "Ball") {
        if (!nh.getParam("observe_target_id", observe_target_id)) {
            ROS_ERROR("observe target id is not set");
            return 0;
        }
    }

    Observer*  obs;
    if (observe_target == "Ball") {
        obs = new BallObserver(nh, poses_source);
    } else if (observe_target == "Friend") {
        obs = new FriendObserver(nh, poses_source, observe_target_id);
    } else {
        obs = new EnemyObserver(nh, poses_source, observe_target_id);
    }

    ros::Rate loop_rate(60);

    while (ros::ok()) {
        obs->update();

        ros::spinOnce();
        loop_rate.sleep();
    }

    return 0;

}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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 <ooxml/resourceids.hxx>
#include <resourcemodel/QNameToString.hxx>
#include "Handler.hxx"

namespace writerfilter {
namespace ooxml
{

/*
  class OOXMLFootnoteHandler
 */
OOXMLFootnoteHandler::OOXMLFootnoteHandler(OOXMLFastContextHandler * pContext)
: mpFastContext(pContext)
{
}

OOXMLFootnoteHandler::~OOXMLFootnoteHandler()
{
}

void OOXMLFootnoteHandler::attribute(Id name, Value & val)
{
    switch (name)
    {
    case NS_ooxml::LN_CT_FtnEdnRef_id:
        mpFastContext->resolveFootnote(sal_Int32(val.getInt()));
        break;
    default:
        break;
    }
}

void OOXMLFootnoteHandler::sprm(Sprm & /*sprm*/)
{
}

/*
  class OOXMLEndnoteHandler
 */
OOXMLEndnoteHandler::OOXMLEndnoteHandler(OOXMLFastContextHandler * pContext)
: mpFastContext(pContext)
{
}

OOXMLEndnoteHandler::~OOXMLEndnoteHandler()
{
}

void OOXMLEndnoteHandler::attribute(Id name, Value & val)
{
    switch (name)
    {
    case NS_ooxml::LN_CT_FtnEdnRef_id:
        mpFastContext->resolveEndnote(sal_Int32(val.getInt()));
        break;
    default:
        break;
    }
}

void OOXMLEndnoteHandler::sprm(Sprm & /*sprm*/)
{
}

/*
  class OOXMLCommentHandler
*/
OOXMLCommentHandler::OOXMLCommentHandler(OOXMLFastContextHandler * pContext)
: mpFastContext(pContext)
{
}

OOXMLCommentHandler::~OOXMLCommentHandler()
{
}

void OOXMLCommentHandler::attribute(Id name, Value & val)
{
    switch (name)
    {
    case NS_ooxml::LN_CT_Markup_id:
        mpFastContext->resolveComment(val.getInt());
        break;
    default:
        ;
    }
}

void OOXMLCommentHandler::sprm(Sprm & /*sprm*/)
{
}

/*
   class OOXMLOLEHandler
*/
OOXMLOLEHandler::OOXMLOLEHandler(OOXMLFastContextHandler * pContext)
: mpFastContext(pContext)
{
}

OOXMLOLEHandler::~OOXMLOLEHandler()
{
}

void OOXMLOLEHandler::attribute(Id name, Value & val)
{
    switch (name)
    {
    case NS_ooxml::LN_CT_OLEObject_r_id:
        mpFastContext->resolveOLE(val.getString());
        break;
    default:
        ;
    }
}

void OOXMLOLEHandler::sprm(Sprm & /*sprm*/)
{
}

/*
  class OOXMLFooterHandler
 */
OOXMLFooterHandler::OOXMLFooterHandler(OOXMLFastContextHandler * pContext)
: mpFastContext(pContext), msStreamId(), mnType(0)
{
}

OOXMLFooterHandler::~OOXMLFooterHandler()
{
    mpFastContext->resolveFooter(mnType, msStreamId);
}

void OOXMLFooterHandler::attribute(Id name, Value & val)
{
    switch (name)
    {
    case NS_ooxml::LN_CT_HdrFtrRef_id:
        msStreamId = val.getString();
        break;
    case NS_ooxml::LN_CT_HdrFtrRef_type:
        mnType = val.getInt();
        break;
    default:
        break;
    }
}

void OOXMLFooterHandler::sprm(Sprm & /*sprm*/)
{
}

/*
  class OOXMLHeaderHandler
 */
OOXMLHeaderHandler::OOXMLHeaderHandler(OOXMLFastContextHandler * pContext)
: mpFastContext(pContext), msStreamId(), mnType(0)
{
}

OOXMLHeaderHandler::~OOXMLHeaderHandler()
{
    mpFastContext->resolveHeader(mnType, msStreamId);
}

void OOXMLHeaderHandler::attribute(Id name, Value & val)
{
    switch (name)
    {
    case NS_ooxml::LN_CT_HdrFtrRef_id:
        msStreamId = val.getString();
        break;
    case NS_ooxml::LN_CT_HdrFtrRef_type:
        mnType = val.getInt();
        break;
    default:
        break;
    }
}

void OOXMLHeaderHandler::sprm(Sprm & /*sprm*/)
{
}

/*
  class OOXMLBreakHandler
 */
OOXMLBreakHandler::OOXMLBreakHandler(Stream &rStream,
                                     OOXMLFastContextHandler * pContext)
: mpFastContext(pContext), mnType(0), mnClear(0),
  mrStream(rStream)
{
}

OOXMLBreakHandler::~OOXMLBreakHandler()
{
    sal_uInt8 tmpBreak[1];
    switch (mnType)
    {
    case NS_ooxml::LN_Value_ST_BrType_column:
        tmpBreak[0] = 0x0E;
        break;
    case NS_ooxml::LN_Value_ST_BrType_page:
        tmpBreak[0] = 0x0C;
        break;
    case NS_ooxml::LN_Value_ST_BrType_textWrapping:
    default: // when no attribute type is present, the spec assume textWrapping
        tmpBreak[0] = 0x0A;
        break;
    }
    mrStream.text(&tmpBreak[0], 1);
}

void OOXMLBreakHandler::attribute(Id name, Value & val)
{
    switch (name)
    {
    case NS_ooxml::LN_CT_Br_type:
        mnType = val.getInt();
        break;
    case NS_ooxml::LN_CT_Br_clear:
        mnClear = val.getInt();
        break;
    default:
        break;
    }
}

void OOXMLBreakHandler::sprm(Sprm & /*sprm*/)
{
}

/*
  class OOXMLPictureHandler
 */
OOXMLPictureHandler::OOXMLPictureHandler(OOXMLFastContextHandler * pContext)
: mpFastContext(pContext)
{
}

OOXMLPictureHandler::~OOXMLPictureHandler()
{
}

void OOXMLPictureHandler::attribute(Id name, Value & val)
{
    if (name == NS_ooxml::LN_AG_Blob_r_embed)
        mpFastContext->resolvePicture(val.getString());
    else
    {
        writerfilter::Reference<Properties>::Pointer_t pProps
            (val.getProperties());
        if (pProps.get() != NULL)
            pProps->resolve(*this);
    }
}

void OOXMLPictureHandler::sprm(Sprm & rSprm)
{
    writerfilter::Reference<Properties>::Pointer_t pProps
        (rSprm.getProps());

    if (pProps.get() != NULL)
        pProps->resolve(*this);
}

/**
   class OOXMLHyperlinkHandler
 */

OOXMLHyperlinkHandler::OOXMLHyperlinkHandler(OOXMLFastContextHandler * pContext)
: mpFastContext(pContext)
{
}

OOXMLHyperlinkHandler::~OOXMLHyperlinkHandler()
{
    ::rtl::OUString sReturn(RTL_CONSTASCII_USTRINGPARAM(" HYPERLINK \""));

    sReturn += mURL;
    sReturn += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("\""));
    sReturn += mFieldCode;

    mpFastContext->characters(sReturn);
}

void OOXMLHyperlinkHandler::attribute(Id name, Value & val)
{
    switch (name)
    {
    case NS_ooxml::LN_CT_Hyperlink_tgtFrame:
        mFieldCode += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" \\t \""));
        mFieldCode += val.getString();
        mFieldCode += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("\""));
        break;
    case NS_ooxml::LN_CT_Hyperlink_tooltip:
        mFieldCode += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" \\o \""));
        mFieldCode += val.getString();
        mFieldCode += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("\""));
        break;
    case NS_ooxml::LN_CT_Hyperlink_docLocation:
        break;
    case NS_ooxml::LN_CT_Hyperlink_history:
        break;
    case NS_ooxml::LN_CT_Hyperlink_anchor:
        mFieldCode += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" \\l \""));
        mFieldCode += val.getString();
        mFieldCode += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("\""));
        break;
    case NS_ooxml::LN_CT_Hyperlink_r_id:
        mURL = mpFastContext->getTargetForId(val.getString());
        break;
    default:
        break;
    }
}

void OOXMLHyperlinkHandler::sprm(Sprm & /*rSprm*/)
{
}
}}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fix for fod#37367 ( docx import of hyperlinks )<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * 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 <ooxml/resourceids.hxx>
#include <resourcemodel/QNameToString.hxx>
#include "Handler.hxx"

namespace writerfilter {
namespace ooxml
{

/*
  class OOXMLFootnoteHandler
 */
OOXMLFootnoteHandler::OOXMLFootnoteHandler(OOXMLFastContextHandler * pContext)
: mpFastContext(pContext)
{
}

OOXMLFootnoteHandler::~OOXMLFootnoteHandler()
{
}

void OOXMLFootnoteHandler::attribute(Id name, Value & val)
{
    switch (name)
    {
    case NS_ooxml::LN_CT_FtnEdnRef_id:
        mpFastContext->resolveFootnote(sal_Int32(val.getInt()));
        break;
    default:
        break;
    }
}

void OOXMLFootnoteHandler::sprm(Sprm & /*sprm*/)
{
}

/*
  class OOXMLEndnoteHandler
 */
OOXMLEndnoteHandler::OOXMLEndnoteHandler(OOXMLFastContextHandler * pContext)
: mpFastContext(pContext)
{
}

OOXMLEndnoteHandler::~OOXMLEndnoteHandler()
{
}

void OOXMLEndnoteHandler::attribute(Id name, Value & val)
{
    switch (name)
    {
    case NS_ooxml::LN_CT_FtnEdnRef_id:
        mpFastContext->resolveEndnote(sal_Int32(val.getInt()));
        break;
    default:
        break;
    }
}

void OOXMLEndnoteHandler::sprm(Sprm & /*sprm*/)
{
}

/*
  class OOXMLCommentHandler
*/
OOXMLCommentHandler::OOXMLCommentHandler(OOXMLFastContextHandler * pContext)
: mpFastContext(pContext)
{
}

OOXMLCommentHandler::~OOXMLCommentHandler()
{
}

void OOXMLCommentHandler::attribute(Id name, Value & val)
{
    switch (name)
    {
    case NS_ooxml::LN_CT_Markup_id:
        mpFastContext->resolveComment(val.getInt());
        break;
    default:
        ;
    }
}

void OOXMLCommentHandler::sprm(Sprm & /*sprm*/)
{
}

/*
   class OOXMLOLEHandler
*/
OOXMLOLEHandler::OOXMLOLEHandler(OOXMLFastContextHandler * pContext)
: mpFastContext(pContext)
{
}

OOXMLOLEHandler::~OOXMLOLEHandler()
{
}

void OOXMLOLEHandler::attribute(Id name, Value & val)
{
    switch (name)
    {
    case NS_ooxml::LN_CT_OLEObject_r_id:
        mpFastContext->resolveOLE(val.getString());
        break;
    default:
        ;
    }
}

void OOXMLOLEHandler::sprm(Sprm & /*sprm*/)
{
}

/*
  class OOXMLFooterHandler
 */
OOXMLFooterHandler::OOXMLFooterHandler(OOXMLFastContextHandler * pContext)
: mpFastContext(pContext), msStreamId(), mnType(0)
{
}

OOXMLFooterHandler::~OOXMLFooterHandler()
{
    mpFastContext->resolveFooter(mnType, msStreamId);
}

void OOXMLFooterHandler::attribute(Id name, Value & val)
{
    switch (name)
    {
    case NS_ooxml::LN_CT_HdrFtrRef_id:
        msStreamId = val.getString();
        break;
    case NS_ooxml::LN_CT_HdrFtrRef_type:
        mnType = val.getInt();
        break;
    default:
        break;
    }
}

void OOXMLFooterHandler::sprm(Sprm & /*sprm*/)
{
}

/*
  class OOXMLHeaderHandler
 */
OOXMLHeaderHandler::OOXMLHeaderHandler(OOXMLFastContextHandler * pContext)
: mpFastContext(pContext), msStreamId(), mnType(0)
{
}

OOXMLHeaderHandler::~OOXMLHeaderHandler()
{
    mpFastContext->resolveHeader(mnType, msStreamId);
}

void OOXMLHeaderHandler::attribute(Id name, Value & val)
{
    switch (name)
    {
    case NS_ooxml::LN_CT_HdrFtrRef_id:
        msStreamId = val.getString();
        break;
    case NS_ooxml::LN_CT_HdrFtrRef_type:
        mnType = val.getInt();
        break;
    default:
        break;
    }
}

void OOXMLHeaderHandler::sprm(Sprm & /*sprm*/)
{
}

/*
  class OOXMLBreakHandler
 */
OOXMLBreakHandler::OOXMLBreakHandler(Stream &rStream,
                                     OOXMLFastContextHandler * pContext)
: mpFastContext(pContext), mnType(0), mnClear(0),
  mrStream(rStream)
{
}

OOXMLBreakHandler::~OOXMLBreakHandler()
{
    sal_uInt8 tmpBreak[1];
    switch (mnType)
    {
    case NS_ooxml::LN_Value_ST_BrType_column:
        tmpBreak[0] = 0x0E;
        break;
    case NS_ooxml::LN_Value_ST_BrType_page:
        tmpBreak[0] = 0x0C;
        break;
    case NS_ooxml::LN_Value_ST_BrType_textWrapping:
    default: // when no attribute type is present, the spec assume textWrapping
        tmpBreak[0] = 0x0A;
        break;
    }
    mrStream.text(&tmpBreak[0], 1);
}

void OOXMLBreakHandler::attribute(Id name, Value & val)
{
    switch (name)
    {
    case NS_ooxml::LN_CT_Br_type:
        mnType = val.getInt();
        break;
    case NS_ooxml::LN_CT_Br_clear:
        mnClear = val.getInt();
        break;
    default:
        break;
    }
}

void OOXMLBreakHandler::sprm(Sprm & /*sprm*/)
{
}

/*
  class OOXMLPictureHandler
 */
OOXMLPictureHandler::OOXMLPictureHandler(OOXMLFastContextHandler * pContext)
: mpFastContext(pContext)
{
}

OOXMLPictureHandler::~OOXMLPictureHandler()
{
}

void OOXMLPictureHandler::attribute(Id name, Value & val)
{
    if (name == NS_ooxml::LN_AG_Blob_r_embed)
        mpFastContext->resolvePicture(val.getString());
    else
    {
        writerfilter::Reference<Properties>::Pointer_t pProps
            (val.getProperties());
        if (pProps.get() != NULL)
            pProps->resolve(*this);
    }
}

void OOXMLPictureHandler::sprm(Sprm & rSprm)
{
    writerfilter::Reference<Properties>::Pointer_t pProps
        (rSprm.getProps());

    if (pProps.get() != NULL)
        pProps->resolve(*this);
}

/**
   class OOXMLHyperlinkHandler
 */

OOXMLHyperlinkHandler::OOXMLHyperlinkHandler(OOXMLFastContextHandler * pContext)
: mpFastContext(pContext)
{
}

OOXMLHyperlinkHandler::~OOXMLHyperlinkHandler()
{
    ::rtl::OUString sReturn(RTL_CONSTASCII_USTRINGPARAM(" HYPERLINK \""));

    sReturn += mURL;
    sReturn += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("\""));
    sReturn += mFieldCode;

    mpFastContext->text(sReturn);
}

void OOXMLHyperlinkHandler::attribute(Id name, Value & val)
{
    switch (name)
    {
    case NS_ooxml::LN_CT_Hyperlink_tgtFrame:
        mFieldCode += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" \\t \""));
        mFieldCode += val.getString();
        mFieldCode += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("\""));
        break;
    case NS_ooxml::LN_CT_Hyperlink_tooltip:
        mFieldCode += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" \\o \""));
        mFieldCode += val.getString();
        mFieldCode += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("\""));
        break;
    case NS_ooxml::LN_CT_Hyperlink_docLocation:
        break;
    case NS_ooxml::LN_CT_Hyperlink_history:
        break;
    case NS_ooxml::LN_CT_Hyperlink_anchor:
        mFieldCode += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" \\l \""));
        mFieldCode += val.getString();
        mFieldCode += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("\""));
        break;
    case NS_ooxml::LN_CT_Hyperlink_r_id:
        mURL = mpFastContext->getTargetForId(val.getString());
        break;
    default:
        break;
    }
}

void OOXMLHyperlinkHandler::sprm(Sprm & /*rSprm*/)
{
}
}}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before><commit_msg>Use correct preprocessor keyword<commit_after><|endoftext|>


<commit_before>/**
 * @brief Analyzer for multi-languages
 * @file MultiLanguageAnalyzer.h
 *
 * @date Jan 4, 2010
 * @author vernkin
 */

/**
 * @brief Rewrite MLA using a fast language detction,
 *     String mode is moved to EnglishAnalyzer,
 *      Char mode is moved to CharAnalyzer.
 * @author Wei
 */

#include "la/analyzer/MultiLanguageAnalyzer.h"

#include <iostream>
using namespace std;
using namespace izenelib::util;
using namespace ilplib::langid;

namespace la
{

MultiLanguageAnalyzer::MultiLanguageAnalyzer() : Analyzer() {}

MultiLanguageAnalyzer::~MultiLanguageAnalyzer() {}

void MultiLanguageAnalyzer::setAnalyzer( Language lang, shared_ptr<Analyzer>& analyzer )
{
    if( lang == OTHER )
        return;
    analyzers_[ lang ] = analyzer;
}

shared_ptr<Analyzer> MultiLanguageAnalyzer::getAnalyzer( MultiLanguageAnalyzer::Language lang ) const
{
    if( lang == OTHER )
        return shared_ptr<Analyzer>();
    return analyzers_[ lang ];
}

void MultiLanguageAnalyzer::setDefaultAnalyzer( shared_ptr<Analyzer>& defAnalyzer )
{
    defAnalyzer_ = defAnalyzer;
}

shared_ptr<Analyzer> MultiLanguageAnalyzer::getDefaultAnalyzer() const
{
    return defAnalyzer_;
}

MultiLanguageAnalyzer::Language MultiLanguageAnalyzer::getCharType( UCS2Char ucs2Char )
{
    if(UString::isThisChineseChar( ucs2Char ) )
        return CHINESE;

    if(UString::isThisAlphaChar( ucs2Char ) )
        return ENGLISH;

    if(UString::isThisKoreanChar( ucs2Char ) )
        return KOREAN;

    if(UString::isThisJapaneseChar( ucs2Char ) )
        return JAPANESE;

    return OTHER;
}

MultiLanguageAnalyzer::Language MultiLanguageAnalyzer::detectLanguage( const UString & input )
{
    LanguageID langId;
    std::string utf8_text;

    input.convertString(utf8_text, izenelib::util::UString::UTF_8);

    langIdAnalyzer_->languageFromString(utf8_text.c_str(), langId);
    switch (langId)
    {
    case LANGUAGE_ID_CHINESE_SIMPLIFIED:
    case LANGUAGE_ID_CHINESE_TRADITIONAL:
        return CHINESE;
    case LANGUAGE_ID_JAPANESE:
        return JAPANESE;
    case LANGUAGE_ID_KOREAN:
        return KOREAN;
    case LANGUAGE_ID_ENGLISH:
        return ENGLISH;
    default:
        return OTHER;
    }
}

/// obsolete
void MultiLanguageAnalyzer::analyzeSynonym(TermList& output, size_t n)
{
    if (analyzers_[CHINESE])
        analyzers_[CHINESE]->analyzeSynonym(output, n);
}

int MultiLanguageAnalyzer::analyzeSynonym(const izenelib::util::UString& inputString, TermList& output)
{
    if (analyzers_[CHINESE])
    {
        return analyzers_[CHINESE]->analyzeSynonym(inputString, output);
    }
    else if (defAnalyzer_)
    {
        return defAnalyzer_->analyzeSynonym(inputString, output);
    }
    else
        return 0;
}

ilplib::langid::Analyzer* MultiLanguageAnalyzer::langIdAnalyzer_;

int MultiLanguageAnalyzer::analyze_impl( const Term& input, void* data, HookType func )
{
    if ( !langIdAnalyzer_ )
    {
        if ( defAnalyzer_ )
        {
            return defAnalyzer_->analyze_impl(input, data, func);
        }
        else
        {
            return 0;
        }
    }

    Language lang = detectLanguage(input.text_);
    if ( lang != OTHER && analyzers_[lang] )
    {
        return analyzers_[lang]->analyze_impl(input, data, func);
    }
    else if ( defAnalyzer_ )
    {
        return defAnalyzer_->analyze_impl(input, data, func);
    }
    else
    {
        return 0;
    }
}

int MultiLanguageAnalyzer::analyze_impl( const Term& input, void* data, HookType func, MultilangGranularity multilangGranularity )
{
    if ( !langIdAnalyzer_ || multilangGranularity != SENTENCE_LEVEL )
        return analyze_impl(input, data, func);

    void** parameters = (void**)data;
    TermIdList * output = (TermIdList*) parameters[0];
    std::string utf8_text;

    input.text_.convertString(utf8_text, izenelib::util::UString::UTF_8);
    const char* p = utf8_text.c_str();
    std::size_t lastpos, pos = 0, globalOffset = 0;
    while (int len = langIdAnalyzer_->sentenceLength(p))
    {
        UString sentence;
        sentence.assign(p, len, izenelib::util::UString::UTF_8);
        Language lang = detectLanguage(sentence);
        lastpos = pos;

        if(lang != OTHER && analyzers_[lang])
            analyzers_[lang]->analyze_impl(sentence, data, func);
        else if(defAnalyzer_)
            defAnalyzer_->analyze_impl(sentence, data, func);

        pos = output->size();

        if(lastpos > 0)
        {
            TermIdList& laInput = (*output);
            for(std::size_t i = lastpos; i < pos; ++i)
                laInput[i].wordOffset_ += globalOffset;
        }
        if (pos > lastpos)
            globalOffset = output->back().wordOffset_ + 1;

        p += len;
    }

    if (output->size() > 0)
        return output->back().wordOffset_;
    else
        return 0;
}
}
<commit_msg>fix analyzeSynonym()<commit_after>/**
 * @brief Analyzer for multi-languages
 * @file MultiLanguageAnalyzer.h
 *
 * @date Jan 4, 2010
 * @author vernkin
 */

/**
 * @brief Rewrite MLA using a fast language detction,
 *     String mode is moved to EnglishAnalyzer,
 *      Char mode is moved to CharAnalyzer.
 * @author Wei
 */

#include "la/analyzer/MultiLanguageAnalyzer.h"

#include <iostream>
using namespace std;
using namespace izenelib::util;
using namespace ilplib::langid;

namespace la
{

MultiLanguageAnalyzer::MultiLanguageAnalyzer() : Analyzer() {}

MultiLanguageAnalyzer::~MultiLanguageAnalyzer() {}

void MultiLanguageAnalyzer::setAnalyzer( Language lang, shared_ptr<Analyzer>& analyzer )
{
    if( lang == OTHER )
        return;
    analyzers_[ lang ] = analyzer;
}

shared_ptr<Analyzer> MultiLanguageAnalyzer::getAnalyzer( MultiLanguageAnalyzer::Language lang ) const
{
    if( lang == OTHER )
        return shared_ptr<Analyzer>();
    return analyzers_[ lang ];
}

void MultiLanguageAnalyzer::setDefaultAnalyzer( shared_ptr<Analyzer>& defAnalyzer )
{
    defAnalyzer_ = defAnalyzer;
}

shared_ptr<Analyzer> MultiLanguageAnalyzer::getDefaultAnalyzer() const
{
    return defAnalyzer_;
}

MultiLanguageAnalyzer::Language MultiLanguageAnalyzer::getCharType( UCS2Char ucs2Char )
{
    if(UString::isThisChineseChar( ucs2Char ) )
        return CHINESE;

    if(UString::isThisAlphaChar( ucs2Char ) )
        return ENGLISH;

    if(UString::isThisKoreanChar( ucs2Char ) )
        return KOREAN;

    if(UString::isThisJapaneseChar( ucs2Char ) )
        return JAPANESE;

    return OTHER;
}

MultiLanguageAnalyzer::Language MultiLanguageAnalyzer::detectLanguage( const UString & input )
{
    LanguageID langId;
    std::string utf8_text;

    input.convertString(utf8_text, izenelib::util::UString::UTF_8);

    langIdAnalyzer_->languageFromString(utf8_text.c_str(), langId);
    switch (langId)
    {
    case LANGUAGE_ID_CHINESE_SIMPLIFIED:
    case LANGUAGE_ID_CHINESE_TRADITIONAL:
        return CHINESE;
    case LANGUAGE_ID_JAPANESE:
        return JAPANESE;
    case LANGUAGE_ID_KOREAN:
        return KOREAN;
    case LANGUAGE_ID_ENGLISH:
        return ENGLISH;
    default:
        return OTHER;
    }
}

/// obsolete
void MultiLanguageAnalyzer::analyzeSynonym(TermList& output, size_t n)
{
    if (analyzers_[CHINESE])
        analyzers_[CHINESE]->analyzeSynonym(output, n);
}

int MultiLanguageAnalyzer::analyzeSynonym(const izenelib::util::UString& inputString, TermList& output)
{
    Language lang = detectLanguage(inputString);

    if (lang != OTHER && analyzers_[lang])
    {
        return analyzers_[lang]->analyzeSynonym(inputString, output);
    }
    else if (defAnalyzer_)
    {
        return defAnalyzer_->analyzeSynonym(inputString, output);
    }
    else
        return 0;
}

ilplib::langid::Analyzer* MultiLanguageAnalyzer::langIdAnalyzer_;

int MultiLanguageAnalyzer::analyze_impl( const Term& input, void* data, HookType func )
{
    if ( !langIdAnalyzer_ )
    {
        if ( defAnalyzer_ )
        {
            return defAnalyzer_->analyze_impl(input, data, func);
        }
        else
        {
            return 0;
        }
    }

    Language lang = detectLanguage(input.text_);
    if ( lang != OTHER && analyzers_[lang] )
    {
        return analyzers_[lang]->analyze_impl(input, data, func);
    }
    else if ( defAnalyzer_ )
    {
        return defAnalyzer_->analyze_impl(input, data, func);
    }
    else
    {
        return 0;
    }
}

int MultiLanguageAnalyzer::analyze_impl( const Term& input, void* data, HookType func, MultilangGranularity multilangGranularity )
{
    if ( !langIdAnalyzer_ || multilangGranularity != SENTENCE_LEVEL )
        return analyze_impl(input, data, func);

    void** parameters = (void**)data;
    TermIdList * output = (TermIdList*) parameters[0];
    std::string utf8_text;

    input.text_.convertString(utf8_text, izenelib::util::UString::UTF_8);
    const char* p = utf8_text.c_str();
    std::size_t lastpos, pos = 0, globalOffset = 0;
    while (int len = langIdAnalyzer_->sentenceLength(p))
    {
        UString sentence;
        sentence.assign(p, len, izenelib::util::UString::UTF_8);
        Language lang = detectLanguage(sentence);
        lastpos = pos;

        if(lang != OTHER && analyzers_[lang])
            analyzers_[lang]->analyze_impl(sentence, data, func);
        else if(defAnalyzer_)
            defAnalyzer_->analyze_impl(sentence, data, func);

        pos = output->size();

        if(lastpos > 0)
        {
            TermIdList& laInput = (*output);
            for(std::size_t i = lastpos; i < pos; ++i)
                laInput[i].wordOffset_ += globalOffset;
        }
        if (pos > lastpos)
            globalOffset = output->back().wordOffset_ + 1;

        p += len;
    }

    if (output->size() > 0)
        return output->back().wordOffset_;
    else
        return 0;
}
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <sal/main.h>
#include <vcl/event.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/fixed.hxx>
#include <vcl/edit.hxx>
#include <vcl/button.hxx>
#include <vcl/lstbox.hxx>
#include <svtools/filectrl.hxx>
#include <tools/urlobj.hxx>
#include <osl/file.hxx>

#include <svtools/docpasswdrequest.hxx>

#include <comphelper/processfactory.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <unotools/streamhelper.hxx>

// Will be in comphelper if CWS MAV09 is integrated
#include <comphelper/storagehelper.hxx>

#include <com/sun/star/lang/XMultiServiceFactory.hpp>

#include <xmlsecurity/xmlsignaturehelper.hxx>
#include <xmlsecurity/digitalsignaturesdialog.hxx>
#include <xmlsecurity/certificatechooser.hxx>
#include <xmlsecurity/biginteger.hxx>

#include <com/sun/star/security/DocumentDigitalSignatures.hpp>

using namespace ::com::sun::star;

void Main();

#define TEXTFIELDWIDTH  80
#define TEXTFIELDSTARTX 10

#define EDITWIDTH       200
#define EDITHEIGHT      20

#define FIXEDLINEHEIGHT 15

#define BUTTONWIDTH     50
#define BUTTONHEIGHT    22
#define BUTTONSPACE     20

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

    SAL_IMPLEMENT_MAIN()
{
    uno::Reference< lang::XMultiServiceFactory > xMSF;
    try
    {
        uno::Reference< uno::XComponentContext > xCtx( cppu::defaultBootstrap_InitialComponentContext() );
        if ( !xCtx.is() )
        {
            OSL_FAIL( "Error creating initial component context!" );
            return -1;
        }

        xMSF = uno::Reference< lang::XMultiServiceFactory >(xCtx->getServiceManager(), uno::UNO_QUERY );

        if ( !xMSF.is() )
        {
            OSL_FAIL( "No service manager!" );
            return -1;
        }
    }
    catch ( uno::Exception const & )
    {
        OSL_FAIL( "Exception during creation of initial component context!" );
        return -1;
    }
    comphelper::setProcessServiceFactory( xMSF );

    InitVCL();
    ::Main();
    DeInitVCL();

    return 0;
}

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

class MyWin : public WorkWindow
{
private:
    FixedLine   maTokenLine;
    CheckBox    maCryptoCheckBox;
    FixedText   maFixedTextTokenName;
    FileControl maEditTokenName;
    FixedLine   maTest1Line;
    FixedText   maFixedTextXMLFileName;
    FileControl maEditXMLFileName;
    FixedText   maFixedTextBINFileName;
    FileControl maEditBINFileName;
    FixedText   maFixedTextSIGFileName;
    FileControl maEditSIGFileName;
    PushButton  maSignButton;
    PushButton  maVerifyButton;
    FixedLine   maTest2Line;
    FixedText   maFixedTextDOCFileName;
    FileControl maEditDOCFileName;
    PushButton  maDigitalSignaturesButton;
    PushButton  maVerifyDigitalSignaturesButton;
    FixedLine   maHintLine;
    FixedText   maHintText;

    DECL_LINK(  CryptoCheckBoxHdl, CheckBox* );
    DECL_LINK(  SignButtonHdl, Button* );
    DECL_LINK(  VerifyButtonHdl, Button* );
    DECL_LINK(  DigitalSignaturesWithServiceHdl, Button* );
    DECL_LINK(  VerifyDigitalSignaturesHdl, Button* );
    DECL_LINK(  DigitalSignaturesWithTokenHdl, Button* );
    DECL_LINK(  StartVerifySignatureHdl, void* );

public:
                MyWin( Window* pParent, WinBits nWinStyle );

};

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

void Main()
{
    MyWin aMainWin( NULL, WB_APP | WB_STDWORK | WB_3DLOOK);
    aMainWin.Show();

    Application::Execute();
}

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

MyWin::MyWin( Window* pParent, WinBits nWinStyle ) :
    WorkWindow( pParent, nWinStyle ),
    maTokenLine( this ),
    maTest1Line( this ),
    maTest2Line( this ),
    maHintLine( this ),
    maFixedTextXMLFileName( this ),
    maEditXMLFileName( this, WB_BORDER ),
    maFixedTextBINFileName( this ),
    maEditBINFileName( this, WB_BORDER ),
    maFixedTextSIGFileName( this ),
    maEditSIGFileName( this, WB_BORDER ),
    maFixedTextTokenName( this ),
    maEditTokenName( this, WB_BORDER ),
    maFixedTextDOCFileName( this ),
    maEditDOCFileName( this, WB_BORDER ),
    maSignButton( this ),
    maVerifyButton( this ),
    maDigitalSignaturesButton( this ),
    maVerifyDigitalSignaturesButton( this ),
    maHintText( this, WB_WORDBREAK ),
    maCryptoCheckBox( this )

{
    Size aOutputSize( 400, 400 );
    SetOutputSizePixel( aOutputSize );
    SetText( OUString("XML Signature Test") );

    long nY = 15;

    maTokenLine.SetPosSizePixel( TEXTFIELDSTARTX, nY, aOutputSize.Width()-2*TEXTFIELDSTARTX, FIXEDLINEHEIGHT );
    maTokenLine.SetText( OUString("Crypto Settings") );
    maTokenLine.Show();

    nY += EDITHEIGHT*3/2;

    maCryptoCheckBox.SetPosSizePixel( TEXTFIELDSTARTX, nY, aOutputSize.Width()-2*TEXTFIELDSTARTX, FIXEDLINEHEIGHT );
    maCryptoCheckBox.SetText( OUString("Use Default Token (NSS option only)") );
    maCryptoCheckBox.Check( sal_True );
    maEditTokenName.Disable();
    maFixedTextTokenName.Disable();
    maCryptoCheckBox.SetClickHdl( LINK( this, MyWin, CryptoCheckBoxHdl ) );
    maCryptoCheckBox.Show();

    nY += EDITHEIGHT;

    maFixedTextTokenName.SetPosSizePixel( TEXTFIELDSTARTX, nY, TEXTFIELDWIDTH, EDITHEIGHT );
    maFixedTextTokenName.SetText( OUString("Crypto Token:") );
    maFixedTextTokenName.Show();

    maEditTokenName.SetPosSizePixel( TEXTFIELDSTARTX+TEXTFIELDWIDTH, nY, EDITWIDTH, EDITHEIGHT );
    maEditTokenName.Show();

    nY += EDITHEIGHT*3;

    maTest2Line.SetPosSizePixel( TEXTFIELDSTARTX, nY, aOutputSize.Width()-2*TEXTFIELDSTARTX, FIXEDLINEHEIGHT );
    maTest2Line.SetText( OUString("Test Office Document") );
    maTest2Line.Show();

    nY += EDITHEIGHT*3/2;

    maFixedTextDOCFileName.SetPosSizePixel( TEXTFIELDSTARTX, nY, TEXTFIELDWIDTH, EDITHEIGHT );
    maFixedTextDOCFileName.SetText( OUString("Office File:") );
    maFixedTextDOCFileName.Show();

    maEditDOCFileName.SetPosSizePixel( TEXTFIELDSTARTX+TEXTFIELDWIDTH, nY, EDITWIDTH, EDITHEIGHT );
    maEditDOCFileName.Show();

    nY += EDITHEIGHT*2;

    maDigitalSignaturesButton.SetPosSizePixel( TEXTFIELDSTARTX, nY, BUTTONWIDTH*2, BUTTONHEIGHT );
    maDigitalSignaturesButton.SetText( OUString("Digital Signatures...") );
    maDigitalSignaturesButton.SetClickHdl( LINK( this, MyWin, DigitalSignaturesWithServiceHdl ) );
    maDigitalSignaturesButton.Show();

    maVerifyDigitalSignaturesButton.SetPosSizePixel( TEXTFIELDSTARTX+BUTTONWIDTH*2+BUTTONSPACE, nY, BUTTONWIDTH*2, BUTTONHEIGHT );
    maVerifyDigitalSignaturesButton.SetText( OUString("Verify Signatures") );
    maVerifyDigitalSignaturesButton.SetClickHdl( LINK( this, MyWin, VerifyDigitalSignaturesHdl ) );
    maVerifyDigitalSignaturesButton.Show();

    nY += EDITHEIGHT*2;

    maHintLine.SetPosSizePixel( TEXTFIELDSTARTX, nY, aOutputSize.Width()-2*TEXTFIELDSTARTX, FIXEDLINEHEIGHT );
    maHintLine.Show();

    nY += EDITHEIGHT*2;

    maHintText.SetPosSizePixel( TEXTFIELDSTARTX, nY, aOutputSize.Width()-2*TEXTFIELDSTARTX, aOutputSize.Height()-nY );
    maHintText.SetText( OUString("Hint: Copy crypto files from xmlsecurity/tools/cryptoken/nss and sample files from xmlsecurity/tools/examples to <temp>/nss.\nThis location will be used from the demo as the default location.") );
    maHintText.Show();

    // Help the user with some default values
    OUString aTempDirURL;
    ::osl::File::getTempDirURL( aTempDirURL );
    INetURLObject aURLObj( aTempDirURL );
    aURLObj.insertName( "nss", true );
    OUString aNSSFolder = aURLObj.getFSysPath( INetURLObject::FSYS_DETECT );
    maEditXMLFileName.SetText( aNSSFolder + "demo-sample.xml" );
    maEditBINFileName.SetText( aNSSFolder + "demo-sample.gif" );
    maEditDOCFileName.SetText( aNSSFolder + "demo-sample.sxw" );
    maEditSIGFileName.SetText( aNSSFolder + "demo-result.xml" );
    maEditTokenName.SetText( aNSSFolder );

#ifdef WNT
    maEditTokenName.SetText( OUString() );
    maEditTokenName.Disable();
    maCryptoCheckBox.Disable();
#endif

}

IMPL_LINK_NOARG(MyWin, CryptoCheckBoxHdl)
{
    if ( maCryptoCheckBox.IsChecked() )
    {
        maEditTokenName.Disable();
        maFixedTextTokenName.Disable();
    }
    else
    {
        maEditTokenName.Enable();
        maFixedTextTokenName.Enable();
    }
    return 1;
}

IMPL_LINK_NOARG(MyWin, DigitalSignaturesWithServiceHdl)
{
    OUString aDocFileName = maEditDOCFileName.GetText();
    uno::Reference < embed::XStorage > xStore = ::comphelper::OStorageHelper::GetStorageFromURL(
            aDocFileName, embed::ElementModes::READWRITE, comphelper::getProcessServiceFactory() );

    uno::Reference< security::XDocumentDigitalSignatures > xD(
        security::DocumentDigitalSignatures::createDefault(comphelper::getProcessComponentContext()) );
    xD->signDocumentContent( xStore, NULL );

    return 0;
}

IMPL_LINK_NOARG(MyWin, VerifyDigitalSignaturesHdl)
{
    OUString aDocFileName = maEditDOCFileName.GetText();
    uno::Reference < embed::XStorage > xStore = ::comphelper::OStorageHelper::GetStorageFromURL(
            aDocFileName, embed::ElementModes::READWRITE, comphelper::getProcessServiceFactory() );

    uno::Reference< security::XDocumentDigitalSignatures > xD(
        security::DocumentDigitalSignatures::createDefault(comphelper::getProcessComponentContext()) );
    uno::Sequence< security::DocumentSignatureInformation > aInfos = xD->verifyDocumentContentSignatures( xStore, NULL );
    int nInfos = aInfos.getLength();
    for ( int n = 0; n < nInfos; n++ )
    {
        security::DocumentSignatureInformation& rInf = aInfos[n];
        OUStringBuffer aText( "The document is signed by\n\n  " );
        aText.append( rInf.Signer->getSubjectName() );
        aText.append( "\n\n The signature is " );
        if ( !rInf.SignatureIsValid )
            aText.append( "NOT " );
        aText.append( "valid" );
        InfoBox( this, aText.makeStringAndClear() ).Execute();
    }

    return 0;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fdo#46808, GetStorageFromURL now takes an XComponentContext<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you 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 .
 */

#include <sal/main.h>
#include <vcl/event.hxx>
#include <vcl/svapp.hxx>
#include <vcl/wrkwin.hxx>
#include <vcl/msgbox.hxx>
#include <vcl/fixed.hxx>
#include <vcl/edit.hxx>
#include <vcl/button.hxx>
#include <vcl/lstbox.hxx>
#include <svtools/filectrl.hxx>
#include <tools/urlobj.hxx>
#include <osl/file.hxx>

#include <svtools/docpasswdrequest.hxx>

#include <comphelper/processfactory.hxx>
#include <cppuhelper/servicefactory.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <unotools/streamhelper.hxx>

// Will be in comphelper if CWS MAV09 is integrated
#include <comphelper/storagehelper.hxx>

#include <com/sun/star/lang/XMultiServiceFactory.hpp>

#include <xmlsecurity/xmlsignaturehelper.hxx>
#include <xmlsecurity/digitalsignaturesdialog.hxx>
#include <xmlsecurity/certificatechooser.hxx>
#include <xmlsecurity/biginteger.hxx>

#include <com/sun/star/security/DocumentDigitalSignatures.hpp>

using namespace ::com::sun::star;

void Main();

#define TEXTFIELDWIDTH  80
#define TEXTFIELDSTARTX 10

#define EDITWIDTH       200
#define EDITHEIGHT      20

#define FIXEDLINEHEIGHT 15

#define BUTTONWIDTH     50
#define BUTTONHEIGHT    22
#define BUTTONSPACE     20

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

    SAL_IMPLEMENT_MAIN()
{
    uno::Reference< lang::XMultiServiceFactory > xMSF;
    try
    {
        uno::Reference< uno::XComponentContext > xCtx( cppu::defaultBootstrap_InitialComponentContext() );
        if ( !xCtx.is() )
        {
            OSL_FAIL( "Error creating initial component context!" );
            return -1;
        }

        xMSF = uno::Reference< lang::XMultiServiceFactory >(xCtx->getServiceManager(), uno::UNO_QUERY );

        if ( !xMSF.is() )
        {
            OSL_FAIL( "No service manager!" );
            return -1;
        }
    }
    catch ( uno::Exception const & )
    {
        OSL_FAIL( "Exception during creation of initial component context!" );
        return -1;
    }
    comphelper::setProcessServiceFactory( xMSF );

    InitVCL();
    ::Main();
    DeInitVCL();

    return 0;
}

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

class MyWin : public WorkWindow
{
private:
    FixedLine   maTokenLine;
    CheckBox    maCryptoCheckBox;
    FixedText   maFixedTextTokenName;
    FileControl maEditTokenName;
    FixedLine   maTest1Line;
    FixedText   maFixedTextXMLFileName;
    FileControl maEditXMLFileName;
    FixedText   maFixedTextBINFileName;
    FileControl maEditBINFileName;
    FixedText   maFixedTextSIGFileName;
    FileControl maEditSIGFileName;
    PushButton  maSignButton;
    PushButton  maVerifyButton;
    FixedLine   maTest2Line;
    FixedText   maFixedTextDOCFileName;
    FileControl maEditDOCFileName;
    PushButton  maDigitalSignaturesButton;
    PushButton  maVerifyDigitalSignaturesButton;
    FixedLine   maHintLine;
    FixedText   maHintText;

    DECL_LINK(  CryptoCheckBoxHdl, CheckBox* );
    DECL_LINK(  SignButtonHdl, Button* );
    DECL_LINK(  VerifyButtonHdl, Button* );
    DECL_LINK(  DigitalSignaturesWithServiceHdl, Button* );
    DECL_LINK(  VerifyDigitalSignaturesHdl, Button* );
    DECL_LINK(  DigitalSignaturesWithTokenHdl, Button* );
    DECL_LINK(  StartVerifySignatureHdl, void* );

public:
                MyWin( Window* pParent, WinBits nWinStyle );

};

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

void Main()
{
    MyWin aMainWin( NULL, WB_APP | WB_STDWORK | WB_3DLOOK);
    aMainWin.Show();

    Application::Execute();
}

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

MyWin::MyWin( Window* pParent, WinBits nWinStyle ) :
    WorkWindow( pParent, nWinStyle ),
    maTokenLine( this ),
    maTest1Line( this ),
    maTest2Line( this ),
    maHintLine( this ),
    maFixedTextXMLFileName( this ),
    maEditXMLFileName( this, WB_BORDER ),
    maFixedTextBINFileName( this ),
    maEditBINFileName( this, WB_BORDER ),
    maFixedTextSIGFileName( this ),
    maEditSIGFileName( this, WB_BORDER ),
    maFixedTextTokenName( this ),
    maEditTokenName( this, WB_BORDER ),
    maFixedTextDOCFileName( this ),
    maEditDOCFileName( this, WB_BORDER ),
    maSignButton( this ),
    maVerifyButton( this ),
    maDigitalSignaturesButton( this ),
    maVerifyDigitalSignaturesButton( this ),
    maHintText( this, WB_WORDBREAK ),
    maCryptoCheckBox( this )

{
    Size aOutputSize( 400, 400 );
    SetOutputSizePixel( aOutputSize );
    SetText( OUString("XML Signature Test") );

    long nY = 15;

    maTokenLine.SetPosSizePixel( TEXTFIELDSTARTX, nY, aOutputSize.Width()-2*TEXTFIELDSTARTX, FIXEDLINEHEIGHT );
    maTokenLine.SetText( OUString("Crypto Settings") );
    maTokenLine.Show();

    nY += EDITHEIGHT*3/2;

    maCryptoCheckBox.SetPosSizePixel( TEXTFIELDSTARTX, nY, aOutputSize.Width()-2*TEXTFIELDSTARTX, FIXEDLINEHEIGHT );
    maCryptoCheckBox.SetText( OUString("Use Default Token (NSS option only)") );
    maCryptoCheckBox.Check( sal_True );
    maEditTokenName.Disable();
    maFixedTextTokenName.Disable();
    maCryptoCheckBox.SetClickHdl( LINK( this, MyWin, CryptoCheckBoxHdl ) );
    maCryptoCheckBox.Show();

    nY += EDITHEIGHT;

    maFixedTextTokenName.SetPosSizePixel( TEXTFIELDSTARTX, nY, TEXTFIELDWIDTH, EDITHEIGHT );
    maFixedTextTokenName.SetText( OUString("Crypto Token:") );
    maFixedTextTokenName.Show();

    maEditTokenName.SetPosSizePixel( TEXTFIELDSTARTX+TEXTFIELDWIDTH, nY, EDITWIDTH, EDITHEIGHT );
    maEditTokenName.Show();

    nY += EDITHEIGHT*3;

    maTest2Line.SetPosSizePixel( TEXTFIELDSTARTX, nY, aOutputSize.Width()-2*TEXTFIELDSTARTX, FIXEDLINEHEIGHT );
    maTest2Line.SetText( OUString("Test Office Document") );
    maTest2Line.Show();

    nY += EDITHEIGHT*3/2;

    maFixedTextDOCFileName.SetPosSizePixel( TEXTFIELDSTARTX, nY, TEXTFIELDWIDTH, EDITHEIGHT );
    maFixedTextDOCFileName.SetText( OUString("Office File:") );
    maFixedTextDOCFileName.Show();

    maEditDOCFileName.SetPosSizePixel( TEXTFIELDSTARTX+TEXTFIELDWIDTH, nY, EDITWIDTH, EDITHEIGHT );
    maEditDOCFileName.Show();

    nY += EDITHEIGHT*2;

    maDigitalSignaturesButton.SetPosSizePixel( TEXTFIELDSTARTX, nY, BUTTONWIDTH*2, BUTTONHEIGHT );
    maDigitalSignaturesButton.SetText( OUString("Digital Signatures...") );
    maDigitalSignaturesButton.SetClickHdl( LINK( this, MyWin, DigitalSignaturesWithServiceHdl ) );
    maDigitalSignaturesButton.Show();

    maVerifyDigitalSignaturesButton.SetPosSizePixel( TEXTFIELDSTARTX+BUTTONWIDTH*2+BUTTONSPACE, nY, BUTTONWIDTH*2, BUTTONHEIGHT );
    maVerifyDigitalSignaturesButton.SetText( OUString("Verify Signatures") );
    maVerifyDigitalSignaturesButton.SetClickHdl( LINK( this, MyWin, VerifyDigitalSignaturesHdl ) );
    maVerifyDigitalSignaturesButton.Show();

    nY += EDITHEIGHT*2;

    maHintLine.SetPosSizePixel( TEXTFIELDSTARTX, nY, aOutputSize.Width()-2*TEXTFIELDSTARTX, FIXEDLINEHEIGHT );
    maHintLine.Show();

    nY += EDITHEIGHT*2;

    maHintText.SetPosSizePixel( TEXTFIELDSTARTX, nY, aOutputSize.Width()-2*TEXTFIELDSTARTX, aOutputSize.Height()-nY );
    maHintText.SetText( OUString("Hint: Copy crypto files from xmlsecurity/tools/cryptoken/nss and sample files from xmlsecurity/tools/examples to <temp>/nss.\nThis location will be used from the demo as the default location.") );
    maHintText.Show();

    // Help the user with some default values
    OUString aTempDirURL;
    ::osl::File::getTempDirURL( aTempDirURL );
    INetURLObject aURLObj( aTempDirURL );
    aURLObj.insertName( "nss", true );
    OUString aNSSFolder = aURLObj.getFSysPath( INetURLObject::FSYS_DETECT );
    maEditXMLFileName.SetText( aNSSFolder + "demo-sample.xml" );
    maEditBINFileName.SetText( aNSSFolder + "demo-sample.gif" );
    maEditDOCFileName.SetText( aNSSFolder + "demo-sample.sxw" );
    maEditSIGFileName.SetText( aNSSFolder + "demo-result.xml" );
    maEditTokenName.SetText( aNSSFolder );

#ifdef WNT
    maEditTokenName.SetText( OUString() );
    maEditTokenName.Disable();
    maCryptoCheckBox.Disable();
#endif

}

IMPL_LINK_NOARG(MyWin, CryptoCheckBoxHdl)
{
    if ( maCryptoCheckBox.IsChecked() )
    {
        maEditTokenName.Disable();
        maFixedTextTokenName.Disable();
    }
    else
    {
        maEditTokenName.Enable();
        maFixedTextTokenName.Enable();
    }
    return 1;
}

IMPL_LINK_NOARG(MyWin, DigitalSignaturesWithServiceHdl)
{
    OUString aDocFileName = maEditDOCFileName.GetText();
    uno::Reference < embed::XStorage > xStore = ::comphelper::OStorageHelper::GetStorageFromURL(
            aDocFileName, embed::ElementModes::READWRITE, comphelper::getProcessComponentContext() );

    uno::Reference< security::XDocumentDigitalSignatures > xD(
        security::DocumentDigitalSignatures::createDefault(comphelper::getProcessComponentContext()) );
    xD->signDocumentContent( xStore, NULL );

    return 0;
}

IMPL_LINK_NOARG(MyWin, VerifyDigitalSignaturesHdl)
{
    OUString aDocFileName = maEditDOCFileName.GetText();
    uno::Reference < embed::XStorage > xStore = ::comphelper::OStorageHelper::GetStorageFromURL(
            aDocFileName, embed::ElementModes::READWRITE, comphelper::getProcessServiceFactory() );

    uno::Reference< security::XDocumentDigitalSignatures > xD(
        security::DocumentDigitalSignatures::createDefault(comphelper::getProcessComponentContext()) );
    uno::Sequence< security::DocumentSignatureInformation > aInfos = xD->verifyDocumentContentSignatures( xStore, NULL );
    int nInfos = aInfos.getLength();
    for ( int n = 0; n < nInfos; n++ )
    {
        security::DocumentSignatureInformation& rInf = aInfos[n];
        OUStringBuffer aText( "The document is signed by\n\n  " );
        aText.append( rInf.Signer->getSubjectName() );
        aText.append( "\n\n The signature is " );
        if ( !rInf.SignatureIsValid )
            aText.append( "NOT " );
        aText.append( "valid" );
        InfoBox( this, aText.makeStringAndClear() ).Execute();
    }

    return 0;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include <gmock/gmock.h>

#include <array>
#include <iostream>

#include <reflectionzeug/Object.h>
#include <scriptzeug/ScriptContext.h>

using namespace reflectionzeug;
using namespace scriptzeug;

int testFunction()
{
    return 42;
}

class RegisteredObject : public Object
{
public:
    RegisteredObject() : Object("registeredObject")
    {
        addFunction("successor", this, &RegisteredObject::successor);
    }

    ~RegisteredObject()
    {
    }

    int successor(int number)
    {
        return number + 1;
    }
};

class MyInterface : public Object
{
public:
    MyInterface() : Object("api")
    {
        // Properties
        addProperty(new RegisteredObject);

        // Functions
        addFunction("test", &testFunction);
        addFunction("countArgs", this, &MyInterface::countArgs);
    }

    ~MyInterface()
    {
    }

    int countArgs(const std::vector<Variant> &args)
    {
        return args.size();
    }
};

class ScriptContext_test : public testing::Test
{
public:
protected:
    virtual void SetUp()
    {
        m_scripting.registerObject(&m_api);

        m_scripting.scriptException.connect( [this] (const std::string & error) -> void {
            m_error = error;
        });
    }

    ScriptContext m_scripting;
    MyInterface m_api;
    Variant m_result;
    std::string m_error;
};

TEST_F(ScriptContext_test, Evaluate)
{
    m_result = m_scripting.evaluate("1 + 2");
    ASSERT_EQ(3, m_result.value<int>());

    m_result = m_scripting.evaluate("'testString'.toUpperCase()");
    ASSERT_EQ("TESTSTRING", m_result.value<std::string>());

}

TEST_F(ScriptContext_test, ErrorHandling)
{
    m_result = m_scripting.evaluate("asd");
    ASSERT_TRUE(m_result.isNull());
    ASSERT_EQ("ReferenceError: identifier 'asd' undefined", m_error);

    m_result = m_scripting.evaluate("api.noFunction();");
    ASSERT_TRUE(m_result.isNull());
    ASSERT_EQ("TypeError: call target not an object", m_error);

    m_result = m_scripting.evaluate("var causesRangeError = new Array(-1);");
    ASSERT_TRUE(m_result.isNull());
    ASSERT_EQ("RangeError: range error (rc -102)", m_error);

    m_result = m_scripting.evaluate("print(1 + 2;");
    ASSERT_TRUE(m_result.isNull());
    ASSERT_EQ("SyntaxError: parse error (line 1)", m_error);
}

TEST_F(ScriptContext_test, RegisterObject_Methods)
{
    m_result = m_scripting.evaluate("api.test();");
    ASSERT_EQ(42, m_result.value<int>());

    m_result = m_scripting.evaluate("api.countArgs([3.5, {a: 100, b: 200}, 12], \"asd\");");
    ASSERT_EQ(2, m_result.value<int>());

    m_result = m_scripting.evaluate("api.countArgs();");
    ASSERT_EQ(0, m_result.value<int>());
}

TEST_F(ScriptContext_test, RegisterObject_SubObjectAccess)
{
    m_result = m_scripting.evaluate("api.registeredObject.successor(6);");
    ASSERT_EQ(7, m_result.value<int>());
}
<commit_msg>Adjust ErrorHandling test to changes in new duktape version 1.1.0<commit_after>#include <gmock/gmock.h>

#include <array>
#include <iostream>

#include <reflectionzeug/Object.h>
#include <scriptzeug/ScriptContext.h>

using namespace reflectionzeug;
using namespace scriptzeug;

int testFunction()
{
    return 42;
}

class RegisteredObject : public Object
{
public:
    RegisteredObject() : Object("registeredObject")
    {
        addFunction("successor", this, &RegisteredObject::successor);
    }

    ~RegisteredObject()
    {
    }

    int successor(int number)
    {
        return number + 1;
    }
};

class MyInterface : public Object
{
public:
    MyInterface() : Object("api")
    {
        // Properties
        addProperty(new RegisteredObject);

        // Functions
        addFunction("test", &testFunction);
        addFunction("countArgs", this, &MyInterface::countArgs);
    }

    ~MyInterface()
    {
    }

    int countArgs(const std::vector<Variant> &args)
    {
        return args.size();
    }
};

class ScriptContext_test : public testing::Test
{
public:
protected:
    virtual void SetUp()
    {
        m_scripting.registerObject(&m_api);

        m_scripting.scriptException.connect( [this] (const std::string & error) -> void {
            m_error = error;
        });
    }

    ScriptContext m_scripting;
    MyInterface m_api;
    Variant m_result;
    std::string m_error;
};

TEST_F(ScriptContext_test, Evaluate)
{
    m_result = m_scripting.evaluate("1 + 2");
    ASSERT_EQ(3, m_result.value<int>());

    m_result = m_scripting.evaluate("'testString'.toUpperCase()");
    ASSERT_EQ("TESTSTRING", m_result.value<std::string>());

}

TEST_F(ScriptContext_test, ErrorHandling)
{
    m_result = m_scripting.evaluate("asd");
    ASSERT_TRUE(m_result.isNull());
    ASSERT_EQ("ReferenceError: identifier 'asd' undefined", m_error);

    m_result = m_scripting.evaluate("api.noFunction();");
    ASSERT_TRUE(m_result.isNull());
    ASSERT_EQ("TypeError: not callable", m_error);

    m_result = m_scripting.evaluate("var causesRangeError = new Array(-1);");
    ASSERT_TRUE(m_result.isNull());
    ASSERT_EQ("RangeError: range error (rc -102)", m_error);

    m_result = m_scripting.evaluate("print(1 + 2;");
    ASSERT_TRUE(m_result.isNull());
    ASSERT_EQ("SyntaxError: parse error (line 1)", m_error);
}

TEST_F(ScriptContext_test, RegisterObject_Methods)
{
    m_result = m_scripting.evaluate("api.test();");
    ASSERT_EQ(42, m_result.value<int>());

    m_result = m_scripting.evaluate("api.countArgs([3.5, {a: 100, b: 200}, 12], \"asd\");");
    ASSERT_EQ(2, m_result.value<int>());

    m_result = m_scripting.evaluate("api.countArgs();");
    ASSERT_EQ(0, m_result.value<int>());
}

TEST_F(ScriptContext_test, RegisterObject_SubObjectAccess)
{
    m_result = m_scripting.evaluate("api.registeredObject.successor(6);");
    ASSERT_EQ(7, m_result.value<int>());
}
<|endoftext|>