<commit_before>#include <agency/new_executor_traits.hpp>
#include <cassert>
#include <iostream>

#include "test_executors.hpp"

template<class Executor>
void test()
{
  using executor_type = Executor;

  {
    // void -> void
    executor_type exec;

    auto void_future = agency::when_all();

    int set_me_to_thirteen = 0;

    auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [&]
    {
      set_me_to_thirteen = 13;
    },
    void_future);

    f.wait();

    assert(set_me_to_thirteen == 13);
    assert(exec.valid());
  }

  {
    // void -> int
    executor_type exec;

    auto void_future = agency::when_all();

    auto f = agency::new_executor_traits<executor_type>::then_execute(exec, []
    {
      return 13;
    },
    void_future);

    assert(f.get() == 13);
    assert(exec.valid());
  }

  {
    // int -> void
    executor_type exec;

    auto int_future = agency::new_executor_traits<executor_type>::template make_ready_future<int>(exec, 13);

    int set_me_to_thirteen = 0;

    auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [&](int& x)
    {
      set_me_to_thirteen = x;
    },
    int_future);

    f.wait();

    assert(set_me_to_thirteen == 13);
    assert(exec.valid());
  }

  {
    // int -> float
    executor_type exec;

    auto int_future = agency::new_executor_traits<executor_type>::template make_ready_future<int>(exec, 13);

    auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [](int &x)
    {
      return float(x) + 1.f;
    },
    int_future);

    assert(f.get() == 14.f);
    assert(exec.valid());
  }
}

int main()
{
  using namespace test_executors;

  test<empty_executor>();
  test<single_agent_when_all_execute_and_select_executor>();
  test<multi_agent_when_all_execute_and_select_executor>();
  test<single_agent_then_execute_executor>();

  test<multi_agent_execute_returning_user_defined_container_executor>();
  test<multi_agent_execute_returning_default_container_executor>();
  test<multi_agent_execute_returning_void_executor>();

  test<multi_agent_async_execute_returning_user_defined_container_executor>();

  std::cout << "OK" << std::endl;

  return 0;
}

<commit_msg>Test multi_agent_async_execute_returning_default_container_executor with test_single_agent_then_execute.cpp.<commit_after>#include <agency/new_executor_traits.hpp>
#include <cassert>
#include <iostream>

#include "test_executors.hpp"

template<class Executor>
void test()
{
  using executor_type = Executor;

  {
    // void -> void
    executor_type exec;

    auto void_future = agency::when_all();

    int set_me_to_thirteen = 0;

    auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [&]
    {
      set_me_to_thirteen = 13;
    },
    void_future);

    f.wait();

    assert(set_me_to_thirteen == 13);
    assert(exec.valid());
  }

  {
    // void -> int
    executor_type exec;

    auto void_future = agency::when_all();

    auto f = agency::new_executor_traits<executor_type>::then_execute(exec, []
    {
      return 13;
    },
    void_future);

    assert(f.get() == 13);
    assert(exec.valid());
  }

  {
    // int -> void
    executor_type exec;

    auto int_future = agency::new_executor_traits<executor_type>::template make_ready_future<int>(exec, 13);

    int set_me_to_thirteen = 0;

    auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [&](int& x)
    {
      set_me_to_thirteen = x;
    },
    int_future);

    f.wait();

    assert(set_me_to_thirteen == 13);
    assert(exec.valid());
  }

  {
    // int -> float
    executor_type exec;

    auto int_future = agency::new_executor_traits<executor_type>::template make_ready_future<int>(exec, 13);

    auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [](int &x)
    {
      return float(x) + 1.f;
    },
    int_future);

    assert(f.get() == 14.f);
    assert(exec.valid());
  }
}

int main()
{
  using namespace test_executors;

  test<empty_executor>();
  test<single_agent_when_all_execute_and_select_executor>();
  test<multi_agent_when_all_execute_and_select_executor>();
  test<single_agent_then_execute_executor>();

  test<multi_agent_execute_returning_user_defined_container_executor>();
  test<multi_agent_execute_returning_default_container_executor>();
  test<multi_agent_execute_returning_void_executor>();

  test<multi_agent_async_execute_returning_user_defined_container_executor>();
  test<multi_agent_async_execute_returning_default_container_executor>();

  std::cout << "OK" << std::endl;

  return 0;
}

<|endoftext|>


<commit_before>#ifndef DKN_HPP_
#define DKN_HPP_
#include "basics.hpp"

#include <vector>
#include <flann/flann.hpp>

template <typename Distance>
std::vector<typename Distance::ResultType> DKN(
        flann::Index<Distance> &index,
        const flann::Matrix<typename Distance::ElementType> &query,
        int k = 3,
        const flann::SearchParams &search_params = flann::SearchParams())
{   /* Get the distances to the k-th nearest neighbor of each element in query
     * using the passed index and search params.
     */
    using std::vector;
    using flann::Matrix;

    typedef typename Distance::ResultType DistanceType;

    // matrices to store the results
    Matrix<int> indices(new int[query.rows*k], query.rows, k);
    Matrix<DistanceType> dists(new DistanceType[query.rows*k], query.rows, k);

    // build the index if necessary
    index.buildIndex();

    // search!
    index.knnSearch(query, indices, dists, k, search_params);

    // get out just the results we want
    vector<DistanceType> dkn;
    dkn.reserve(query.rows);
    for (size_t i = 0; i < query.rows; i++) {
        dkn.push_back(dists[i][k-1]);
    }

    delete[] indices.ptr();
    delete[] dists.ptr();

    return dkn;
}

#endif
<commit_msg>flann::L2 is the *squared* euclidean distance, silly<commit_after>#ifndef DKN_HPP_
#define DKN_HPP_
#include "basics.hpp"

#include <cmath>
#include <vector>
#include <flann/flann.hpp>

template <typename Distance>
std::vector<typename Distance::ResultType> DKN(
        flann::Index<Distance> &index,
        const flann::Matrix<typename Distance::ElementType> &query,
        int k = 3,
        const flann::SearchParams &search_params = flann::SearchParams(),
        bool take_sqrt = true)
{   /* Get the distances to the k-th nearest neighbor of each element in query
     * using the passed index and search params.
     *
     * Because flann::L2 is actually the squared Euclidean distance, this
     * function by default square-roots the results. Pass take_sqrt=false to
     * avoid this.
     * */
    using std::vector;
    using flann::Matrix;

    typedef typename Distance::ResultType DistanceType;

    // matrices to store the results
    Matrix<int> indices(new int[query.rows*k], query.rows, k);
    Matrix<DistanceType> dists(new DistanceType[query.rows*k], query.rows, k);

    // build the index if necessary
    index.buildIndex();

    // search!
    index.knnSearch(query, indices, dists, k, search_params);

    // get out just the results we want
    vector<DistanceType> dkn;
    dkn.reserve(query.rows);
    if (take_sqrt)
        for (size_t i = 0; i < query.rows; i++)
            dkn.push_back(std::sqrt(dists[i][k-1]));
    else
        for (size_t i = 0; i < query.rows; i++)
            dkn.push_back(dists[i][k-1]);

    delete[] indices.ptr();
    delete[] dists.ptr();

    return dkn;
}

#endif
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/Runtime/Metadata.h"
#include "swift/Demangling/ManglingMacros.h"

using namespace swift;

// Placeholders for Swift functions that the C++ runtime references
// but that the test code does not link to.

// AnyHashable

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_makeAnyHashableUsingDefaultRepresentation(
  const OpaqueValue *value,
  const void *anyHashableResultPointer,
  const Metadata *T,
  const WitnessTable *hashableWT
) {
  abort();
}

SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss11AnyHashableVMn[1] = {0};

// SwiftHashableSupport

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_stdlib_Hashable_isEqual_indirect(
  const void *lhsValue, const void *rhsValue, const Metadata *type,
  const void *wt) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
intptr_t _swift_stdlib_Hashable_hashValue_indirect(
  const void *value, const Metadata *type, const void *wt) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_convertToAnyHashableIndirect(
  OpaqueValue *source, OpaqueValue *destination, const Metadata *sourceType,
  const void *sourceConformance) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_anyHashableDownCastConditionalIndirect(
  OpaqueValue *source, OpaqueValue *destination, const Metadata *targetType) {
  abort();
}

// Casting

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_arrayDownCastIndirect(OpaqueValue *destination,
                                  OpaqueValue *source,
                                  const Metadata *sourceValueType,
                                  const Metadata *targetValueType) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_arrayDownCastConditionalIndirect(OpaqueValue *destination,
                                             OpaqueValue *source,
                                             const Metadata *sourceValueType,
                                             const Metadata *targetValueType) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_setDownCastIndirect(OpaqueValue *destination,
                                OpaqueValue *source,
                                const Metadata *sourceValueType,
                                const Metadata *targetValueType,
                                const void *sourceValueHashable,
                                const void *targetValueHashable) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_setDownCastConditionalIndirect(OpaqueValue *destination,
                                           OpaqueValue *source,
                                           const Metadata *sourceValueType,
                                           const Metadata *targetValueType,
                                           const void *sourceValueHashable,
                                           const void *targetValueHashable) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_dictionaryDownCastIndirect(OpaqueValue *destination,
                                       OpaqueValue *source,
                                       const Metadata *sourceKeyType,
                                       const Metadata *sourceValueType,
                                       const Metadata *targetKeyType,
                                       const Metadata *targetValueType,
                                       const void *sourceKeyHashable,
                                       const void *targetKeyHashable) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_dictionaryDownCastConditionalIndirect(OpaqueValue *destination,
                                        OpaqueValue *source,
                                        const Metadata *sourceKeyType,
                                        const Metadata *sourceValueType,
                                        const Metadata *targetKeyType,
                                        const Metadata *targetValueType,
                                        const void *sourceKeyHashable,
                                        const void *targetKeyHashable) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _bridgeNonVerbatimBoxedValue(const OpaqueValue *sourceValue,
                                  OpaqueValue *destValue,
                                  const Metadata *nativeType) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _bridgeNonVerbatimFromObjectiveCToAny(HeapObject *sourceValue,
                                           OpaqueValue *destValue) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool swift_unboxFromSwiftValueWithType(OpaqueValue *source,
                                       OpaqueValue *result,
                                       const Metadata *destinationType) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool swift_swiftValueConformsTo(const Metadata *destinationType) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_API
HeapObject *$ss27_bridgeAnythingToObjectiveCyyXlxlF(OpaqueValue *src, const Metadata *srcType) {
  abort();
}

// ErrorObject

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
int $ss13_getErrorCodeySiSPyxGs0B0RzlF(void *) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void *$ss23_getErrorDomainNSStringyyXlSPyxGs0B0RzlF(void *) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void *$ss29_getErrorUserInfoNSDictionaryyyXlSgSPyxGs0B0RzlF(void *) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void *$ss32_getErrorEmbeddedNSErrorIndirectyyXlSgSPyxGs0B0RzlF(void *) {
  abort();
}

// Hashable

SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $SkMp[1] = {0};

SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSHMp[1] = {0};

// Array

SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSaMn[1] = {0};

// Dictionary

SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ssSdVMn[1] = {0};

SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSDMn[1] = {0};

// Set

SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ssSeVMn[1] = {0};

SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sShMn[1] = {0};

// Mirror

// protocol witness table for Swift._ClassSuperMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss17_ClassSuperMirrorVs01_C0sWP[1] = {0};

// type metadata accessor for Swift._ClassSuperMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss17_ClassSuperMirrorVMa[1] = {0};

// protocol witness table for Swift._MetatypeMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss15_MetatypeMirrorVs01_B0sWP[1] = {0};

// type metadata accessor for Swift._MetatypeMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss15_MetatypeMirrorVMa[1] = {0};

// protocol witness table for Swift._EnumMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss11_EnumMirrorVs01_B0sWP[1] = {0};

// type metadata accessor for Swift._EnumMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss11_EnumMirrorVMa[1] = {0};

// protocol witness table for Swift._OpaqueMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss13_OpaqueMirrorVs01_B0sWP[1] = {0};

// type metadata accessor for Swift._OpaqueMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss13_OpaqueMirrorVMa[1] = {0};

// protocol witness table for Swift._StructMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss13_StructMirrorVs01_B0sWP[1] = {0};

// type metadata accessor for Swift._StructMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss13_StructMirrorVMa[1] = {0};

// protocol witness table for Swift._TupleMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss12_TupleMirrorVs01_B0sWP[1] = {0};

// type metadata accessor for Swift._TupleMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss12_TupleMirrorVMa[1] = {0};

// protocol witness table for Swift._ClassMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss12_ClassMirrorVs01_B0sWP[1] = {0};

// type metadata accessor for Swift._ClassMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss12_ClassMirrorVMa[1] = {0};

// KeyPath

SWIFT_RUNTIME_STDLIB_SPI
const HeapObject *swift_getKeyPathImpl(const void *p,
                                       const void *e,
                                       const void *a) {
  abort();
}

// playground print hook

struct swift_closure {
  void *fptr;
  HeapObject *context;
};
SWIFT_RUNTIME_STDLIB_API SWIFT_CC(swift) swift_closure
MANGLE_SYM(s20_playgroundPrintHookySScSgvg)() {
  return {nullptr, nullptr};
}

// ObjectiveC Bridgeable

SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss21_ObjectiveCBridgeableMp[1] = {0};

<commit_msg>tests: stub out more of the stdlib<commit_after>//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/Runtime/Metadata.h"
#include "swift/Demangling/ManglingMacros.h"

using namespace swift;

// Placeholders for Swift functions that the C++ runtime references
// but that the test code does not link to.

// AnyHashable

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_makeAnyHashableUsingDefaultRepresentation(
  const OpaqueValue *value,
  const void *anyHashableResultPointer,
  const Metadata *T,
  const WitnessTable *hashableWT
) {
  abort();
}

SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss11AnyHashableVMn[1] = {0};

// SwiftHashableSupport

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_stdlib_Hashable_isEqual_indirect(
  const void *lhsValue, const void *rhsValue, const Metadata *type,
  const void *wt) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
intptr_t _swift_stdlib_Hashable_hashValue_indirect(
  const void *value, const Metadata *type, const void *wt) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_convertToAnyHashableIndirect(
  OpaqueValue *source, OpaqueValue *destination, const Metadata *sourceType,
  const void *sourceConformance) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_anyHashableDownCastConditionalIndirect(
  OpaqueValue *source, OpaqueValue *destination, const Metadata *targetType) {
  abort();
}

// Casting

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_arrayDownCastIndirect(OpaqueValue *destination,
                                  OpaqueValue *source,
                                  const Metadata *sourceValueType,
                                  const Metadata *targetValueType) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_arrayDownCastConditionalIndirect(OpaqueValue *destination,
                                             OpaqueValue *source,
                                             const Metadata *sourceValueType,
                                             const Metadata *targetValueType) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_setDownCastIndirect(OpaqueValue *destination,
                                OpaqueValue *source,
                                const Metadata *sourceValueType,
                                const Metadata *targetValueType,
                                const void *sourceValueHashable,
                                const void *targetValueHashable) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_setDownCastConditionalIndirect(OpaqueValue *destination,
                                           OpaqueValue *source,
                                           const Metadata *sourceValueType,
                                           const Metadata *targetValueType,
                                           const void *sourceValueHashable,
                                           const void *targetValueHashable) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_dictionaryDownCastIndirect(OpaqueValue *destination,
                                       OpaqueValue *source,
                                       const Metadata *sourceKeyType,
                                       const Metadata *sourceValueType,
                                       const Metadata *targetKeyType,
                                       const Metadata *targetValueType,
                                       const void *sourceKeyHashable,
                                       const void *targetKeyHashable) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_dictionaryDownCastConditionalIndirect(OpaqueValue *destination,
                                        OpaqueValue *source,
                                        const Metadata *sourceKeyType,
                                        const Metadata *sourceValueType,
                                        const Metadata *targetKeyType,
                                        const Metadata *targetValueType,
                                        const void *sourceKeyHashable,
                                        const void *targetKeyHashable) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _bridgeNonVerbatimBoxedValue(const OpaqueValue *sourceValue,
                                  OpaqueValue *destValue,
                                  const Metadata *nativeType) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _bridgeNonVerbatimFromObjectiveCToAny(HeapObject *sourceValue,
                                           OpaqueValue *destValue) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool swift_unboxFromSwiftValueWithType(OpaqueValue *source,
                                       OpaqueValue *result,
                                       const Metadata *destinationType) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool swift_swiftValueConformsTo(const Metadata *destinationType) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_API
HeapObject *$ss27_bridgeAnythingToObjectiveCyyXlxlF(OpaqueValue *src, const Metadata *srcType) {
  abort();
}

// ErrorObject

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
int $ss13_getErrorCodeySiSPyxGs0B0RzlF(void *) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void *$ss23_getErrorDomainNSStringyyXlSPyxGs0B0RzlF(void *) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void *$ss29_getErrorUserInfoNSDictionaryyyXlSgSPyxGs0B0RzlF(void *) {
  abort();
}

SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void *$ss32_getErrorEmbeddedNSErrorIndirectyyXlSgSPyxGs0B0RzlF(void *) {
  abort();
}

// Hashable

SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $SkMp[1] = {0};

SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSHMp[1] = {0};

// Array

SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSaMn[1] = {0};

// Dictionary

SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ssSdVMn[1] = {0};

SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sSDMn[1] = {0};

// Set

SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ssSeVMn[1] = {0};

SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $sShMn[1] = {0};

// Mirror

// protocol witness table for Swift._ClassSuperMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss17_ClassSuperMirrorVs01_C0sWP[1] = {0};

// type metadata accessor for Swift._ClassSuperMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss17_ClassSuperMirrorVMa[1] = {0};

// protocol witness table for Swift._MetatypeMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss15_MetatypeMirrorVs01_B0sWP[1] = {0};

// type metadata accessor for Swift._MetatypeMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss15_MetatypeMirrorVMa[1] = {0};

// protocol witness table for Swift._EnumMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss11_EnumMirrorVs01_B0sWP[1] = {0};

// type metadata accessor for Swift._EnumMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss11_EnumMirrorVMa[1] = {0};

// protocol witness table for Swift._OpaqueMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss13_OpaqueMirrorVs01_B0sWP[1] = {0};

// type metadata accessor for Swift._OpaqueMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss13_OpaqueMirrorVMa[1] = {0};

// protocol witness table for Swift._StructMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss13_StructMirrorVs01_B0sWP[1] = {0};

// type metadata accessor for Swift._StructMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss13_StructMirrorVMa[1] = {0};

// protocol witness table for Swift._TupleMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss12_TupleMirrorVs01_B0sWP[1] = {0};

// type metadata accessor for Swift._TupleMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss12_TupleMirrorVMa[1] = {0};

// protocol witness table for Swift._ClassMirror : Swift._Mirror in Swift
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss12_ClassMirrorVs01_B0sWP[1] = {0};

// type metadata accessor for Swift._ClassMirror
SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss12_ClassMirrorVMa[1] = {0};

// KeyPath

SWIFT_RUNTIME_STDLIB_SPI
const HeapObject *swift_getKeyPathImpl(const void *p,
                                       const void *e,
                                       const void *a) {
  abort();
}

// playground print hook

struct swift_closure {
  void *fptr;
  HeapObject *context;
};
SWIFT_RUNTIME_STDLIB_API SWIFT_CC(swift) swift_closure
MANGLE_SYM(s20_playgroundPrintHookySScSgvg)() {
  return {nullptr, nullptr};
}

// ObjectiveC Bridgeable

SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss21_ObjectiveCBridgeableMp[1] = {0};

// Key Path

SWIFT_RUNTIME_STDLIB_INTERNAL
const long long $ss7KeyPathCMo[1] = {0};

<|endoftext|>


<commit_before><commit_msg>Fix enabling timelineSemaphore feature<commit_after><|endoftext|>


<commit_before>/*
 *  qi_rfprofile.cpp
 *
 *  Copyright (c) 2017 Tobias Wood.
 *
 *  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/.
 *
 */

#include "Eigen/Core"

#include <unsupported/Eigen/Splines>

#include "Args.h"
#include "ImageIO.h"
#include "ImageTypes.h"
#include "JSON.h"
#include "Monitor.h"
#include "Spline.h"
#include "Util.h"
#include "itkImageMomentsCalculator.h"
#include "itkImageSliceIteratorWithIndex.h"
#include "itkImageSource.h"

namespace itk {

class ProfileImage : public ImageSource<QI::VolumeF> {
  public:
    using Self       = ProfileImage;
    using Superclass = ImageSource<QI::VectorVolumeF>;
    using TRegion    = QI::VectorVolumeF::RegionType;
    using Pointer    = SmartPointer<Self>;

    itkNewMacro(Self);
    itkTypeMacro(Self, ImageSource);

    void SetReference(const SmartPointer<QI::VolumeF> ref) { m_reference = ref; }
    void SetDebug(const bool d) { m_debug = d; }
    void SetDim(const int d) {
        if ((m_dim < 0) || (m_dim > 2)) {
            QI::Fail("Invalid dimension for RF profile, must be 0-2");
        }
        m_dim = d;
    }
    void SetRF(const Eigen::ArrayXd pos, const Eigen::ArrayXd vals) {
        m_spline = QI::SplineInterpolator(pos, vals);
        QI::Log(m_debug, "{}", m_spline);
    }

    void SetMask(const QI::VolumeF *mask) { this->SetNthInput(1, const_cast<QI::VolumeF *>(mask)); }
    void SetCenterMask(const bool cm) { this->m_centerMask = cm; }
    typename QI::VolumeF::ConstPointer GetMask() const {
        return static_cast<const QI::VolumeF *>(this->ProcessObject::GetInput(1));
    }

    void GenerateOutputInformation() ITK_OVERRIDE {
        auto output = this->GetOutput();
        output->SetRegions(m_reference->GetLargestPossibleRegion());
        output->SetSpacing(m_reference->GetSpacing());
        output->SetDirection(m_reference->GetDirection());
        output->SetOrigin(m_reference->GetOrigin());
        output->Allocate();
    }

  protected:
    SmartPointer<QI::VolumeF> m_reference;
    QI::SplineInterpolator    m_spline;
    bool                      m_debug = false, m_centerMask = false;
    int                       m_dim = 0;

    ProfileImage() {}
    ~ProfileImage() {}
    void DynamicThreadedGenerateData(const TRegion &region) ITK_OVERRIDE {
        auto                                     output = this->GetOutput();
        ImageSliceIteratorWithIndex<QI::VolumeF> imageIt(output, region);
        imageIt.SetFirstDirection((m_dim + 1) % 3);
        imageIt.SetSecondDirection((m_dim + 2) % 3);
        imageIt.GoToBegin();
        ImageSliceIteratorWithIndex<QI::VolumeF> it_B1(m_reference, region);
        it_B1.SetFirstDirection((m_dim + 1) % 3);
        it_B1.SetSecondDirection((m_dim + 2) % 3);
        it_B1.GoToBegin();

        const auto                                    mask = this->GetMask();
        ImageSliceConstIteratorWithIndex<QI::VolumeF> maskIter;
        if (mask) {
            maskIter = ImageSliceConstIteratorWithIndex<QI::VolumeF>(mask, region);
            maskIter.SetFirstDirection(0);
            maskIter.SetSecondDirection(1);
            maskIter.GoToBegin();
        }

        QI::VectorVolumeF::PointType pt_center;
        if (mask && m_centerMask) {
            auto moments = itk::ImageMomentsCalculator<QI::VolumeF>::New();
            moments->SetImage(mask);
            moments->Compute();
            QI::Log(m_debug, "Mask CoG is: {}", moments->GetCenterOfGravity());
            pt_center = moments->GetCenterOfGravity();
        } else {
            // Calculate geometric center
            QI::VectorVolumeF::IndexType idx_center;
            for (int i = 0; i < 3; i++) {
                idx_center[i] = m_reference->GetLargestPossibleRegion().GetSize()[i] / 2;
            }
            m_reference->TransformIndexToPhysicalPoint(idx_center, pt_center);
        }

        while (!imageIt.IsAtEnd()) {
            QI::VectorVolumeF::PointType pt, pt_rf;
            m_reference->TransformIndexToPhysicalPoint(imageIt.GetIndex(), pt);
            pt_rf     = pt - pt_center;
            float val = m_spline(pt_rf[m_dim]);
            QI::Log(m_debug,
                    "Slice co-ordinate: {} Spline Point: {} Value: {}",
                    pt_rf,
                    pt_rf[m_dim],
                    val);
            while (!imageIt.IsAtEndOfSlice()) {
                while (!imageIt.IsAtEndOfLine()) {
                    if (!mask || maskIter.Get()) {
                        imageIt.Set(val * it_B1.Get());
                    } else {
                        imageIt.Set(0.);
                    }
                    ++imageIt;
                    ++it_B1;
                    if (mask) {
                        ++maskIter;
                    }
                }
                imageIt.NextLine();
                it_B1.NextLine();
                if (mask)
                    maskIter.NextLine();
            }
            imageIt.NextSlice();
            it_B1.NextSlice();
            if (mask) {
                maskIter.NextSlice();
            }
        }
    }

  private:
    ProfileImage(const Self &);
    void operator=(const Self &);
};

} // End namespace itk

int main(int argc, char **argv) {
    Eigen::initParallel();
    args::ArgumentParser parser("Generates a relative B1 map from a B1+ and RF profile.\nInput is "
                                "the B1+ map.\nhttp://github.com/spinicist/QUIT");
    args::Positional<std::string> b1plus_path(parser, "B1+_FILE", "Input B1+ file");
    args::Positional<std::string> output_path(parser, "B1_FILE", "Output relative B1 file");

    args::HelpFlag       help(parser, "HELP", "Show this help menu", {'h', "help"});
    args::Flag           verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"});
    args::ValueFlag<int> threads(parser,
                                 "THREADS",
                                 "Use N threads (default=4, 0=hardware limit)",
                                 {'T', "threads"},
                                 QI::GetDefaultThreads());
    args::ValueFlag<std::string> mask(
        parser, "MASK", "Only process voxels within the mask", {'m', "mask"});
    args::Flag                   centerMask(parser,
                          "CENTER ON MASK",
                          "Set the center of the slab to the center of the mask",
                          {'c', "center"});
    args::ValueFlag<std::string> subregion(
        parser,
        "REGION",
        "Process subregion starting at voxel I,J,K with size SI,SJ,SK",
        {'s', "subregion"});
    args::ValueFlag<int> dimension(
        parser, "DIMENSION", "Which dimension to calculate the profile over", {"dim"}, 2);
    args::ValueFlag<std::string> infile(
        parser, "FILE", "Read JSON input from file instead of stdin", {"json"});
    QI::ParseArgs(parser, argc, argv, verbose, threads);

    auto reference = QI::ReadImage(QI::CheckPos(b1plus_path), verbose);

    QI::Log(verbose, "Reading slab profile");
    json input   = infile ? QI::ReadJSON(infile.Get()) : QI::ReadJSON(std::cin);
    auto rf_pos  = QI::ArrayFromJSON(input, "rf_pos");
    auto rf_vals = QI::ArrayFromJSON(input, "rf_vals");

    QI::Log(verbose, "Profile points = {}", rf_pos.rows());
    QI::Log(verbose, "Generating image...");
    auto image = itk::ProfileImage::New();
    image->SetReference(reference);
    image->SetRF(rf_pos, rf_vals);
    image->SetDim(dimension.Get());
    image->SetCenterMask(centerMask);
    image->SetDebug(true);
    if (mask)
        image->SetMask(QI::ReadImage(mask.Get(), verbose));
    if (verbose) {
        auto monitor = QI::GenericMonitor::New();
        image->AddObserver(itk::ProgressEvent(), monitor);
    }
    image->Update();
    QI::WriteImage(image->GetOutput(), QI::CheckPos(output_path), verbose);
    return EXIT_SUCCESS;
}
<commit_msg>BUG Fixes RF profiles for obliqued images<commit_after>/*
 *  qi_rfprofile.cpp
 *
 *  Copyright (c) 2017 Tobias Wood.
 *
 *  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/.
 *
 */

#include "Eigen/Core"

#include <unsupported/Eigen/Splines>

#include "Args.h"
#include "ImageIO.h"
#include "ImageTypes.h"
#include "JSON.h"
#include "Monitor.h"
#include "Spline.h"
#include "Util.h"
#include "itkImageMomentsCalculator.h"
#include "itkImageSliceIteratorWithIndex.h"
#include "itkImageSource.h"

namespace itk {

class ProfileImage : public ImageSource<QI::VolumeF> {
  public:
    using Self       = ProfileImage;
    using Superclass = ImageSource<QI::VectorVolumeF>;
    using TRegion    = QI::VectorVolumeF::RegionType;
    using Pointer    = SmartPointer<Self>;

    itkNewMacro(Self);
    itkTypeMacro(Self, ImageSource);

    void SetReference(const SmartPointer<QI::VolumeF> ref) { m_reference = ref; }
    void SetDebug(const bool d) { m_debug = d; }
    void SetDim(const int d) {
        if ((m_dim < 0) || (m_dim > 2)) {
            QI::Fail("Invalid dimension for RF profile, must be 0-2");
        }
        m_dim = d;
    }
    void SetRF(const Eigen::ArrayXd pos, const Eigen::ArrayXd vals) {
        m_spline = QI::SplineInterpolator(pos, vals);
        QI::Log(m_debug, "{}", m_spline);
    }

    void SetMask(const QI::VolumeF *mask) { this->SetNthInput(1, const_cast<QI::VolumeF *>(mask)); }
    void SetCenterMask(const bool cm) { this->m_centerMask = cm; }
    typename QI::VolumeF::ConstPointer GetMask() const {
        return static_cast<const QI::VolumeF *>(this->ProcessObject::GetInput(1));
    }

    void GenerateOutputInformation() ITK_OVERRIDE {
        auto output = this->GetOutput();
        output->SetRegions(m_reference->GetLargestPossibleRegion());
        output->SetSpacing(m_reference->GetSpacing());
        output->SetDirection(m_reference->GetDirection());
        output->SetOrigin(m_reference->GetOrigin());
        output->Allocate();
    }

  protected:
    SmartPointer<QI::VolumeF> m_reference;
    QI::SplineInterpolator    m_spline;
    bool                      m_debug = false, m_centerMask = false;
    int                       m_dim = 0;

    ProfileImage() {}
    ~ProfileImage() {}
    void DynamicThreadedGenerateData(const TRegion &region) ITK_OVERRIDE {
        auto const output = this->GetOutput();
        auto const mask   = this->GetMask();
        auto const dim1   = (m_dim + 1) % 3;
        auto const dim2   = (m_dim + 2) % 3;

        ImageSliceIteratorWithIndex<QI::VolumeF> imageIt(output, region);
        imageIt.SetFirstDirection(dim1);
        imageIt.SetSecondDirection(dim2);

        ImageSliceIteratorWithIndex<QI::VolumeF> it_B1(m_reference, region);
        it_B1.SetFirstDirection(dim1);
        it_B1.SetSecondDirection(dim2);

        ImageSliceConstIteratorWithIndex<QI::VolumeF> maskIter;
        if (mask) {
            maskIter = ImageSliceConstIteratorWithIndex<QI::VolumeF>(mask, region);
            maskIter.SetFirstDirection(dim1);
            maskIter.SetSecondDirection(dim2);
            maskIter.GoToBegin();
        }

        QI::VectorVolumeF::PointType pt_center;
        if (mask && m_centerMask) {
            auto moments = itk::ImageMomentsCalculator<QI::VolumeF>::New();
            moments->SetImage(mask);
            moments->Compute();
            QI::Log(m_debug, "Mask CoG is: {}", moments->GetCenterOfGravity());
            pt_center = moments->GetCenterOfGravity();
        } else {
            // Calculate geometric center
            QI::VectorVolumeF::IndexType idx_center;
            for (int i = 0; i < 3; i++) {
                idx_center[i] = m_reference->GetLargestPossibleRegion().GetSize()[i] / 2;
            }
            m_reference->TransformIndexToPhysicalPoint(idx_center, pt_center);
        }

        // Now get physical space index to deal with obliqued scans
        QI::VectorVolumeF::IndexType index1, index2;
        index1.Fill(0);
        index2.Fill(0);
        index2[m_dim] = 1;
        QI::VectorVolumeF::PointType pt1, pt2;
        m_reference->TransformIndexToPhysicalPoint(index1, pt1);
        m_reference->TransformIndexToPhysicalPoint(index2, pt2);
        auto const diff     = pt2 - pt1;
        int        phys_dim = 0;
        if (fabs(diff[1]) > fabs(diff[0])) {
            if (fabs(diff[2]) > fabs(diff[1])) {
                phys_dim = 2;
            }
            phys_dim = 1;
        }
        QI::Log(m_debug, "Physical dimension: {}", phys_dim);

        while (!imageIt.IsAtEnd()) {
            QI::VectorVolumeF::PointType pt, pt_rf;
            m_reference->TransformIndexToPhysicalPoint(imageIt.GetIndex(), pt);
            pt_rf     = pt - pt_center;
            float val = m_spline(pt_rf[phys_dim]);
            QI::Log(m_debug, "Absolute co-ord: {} Relative co-ord: {} Value: {}", pt, pt_rf, val);
            while (!imageIt.IsAtEndOfSlice()) {
                while (!imageIt.IsAtEndOfLine()) {
                    if (!mask || maskIter.Get()) {
                        imageIt.Set(val * it_B1.Get());
                    } else {
                        imageIt.Set(0.);
                    }
                    ++imageIt;
                    ++it_B1;
                    if (mask) {
                        ++maskIter;
                    }
                }
                imageIt.NextLine();
                it_B1.NextLine();
                if (mask)
                    maskIter.NextLine();
            }
            imageIt.NextSlice();
            it_B1.NextSlice();
            if (mask) {
                maskIter.NextSlice();
            }
        }
    }

  private:
    ProfileImage(const Self &);
    void operator=(const Self &);
};

} // End namespace itk

int main(int argc, char **argv) {
    Eigen::initParallel();
    args::ArgumentParser parser("Generates a relative B1 map from a B1+ and RF profile.\nInput is "
                                "the B1+ map.\nhttp://github.com/spinicist/QUIT");
    args::Positional<std::string> b1plus_path(parser, "B1+_FILE", "Input B1+ file");
    args::Positional<std::string> output_path(parser, "B1_FILE", "Output relative B1 file");

    args::HelpFlag       help(parser, "HELP", "Show this help menu", {'h', "help"});
    args::Flag           verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"});
    args::ValueFlag<int> threads(parser,
                                 "THREADS",
                                 "Use N threads (default=4, 0=hardware limit)",
                                 {'T', "threads"},
                                 QI::GetDefaultThreads());
    args::ValueFlag<std::string> mask(
        parser, "MASK", "Only process voxels within the mask", {'m', "mask"});
    args::Flag                   centerMask(parser,
                          "CENTER ON MASK",
                          "Set the center of the slab to the center of the mask",
                          {'c', "center"});
    args::ValueFlag<std::string> subregion(
        parser,
        "REGION",
        "Process subregion starting at voxel I,J,K with size SI,SJ,SK",
        {'s', "subregion"});
    args::ValueFlag<int> dimension(
        parser, "DIMENSION", "Which dimension to calculate the profile over", {"dim"}, 2);
    args::ValueFlag<std::string> infile(
        parser, "FILE", "Read JSON input from file instead of stdin", {"json"});
    QI::ParseArgs(parser, argc, argv, verbose, threads);

    auto reference = QI::ReadImage(QI::CheckPos(b1plus_path), verbose);

    QI::Log(verbose, "Reading slab profile");
    json input   = infile ? QI::ReadJSON(infile.Get()) : QI::ReadJSON(std::cin);
    auto rf_pos  = QI::ArrayFromJSON(input, "rf_pos");
    auto rf_vals = QI::ArrayFromJSON(input, "rf_vals");

    QI::Log(verbose, "Profile points = {}", rf_pos.rows());
    QI::Log(verbose, "Generating image...");
    auto image = itk::ProfileImage::New();
    image->SetReference(reference);
    image->SetRF(rf_pos, rf_vals);
    image->SetDim(dimension.Get());
    image->SetDebug(verbose);
    if (mask) {
        image->SetMask(QI::ReadImage(mask.Get(), verbose));
        image->SetCenterMask(centerMask);
    }
    if (verbose) {
        auto monitor = QI::GenericMonitor::New();
        image->AddObserver(itk::ProgressEvent(), monitor);
    }
    image->Update();
    QI::WriteImage(image->GetOutput(), QI::CheckPos(output_path), verbose);
    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include "../include/rapid-cxx-test/unit_test.hpp"

TEST_SUITE(basic_example)

TEST_CASE(compiler_not_useless)
{
    int x = 0;
    AT_RTIME_EQ(x, 0);
    x = 1;
    AT_RTIME_EQ(x, 1);
}

TEST_SUITE_END()
<commit_msg>remove old example<commit_after><|endoftext|>


<commit_before>// @(#)root/gui:$Name:  $:$Id: TGIcon.cxx,v 1.11 2006/04/24 13:51:06 antcheva Exp $
// Author: Fons Rademakers   05/01/98

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/
/**************************************************************************

    This source is based on Xclass95, a Win95-looking GUI toolkit.
    Copyright (C) 1996, 1997 David Barth, Ricky Ralston, Hector Peraza.

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

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

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TGIcon                                                               //
//                                                                      //
// This class handles GUI icons.                                        //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TGIcon.h"
#include "TGPicture.h"
#include "TSystem.h"
#include "TImage.h"
#include "Riostream.h"
#include "TMath.h"
#include "TGFileDialog.h"
#include "TGMsgBox.h"
#include "TVirtualDragManager.h"

ClassImp(TGIcon)

//______________________________________________________________________________
TGIcon::TGIcon(const TGWindow *p, const char *image) : TGFrame(p, 1, 1)
{
   // Create icon.

   fPic = 0;
   char *path;

   if (!image) {
      const char *rootsys = gSystem->ExpandPathName("$ROOTSYS");
      path = gSystem->ConcatFileName(rootsys, "icons/bld_rgb.xpm");
   }
   fPath = gSystem->DirName(path);

   fImage = TImage::Open(path);
   fPic = fClient->GetPicturePool()->GetPicture(Form("%s_%dx%d", gSystem->BaseName(path),
                                                fImage->GetWidth(), fImage->GetHeight()),
                                                fImage->GetPixmap(), fImage->GetMask());
   TGFrame::Resize(fImage->GetWidth(), fImage->GetHeight());
   SetWindowName();
   delete path;
}

//______________________________________________________________________________
TGIcon::~TGIcon()
{
   // Delete icon and free picture.

   if (fPic) fClient->FreePicture(fPic);
}

//______________________________________________________________________________
void TGIcon::SetPicture(const TGPicture *pic)
{
   // Set icon picture.

   fPic = pic;
   gVirtualX->ClearWindow(fId);
   fClient->NeedRedraw(this);
}

//______________________________________________________________________________
void TGIcon::SetImage(const char *img)
{
   // Set icon image.

   //delete fImage;
   TImage *i = TImage::Open(img);
   fPath = gSystem->DirName(img);

   SetImage(i);
}

//______________________________________________________________________________
void TGIcon::SetImage(TImage *img)
{
   // Change icon image.

   if (!img) {
      return;
   }

   //delete fImage;  !! mem.leak!!
   fImage = img;
   Resize(fImage->GetWidth(), fImage->GetHeight());
}

//______________________________________________________________________________
TGDimension TGIcon::GetDefaultSize() const
{
   // Return size of icon.

   return TGDimension((fPic) ? fPic->GetWidth()  : fWidth,
                      (fPic) ? fPic->GetHeight() : fHeight);
}

//______________________________________________________________________________
void TGIcon::DoRedraw()
{
   // Redraw picture.

   Bool_t border = (GetOptions() & kRaisedFrame) ||
                   (GetOptions() & kSunkenFrame) ||
                   (GetOptions() & kDoubleBorder);

   if (fPic) fPic->Draw(fId, GetBckgndGC()(), border, border);
   DrawBorder();
}

//______________________________________________________________________________
void TGIcon::Resize(UInt_t w, UInt_t h)
{
   // Resize.

   //if (fImage && (TMath::Abs(Int_t(fImage->GetWidth() - w)) < 5) &&
   //    (TMath::Abs(Int_t(fImage->GetHeight() - h)) < 5)) {
   //   return;
   //}

   gVirtualX->ClearWindow(fId);
   TGFrame::Resize(w, h);

   if (!fImage) {
      fImage = TImage::Create();
      if (fPic) fImage->SetImage(fPic->GetPicture(), fPic->GetMask());
   }
   if (fPic) {
      fClient->FreePicture(fPic);
   }
   Bool_t border = (GetOptions() & kRaisedFrame) ||
                   (GetOptions() & kSunkenFrame) ||
                   (GetOptions() & kDoubleBorder);

   fImage->Scale(w - 2*border, h - 2*border);
   fPic = fClient->GetPicturePool()->GetPicture(Form("%s_%dx%d", fImage->GetName(),
                                                fImage->GetWidth(), fImage->GetHeight()),
                                                fImage->GetPixmap(), fImage->GetMask());
   fClient->NeedRedraw(this);
}

//______________________________________________________________________________
void TGIcon::MoveResize(Int_t x, Int_t y, UInt_t w, UInt_t h)
{
   // Move icon to (x,y) and resize it to (w,h).

   Move(x, y);
   Resize(w, h);
}

//______________________________________________________________________________
void TGIcon::Reset()
{
   // Reset icon to original image. It can be used only via context menu.

   if (!fImage || !fClient->IsEditable()) return;

   TString name = fImage->GetName();
   name.Chop();
   char *path = gSystem->ConcatFileName(fPath.Data(), name.Data());
   SetImage(path);

   delete path;
}

//______________________________________________________________________________
void TGIcon::ChangeImage()
{
   // Invoke file dialog to assign a new image.

   static const char *gImageTypes[] = {"XPM",     "*.xpm",
                                       "GIF",     "*.gif",
                                       "PNG",     "*.png",
                                       "JPEG",    "*.jpg",
                                       "TARGA",   "*.tga",
                                       "ICO",     "*.ico",
                                       "XCF",     "*.xcf",
                                       "CURSORS", "*.cur",
                                       "PPM",     "*.ppm",
                                       "PNM",     "*.pnm",
                                       "XBM",     "*.xbm",
                                       "TIFF",    "*.tiff",
                                       "BMP",     "*.bmp",
                                       "Enacapsulated PostScript", "*.eps",
                                       "PostScript", "*.ps",
                                       "PDF",        "*.pdf",
                                       "ASImage XML","*.xml",
                                       "All files",  "*",
                                        0,             0 };

   TGFileInfo fi;
   static TString dir(".");
   static Bool_t overwr = kFALSE;
   const char *fname;

   fi.fFileTypes = gImageTypes;
   fi.fIniDir    = StrDup(dir);
   fi.fOverwrite = overwr;

   TGWindow *root = (TGWindow*)fClient->GetRoot();
   gDragManager->SetEditable(kFALSE);

   new TGFileDialog(fClient->GetDefaultRoot(), this, kFDOpen, &fi);

   if (!fi.fFilename) {
      root->SetEditable(kTRUE);
      gDragManager->SetEditable(kTRUE);
      return;
   }

   dir    = fi.fIniDir;
   overwr = fi.fOverwrite;
   fname  = fi.fFilename;

   fImage = TImage::Open(fname);

   if (!fImage) {
      Int_t retval;
      new TGMsgBox(fClient->GetDefaultRoot(), this, "Error...",
                   Form("Cannot read image file (%s)", fname),
                   kMBIconExclamation, kMBRetry | kMBCancel, &retval);

      if (retval == kMBRetry) {
         ChangeImage();
      }
   } else {
      SetImage(fImage);
   }
   root->SetEditable(kTRUE);
   gDragManager->SetEditable(kTRUE);
}

//______________________________________________________________________________
void TGIcon::SavePrimitive(ofstream &out, Option_t *option)
{
    // Save an icon widget as a C++ statement(s) on output stream out.

   char quote = '"';

   if (fBackground != GetDefaultFrameBackground()) SaveUserColor(out, option);

   if (!fPic) {
      Error("SavePrimitive()", "icon pixmap not found ");
      return;
   }

   const char *picname = fPic->GetName();

   out <<"   TGIcon *";
   out << GetName() << " = new TGIcon(" << fParent->GetName()
       << ",gClient->GetPicture(" << quote
       << gSystem->ExpandPathName(gSystem->UnixPathName(picname))                       // if no path
       << quote << ")" << "," << GetWidth() << "," << GetHeight();

   if (fBackground == GetDefaultFrameBackground()) {
      if (!GetOptions()) {
         out <<");" << endl;
      } else {
         out << "," << GetOptionString() <<");" << endl;
      }
   } else {
      out << "," << GetOptionString() << ",ucolor);" << endl;
   }
}
<commit_msg>From Bertrand: - Fix TGIcon layout problem introduced recently<commit_after>// @(#)root/gui:$Name:  $:$Id: TGIcon.cxx,v 1.12 2006/04/25 08:47:30 antcheva Exp $
// Author: Fons Rademakers   05/01/98

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/
/**************************************************************************

    This source is based on Xclass95, a Win95-looking GUI toolkit.
    Copyright (C) 1996, 1997 David Barth, Ricky Ralston, Hector Peraza.

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

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

//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TGIcon                                                               //
//                                                                      //
// This class handles GUI icons.                                        //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TGIcon.h"
#include "TGPicture.h"
#include "TSystem.h"
#include "TImage.h"
#include "Riostream.h"
#include "TMath.h"
#include "TGFileDialog.h"
#include "TGMsgBox.h"
#include "TVirtualDragManager.h"

ClassImp(TGIcon)

//______________________________________________________________________________
TGIcon::TGIcon(const TGWindow *p, const char *image) : TGFrame(p, 1, 1)
{
   // Create icon.

   fPic = 0;
   char *path;

   if (!image) {
      const char *rootsys = gSystem->ExpandPathName("$ROOTSYS");
      path = gSystem->ConcatFileName(rootsys, "icons/bld_rgb.xpm");
   } else {
      path = strdup(image);
   }
   fPath = gSystem->DirName(path);

   fImage = TImage::Open(path);
   fPic = fClient->GetPicturePool()->GetPicture(gSystem->BaseName(path),
                                                fImage->GetPixmap(), fImage->GetMask());
   TGFrame::Resize(fImage->GetWidth(), fImage->GetHeight());
   SetWindowName();
   delete path;
}

//______________________________________________________________________________
TGIcon::~TGIcon()
{
   // Delete icon and free picture.

   if (fPic) fClient->FreePicture(fPic);
}

//______________________________________________________________________________
void TGIcon::SetPicture(const TGPicture *pic)
{
   // Set icon picture.

   fPic = pic;
   gVirtualX->ClearWindow(fId);
   fClient->NeedRedraw(this);
}

//______________________________________________________________________________
void TGIcon::SetImage(const char *img)
{
   // Set icon image.

   //delete fImage;
   TImage *i = TImage::Open(img);
   fPath = gSystem->DirName(img);

   SetImage(i);
}

//______________________________________________________________________________
void TGIcon::SetImage(TImage *img)
{
   // Change icon image.

   if (!img) {
      return;
   }

   //delete fImage;  !! mem.leak!!
   fImage = img;
   Resize(fImage->GetWidth(), fImage->GetHeight());
}

//______________________________________________________________________________
TGDimension TGIcon::GetDefaultSize() const
{
   // Return size of icon.

   return TGDimension((fPic) ? fPic->GetWidth()  : fWidth,
                      (fPic) ? fPic->GetHeight() : fHeight);
}

//______________________________________________________________________________
void TGIcon::DoRedraw()
{
   // Redraw picture.

   Bool_t border = (GetOptions() & kRaisedFrame) ||
                   (GetOptions() & kSunkenFrame) ||
                   (GetOptions() & kDoubleBorder);

   if (fPic) fPic->Draw(fId, GetBckgndGC()(), border, border);
   if (border)  DrawBorder();
}

//______________________________________________________________________________
void TGIcon::Resize(UInt_t w, UInt_t h)
{
   // Resize.

   TGFrame::Resize(w, h);

   // allow dynamic resize of icon during guibuilding
   if (!fClient->IsEditable()) {
      return;
   }
   gVirtualX->ClearWindow(fId);

   if (!fImage) {
      fImage = TImage::Create();
      if (fPic) {
         fImage->SetName(fPic->GetName());
         fImage->SetImage(fPic->GetPicture(), fPic->GetMask());
      }
   }
   if (fPic) {
      fClient->FreePicture(fPic);
   }
   Bool_t border = (GetOptions() & kRaisedFrame) ||
                   (GetOptions() & kSunkenFrame) ||
                   (GetOptions() & kDoubleBorder);

   fImage->Scale(w - 2*border, h - 2*border);
   fPic = fClient->GetPicturePool()->GetPicture(fImage->GetName(),
                                                fImage->GetPixmap(), fImage->GetMask());
   fClient->NeedRedraw(this);
}

//______________________________________________________________________________
void TGIcon::MoveResize(Int_t x, Int_t y, UInt_t w, UInt_t h)
{
   // Move icon to (x,y) and resize it to (w,h).

   Move(x, y);
   Resize(w, h);
}

//______________________________________________________________________________
void TGIcon::Reset()
{
   // Reset icon to original image. It can be used only via context menu.

   if (!fImage || !fClient->IsEditable()) return;

   TString name = fImage->GetName();
   name.Chop();
   char *path = gSystem->ConcatFileName(fPath.Data(), name.Data());
   SetImage(path);

   delete path;
}

//______________________________________________________________________________
void TGIcon::ChangeImage()
{
   // Invoke file dialog to assign a new image.
   // This method is activated via context menu during guibuilding.

   static const char *gImageTypes[] = {"All files", "*",
                                       "XPM",     "*.xpm",
                                       "GIF",     "*.gif",
                                       "PNG",     "*.png",
                                       "JPEG",    "*.jpg",
                                       "TARGA",   "*.tga",
                                       "BMP",     "*.bmp",
                                       "ICO",     "*.ico",
                                       "XCF",     "*.xcf",
                                       "CURSORS", "*.cur",
                                       "PPM",     "*.ppm",
                                       "PNM",     "*.pnm",
                                       "XBM",     "*.xbm",
                                       "TIFF",    "*.tiff",
                                       "Enacapsulated PostScript", "*.eps",
                                       "PostScript", "*.ps",
                                       "PDF",        "*.pdf",
                                       "ASImage XML","*.xml",
                                        0,             0 };

   TGFileInfo fi;
   static TString dir(".");
   static Bool_t overwr = kFALSE;
   const char *fname;

   fi.fFileTypes = gImageTypes;
   fi.fIniDir    = StrDup(dir);
   fi.fOverwrite = overwr;

   TGWindow *root = (TGWindow*)fClient->GetRoot();
   gDragManager->SetEditable(kFALSE);

   new TGFileDialog(fClient->GetDefaultRoot(), this, kFDOpen, &fi);

   if (!fi.fFilename) {
      root->SetEditable(kTRUE);
      gDragManager->SetEditable(kTRUE);
      return;
   }

   dir    = fi.fIniDir;
   overwr = fi.fOverwrite;
   fname  = fi.fFilename;

   fImage = TImage::Open(fname);

   if (!fImage) {
      Int_t retval;
      new TGMsgBox(fClient->GetDefaultRoot(), this, "Error...",
                   Form("Cannot read image file (%s)", fname),
                   kMBIconExclamation, kMBRetry | kMBCancel, &retval);

      if (retval == kMBRetry) {
         ChangeImage();
      }
   } else {
      SetImage(fImage);
   }
   root->SetEditable(kTRUE);
   gDragManager->SetEditable(kTRUE);
}

//______________________________________________________________________________
void TGIcon::SavePrimitive(ofstream &out, Option_t *option)
{
    // Save an icon widget as a C++ statement(s) on output stream out.

   char quote = '"';

   if (fBackground != GetDefaultFrameBackground()) SaveUserColor(out, option);

   if (!fPic) {
      Error("SavePrimitive()", "icon pixmap not found ");
      return;
   }

   const char *picname = fPic->GetName();

   out <<"   TGIcon *";
   out << GetName() << " = new TGIcon(" << fParent->GetName()
       << ",gClient->GetPicture(" << quote
       << gSystem->ExpandPathName(gSystem->UnixPathName(picname))                       // if no path
       << quote << ")" << "," << GetWidth() << "," << GetHeight();

   if (fBackground == GetDefaultFrameBackground()) {
      if (!GetOptions()) {
         out <<");" << endl;
      } else {
         out << "," << GetOptionString() <<");" << endl;
      }
   } else {
      out << "," << GetOptionString() << ",ucolor);" << endl;
   }
}
<|endoftext|>


<commit_before>/*
Copyright (C) 2020 The Falco Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include <json/json.h>

#include "formats.h"
#include "falco_engine.h"
#include "banned.h" // This raises a compilation error when certain functions are used

sinsp *falco_formats::s_inspector = NULL;
falco_engine *falco_formats::s_engine = NULL;
bool falco_formats::s_json_output = false;
bool falco_formats::s_json_include_output_property = true;
sinsp_evt_formatter_cache *falco_formats::s_formatters = NULL;

const static struct luaL_reg ll_falco[] =
	{
		{"formatter", &falco_formats::lua_formatter},
		{"free_formatter", &falco_formats::lua_free_formatter},
		{NULL, NULL}};

void falco_formats::init(sinsp *inspector,
			 falco_engine *engine,
			 lua_State *ls,
			 bool json_output,
			 bool json_include_output_property)
{
	s_inspector = inspector;
	s_engine = engine;
	s_json_output = json_output;
	s_json_include_output_property = json_include_output_property;
	if(!s_formatters)
	{
		s_formatters = new sinsp_evt_formatter_cache(s_inspector);
	}

	luaL_openlib(ls, "formats", ll_falco, 0);
}

int falco_formats::lua_formatter(lua_State *ls)
{
	string source = luaL_checkstring(ls, -2);
	string format = luaL_checkstring(ls, -1);

	try
	{
		if(source == "syscall")
		{
			sinsp_evt_formatter *formatter;
			formatter = new sinsp_evt_formatter(s_inspector, format);
			lua_pushlightuserdata(ls, formatter);
		}
		else
		{
			json_event_formatter *formatter;
			formatter = new json_event_formatter(s_engine->json_factory(), format);
			lua_pushlightuserdata(ls, formatter);
		}
	}
	catch(sinsp_exception &e)
	{
		luaL_error(ls, "Invalid output format '%s': '%s'", format.c_str(), e.what());
	}
	catch(falco_exception &e)
	{
		luaL_error(ls, "Invalid output format '%s': '%s'", format.c_str(), e.what());
	}

	return 1;
}

int falco_formats::lua_free_formatter(lua_State *ls)
{
	if(!lua_islightuserdata(ls, -1) ||
	   !lua_isstring(ls, -2))

	{
		luaL_error(ls, "Invalid argument passed to free_formatter");
	}

	string source = luaL_checkstring(ls, -2);

	if(source == "syscall")
	{
		sinsp_evt_formatter *formatter = (sinsp_evt_formatter *)lua_topointer(ls, -1);
		delete(formatter);
	}
	else
	{
		json_event_formatter *formatter = (json_event_formatter *)lua_topointer(ls, -1);
		delete(formatter);
	}

	return 0;
}

string falco_formats::format_event(const gen_event *evt, const std::string &rule, const std::string &source,
				   const std::string &level, const std::string &format)
{

	string line;
	string json_line;
	string sformat = format;

	if(strcmp(source.c_str(), "syscall") == 0)
	{
		// This is "output"
		s_formatters->tostring((sinsp_evt *)evt, sformat, &line);

		if(s_json_output)
		{
			sinsp_evt::param_fmt cur_fmt = s_inspector->get_buffer_format();
			switch(cur_fmt)
			{
			case sinsp_evt::PF_NORMAL:
				s_inspector->set_buffer_format(sinsp_evt::PF_JSON);
				break;
			case sinsp_evt::PF_EOLS:
				s_inspector->set_buffer_format(sinsp_evt::PF_JSONEOLS);
				break;
			case sinsp_evt::PF_HEX:
				s_inspector->set_buffer_format(sinsp_evt::PF_JSONHEX);
				break;
			case sinsp_evt::PF_HEXASCII:
				s_inspector->set_buffer_format(sinsp_evt::PF_JSONHEXASCII);
				break;
			case sinsp_evt::PF_BASE64:
				s_inspector->set_buffer_format(sinsp_evt::PF_JSONBASE64);
				break;
			default:
				// do nothing
				break;
			}
			// This is output fields
			s_formatters->tostring((sinsp_evt *)evt, sformat, &json_line);

			// The formatted string might have a leading newline. If it does, remove it.
			if(json_line[0] == '\n')
			{
				json_line.erase(0, 1);
			}
			s_inspector->set_buffer_format(cur_fmt);
		}
	}
	else
	{
		json_event_formatter formatter(s_engine->json_factory(), sformat);

		line = formatter.tostring((json_event *)evt);

		if(s_json_output)
		{
			json_line = formatter.tojson((json_event *)evt);
		}
	}

	// For JSON output, the formatter returned a json-as-text
	// object containing all the fields in the original format
	// message as well as the event time in ns. Use this to build
	// a more detailed object containing the event time, rule,
	// severity, full output, and fields.
	if(s_json_output)
	{
		Json::Value event;
		Json::FastWriter writer;
		string full_line;

		// Convert the time-as-nanoseconds to a more json-friendly ISO8601.
		time_t evttime = evt->get_ts() / 1000000000;
		char time_sec[20]; // sizeof "YYYY-MM-DDTHH:MM:SS"
		char time_ns[12];  // sizeof ".sssssssssZ"
		string iso8601evttime;

		strftime(time_sec, sizeof(time_sec), "%FT%T", gmtime(&evttime));
		snprintf(time_ns, sizeof(time_ns), ".%09luZ", evt->get_ts() % 1000000000);
		iso8601evttime = time_sec;
		iso8601evttime += time_ns;
		event["time"] = iso8601evttime;
		event["rule"] = rule;
		event["priority"] = level;

		if(s_json_include_output_property)
		{
			// This is the filled-in output line.
			event["output"] = line;
		}

		full_line = writer.write(event);

		// Json::FastWriter may add a trailing newline. If it
		// does, remove it.
		if(full_line[full_line.length() - 1] == '\n')
		{
			full_line.resize(full_line.length() - 1);
		}

		// Cheat-graft the output from the formatter into this
		// string. Avoids an unnecessary json parse just to
		// merge the formatted fields at the object level.
		full_line.pop_back();
		full_line.append(", \"output_fields\": ");
		full_line.append(json_line);
		full_line.append("}");
		line = full_line;
	}

	return line.c_str();
}

map<string, string> falco_formats::resolve_tokens(const gen_event *evt, const std::string &source, const std::string &format)
{
	string sformat = format;
	map<string, string> values;
	if(source == "syscall")
	{
		s_formatters->resolve_tokens((sinsp_evt *)evt, sformat, values);
	}
	// k8s_audit
	else
	{
		json_event_formatter json_formatter(s_engine->json_factory(), sformat);
		values = json_formatter.tomap((json_event *)evt);
	}
	return values;
}
<commit_msg>fix(userspace/engine): free formatters, if any<commit_after>/*
Copyright (C) 2020 The Falco Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include <json/json.h>

#include "formats.h"
#include "falco_engine.h"
#include "banned.h" // This raises a compilation error when certain functions are used

sinsp *falco_formats::s_inspector = NULL;
falco_engine *falco_formats::s_engine = NULL;
bool falco_formats::s_json_output = false;
bool falco_formats::s_json_include_output_property = true;
sinsp_evt_formatter_cache *falco_formats::s_formatters = NULL;

const static struct luaL_reg ll_falco[] =
	{
		{"formatter", &falco_formats::lua_formatter},
		{"free_formatter", &falco_formats::lua_free_formatter},
		{NULL, NULL}};

void falco_formats::init(sinsp *inspector,
			 falco_engine *engine,
			 lua_State *ls,
			 bool json_output,
			 bool json_include_output_property)
{
	s_inspector = inspector;
	s_engine = engine;
	s_json_output = json_output;
	s_json_include_output_property = json_include_output_property;
	if(!s_formatters)
	{
		delete(s_formatters);
	}
	s_formatters = new sinsp_evt_formatter_cache(s_inspector);

	luaL_openlib(ls, "formats", ll_falco, 0);
}

int falco_formats::lua_formatter(lua_State *ls)
{
	string source = luaL_checkstring(ls, -2);
	string format = luaL_checkstring(ls, -1);

	try
	{
		if(source == "syscall")
		{
			sinsp_evt_formatter *formatter;
			formatter = new sinsp_evt_formatter(s_inspector, format);
			lua_pushlightuserdata(ls, formatter);
		}
		else
		{
			json_event_formatter *formatter;
			formatter = new json_event_formatter(s_engine->json_factory(), format);
			lua_pushlightuserdata(ls, formatter);
		}
	}
	catch(sinsp_exception &e)
	{
		luaL_error(ls, "Invalid output format '%s': '%s'", format.c_str(), e.what());
	}
	catch(falco_exception &e)
	{
		luaL_error(ls, "Invalid output format '%s': '%s'", format.c_str(), e.what());
	}

	return 1;
}

int falco_formats::lua_free_formatter(lua_State *ls)
{
	if(!lua_islightuserdata(ls, -1) ||
	   !lua_isstring(ls, -2))

	{
		luaL_error(ls, "Invalid argument passed to free_formatter");
	}

	string source = luaL_checkstring(ls, -2);

	if(source == "syscall")
	{
		sinsp_evt_formatter *formatter = (sinsp_evt_formatter *)lua_topointer(ls, -1);
		delete(formatter);
	}
	else
	{
		json_event_formatter *formatter = (json_event_formatter *)lua_topointer(ls, -1);
		delete(formatter);
	}

	return 0;
}

string falco_formats::format_event(const gen_event *evt, const std::string &rule, const std::string &source,
				   const std::string &level, const std::string &format)
{

	string line;
	string json_line;
	string sformat = format;

	if(strcmp(source.c_str(), "syscall") == 0)
	{
		// This is "output"
		s_formatters->tostring((sinsp_evt *)evt, sformat, &line);

		if(s_json_output)
		{
			sinsp_evt::param_fmt cur_fmt = s_inspector->get_buffer_format();
			switch(cur_fmt)
			{
			case sinsp_evt::PF_NORMAL:
				s_inspector->set_buffer_format(sinsp_evt::PF_JSON);
				break;
			case sinsp_evt::PF_EOLS:
				s_inspector->set_buffer_format(sinsp_evt::PF_JSONEOLS);
				break;
			case sinsp_evt::PF_HEX:
				s_inspector->set_buffer_format(sinsp_evt::PF_JSONHEX);
				break;
			case sinsp_evt::PF_HEXASCII:
				s_inspector->set_buffer_format(sinsp_evt::PF_JSONHEXASCII);
				break;
			case sinsp_evt::PF_BASE64:
				s_inspector->set_buffer_format(sinsp_evt::PF_JSONBASE64);
				break;
			default:
				// do nothing
				break;
			}
			// This is output fields
			s_formatters->tostring((sinsp_evt *)evt, sformat, &json_line);

			// The formatted string might have a leading newline. If it does, remove it.
			if(json_line[0] == '\n')
			{
				json_line.erase(0, 1);
			}
			s_inspector->set_buffer_format(cur_fmt);
		}
	}
	else
	{
		json_event_formatter formatter(s_engine->json_factory(), sformat);

		line = formatter.tostring((json_event *)evt);

		if(s_json_output)
		{
			json_line = formatter.tojson((json_event *)evt);
		}
	}

	// For JSON output, the formatter returned a json-as-text
	// object containing all the fields in the original format
	// message as well as the event time in ns. Use this to build
	// a more detailed object containing the event time, rule,
	// severity, full output, and fields.
	if(s_json_output)
	{
		Json::Value event;
		Json::FastWriter writer;
		string full_line;

		// Convert the time-as-nanoseconds to a more json-friendly ISO8601.
		time_t evttime = evt->get_ts() / 1000000000;
		char time_sec[20]; // sizeof "YYYY-MM-DDTHH:MM:SS"
		char time_ns[12];  // sizeof ".sssssssssZ"
		string iso8601evttime;

		strftime(time_sec, sizeof(time_sec), "%FT%T", gmtime(&evttime));
		snprintf(time_ns, sizeof(time_ns), ".%09luZ", evt->get_ts() % 1000000000);
		iso8601evttime = time_sec;
		iso8601evttime += time_ns;
		event["time"] = iso8601evttime;
		event["rule"] = rule;
		event["priority"] = level;

		if(s_json_include_output_property)
		{
			// This is the filled-in output line.
			event["output"] = line;
		}

		full_line = writer.write(event);

		// Json::FastWriter may add a trailing newline. If it
		// does, remove it.
		if(full_line[full_line.length() - 1] == '\n')
		{
			full_line.resize(full_line.length() - 1);
		}

		// Cheat-graft the output from the formatter into this
		// string. Avoids an unnecessary json parse just to
		// merge the formatted fields at the object level.
		full_line.pop_back();
		full_line.append(", \"output_fields\": ");
		full_line.append(json_line);
		full_line.append("}");
		line = full_line;
	}

	return line.c_str();
}

map<string, string> falco_formats::resolve_tokens(const gen_event *evt, const std::string &source, const std::string &format)
{
	string sformat = format;
	map<string, string> values;
	if(source == "syscall")
	{
		s_formatters->resolve_tokens((sinsp_evt *)evt, sformat, values);
	}
	// k8s_audit
	else
	{
		json_event_formatter json_formatter(s_engine->json_factory(), sformat);
		values = json_formatter.tomap((json_event *)evt);
	}
	return values;
}
<|endoftext|>


<commit_before>#include <iostream>
#include "semilinSetNdd.h"

int static_i = 0;

bool SemilinSetNdd::genepi_init(std::string pluginname, int number_of_variables)
{
  genepi_loader_init();
  genepi_loader_load_default_plugins();
  plugin = genepi_loader_get_plugin(pluginname.c_str());
  std::cout << "Plugin: " << genepi_plugin_get_name(plugin) << std::endl;
  // TODO: use of cache???
  solver = genepi_solver_create(plugin, 0, 0, 0);
  k = number_of_variables;
  return true; // TODO: return correct value!
}

bool SemilinSetNdd::genepi_dealloc() {
  genepi_solver_delete(solver);
  genepi_plugin_del_reference(plugin);
  genepi_loader_terminate();
  return true;
}

SemilinSetNdd::SemilinSetNdd() : set(Genepi(solver, k, false)) {
}

SemilinSetNdd::SemilinSetNdd(int zero) : set(Genepi(solver, k, false)) {
  assert(zero == 0);
}

SemilinSetNdd::SemilinSetNdd(VarId var) : SemilinSetNdd(var, 1) {
}

SemilinSetNdd::SemilinSetNdd(VarId var, int cnt) {
  auto v = var_map.find(var);
  if(v == var_map.end())
  {
    var_map.insert(std::make_pair(var, var_map.size()));
    v = var_map.find(var);
  }

  int position = v->second; // which position is this variable on?
  std::vector<int> alpha(k);
  alpha.at(position) = cnt;

  this->set = Genepi(solver, alpha, false);
  this->offsets.insert(this->offsets.end(), std::vector<int>(k));
  this->offsets.at(0).at(position) = cnt;
}
SemilinSetNdd::SemilinSetNdd(Genepi set, std::vector<std::vector<int>> offsets) : set(set), offsets(offsets){
}

SemilinSetNdd::SemilinSetNdd(const SemilinSetNdd& expr) : set(expr.set), offsets(expr.offsets) {
}

SemilinSetNdd::~SemilinSetNdd() {
}

SemilinSetNdd SemilinSetNdd::operator=(const SemilinSetNdd& term) {
  this->set = term.set;
  this->offsets = term.offsets;
  return *this;
}

SemilinSetNdd SemilinSetNdd::operator+=(const SemilinSetNdd& term) {
  this->set = this->set.union_op(term.set);
  this->offsets.insert(this->offsets.begin(), term.offsets.begin(), term.offsets.end());
  return *this;
}

SemilinSetNdd SemilinSetNdd::operator*=(const SemilinSetNdd& term) {
  std::vector<int> sel_a(3*k, 1);
  std::vector<int> sel_b(3*k, 1);
  std::vector<int> sel_res(3*k, 1);
  for(int i = 0; i < k; i++)
  {
    sel_a[3*i]     = 0;
    sel_b[3*i+1]   = 0;
    sel_res[3*i+2] = 0;
  }

  // inverse projection from original dimensions to an extended version, which is intersected with the natural numbers
  Genepi a_ext(this->set.invproject(sel_a).intersect(Genepi(solver, 3*k, true)));
  Genepi b_ext(term.set.invproject(sel_b).intersect(Genepi(solver, 3*k, true)));

  std::vector<int> generic_alpha = {1, 1, -1}; // 1*a[i]+1*b[i]-1*c[i]=0
  Genepi generic_sum(solver, generic_alpha, 0);

  std::vector<int> component_selection(3*k, 1);

  // initialize the result automaton with (a_i,b_i,N) for i in 0..k-1
  Genepi result(solver, 3*k, true); // natural numbers
  result = result.intersect(a_ext).intersect(b_ext);

  // one run for each variable
  for(int i = 0; i < k; i++)
  {
    // TODO: figure out, if precalculating this and apply inv_project has better complexity
    // than always create a new sum automaton for different components
    component_selection[3*i]   = 0;
    component_selection[3*i+1] = 0;
    component_selection[3*i+2] = 0;
    // inverse projection on generic sum automaton to create automaton for component i
    Genepi component_sum(generic_sum.invproject(component_selection));
    // use this sum automaton on the intermediate result
    result = result.intersect(component_sum);

    component_selection[3*i]   = 1; // reset component_selection
    component_selection[3*i+1] = 1;
    component_selection[3*i+2] = 1;
    this->offsets.insert(this->offsets.begin(), term.offsets.begin(), term.offsets.end());
  }

  this->set = result.project(sel_res);
  return *this;

}

bool SemilinSetNdd::operator < (const SemilinSetNdd& term) const {
  return this->set < term.set;
}
bool SemilinSetNdd::operator == (const SemilinSetNdd& term) const {
  return this->set == term.set;
}
SemilinSetNdd SemilinSetNdd::star () const {
  SemilinSetNdd offset_star = one();
  for(auto offset : this->offsets) {
    offset_star *= SemilinSetNdd(Genepi(this->solver, offset, true),{}); // offsets are used and converted to generators
  }

  SemilinSetNdd result = one();

  for(int i = 0; i < k; i++) {
    SemilinSetNdd temp = *this;
    // TODO: this is a very naive version of calculating temp^i (there are better methods...)
    for(int j = 0; j < i; j++) {
      temp *= *this;
    }
    if(i > 1) {
      temp *= offset_star;
    }
    result += temp;
  }
  return result;
}

SemilinSetNdd SemilinSetNdd::null() {
  if(!SemilinSetNdd::elem_null)
    SemilinSetNdd::elem_null = std::shared_ptr<SemilinSetNdd>(new SemilinSetNdd());
  return *SemilinSetNdd::elem_null;
}

SemilinSetNdd SemilinSetNdd::one() {
  if(!SemilinSetNdd::elem_one)
    SemilinSetNdd::elem_one = std::shared_ptr<SemilinSetNdd>(new SemilinSetNdd(Genepi(solver, std::vector<int>(k,0), false), {}));
  return *SemilinSetNdd::elem_one;
}

std::string SemilinSetNdd::string() const {
  // TODO: is there a better way to express the automaton than producing a graph?
  return this->set.output("result", static_i++, "");
}

const bool SemilinSetNdd::is_idempotent = true;
const bool SemilinSetNdd::is_commutative = true;
std::shared_ptr<SemilinSetNdd> SemilinSetNdd::elem_null;
std::shared_ptr<SemilinSetNdd> SemilinSetNdd::elem_one;
genepi_solver* SemilinSetNdd::solver;
genepi_plugin* SemilinSetNdd::plugin;
std::unordered_map<VarId, int> SemilinSetNdd::var_map;
int SemilinSetNdd::k = 0;
<commit_msg>fixed a bug in semilinsetndd...<commit_after>#include <iostream>
#include "semilinSetNdd.h"

int static_i = 0;

// insert an offset if it is unique in offsets
std::vector<std::vector<int>>& insert_offset(std::vector<std::vector<int>>& offsets, const std::vector<int>& offset) {
  if(std::find(offsets.begin(), offsets.end(), offset) == offsets.end())
  {
    offsets.push_back(offset);
  }
  return offsets;
}

std::vector<std::vector<int>> multiply_offsets(const std::vector<std::vector<int>>& offsets1, const std::vector<std::vector<int>>& offsets2) {
  std::vector<std::vector<int>> offsets;
  for(auto o1 : offsets1) {
    for(auto o2 : offsets2) {
      assert(o1.size() == o2.size());
      std::vector<int> o(o1.size());
      for(int i=0; i<o1.size(); ++i) {
        o.at(i) = o1.at(i) + o2.at(i);
      }
      offsets = insert_offset(offsets, o);
    }
  }
  return offsets;
}

bool SemilinSetNdd::genepi_init(std::string pluginname, int number_of_variables)
{
  genepi_loader_init();
  genepi_loader_load_default_plugins();
  plugin = genepi_loader_get_plugin(pluginname.c_str());
  std::cout << "Plugin: " << genepi_plugin_get_name(plugin) << std::endl;
  // TODO: use of cache???
  solver = genepi_solver_create(plugin, 0, 0, 0);
  k = number_of_variables;
  return true; // TODO: return correct value!
}

bool SemilinSetNdd::genepi_dealloc() {
  genepi_solver_delete(solver);
  genepi_plugin_del_reference(plugin);
  genepi_loader_terminate();
  return true;
}

SemilinSetNdd::SemilinSetNdd() : set(Genepi(solver, k, false)) {
}

SemilinSetNdd::SemilinSetNdd(int zero) : set(Genepi(solver, k, false)) {
  assert(zero == 0);
}

SemilinSetNdd::SemilinSetNdd(VarId var) : SemilinSetNdd(var, 1) {
}

SemilinSetNdd::SemilinSetNdd(VarId var, int cnt) {
  auto v = var_map.find(var);
  if(v == var_map.end())
  {
    var_map.insert(std::make_pair(var, var_map.size()));
    v = var_map.find(var);
  }

  int position = v->second; // which position is this variable on?
  std::vector<int> alpha(k);
  alpha.at(position) = cnt;

  this->set = Genepi(solver, alpha, false);
  this->offsets.push_back(std::vector<int>(k,0));
  this->offsets.at(0).at(position) = cnt;
}
SemilinSetNdd::SemilinSetNdd(Genepi set, std::vector<std::vector<int>> offsets) : set(set), offsets(offsets){
}

SemilinSetNdd::SemilinSetNdd(const SemilinSetNdd& expr) : set(expr.set), offsets(expr.offsets) {
}

SemilinSetNdd::~SemilinSetNdd() {
}

SemilinSetNdd SemilinSetNdd::operator=(const SemilinSetNdd& term) {
  this->set = term.set;
  this->offsets = term.offsets;
  return *this;
}

SemilinSetNdd SemilinSetNdd::operator+=(const SemilinSetNdd& term) {
  this->set = this->set.union_op(term.set);
  for(auto offset : term.offsets)
    insert_offset(this->offsets, offset);
  return *this;
}

SemilinSetNdd SemilinSetNdd::operator*=(const SemilinSetNdd& term) {
  std::vector<int> sel_a(3*k, 1);
  std::vector<int> sel_b(3*k, 1);
  std::vector<int> sel_res(3*k, 1);
  for(int i = 0; i < k; i++)
  {
    sel_a[3*i]     = 0;
    sel_b[3*i+1]   = 0;
    sel_res[3*i+2] = 0;
  }

  // inverse projection from original dimensions to an extended version, which is intersected with the natural numbers
  Genepi a_ext(this->set.invproject(sel_a).intersect(Genepi(solver, 3*k, true)));
  Genepi b_ext(term.set.invproject(sel_b).intersect(Genepi(solver, 3*k, true)));

  std::vector<int> generic_alpha = {1, 1, -1}; // 1*a[i]+1*b[i]-1*c[i]=0
  Genepi generic_sum(solver, generic_alpha, 0);

  std::vector<int> component_selection(3*k, 1);

  // initialize the result automaton with (a_i,b_i,N) for i in 0..k-1
  Genepi result(solver, 3*k, true); // natural numbers
  result = result.intersect(a_ext).intersect(b_ext);

  // one run for each variable
  for(int i = 0; i < k; i++)
  {
    // TODO: figure out, if precalculating this and apply inv_project has better complexity
    // than always create a new sum automaton for different components
    component_selection[3*i]   = 0;
    component_selection[3*i+1] = 0;
    component_selection[3*i+2] = 0;
    // inverse projection on generic sum automaton to create automaton for component i
    Genepi component_sum(generic_sum.invproject(component_selection));
    // use this sum automaton on the intermediate result
    result = result.intersect(component_sum);

    component_selection[3*i]   = 1; // reset component_selection
    component_selection[3*i+1] = 1;
    component_selection[3*i+2] = 1;
  }
  this->offsets = multiply_offsets(this->offsets, term.offsets);
  this->set = result.project(sel_res);
  return *this;

}

bool SemilinSetNdd::operator < (const SemilinSetNdd& term) const {
  return this->set < term.set;
}
bool SemilinSetNdd::operator == (const SemilinSetNdd& term) const {
  return this->set == term.set;
}
SemilinSetNdd SemilinSetNdd::star () const {
  SemilinSetNdd offset_star = one();
  for(auto offset : this->offsets) {
    offset_star *= SemilinSetNdd(Genepi(this->solver, offset, true),{}); // offsets are used and converted to generators
  }

  SemilinSetNdd result = one(); // result = 1

  for(int i = 1; i <= k; i++) { // 1..k
    SemilinSetNdd temp = *this; // S^1
    // TODO: this is a very naive version of calculating S^i (there are better methods...)
    for(int j = 1; j < i; j++) { // 1..j-1: j=2 1..1 -> S^2, j=3 1..2 -> S^3
      temp *= *this;
    }
    // temp = S^i
    temp *= offset_star; // S^i * offset_star
    result += temp;
  }
  return result;
}

SemilinSetNdd SemilinSetNdd::null() {
  if(!SemilinSetNdd::elem_null)
    SemilinSetNdd::elem_null = std::shared_ptr<SemilinSetNdd>(new SemilinSetNdd());
  return *SemilinSetNdd::elem_null;
}

SemilinSetNdd SemilinSetNdd::one() {
  if(!SemilinSetNdd::elem_one)
    SemilinSetNdd::elem_one = std::shared_ptr<SemilinSetNdd>(new SemilinSetNdd(Genepi(solver, std::vector<int>(k,0), false), {std::vector<int>(k,0)}));
  return *SemilinSetNdd::elem_one;
}

std::string SemilinSetNdd::string() const {
  // TODO: is there a better way to express the automaton than producing a graph?
  return this->set.output("result", static_i++, "");
}

const bool SemilinSetNdd::is_idempotent = true;
const bool SemilinSetNdd::is_commutative = true;
std::shared_ptr<SemilinSetNdd> SemilinSetNdd::elem_null;
std::shared_ptr<SemilinSetNdd> SemilinSetNdd::elem_one;
genepi_solver* SemilinSetNdd::solver;
genepi_plugin* SemilinSetNdd::plugin;
std::unordered_map<VarId, int> SemilinSetNdd::var_map;
int SemilinSetNdd::k = 0;
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "rubberbandselectionmanipulator.h"

#include "formeditorscene.h"

namespace QmlDesigner {

RubberBandSelectionManipulator::RubberBandSelectionManipulator(LayerItem *layerItem, FormEditorView *editorView)
    : m_selectionRectangleElement(layerItem),
    m_editorView(editorView),
    m_beginFormEditorItem(0),
    m_isActive(false)
{
    m_selectionRectangleElement.hide();
}

void RubberBandSelectionManipulator::clear()
{
    m_selectionRectangleElement.clear();
    m_isActive = false;
    m_beginPoint = QPointF();
    m_itemList.clear();
    m_oldSelectionList.clear();
}

FormEditorItem *RubberBandSelectionManipulator::topFormEditorItem(const QList<QGraphicsItem*> &itemList)
{
    foreach (QGraphicsItem *item, itemList) {
        FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);

        if (formEditorItem)
        {
            return formEditorItem;
        }
    }

    return m_editorView->scene()->rootFormEditorItem();
}

void RubberBandSelectionManipulator::begin(const QPointF& beginPoint)
{
    m_beginPoint = beginPoint;
    m_selectionRectangleElement.setRect(m_beginPoint, m_beginPoint);
    m_selectionRectangleElement.show();
    m_isActive = true;
    m_beginFormEditorItem = topFormEditorItem(m_editorView->scene()->items(beginPoint));
    m_oldSelectionList = toQmlItemNodeList(m_editorView->selectedModelNodes());
}

void RubberBandSelectionManipulator::update(const QPointF& updatePoint)
{
    m_selectionRectangleElement.setRect(m_beginPoint, updatePoint);
}

void RubberBandSelectionManipulator::end()
{
    m_oldSelectionList.clear();
    m_selectionRectangleElement.hide();
    m_isActive = false;
}

void RubberBandSelectionManipulator::select(SelectionType selectionType)
{
    if (!m_beginFormEditorItem)
        return;

    QList<QGraphicsItem*> itemList = m_editorView->scene()->items(m_selectionRectangleElement.rect(), Qt::IntersectsItemShape);
    QList<QmlItemNode> newNodeList;

    foreach (QGraphicsItem* item, itemList)
    {
        FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);

        if (formEditorItem
                && formEditorItem->qmlItemNode().isValid()
                && m_beginFormEditorItem->childItems().contains(formEditorItem)
                && formEditorItem->qmlItemNode().instanceIsMovable()
                && !formEditorItem->qmlItemNode().instanceIsInLayoutable())
        {
            newNodeList.append(formEditorItem->qmlItemNode());
        }
    }

    if (newNodeList.isEmpty()
            && m_beginFormEditorItem->qmlItemNode().isValid()
            && m_beginFormEditorItem->qmlItemNode().instanceIsMovable()
            && !m_beginFormEditorItem->qmlItemNode().instanceIsInLayoutable())
        newNodeList.append(m_beginFormEditorItem->qmlItemNode());

    QList<QmlItemNode> nodeList;

    switch (selectionType) {
    case AddToSelection: {
            nodeList.append(m_oldSelectionList);
            nodeList.append(newNodeList);
        }
        break;
    case ReplaceSelection: {
            nodeList.append(newNodeList);
        }
        break;
    case RemoveFromSelection: {
            QSet<QmlItemNode> oldSelectionSet(m_oldSelectionList.toSet());
            QSet<QmlItemNode> newSelectionSet(newNodeList.toSet());
            nodeList.append(oldSelectionSet.subtract(newSelectionSet).toList());
        }
    }

    m_editorView->setSelectedModelNodes(toModelNodeList(nodeList));
}

void RubberBandSelectionManipulator::setItems(const QList<FormEditorItem*> &itemList)
{
    m_itemList = itemList;
}

QPointF RubberBandSelectionManipulator::beginPoint() const
{
    return m_beginPoint;
}

bool RubberBandSelectionManipulator::isActive() const
{
    return m_isActive;
}

}
<commit_msg>QmlDesigner: Items should be only selected if the have no xy binding<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "rubberbandselectionmanipulator.h"

#include "formeditorscene.h"

namespace QmlDesigner {

RubberBandSelectionManipulator::RubberBandSelectionManipulator(LayerItem *layerItem, FormEditorView *editorView)
    : m_selectionRectangleElement(layerItem),
    m_editorView(editorView),
    m_beginFormEditorItem(0),
    m_isActive(false)
{
    m_selectionRectangleElement.hide();
}

void RubberBandSelectionManipulator::clear()
{
    m_selectionRectangleElement.clear();
    m_isActive = false;
    m_beginPoint = QPointF();
    m_itemList.clear();
    m_oldSelectionList.clear();
}

FormEditorItem *RubberBandSelectionManipulator::topFormEditorItem(const QList<QGraphicsItem*> &itemList)
{
    foreach (QGraphicsItem *item, itemList) {
        FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);

        if (formEditorItem)
        {
            return formEditorItem;
        }
    }

    return m_editorView->scene()->rootFormEditorItem();
}

void RubberBandSelectionManipulator::begin(const QPointF& beginPoint)
{
    m_beginPoint = beginPoint;
    m_selectionRectangleElement.setRect(m_beginPoint, m_beginPoint);
    m_selectionRectangleElement.show();
    m_isActive = true;
    m_beginFormEditorItem = topFormEditorItem(m_editorView->scene()->items(beginPoint));
    m_oldSelectionList = toQmlItemNodeList(m_editorView->selectedModelNodes());
}

void RubberBandSelectionManipulator::update(const QPointF& updatePoint)
{
    m_selectionRectangleElement.setRect(m_beginPoint, updatePoint);
}

void RubberBandSelectionManipulator::end()
{
    m_oldSelectionList.clear();
    m_selectionRectangleElement.hide();
    m_isActive = false;
}

void RubberBandSelectionManipulator::select(SelectionType selectionType)
{
    if (!m_beginFormEditorItem)
        return;

    QList<QGraphicsItem*> itemList = m_editorView->scene()->items(m_selectionRectangleElement.rect(), Qt::IntersectsItemShape);
    QList<QmlItemNode> newNodeList;

    foreach (QGraphicsItem* item, itemList)
    {
        FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item);

        if (formEditorItem
                && formEditorItem->qmlItemNode().isValid()
                && m_beginFormEditorItem->childItems().contains(formEditorItem)
                && formEditorItem->qmlItemNode().instanceIsMovable()
                && formEditorItem->qmlItemNode().modelIsMovable()
                && !formEditorItem->qmlItemNode().instanceIsInLayoutable())
        {
            newNodeList.append(formEditorItem->qmlItemNode());
        }
    }

    if (newNodeList.isEmpty()
            && m_beginFormEditorItem->qmlItemNode().isValid()
            && m_beginFormEditorItem->qmlItemNode().instanceIsMovable()
            && m_beginFormEditorItem->qmlItemNode().modelIsMovable()
            && !m_beginFormEditorItem->qmlItemNode().instanceIsInLayoutable())
        newNodeList.append(m_beginFormEditorItem->qmlItemNode());

    QList<QmlItemNode> nodeList;

    switch (selectionType) {
    case AddToSelection: {
            nodeList.append(m_oldSelectionList);
            nodeList.append(newNodeList);
        }
        break;
    case ReplaceSelection: {
            nodeList.append(newNodeList);
        }
        break;
    case RemoveFromSelection: {
            QSet<QmlItemNode> oldSelectionSet(m_oldSelectionList.toSet());
            QSet<QmlItemNode> newSelectionSet(newNodeList.toSet());
            nodeList.append(oldSelectionSet.subtract(newSelectionSet).toList());
        }
    }

    m_editorView->setSelectedModelNodes(toModelNodeList(nodeList));
}

void RubberBandSelectionManipulator::setItems(const QList<FormEditorItem*> &itemList)
{
    m_itemList = itemList;
}

QPointF RubberBandSelectionManipulator::beginPoint() const
{
    return m_beginPoint;
}

bool RubberBandSelectionManipulator::isActive() const
{
    return m_isActive;
}

}
<|endoftext|>