<commit_before>//===--- SILLowerAggregateInstrs.cpp - Aggregate insts to Scalar insts  ---===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Simplify aggregate instructions into scalar instructions.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "sil-lower-aggregate-instrs"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/TypeLowering.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
using namespace swift;
using namespace swift::Lowering;

STATISTIC(NumExpand, "Number of instructions expanded");

//===----------------------------------------------------------------------===//
//                      Higher Level Operation Expansion
//===----------------------------------------------------------------------===//

/// \brief Lower copy_addr into loads/stores/retain/release if we have a
/// non-address only type. We do this here so we can process the resulting
/// loads/stores.
///
/// This peephole implements the following optimizations:
///
/// copy_addr %0 to %1 : $*T
/// ->
///     %new = load %0 : $*T        // Load the new value from the source
///     %old = load %1 : $*T        // Load the old value from the destination
///     strong_retain %new : $T     // Retain the new value
///     strong_release %old : $T    // Release the old
///     store %new to %1 : $*T      // Store the new value to the destination
///
/// copy_addr [take] %0 to %1 : $*T
/// ->
///     %new = load %0 : $*T
///     %old = load %1 : $*T
///     // no retain of %new!
///     strong_release %old : $T
///     store %new to %1 : $*T
///
/// copy_addr %0 to [initialization] %1 : $*T
/// ->
///     %new = load %0 : $*T
///     strong_retain %new : $T
///     // no load/release of %old!
///     store %new to %1 : $*T
///
/// copy_addr [take] %0 to [initialization] %1 : $*T
/// ->
///     %new = load %0 : $*T
///     // no retain of %new!
///     // no load/release of %old!
///     store %new to %1 : $*T
static bool expandCopyAddr(CopyAddrInst *CA) {
  SILModule &M = CA->getModule();
  SILValue Source = CA->getSrc();

  // If we have an address only type don't do anything.
  SILType SrcType = Source->getType();
  if (SrcType.isAddressOnly(M))
    return false;

  SILBuilderWithScope Builder(CA);

  // %new = load %0 : $*T
  LoadInst *New = Builder.createLoad(CA->getLoc(), Source);

  SILValue Destination = CA->getDest();

  // If our object type is not trivial, we may need to release the old value and
  // retain the new one.

  auto &TL = M.getTypeLowering(SrcType);

  // If we have a non-trivial type...
  if (!TL.isTrivial()) {

    // If we are not initializing:
    // %old = load %1 : $*T
    IsInitialization_t IsInit = CA->isInitializationOfDest();
    LoadInst *Old = nullptr;
    if (IsInitialization_t::IsNotInitialization == IsInit) {
      Old = Builder.createLoad(CA->getLoc(), Destination);
    }

    // If we are not taking and have a reference type:
    //   strong_retain %new : $*T
    // or if we have a non-trivial non-reference type.
    //   retain_value %new : $*T
    IsTake_t IsTake = CA->isTakeOfSrc();
    if (IsTake_t::IsNotTake == IsTake) {
      TL.emitLoweredRetainValue(Builder, CA->getLoc(), New,
                              TypeLowering::LoweringStyle::DeepNoEnum);
    }

    // If we are not initializing:
    // strong_release %old : $*T
    //   *or*
    // release_value %new : $*T
    if (Old) {
      TL.emitLoweredReleaseValue(Builder, CA->getLoc(), Old,
                                 TypeLowering::LoweringStyle::DeepNoEnum);
    }
  }

  // Create the store.
  Builder.createStore(CA->getLoc(), New, Destination);

  ++NumExpand;
  return true;
}

static bool expandDestroyAddr(DestroyAddrInst *DA) {
  SILModule &Module = DA->getModule();
  SILBuilderWithScope Builder(DA);

  // Strength reduce destroy_addr inst into release/store if
  // we have a non-address only type.
  SILValue Addr = DA->getOperand();

  // If we have an address only type, do nothing.
  SILType Type = Addr->getType();
  if (Type.isAddressOnly(Module))
    return false;

  // If we have a non-trivial type...
  if (!Type.isTrivial(Module)) {
    // If we have a type with reference semantics, emit a load/strong release.
    LoadInst *LI = Builder.createLoad(DA->getLoc(), Addr);
    auto &TL = Module.getTypeLowering(Type);
    TL.emitLoweredReleaseValue(Builder, DA->getLoc(), LI,
                               TypeLowering::LoweringStyle::DeepNoEnum);
  }

  ++NumExpand;
  return true;
}

static bool expandReleaseValue(ReleaseValueInst *DV) {
  SILModule &Module = DV->getModule();
  SILBuilderWithScope Builder(DV);

  // Strength reduce destroy_addr inst into release/store if
  // we have a non-address only type.
  SILValue Value = DV->getOperand();

  // If we have an address only type, do nothing.
  SILType Type = Value->getType();
  assert(Type.isLoadable(Module) &&
         "release_value should never be called on a non-loadable type.");

  auto &TL = Module.getTypeLowering(Type);
  TL.emitLoweredReleaseValue(Builder, DV->getLoc(), Value,
                             TypeLowering::LoweringStyle::DeepNoEnum);

  DEBUG(llvm::dbgs() << "    Expanding Destroy Value: " << *DV);

  ++NumExpand;
  return true;
}

static bool expandRetainValue(RetainValueInst *CV) {
  SILModule &Module = CV->getModule();
  SILBuilderWithScope Builder(CV);

  // Strength reduce destroy_addr inst into release/store if
  // we have a non-address only type.
  SILValue Value = CV->getOperand();

  // If we have an address only type, do nothing.
  SILType Type = Value->getType();
  assert(Type.isLoadable(Module) && "Copy Value can only be called on loadable "
         "types.");

  auto &TL = Module.getTypeLowering(Type);
  TL.emitLoweredRetainValue(Builder, CV->getLoc(), Value,
                          TypeLowering::LoweringStyle::DeepNoEnum);

  DEBUG(llvm::dbgs() << "    Expanding Copy Value: " << *CV);

  ++NumExpand;
  return true;
}

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

static bool processFunction(SILFunction &Fn) {
  bool Changed = false;
  for (auto BI = Fn.begin(), BE = Fn.end(); BI != BE; ++BI) {
    auto II = BI->begin(), IE = BI->end();
    while (II != IE) {
      SILInstruction *Inst = &*II;

      DEBUG(llvm::dbgs() << "Visiting: " << *Inst);

      if (auto *CA = dyn_cast<CopyAddrInst>(Inst))
        if (expandCopyAddr(CA)) {
          ++II;
          CA->eraseFromParent();
          Changed = true;
          continue;
        }

      if (auto *DA = dyn_cast<DestroyAddrInst>(Inst))
        if (expandDestroyAddr(DA)) {
          ++II;
          DA->eraseFromParent();
          Changed = true;
          continue;
        }

      if (auto *CV = dyn_cast<RetainValueInst>(Inst))
        if (expandRetainValue(CV)) {
          ++II;
          CV->eraseFromParent();
          Changed = true;
          continue;
        }

      if (auto *DV = dyn_cast<ReleaseValueInst>(Inst))
        if (expandReleaseValue(DV)) {
          ++II;
          DV->eraseFromParent();
          Changed = true;
          continue;
        }

      ++II;
    }
  }
  return Changed;
}

namespace {
class SILLowerAggregate : public SILFunctionTransform {

  /// The entry point to the transformation.
  void run() override {
    SILFunction *F = getFunction();
    DEBUG(llvm::dbgs() << "***** LowerAggregate on function: " <<
          F->getName() << " *****\n");
    bool Changed = processFunction(*F);
    if (Changed) {
      invalidateAnalysis(SILAnalysis::InvalidationKind::CallsAndInstructions);
    }
  }

  StringRef getName() override { return "Lower Aggregate Instructions"; }
};
} // end anonymous namespace

SILTransform *swift::createLowerAggregateInstrs() {
  return new SILLowerAggregate();
}
<commit_msg>Fix typo in comment.<commit_after>//===--- SILLowerAggregateInstrs.cpp - Aggregate insts to Scalar insts  ---===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Simplify aggregate instructions into scalar instructions.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "sil-lower-aggregate-instrs"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SILOptimizer/Utils/Local.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/TypeLowering.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Debug.h"
using namespace swift;
using namespace swift::Lowering;

STATISTIC(NumExpand, "Number of instructions expanded");

//===----------------------------------------------------------------------===//
//                      Higher Level Operation Expansion
//===----------------------------------------------------------------------===//

/// \brief Lower copy_addr into loads/stores/retain/release if we have a
/// non-address only type. We do this here so we can process the resulting
/// loads/stores.
///
/// This peephole implements the following optimizations:
///
/// copy_addr %0 to %1 : $*T
/// ->
///     %new = load %0 : $*T        // Load the new value from the source
///     %old = load %1 : $*T        // Load the old value from the destination
///     strong_retain %new : $T     // Retain the new value
///     strong_release %old : $T    // Release the old
///     store %new to %1 : $*T      // Store the new value to the destination
///
/// copy_addr [take] %0 to %1 : $*T
/// ->
///     %new = load %0 : $*T
///     %old = load %1 : $*T
///     // no retain of %new!
///     strong_release %old : $T
///     store %new to %1 : $*T
///
/// copy_addr %0 to [initialization] %1 : $*T
/// ->
///     %new = load %0 : $*T
///     strong_retain %new : $T
///     // no load/release of %old!
///     store %new to %1 : $*T
///
/// copy_addr [take] %0 to [initialization] %1 : $*T
/// ->
///     %new = load %0 : $*T
///     // no retain of %new!
///     // no load/release of %old!
///     store %new to %1 : $*T
static bool expandCopyAddr(CopyAddrInst *CA) {
  SILModule &M = CA->getModule();
  SILValue Source = CA->getSrc();

  // If we have an address only type don't do anything.
  SILType SrcType = Source->getType();
  if (SrcType.isAddressOnly(M))
    return false;

  SILBuilderWithScope Builder(CA);

  // %new = load %0 : $*T
  LoadInst *New = Builder.createLoad(CA->getLoc(), Source);

  SILValue Destination = CA->getDest();

  // If our object type is not trivial, we may need to release the old value and
  // retain the new one.

  auto &TL = M.getTypeLowering(SrcType);

  // If we have a non-trivial type...
  if (!TL.isTrivial()) {

    // If we are not initializing:
    // %old = load %1 : $*T
    IsInitialization_t IsInit = CA->isInitializationOfDest();
    LoadInst *Old = nullptr;
    if (IsInitialization_t::IsNotInitialization == IsInit) {
      Old = Builder.createLoad(CA->getLoc(), Destination);
    }

    // If we are not taking and have a reference type:
    //   strong_retain %new : $*T
    // or if we have a non-trivial non-reference type.
    //   retain_value %new : $*T
    IsTake_t IsTake = CA->isTakeOfSrc();
    if (IsTake_t::IsNotTake == IsTake) {
      TL.emitLoweredRetainValue(Builder, CA->getLoc(), New,
                              TypeLowering::LoweringStyle::DeepNoEnum);
    }

    // If we are not initializing:
    // strong_release %old : $*T
    //   *or*
    // release_value %old : $*T
    if (Old) {
      TL.emitLoweredReleaseValue(Builder, CA->getLoc(), Old,
                                 TypeLowering::LoweringStyle::DeepNoEnum);
    }
  }

  // Create the store.
  Builder.createStore(CA->getLoc(), New, Destination);

  ++NumExpand;
  return true;
}

static bool expandDestroyAddr(DestroyAddrInst *DA) {
  SILModule &Module = DA->getModule();
  SILBuilderWithScope Builder(DA);

  // Strength reduce destroy_addr inst into release/store if
  // we have a non-address only type.
  SILValue Addr = DA->getOperand();

  // If we have an address only type, do nothing.
  SILType Type = Addr->getType();
  if (Type.isAddressOnly(Module))
    return false;

  // If we have a non-trivial type...
  if (!Type.isTrivial(Module)) {
    // If we have a type with reference semantics, emit a load/strong release.
    LoadInst *LI = Builder.createLoad(DA->getLoc(), Addr);
    auto &TL = Module.getTypeLowering(Type);
    TL.emitLoweredReleaseValue(Builder, DA->getLoc(), LI,
                               TypeLowering::LoweringStyle::DeepNoEnum);
  }

  ++NumExpand;
  return true;
}

static bool expandReleaseValue(ReleaseValueInst *DV) {
  SILModule &Module = DV->getModule();
  SILBuilderWithScope Builder(DV);

  // Strength reduce destroy_addr inst into release/store if
  // we have a non-address only type.
  SILValue Value = DV->getOperand();

  // If we have an address only type, do nothing.
  SILType Type = Value->getType();
  assert(Type.isLoadable(Module) &&
         "release_value should never be called on a non-loadable type.");

  auto &TL = Module.getTypeLowering(Type);
  TL.emitLoweredReleaseValue(Builder, DV->getLoc(), Value,
                             TypeLowering::LoweringStyle::DeepNoEnum);

  DEBUG(llvm::dbgs() << "    Expanding Destroy Value: " << *DV);

  ++NumExpand;
  return true;
}

static bool expandRetainValue(RetainValueInst *CV) {
  SILModule &Module = CV->getModule();
  SILBuilderWithScope Builder(CV);

  // Strength reduce destroy_addr inst into release/store if
  // we have a non-address only type.
  SILValue Value = CV->getOperand();

  // If we have an address only type, do nothing.
  SILType Type = Value->getType();
  assert(Type.isLoadable(Module) && "Copy Value can only be called on loadable "
         "types.");

  auto &TL = Module.getTypeLowering(Type);
  TL.emitLoweredRetainValue(Builder, CV->getLoc(), Value,
                          TypeLowering::LoweringStyle::DeepNoEnum);

  DEBUG(llvm::dbgs() << "    Expanding Copy Value: " << *CV);

  ++NumExpand;
  return true;
}

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

static bool processFunction(SILFunction &Fn) {
  bool Changed = false;
  for (auto BI = Fn.begin(), BE = Fn.end(); BI != BE; ++BI) {
    auto II = BI->begin(), IE = BI->end();
    while (II != IE) {
      SILInstruction *Inst = &*II;

      DEBUG(llvm::dbgs() << "Visiting: " << *Inst);

      if (auto *CA = dyn_cast<CopyAddrInst>(Inst))
        if (expandCopyAddr(CA)) {
          ++II;
          CA->eraseFromParent();
          Changed = true;
          continue;
        }

      if (auto *DA = dyn_cast<DestroyAddrInst>(Inst))
        if (expandDestroyAddr(DA)) {
          ++II;
          DA->eraseFromParent();
          Changed = true;
          continue;
        }

      if (auto *CV = dyn_cast<RetainValueInst>(Inst))
        if (expandRetainValue(CV)) {
          ++II;
          CV->eraseFromParent();
          Changed = true;
          continue;
        }

      if (auto *DV = dyn_cast<ReleaseValueInst>(Inst))
        if (expandReleaseValue(DV)) {
          ++II;
          DV->eraseFromParent();
          Changed = true;
          continue;
        }

      ++II;
    }
  }
  return Changed;
}

namespace {
class SILLowerAggregate : public SILFunctionTransform {

  /// The entry point to the transformation.
  void run() override {
    SILFunction *F = getFunction();
    DEBUG(llvm::dbgs() << "***** LowerAggregate on function: " <<
          F->getName() << " *****\n");
    bool Changed = processFunction(*F);
    if (Changed) {
      invalidateAnalysis(SILAnalysis::InvalidationKind::CallsAndInstructions);
    }
  }

  StringRef getName() override { return "Lower Aggregate Instructions"; }
};
} // end anonymous namespace

SILTransform *swift::createLowerAggregateInstrs() {
  return new SILLowerAggregate();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <assert.h>

#include "differential_fuzzer.h"
#include "logger.h"

// ---------------------------------------------------------------------------------
// ----------------------------------- Deleters ------------------------------------
// ---------------------------------------------------------------------------------

void differential_fuzzer::parser::DeleteAssociatedParserName(AssociatedParserName* delete_me)
{
    while (delete_me != nullptr)
    {
        AssociatedParserName* next = delete_me->next_parser;

        delete delete_me;

        delete_me = next;
    }
}

void differential_fuzzer::parser::DeleteEquivalenceNormalizedOutputs
    (EquivalenceNormalizedOutputs* delete_me)
{
    while (delete_me != nullptr)
    {
        EquivalenceNormalizedOutputs* next = delete_me->next;

        // Makes deletions
        delete delete_me->representative;
        DeleteAssociatedParserName(delete_me->container_basket);
        delete delete_me;

        //Move next
        delete_me = next;
    }
}

// ---------------------------------------------------------------------------------
// --------------------------- struc print functions -------------------------------
// ---------------------------------------------------------------------------------

void differential_fuzzer::parser::PrintParserList(AssociatedParserName* head)
{
    AssociatedParserName* ptr = head;

    if (ptr != nullptr)
    {
        std::cerr << "- ";
    }

    while (ptr != nullptr)
    {
        std::cerr << ptr->name;

        ptr = ptr->next_parser;

        if (ptr == nullptr)
        {
            std::cerr << std::endl;
        }
        else
        {
            std::cerr << std::endl << "- ";
        }
    }
}

// Ouput in cerr:
// Ex.:
//--- Printing Results
// Set #1:
// - parser_2
// Set #2:
// - parser_1
// - parser_3
void differential_fuzzer::parser::PrintEquivalenceNormalizedOutputs(EquivalenceNormalizedOutputs* head)
{
    EquivalenceNormalizedOutputs* ptr = head;

    std::cerr << "--- Printing Results" << std::endl;

    int set_id = 1;

    while (ptr != nullptr)
    {
        std::cerr << "Set #" << set_id << ":" << std::endl;

        set_id++;

        if (ptr->container_basket != nullptr)
        {
            PrintParserList(ptr->container_basket);
        }
        else
        {
            std::cerr << "ERROR: basket not selected" << std::endl;
        }

        ptr = ptr->next;

    }
}

// ---------------------------------------------------------------------------------
// ------------------------------ struc functions ----------------------------------
// ---------------------------------------------------------------------------------

void differential_fuzzer::parser::AddToAssociatedParserName(AssociatedParserName** head,
    std::string name)
{
    AssociatedParserName* ptr =  new AssociatedParserName;

    ptr->name = name;
    ptr->next_parser = *head;

    *head = ptr;
}

// Function checks if a parser has an output that matches the representative of one
// of the already existing EquivalenceNormalizedOutputs list. If the output of the new
// parser matches a representative, its name is saved to the AssociatedParserName
// list of that particular EquivalenceNormalizedOutputs node. If the output of a new
// parser does not match a previous representative, a new EquivalenceNormalizedOutputs
// node is created, and added to the original EquivalenceNormalizedOutputs with the
// output of the parser being saved as the representative of that
// EquivalenceNormalizedOutputs node.
//
// If the parser output has matched a previous representative, the function returns
// true. If the parser output has not matched a previous representative, the
// function returns false
bool differential_fuzzer::parser::CheckAndAdd(differential_parser::Parser* parser,
    EquivalenceNormalizedOutputs** head, const uint8_t* input_data, size_t size_of_input)
{
    // Iterator:
    EquivalenceNormalizedOutputs* ptr = *head;

    std::string* local_error = new std::string();

    void* temp_parse_holder = parser->parse(input_data, size_of_input, local_error);

    if (temp_parse_holder == nullptr)
    {
        delete local_error;
        return false;
    }

    if (differential_parser::NormalizedOutput* parser_output =
        parser->normalize(temp_parse_holder, local_error))
    {
        // Iterate through the different EquivalenceNormalizedOutputs
        while (ptr != nullptr)
        {
            if (parser_output->equivalent(ptr->representative))
            {
                AddToAssociatedParserName(&ptr->container_basket, parser->getName());

                delete parser_output;

                return true;
            }
            ptr = ptr->next;
        }

        bool is_first = (*head == nullptr);

        ptr = new EquivalenceNormalizedOutputs;
        ptr->representative = parser_output;
        ptr->container_basket = new AssociatedParserName;
        ptr->container_basket->name = parser->getName();
        ptr->container_basket->next_parser = nullptr;
        ptr->next = *head;

        *head = ptr;

        return is_first;
    }
    else
    {
        return false;
    }
}

bool differential_fuzzer::fuzzer::DifferentiallyFuzz(differential_parser::Parser** parser_array,
    int number_of_parsers, const uint8_t* input_data, size_t size_of_input)
{
    if (number_of_parsers <= 0)
    {
        std::cerr << "ERROR: No parsers passed to 'DifferentiallyFuzz' function"
            << std::endl;
        return false;
    }

    // Creates iteration structure
    parser::EquivalenceNormalizedOutputs* head = nullptr;

    bool all_parser_are_similar = true;

    for (int i = 0; i < number_of_parsers; i++)
    {
        if (!CheckAndAdd(parser_array[i], &head, input_data, size_of_input))
        {
            all_parser_are_similar = false;
        }
    }

    TEST_NODE_PPRINT(head);

    DeleteEquivalenceNormalizedOutputs(head);

    return all_parser_are_similar;
}<commit_msg>Roll back differential fuzzer for proper branch scope<commit_after>#include <iostream>
#include <string>
#include <assert.h>

#include "differential_fuzzer.h"
#include "logger.h"

// ---------------------------------------------------------------------------------
// ----------------------------------- Deleters ------------------------------------
// ---------------------------------------------------------------------------------

void differential_fuzzer::parser::DeleteAssociatedParserName(AssociatedParserName* delete_me)
{
    while (delete_me != nullptr)
    {
        AssociatedParserName* next = delete_me->next_parser;

        delete delete_me;

        delete_me = next;
    }
}

void differential_fuzzer::parser::DeleteEquivalenceNormalizedOutputs
    (EquivalenceNormalizedOutputs* delete_me)
{
    while (delete_me != nullptr)
    {
        EquivalenceNormalizedOutputs* next = delete_me->next;

        // Makes deletions
        delete delete_me->representative;
        DeleteAssociatedParserName(delete_me->container_basket);
        delete delete_me;

        //Move next
        delete_me = next;
    }
}

// ---------------------------------------------------------------------------------
// --------------------------- struc print functions -------------------------------
// ---------------------------------------------------------------------------------

void differential_fuzzer::parser::PrintParserList(AssociatedParserName* head)
{
    AssociatedParserName* ptr = head;

    if (ptr != nullptr)
    {
        std::cerr << "- ";
    }

    while (ptr != nullptr)
    {
        std::cerr << ptr->name;

        ptr = ptr->next_parser;

        if (ptr == nullptr)
        {
            std::cerr << std::endl;
        }
        else
        {
            std::cerr << std::endl << "- ";
        }
    }
}

// Ouput in cerr:
// Ex.:
//--- Printing Results
// Set #1:
// - parser_2
// Set #2:
// - parser_1
// - parser_3
void differential_fuzzer::parser::PrintEquivalenceNormalizedOutputs(EquivalenceNormalizedOutputs* head)
{
    EquivalenceNormalizedOutputs* ptr = head;

    std::cerr << "--- Printing Results" << std::endl;

    int set_id = 1;

    while (ptr != nullptr)
    {
        std::cerr << "Set #" << set_id << ":" << std::endl;

        set_id++;

        if (ptr->container_basket != nullptr)
        {
            PrintParserList(ptr->container_basket);
        }
        else
        {
            std::cerr << "ERROR: basket not selected" << std::endl;
        }

        ptr = ptr->next;

    }
}

// ---------------------------------------------------------------------------------
// ------------------------------ struc functions ----------------------------------
// ---------------------------------------------------------------------------------

void differential_fuzzer::parser::AddToAssociatedParserName(AssociatedParserName** head,
    std::string name)
{
    AssociatedParserName* ptr =  new AssociatedParserName;

    ptr->name = name;
    ptr->next_parser = *head;

    *head = ptr;
}

// Function checks if a parser has an output that matches the representative of one
// of the already existing EquivalenceNormalizedOutputs list. If the output of the new
// parser matches a representative, its name is saved to the AssociatedParserName
// list of that particular EquivalenceNormalizedOutputs node. If the output of a new
// parser does not match a previous representative, a new EquivalenceNormalizedOutputs
// node is created, and added to the original EquivalenceNormalizedOutputs with the
// output of the parser being saved as the representative of that
// EquivalenceNormalizedOutputs node.
//
// If the parser output has matched a previous representative, the function returns
// true. If the parser output has not matched a previous representative, the
// function returns false
bool differential_fuzzer::parser::CheckAndAdd(differential_parser::Parser* parser,
    EquivalenceNormalizedOutputs** head, const uint8_t* input_data, size_t size_of_input)
{
    // Iterator:
    EquivalenceNormalizedOutputs* ptr = *head;

    std::string* local_error = new std::string();

    void* temp_parse_holder = parser->parse(input_data, size_of_input, local_error);

    differential_parser::NormalizedOutput* parser_output =
        parser->normalize(temp_parse_holder, local_error);

    // Iterate through the different EquivalenceNormalizedOutputs
    while (ptr != nullptr)
    {
        if (parser_output->equivalent(ptr->representative))
        {
            AddToAssociatedParserName(&ptr->container_basket, parser->getName());

            delete parser_output;

            return true;
        }
        ptr = ptr->next;
    }

    bool is_first = (*head == nullptr);

    ptr = new EquivalenceNormalizedOutputs;
    ptr->representative = parser_output;
    ptr->container_basket = new AssociatedParserName;
    ptr->container_basket->name = parser->getName();
    ptr->container_basket->next_parser = nullptr;
    ptr->next = *head;

    *head = ptr;

    return is_first;
}

bool differential_fuzzer::fuzzer::DifferentiallyFuzz(differential_parser::Parser** parser_array,
    int number_of_parsers, const uint8_t* input_data, size_t size_of_input)
{
    if (number_of_parsers <= 0)
    {
        std::cerr << "ERROR: No parsers passed to 'DifferentiallyFuzz' function"
            << std::endl;
        return false;
    }

    // Creates iteration structure
    parser::EquivalenceNormalizedOutputs* head = nullptr;

    bool all_parser_are_similar = true;

    for (int i = 0; i < number_of_parsers; i++)
    {
        if (!CheckAndAdd(parser_array[i], &head, input_data, size_of_input))
        {
            all_parser_are_similar = false;
        }
    }

    TEST_NODE_PPRINT(head);

    DeleteEquivalenceNormalizedOutputs(head);

    return all_parser_are_similar;
}<|endoftext|>


<commit_before>#ifndef UTIL_CACHE_HPP__
#define UTIL_CACHE_HPP__

#include <map>
#include <queue>
#include "assert.h"

class size_limit_policy {

public:

	size_limit_policy() : _max_size(256) {}

	void set_max_size(size_t size) { _max_size = size; }

protected:

	template <typename K, typename V>
	bool limit_exceeded(const std::map<K,V>& cache) const {

		return (cache.size() > _max_size);
	}

private:

	size_t _max_size;
};

template <typename K, typename V>
class eliminate_oldest_first {

protected:

	void notify_put(const K& k, const V&) {

		_keys.push(k);
	}

	void eliminate_item(std::map<K,V>& cache) {

		UTIL_ASSERT_REL(cache.size(), ==, _keys.size())
		UTIL_ASSERT_REL(cache.size(), >, 0)

		K oldest = _keys.front();
		_keys.pop();

		UTIL_ASSERT_REL(cache.count(oldest), ==, 1)

		cache.erase(oldest);
	}

private:

	std::queue<K> _keys;
};

template <typename K, typename V, typename LimitPolicy = size_limit_policy, typename EliminationPolicy = eliminate_oldest_first<K,V>>
class cache : public LimitPolicy, public EliminationPolicy {

public:

	template <typename Factory>
	V get(const K& k, const Factory& factory) {

		if (_cache.count(k))
			return _cache[k];

		V v = factory();
		put(k, v);

		while (LimitPolicy::limit_exceeded(_cache))
			EliminationPolicy::eliminate_item(_cache);

		return v;
	}

	size_t size() const { return _cache.size(); }

private:

	void put(const K& k, V v) {

		_cache[k] = v;
		EliminationPolicy::notify_put(k, v);
	}

	std::map<K,V> _cache;
};

#endif // UTIL_CACHE_HPP__

<commit_msg>added clear() to cache<commit_after>#ifndef UTIL_CACHE_HPP__
#define UTIL_CACHE_HPP__

#include <map>
#include <queue>
#include "assert.h"

class size_limit_policy {

public:

	size_limit_policy() : _max_size(256) {}

	void set_max_size(size_t size) { _max_size = size; }

protected:

	template <typename K, typename V>
	bool limit_exceeded(const std::map<K,V>& cache) const {

		return (cache.size() > _max_size);
	}

private:

	size_t _max_size;
};

template <typename K, typename V>
class eliminate_oldest_first {

protected:

	void notify_put(const K& k, const V&) {

		_keys.push(k);
	}

	void eliminate_item(std::map<K,V>& cache) {

		UTIL_ASSERT_REL(cache.size(), ==, _keys.size())
		UTIL_ASSERT_REL(cache.size(), >, 0)

		K oldest = _keys.front();
		_keys.pop();

		UTIL_ASSERT_REL(cache.count(oldest), ==, 1)

		cache.erase(oldest);
	}

private:

	std::queue<K> _keys;
};

template <typename K, typename V, typename LimitPolicy = size_limit_policy, typename EliminationPolicy = eliminate_oldest_first<K,V>>
class cache : public LimitPolicy, public EliminationPolicy {

public:

	template <typename Factory>
	V get(const K& k, const Factory& factory) {

		if (_cache.count(k))
			return _cache[k];

		V v = factory();
		put(k, v);

		while (LimitPolicy::limit_exceeded(_cache))
			EliminationPolicy::eliminate_item(_cache);

		return v;
	}

	size_t size() const { return _cache.size(); }

	bool clear() { if (!size()) return false; _cache.clear(); return true; }

private:

	void put(const K& k, V v) {

		_cache[k] = v;
		EliminationPolicy::notify_put(k, v);
	}

	std::map<K,V> _cache;
};

#endif // UTIL_CACHE_HPP__

<|endoftext|>


<commit_before>/******************************************************************************

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

******************************************************************************/
#include "nomlib/graphics/Image.hpp"

namespace nom {

Image::Image ( void ) : image_ ( nullptr, priv::FreeSurface )
{
  NOM_LOG_TRACE ( NOM );
}

Image::~Image ( void )
{
  NOM_LOG_TRACE ( NOM );
}

Image::Image ( uint32 flags ) : image_ ( nullptr, priv::FreeSurface )
{
NOM_LOG_TRACE ( NOM );

  if ( IMG_Init ( flags ) != flags )
  {
NOM_LOG_ERR ( NOM, IMG_GetError() );
  }

  atexit ( IMG_Quit );
}

Image::Image ( const Image& copy )  :
  image_ { copy.image(), priv::FreeSurface },
  position_ { copy.position_ }
{
  NOM_LOG_TRACE ( NOM );
}

Image& Image::operator = ( const Image& other )
{
  this->image_ = other.image_;
  this->position_ = other.position_;

  return *this;
}

Image::SharedPtr Image::clone ( void ) const
{
  return Image::SharedPtr ( new Image ( *this ) );
}

bool Image::initialize( void* pixels, int32 width, int32 height,
                        int32 bits_per_pixel, uint16 pitch,
                        uint32 Rmask, uint32 Gmask, uint32 Bmask, uint32 Amask
                      )
{
  NOM_LOG_TRACE ( NOM );

  this->image_.reset ( SDL_CreateRGBSurfaceFrom ( pixels, width, height, bits_per_pixel, pitch, Rmask, Gmask, Bmask, Amask ), priv::FreeSurface );
  //this->set_bounds ( IntRect( 0, 0, width, height) );

  if ( this->valid() == false )
  {
    NOM_LOG_ERR ( NOM, SDL_GetError() );
    return false;
  }

  return true;
}

bool Image::initialize ( int32 width, int32 height, uint8 bits_per_pixel, uint32 Rmask, uint32 Gmask, uint32 Bmask, uint32 Amask )
{
  NOM_LOG_TRACE ( NOM );

  this->image_.reset ( SDL_CreateRGBSurface ( 0, width, height, bits_per_pixel, Rmask, Gmask, Bmask, Amask ), priv::FreeSurface );
  //this->set_bounds ( IntRect( 0, 0, width, height) );

  if ( this->valid() == false )
  {
NOM_LOG_ERR ( NOM, SDL_GetError() );
    return false;
  }

  // If the video surface is marked for color keying transparency, we need to
  // set it up here and now!
  // if ( colorkey )
  // {
  //   if ( this->set_colorkey ( this->colorkey(), true ) == false )
  //   {
  //     NOM_LOG_ERR ( NOM, "Could not create the video surface with color key transparency." );
  //     return false;
  //   }
  // }

  return true;
}

bool Image::initialize ( SDL_SURFACE::RawPtr buffer )
{
  if ( this->valid() == true ) this->image_.reset();

  this->image_.reset ( buffer, priv::FreeSurface );

  if ( this->valid() == false )
  {
    NOM_LOG_ERR ( NOM, "Could not initialize Image from existing surface: " + std::string(SDL_GetError()) );
    return false;
  }

  return true;
}

bool Image::initialize ( const Point2i& size, uint8 bpp )
{
  // Let SDL handle figuring out the color masks
  if ( this->initialize ( size.x, size.y, bpp, 0, 0, 0, 0 ) == false )
  {
    NOM_LOG_ERR(NOM,"Could not initialize Image from dimensions:" );
    NOM_DUMP_VAR(size.x);
    NOM_DUMP_VAR(size.y);
    return false;
  }

  return true;
}

Image::RawPtr Image::get ( void ) const
{
  return this;
}

SDL_SURFACE::RawPtr Image::image ( void ) const
{
  return this->image_.get();
}

bool Image::valid ( void ) const
{
  if ( this->image() != nullptr ) return true;

  return false;
}

int32 Image::width ( void ) const
{
  SDL_Surface* buffer = this->image();
  return buffer->w;
}

int32 Image::height ( void ) const
{
  SDL_Surface* buffer = this->image();
  return buffer->h;
}

void* Image::pixels ( void ) const
{
  SDL_Surface* buffer = this->image();
  return buffer->pixels;
}

uint16 Image::pitch ( void ) const
{
  SDL_Surface* buffer = this->image();
  return buffer->pitch;
}

uint8 Image::bits_per_pixel ( void ) const
{
  SDL_Surface* buffer = this->image();

  return buffer->format->BitsPerPixel;
}

const SDL_PIXELFORMAT::RawPtr Image::pixel_format ( void ) const
{
  SDL_Surface* buffer = this->image();
  return buffer->format;
}

const uint32 Image::red_mask ( void ) const
{
  return this->pixel_format()->Rmask;
}

const uint32 Image::green_mask ( void ) const
{
  return this->pixel_format()->Gmask;
}

const uint32 Image::blue_mask ( void ) const
{
  return this->pixel_format()->Bmask;
}

const uint32 Image::alpha_mask ( void ) const
{
  return this->pixel_format()->Amask;
}

const IntRect Image::bounds ( void ) const
{
  SDL_Rect bounds;

  // Return values are put into the clip_buffer SDL_Rect after executing:
  SDL_GetClipRect ( this->image(), &bounds );

  // Now transfer the values into our preferred data container type
  return IntRect(bounds.x, bounds.y, bounds.w, bounds.h);
}

bool Image::must_lock ( void ) const
{
  if ( SDL_MUSTLOCK ( this->image() ) ) return true;

  return false;
}

bool Image::locked ( void ) const
{
  return this->image()->locked;
}

const uint8 Image::alpha ( void ) const
{
  uint8 alpha;

  if ( SDL_GetSurfaceAlphaMod ( this->image(), &alpha ) != 0 )
  {
    NOM_LOG_ERR ( NOM, SDL_GetError() );
    return 0;
  }

  return alpha;
}

void Image::set_bounds ( const IntRect& bounds )
{
  SDL_Rect clip = SDL_RECT(bounds);

  // As per libSDL docs, if SDL_Rect is nullptr, the clipping rectangle is set
  // to the full size of the surface
  SDL_SetClipRect ( this->image(), &clip );
}

bool Image::load ( const std::string& filename, uint32 pixel_format )
{
  SDL_Surface *buffer = IMG_Load ( filename.c_str() );

  if ( buffer == nullptr )
  {
NOM_LOG_ERR ( NOM, IMG_GetError() );
    priv::FreeSurface ( buffer );
    return false;
  }

  this->image_.reset ( SDL_ConvertSurfaceFormat ( buffer, pixel_format, 0 ), priv::FreeSurface );
  priv::FreeSurface ( buffer );

  return true;
}

bool Image::load_bmp ( const std::string& filename, uint32 pixel_format )
{
  SDL_Surface *buffer = IMG_Load ( filename.c_str() );
  if ( buffer == nullptr )
  {
    NOM_LOG_ERR ( NOM, IMG_GetError() );
    priv::FreeSurface ( buffer );
    return false;
  }

  this->image_.reset ( SDL_ConvertSurfaceFormat ( buffer, pixel_format, 0 ), priv::FreeSurface );
  priv::FreeSurface ( buffer );

  return true;
}

bool Image::save_bmp ( const std::string& filename ) const
{
  if ( SDL_SaveBMP ( this->image(), filename.c_str() ) != 0 )
  {
    NOM_LOG_ERR ( NOM, SDL_GetError() );
    return false;
  }

  return true;
}

bool Image::save_png ( const std::string& filename ) const
{
  // Undocumented method for writing out a PNG file with SDL2_image
  if ( IMG_SavePNG ( this->image(), filename.c_str() ) != 0 )
  {
    NOM_LOG_ERR ( NOM, SDL_GetError() );
    return false;
  }

  return true;
}

const Point2i Image::size ( void ) const
{
  SDL_Surface* buffer = this->image();
  Point2i image_pos ( buffer->w, buffer->h );

  return image_pos;
}

const Color4u Image::colorkey ( void ) const
{
  SDL_Surface* buffer = this->image();
  uint32 transparent_color = 0;
  Color4u key;

  if ( SDL_GetColorKey ( this->image(), &transparent_color ) != 0 )
  {
    NOM_LOG_ERR ( NOM, SDL_GetError() );
    return NOM_COLOR4U_BLACK;
  }

  return nom::pixel ( transparent_color, buffer->format ); // SDL_helper function
}

const SDL_BlendMode Image::blend_mode ( void ) const
{
  SDL_BlendMode blend;

  if ( SDL_GetSurfaceBlendMode ( this->image(), &blend ) != 0 )
  {
NOM_LOG_ERR ( NOM, SDL_GetError() );
    return blend;
  }

  return blend;
}

const Point2i Image::position ( void ) const
{
  return this->position_;
}

bool Image::set_colorkey ( const Color4u& colorkey, bool flag )
{
  SDL_Surface* buffer = this->image();
  uint32 transparent_color = RGB ( colorkey, buffer->format );

  if ( this->valid() == false )
  {
NOM_LOG_ERR ( NOM, "Could not set color key: invalid image buffer." );
    priv::FreeSurface ( buffer );
    return false;
  }

  if ( SDL_SetColorKey ( buffer, SDL_BOOL(flag), transparent_color ) != 0 )
  {
NOM_LOG_ERR ( NOM, SDL_GetError() );
    priv::FreeSurface ( buffer );
    return false;
  }

  return true;
}

bool Image::RLE ( bool flag )
{
  if ( SDL_SetSurfaceRLE ( this->image(), SDL_BOOL(flag) ) != 0 )
  {
NOM_LOG_ERR ( NOM, SDL_GetError() );
    return false;
  }
  return true;
}

uint32 Image::pixel ( int32 x, int32 y )
{
  switch ( this->bits_per_pixel() )
  {
    default: return -1; break; // Unknown

    case 8:
    {
      uint8* pixels = static_cast<uint8*> ( this->pixels() );

      return pixels[ ( y * this->pitch() ) + x ];
    }
    break;

    case 16:
    {
      uint16* pixels = static_cast<uint16*> ( this->pixels() );

      return pixels[ ( y * this->pitch() / 2 ) + x ];
    }
    break;

    case 24:
    {
      uint8* pixels = static_cast<uint8*> ( this->pixels() );

      return pixels[ ( y * this->pitch() ) + x ];
    }
    break;

    case 32:
    {
      uint32* pixels = static_cast<uint32*> ( this->pixels() );

      return pixels[ ( y * this->pitch()/4 ) + x ];
    }
    break;
  } // end switch
}

bool Image::set_blend_mode ( const SDL_BlendMode blend )
{
  if ( SDL_SetSurfaceBlendMode ( this->image(), blend ) != 0 )
  {
NOM_LOG_ERR ( NOM, SDL_GetError() );
    return false;
  }

  return true;
}

bool Image::lock ( void ) const
{
  if ( SDL_BOOL ( this->must_lock() ) )
  {
    if ( SDL_LockSurface ( this->image() ) != 0 )
    {
NOM_LOG_ERR ( NOM, "Could not lock video surface memory." );
      return false;
    }
  }

  return true;
}

void Image::unlock ( void ) const
{
  SDL_UnlockSurface ( this->image() );
}

bool Image::set_alpha ( uint8 opacity )
{
  NOM_ASSERT ( ! ( opacity > nom::ALPHA_OPAQUE ) || ( opacity < nom::ALPHA_TRANSPARENT ) );

  if ( SDL_SetSurfaceAlphaMod ( this->image(), opacity ) != 0 )
  {
    NOM_LOG_ERR ( NOM, SDL_GetError() );
    return false;
  }

  return true;
}

void Image::set_position ( const Point2i& pos )
{
  this->position_.x = pos.x;
  this->position_.y = pos.y;
}

} // namespace nom
<commit_msg>Image: Add additional err checks to save_[bmp|png] methods<commit_after>/******************************************************************************

  nomlib - C++11 cross-platform game engine

Copyright (c) 2013, Jeffrey Carpenter <jeffrey.carp@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

******************************************************************************/
#include "nomlib/graphics/Image.hpp"

namespace nom {

Image::Image ( void ) : image_ ( nullptr, priv::FreeSurface )
{
  NOM_LOG_TRACE ( NOM );
}

Image::~Image ( void )
{
  NOM_LOG_TRACE ( NOM );
}

Image::Image ( uint32 flags ) : image_ ( nullptr, priv::FreeSurface )
{
NOM_LOG_TRACE ( NOM );

  if ( IMG_Init ( flags ) != flags )
  {
NOM_LOG_ERR ( NOM, IMG_GetError() );
  }

  atexit ( IMG_Quit );
}

Image::Image ( const Image& copy )  :
  image_ { copy.image(), priv::FreeSurface },
  position_ { copy.position_ }
{
  NOM_LOG_TRACE ( NOM );
}

Image& Image::operator = ( const Image& other )
{
  this->image_ = other.image_;
  this->position_ = other.position_;

  return *this;
}

Image::SharedPtr Image::clone ( void ) const
{
  return Image::SharedPtr ( new Image ( *this ) );
}

bool Image::initialize( void* pixels, int32 width, int32 height,
                        int32 bits_per_pixel, uint16 pitch,
                        uint32 Rmask, uint32 Gmask, uint32 Bmask, uint32 Amask
                      )
{
  NOM_LOG_TRACE ( NOM );

  this->image_.reset ( SDL_CreateRGBSurfaceFrom ( pixels, width, height, bits_per_pixel, pitch, Rmask, Gmask, Bmask, Amask ), priv::FreeSurface );
  //this->set_bounds ( IntRect( 0, 0, width, height) );

  if ( this->valid() == false )
  {
    NOM_LOG_ERR ( NOM, SDL_GetError() );
    return false;
  }

  return true;
}

bool Image::initialize ( int32 width, int32 height, uint8 bits_per_pixel, uint32 Rmask, uint32 Gmask, uint32 Bmask, uint32 Amask )
{
  NOM_LOG_TRACE ( NOM );

  this->image_.reset ( SDL_CreateRGBSurface ( 0, width, height, bits_per_pixel, Rmask, Gmask, Bmask, Amask ), priv::FreeSurface );
  //this->set_bounds ( IntRect( 0, 0, width, height) );

  if ( this->valid() == false )
  {
NOM_LOG_ERR ( NOM, SDL_GetError() );
    return false;
  }

  // If the video surface is marked for color keying transparency, we need to
  // set it up here and now!
  // if ( colorkey )
  // {
  //   if ( this->set_colorkey ( this->colorkey(), true ) == false )
  //   {
  //     NOM_LOG_ERR ( NOM, "Could not create the video surface with color key transparency." );
  //     return false;
  //   }
  // }

  return true;
}

bool Image::initialize ( SDL_SURFACE::RawPtr buffer )
{
  if ( this->valid() == true ) this->image_.reset();

  this->image_.reset ( buffer, priv::FreeSurface );

  if ( this->valid() == false )
  {
    NOM_LOG_ERR ( NOM, "Could not initialize Image from existing surface: " + std::string(SDL_GetError()) );
    return false;
  }

  return true;
}

bool Image::initialize ( const Point2i& size, uint8 bpp )
{
  // Let SDL handle figuring out the color masks
  if ( this->initialize ( size.x, size.y, bpp, 0, 0, 0, 0 ) == false )
  {
    NOM_LOG_ERR(NOM,"Could not initialize Image from dimensions:" );
    NOM_DUMP_VAR(size.x);
    NOM_DUMP_VAR(size.y);
    return false;
  }

  return true;
}

Image::RawPtr Image::get ( void ) const
{
  return this;
}

SDL_SURFACE::RawPtr Image::image ( void ) const
{
  return this->image_.get();
}

bool Image::valid ( void ) const
{
  if ( this->image() != nullptr ) return true;

  return false;
}

int32 Image::width ( void ) const
{
  SDL_Surface* buffer = this->image();
  return buffer->w;
}

int32 Image::height ( void ) const
{
  SDL_Surface* buffer = this->image();
  return buffer->h;
}

void* Image::pixels ( void ) const
{
  SDL_Surface* buffer = this->image();
  return buffer->pixels;
}

uint16 Image::pitch ( void ) const
{
  SDL_Surface* buffer = this->image();
  return buffer->pitch;
}

uint8 Image::bits_per_pixel ( void ) const
{
  SDL_Surface* buffer = this->image();

  return buffer->format->BitsPerPixel;
}

const SDL_PIXELFORMAT::RawPtr Image::pixel_format ( void ) const
{
  SDL_Surface* buffer = this->image();
  return buffer->format;
}

const uint32 Image::red_mask ( void ) const
{
  return this->pixel_format()->Rmask;
}

const uint32 Image::green_mask ( void ) const
{
  return this->pixel_format()->Gmask;
}

const uint32 Image::blue_mask ( void ) const
{
  return this->pixel_format()->Bmask;
}

const uint32 Image::alpha_mask ( void ) const
{
  return this->pixel_format()->Amask;
}

const IntRect Image::bounds ( void ) const
{
  SDL_Rect bounds;

  // Return values are put into the clip_buffer SDL_Rect after executing:
  SDL_GetClipRect ( this->image(), &bounds );

  // Now transfer the values into our preferred data container type
  return IntRect(bounds.x, bounds.y, bounds.w, bounds.h);
}

bool Image::must_lock ( void ) const
{
  if ( SDL_MUSTLOCK ( this->image() ) ) return true;

  return false;
}

bool Image::locked ( void ) const
{
  return this->image()->locked;
}

const uint8 Image::alpha ( void ) const
{
  uint8 alpha;

  if ( SDL_GetSurfaceAlphaMod ( this->image(), &alpha ) != 0 )
  {
    NOM_LOG_ERR ( NOM, SDL_GetError() );
    return 0;
  }

  return alpha;
}

void Image::set_bounds ( const IntRect& bounds )
{
  SDL_Rect clip = SDL_RECT(bounds);

  // As per libSDL docs, if SDL_Rect is nullptr, the clipping rectangle is set
  // to the full size of the surface
  SDL_SetClipRect ( this->image(), &clip );
}

bool Image::load ( const std::string& filename, uint32 pixel_format )
{
  SDL_Surface *buffer = IMG_Load ( filename.c_str() );

  if ( buffer == nullptr )
  {
NOM_LOG_ERR ( NOM, IMG_GetError() );
    priv::FreeSurface ( buffer );
    return false;
  }

  this->image_.reset ( SDL_ConvertSurfaceFormat ( buffer, pixel_format, 0 ), priv::FreeSurface );
  priv::FreeSurface ( buffer );

  return true;
}

bool Image::load_bmp ( const std::string& filename, uint32 pixel_format )
{
  SDL_Surface *buffer = IMG_Load ( filename.c_str() );
  if ( buffer == nullptr )
  {
    NOM_LOG_ERR ( NOM, IMG_GetError() );
    priv::FreeSurface ( buffer );
    return false;
  }

  this->image_.reset ( SDL_ConvertSurfaceFormat ( buffer, pixel_format, 0 ), priv::FreeSurface );
  priv::FreeSurface ( buffer );

  return true;
}

bool Image::save_bmp ( const std::string& filename ) const
{
  if ( this->valid() == false )
  {
    NOM_LOG_ERR(NOM, "Image is not valid for saving output" );
    return false;
  }

  if ( SDL_SaveBMP ( this->image(), filename.c_str() ) != 0 )
  {
    NOM_LOG_ERR ( NOM, SDL_GetError() );
    return false;
  }

  return true;
}

bool Image::save_png ( const std::string& filename ) const
{
  if ( this->valid() == false )
  {
    NOM_LOG_ERR(NOM, "Image is not valid for saving output" );
    return false;
  }

  // Undocumented method for writing out a PNG file with SDL2_image
  if ( IMG_SavePNG ( this->image(), filename.c_str() ) != 0 )
  {
    NOM_LOG_ERR ( NOM, SDL_GetError() );
    return false;
  }

  return true;
}

const Point2i Image::size ( void ) const
{
  SDL_Surface* buffer = this->image();
  Point2i image_pos ( buffer->w, buffer->h );

  return image_pos;
}

const Color4u Image::colorkey ( void ) const
{
  SDL_Surface* buffer = this->image();
  uint32 transparent_color = 0;
  Color4u key;

  if ( SDL_GetColorKey ( this->image(), &transparent_color ) != 0 )
  {
    NOM_LOG_ERR ( NOM, SDL_GetError() );
    return NOM_COLOR4U_BLACK;
  }

  return nom::pixel ( transparent_color, buffer->format ); // SDL_helper function
}

const SDL_BlendMode Image::blend_mode ( void ) const
{
  SDL_BlendMode blend;

  if ( SDL_GetSurfaceBlendMode ( this->image(), &blend ) != 0 )
  {
NOM_LOG_ERR ( NOM, SDL_GetError() );
    return blend;
  }

  return blend;
}

const Point2i Image::position ( void ) const
{
  return this->position_;
}

bool Image::set_colorkey ( const Color4u& colorkey, bool flag )
{
  SDL_Surface* buffer = this->image();
  uint32 transparent_color = RGB ( colorkey, buffer->format );

  if ( this->valid() == false )
  {
NOM_LOG_ERR ( NOM, "Could not set color key: invalid image buffer." );
    priv::FreeSurface ( buffer );
    return false;
  }

  if ( SDL_SetColorKey ( buffer, SDL_BOOL(flag), transparent_color ) != 0 )
  {
NOM_LOG_ERR ( NOM, SDL_GetError() );
    priv::FreeSurface ( buffer );
    return false;
  }

  return true;
}

bool Image::RLE ( bool flag )
{
  if ( SDL_SetSurfaceRLE ( this->image(), SDL_BOOL(flag) ) != 0 )
  {
NOM_LOG_ERR ( NOM, SDL_GetError() );
    return false;
  }
  return true;
}

uint32 Image::pixel ( int32 x, int32 y )
{
  switch ( this->bits_per_pixel() )
  {
    default: return -1; break; // Unknown

    case 8:
    {
      uint8* pixels = static_cast<uint8*> ( this->pixels() );

      return pixels[ ( y * this->pitch() ) + x ];
    }
    break;

    case 16:
    {
      uint16* pixels = static_cast<uint16*> ( this->pixels() );

      return pixels[ ( y * this->pitch() / 2 ) + x ];
    }
    break;

    case 24:
    {
      uint8* pixels = static_cast<uint8*> ( this->pixels() );

      return pixels[ ( y * this->pitch() ) + x ];
    }
    break;

    case 32:
    {
      uint32* pixels = static_cast<uint32*> ( this->pixels() );

      return pixels[ ( y * this->pitch()/4 ) + x ];
    }
    break;
  } // end switch
}

bool Image::set_blend_mode ( const SDL_BlendMode blend )
{
  if ( SDL_SetSurfaceBlendMode ( this->image(), blend ) != 0 )
  {
NOM_LOG_ERR ( NOM, SDL_GetError() );
    return false;
  }

  return true;
}

bool Image::lock ( void ) const
{
  if ( SDL_BOOL ( this->must_lock() ) )
  {
    if ( SDL_LockSurface ( this->image() ) != 0 )
    {
NOM_LOG_ERR ( NOM, "Could not lock video surface memory." );
      return false;
    }
  }

  return true;
}

void Image::unlock ( void ) const
{
  SDL_UnlockSurface ( this->image() );
}

bool Image::set_alpha ( uint8 opacity )
{
  NOM_ASSERT ( ! ( opacity > nom::ALPHA_OPAQUE ) || ( opacity < nom::ALPHA_TRANSPARENT ) );

  if ( SDL_SetSurfaceAlphaMod ( this->image(), opacity ) != 0 )
  {
    NOM_LOG_ERR ( NOM, SDL_GetError() );
    return false;
  }

  return true;
}

void Image::set_position ( const Point2i& pos )
{
  this->position_.x = pos.x;
  this->position_.y = pos.y;
}

} // namespace nom
<|endoftext|>


<commit_before>// =====================================================================================
//
//       Filename:  TANGDIV.cpp
//
//    Description:  http://www.codechef.com/problems/TANGDIV
//
//        Version:  1.0
//        Created:  Wednesday 16 April 2014 01:22:20  IST
//       Revision:  none
//       Compiler:  g++
//
//         Author:  Brajesh Kumar (), kbrajesh176@gmail.com
//   Organization:
//
// =====================================================================================

//Data Structure includes
#include<vector>
#include<stack>
#include<set>
#include<bitset>
#include<map>
#include<queue>
#include<deque>
#include<string>

//Other Includes
#include<iostream>
#include<fstream>
#include<algorithm>
#include<cstring>
#include<cassert>
#include<cstdlib>
#include<cstdio>
#include<cmath>

using namespace std;

#define FOR(i,a,b) for(int i=a;i<b;i++)
#define REP(i,n) FOR(i,0,n)
#define pb push_back
#define mp make_pair
#define s(n) scanf("%d",&n)
#define sl(n) scanf("%lld",&n)
#define sf(n) scanf("%lf",&n)
#define ss(n) scanf("%s",n)
#define fill(a,v) memset(a, v, sizeof a)
#define sz(a) int((a).size())
#define INF (int)1e9
#define EPS 1e-9
#define bitcount __builtin_popcount
#define all(c) (c).begin(), (c).end()
#define maX(a,b) (a>b?a:b)
#define miN(a,b) (a<b?a:b)
#define DREP(a) sort(all(a)); a.erase(unique(all(a)),a.end())
#define INDEX(arr,ind) lower_bound(all(arr),ind)-arr.begin()
#define tr(c,i) for(typeof((c).begin()) i = (c).begin(); i != (c).end(); i++)
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x) != (c).end())

typedef vector<int> VI;
typedef vector<vector<int> > VVI;
typedef long long LL;
typedef vector<long long > VLL;
typedef pair<int, int > PII;
typedef vector< PII > VPII;
/*Main Code*/
#define EXIT_SUCCESS 0
// ===  FUNCTION  ======================================================================
//         Name:  main
//  Description:  main function
// =====================================================================================
//set<int> myset;
    int
main ( int argc, char *argv[] ){
//	ios_base::sync_with_stdio(false);
    int t;
    int n,k,p;
    int x,y;
    for(s(t);t;t--){
        set<int> myset;
        //myset.clear();
        s(n); s(k); s(p);
        REP(i,k){
           s(x); s(y);
           myset.insert(x);
        }

        int flag = true;
        REP(i,p){
            s(x); s(y);
            if(myset.find(x) == myset.end()){
                flag = false;
            }
        }
        if(flag){
            printf("Yes\n");
            //cout<<"Yes\n";
        } else {
            printf("No\n");
            //cout<<"No\n";
        }
    }

	return EXIT_SUCCESS;
}		// ----------  end of function main  ----------

<commit_msg>add tangdiv<commit_after>// =====================================================================================
//
//       Filename:  TANGDIV.cpp
//
//    Description:  http://www.codechef.com/problems/TANGDIV
//
//        Version:  1.0
//        Created:  Wednesday 16 April 2014 01:22:20  IST
//       Revision:  none
//       Compiler:  g++
//
//         Author:  Brajesh Kumar (), kbrajesh176@gmail.com
//   Organization:
//
// =====================================================================================

//Data Structure includes
#include<vector>
#include<stack>
#include<set>
#include<bitset>
#include<map>
#include<queue>
#include<deque>
#include<string>

//Other Includes
#include<iostream>
#include<fstream>
#include<algorithm>
#include<cstring>
#include<cassert>
#include<cstdlib>
#include<cstdio>
#include<cmath>

using namespace std;

#define FOR(i,a,b) for(int i=a;i<b;i++)
#define REP(i,n) FOR(i,0,n)
#define pb push_back
#define mp make_pair
#define s(n) scanf("%d",&n)
#define sl(n) scanf("%lld",&n)
#define sf(n) scanf("%lf",&n)
#define ss(n) scanf("%s",n)
#define fill(a,v) memset(a, v, sizeof a)
#define sz(a) int((a).size())
#define INF (int)1e9
#define EPS 1e-9
#define bitcount __builtin_popcount
#define all(c) (c).begin(), (c).end()
#define maX(a,b) (a>b?a:b)
#define miN(a,b) (a<b?a:b)
#define DREP(a) sort(all(a)); a.erase(unique(all(a)),a.end())
#define INDEX(arr,ind) lower_bound(all(arr),ind)-arr.begin()
#define tr(c,i) for(typeof((c).begin()) i = (c).begin(); i != (c).end(); i++)
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x) != (c).end())

typedef vector<int> VI;
typedef vector<vector<int> > VVI;
typedef long long LL;
typedef vector<long long > VLL;
typedef pair<int, int > PII;
typedef vector< PII > VPII;
/*Main Code*/
#define EXIT_SUCCESS 0
// ===  FUNCTION  ======================================================================
//         Name:  main
//  Description:  main function
// =====================================================================================
//set<int> myset;
    int
main ( int argc, char *argv[] ){
//	ios_base::sync_with_stdio(false);
    int t;
    int n,k,p;
    int x,y;
    for(s(t);t;t--){
        set<int> myset;
        //myset.clear();
        s(n); s(k); s(p);
        REP(i,k){
           s(x); s(y);
           myset.insert(x);
        }

        int flag = true;
        REP(i,p){
            s(x); s(y);
            if(myset.find(x) == myset.end()){
                flag = false;
            }
        }
        if(flag){
            printf("Yes\n");
            //cout<<"Yes\n";
        } else {
            printf("No\n");
            //cout<<"No\n";
        }
    }

	return EXIT_SUCCESS;
}		// ----------  end of function main  ----------

<|endoftext|>


<commit_before>#include "mainwindow.h"

#include <QCloseEvent>

namespace NeovimQt {

MainWindow::MainWindow(NeovimConnector *c, QWidget *parent)
:QMainWindow(parent), m_nvim(0), m_errorWidget(0), m_shell(0),
	m_delayedShow(false)
{
	m_errorWidget = new ErrorWidget();
	newDockWidgetFor(m_errorWidget);
	m_errorWidget->setVisible(false);

	init(c);
}

void MainWindow::init(NeovimConnector *c)
{
	if (m_shell) {
		m_shell->deleteLater();
	}
	if (m_nvim) {
		m_nvim->deleteLater();
	}

	m_nvim = c;
	m_shell = new Shell(c);
	setCentralWidget(m_shell);
	connect(m_shell, SIGNAL(neovimTitleChanged(const QString &)),
			this, SLOT(neovimSetTitle(const QString &)));
	connect(m_nvim, &NeovimConnector::processExited,
			this, &MainWindow::neovimExited);
	connect(m_nvim, &NeovimConnector::error,
			this, &MainWindow::neovimError);
	connect(m_errorWidget, &ErrorWidget::reconnectNeovim,
			this, &MainWindow::reconnectNeovim);
	connect(m_shell, &Shell::neovimResized,
			this, &MainWindow::neovimWidgetResized);
	m_shell->setFocus(Qt::OtherFocusReason);

	if (m_nvim->errorCause()) {
		neovimError(m_nvim->errorCause());
	}
}

QDockWidget* MainWindow::newDockWidgetFor(QWidget *w)
{
	QDockWidget *dock = new QDockWidget(this);
	dock->setAllowedAreas(Qt::TopDockWidgetArea);
	dock->setWidget(w);
	dock->setFeatures(QDockWidget::NoDockWidgetFeatures);
	dock->setTitleBarWidget(new QWidget(this));
	addDockWidget(Qt::TopDockWidgetArea, dock);
	return dock;
}

/** The Neovim process has exited */
void MainWindow::neovimExited(int status)
{
	showIfDelayed();

	if (m_nvim->errorCause() != NeovimConnector::NoError) {
		m_errorWidget->setText(m_nvim->errorString());
		m_errorWidget->showReconnect(m_nvim->canReconnect());
		m_errorWidget->setVisible(true);
	} else if (status != 0) {
		m_errorWidget->setText(QString("Neovim exited with status code (%1)").arg(status));
		m_errorWidget->showReconnect(m_nvim->canReconnect());
		m_errorWidget->setVisible(true);
	} else {
		close();
	}
}
void MainWindow::neovimError(NeovimConnector::NeovimError err)
{
	showIfDelayed();

	switch(err) {
	case NeovimConnector::FailedToStart:
		m_errorWidget->setText("Unable to start nvim: " + m_nvim->errorString());
		break;
	default:
		m_errorWidget->setText(m_nvim->errorString());
	}
	m_errorWidget->showReconnect(m_nvim->canReconnect());
	m_errorWidget->setVisible(true);
}

void MainWindow::neovimSetTitle(const QString &title)
{
	this->setWindowTitle(title);
}

void MainWindow::reconnectNeovim()
{
	if (m_nvim->canReconnect()) {
		init(m_nvim->reconnect());
	}
	m_errorWidget->setVisible(false);
}

void MainWindow::closeEvent(QCloseEvent *ev)
{
	// Never unless the Neovim shell closes too
	if (m_shell->close()) {
		QWidget::closeEvent(ev);
	} else {
		ev->ignore();
	}
}

void MainWindow::neovimWidgetResized(const QSize& newSize)
{
	showIfDelayed();

	if ((windowState() & Qt::WindowMaximized)) {
		if (newSize.width() > width() || newSize.height() > height()) {
			// If the Neovim shell is larger than the main window, resize it
			// to fit
			// TODO: size() is not ideal, if the mainwindow has toolbars, or
			// docks this will be incorrect
			m_shell->resizeNeovim(size());
		}
	} else {
		// Dont use ::adjustSize() here, it does not respect the new sizeHint()
		resize(sizeHint());
	}
}

/**
 * Call show() after a 1s delay or when Neovim connects,
 * whichever comes first
 */
void MainWindow::delayedShow(bool show)
{
	m_delayedShow = show;
	QTimer *t = new QTimer(this);
	t->setSingleShot(true);
	t->setInterval(1000);
	connect(t, &QTimer::timeout, this, &QMainWindow::show);
}

void MainWindow::showIfDelayed()
{
	if (m_delayedShow && !isVisible()) {
		this->show();
	}
	m_delayedShow = false;
}

} // Namespace

<commit_msg>GUI: Fix MainWindow::delayedShow<commit_after>#include "mainwindow.h"

#include <QCloseEvent>

namespace NeovimQt {

MainWindow::MainWindow(NeovimConnector *c, QWidget *parent)
:QMainWindow(parent), m_nvim(0), m_errorWidget(0), m_shell(0),
	m_delayedShow(false)
{
	m_errorWidget = new ErrorWidget();
	newDockWidgetFor(m_errorWidget);
	m_errorWidget->setVisible(false);

	init(c);
}

void MainWindow::init(NeovimConnector *c)
{
	if (m_shell) {
		m_shell->deleteLater();
	}
	if (m_nvim) {
		m_nvim->deleteLater();
	}

	m_nvim = c;
	m_shell = new Shell(c);
	setCentralWidget(m_shell);
	connect(m_shell, SIGNAL(neovimTitleChanged(const QString &)),
			this, SLOT(neovimSetTitle(const QString &)));
	connect(m_nvim, &NeovimConnector::processExited,
			this, &MainWindow::neovimExited);
	connect(m_nvim, &NeovimConnector::error,
			this, &MainWindow::neovimError);
	connect(m_errorWidget, &ErrorWidget::reconnectNeovim,
			this, &MainWindow::reconnectNeovim);
	connect(m_shell, &Shell::neovimResized,
			this, &MainWindow::neovimWidgetResized);
	m_shell->setFocus(Qt::OtherFocusReason);

	if (m_nvim->errorCause()) {
		neovimError(m_nvim->errorCause());
	}
}

QDockWidget* MainWindow::newDockWidgetFor(QWidget *w)
{
	QDockWidget *dock = new QDockWidget(this);
	dock->setAllowedAreas(Qt::TopDockWidgetArea);
	dock->setWidget(w);
	dock->setFeatures(QDockWidget::NoDockWidgetFeatures);
	dock->setTitleBarWidget(new QWidget(this));
	addDockWidget(Qt::TopDockWidgetArea, dock);
	return dock;
}

/** The Neovim process has exited */
void MainWindow::neovimExited(int status)
{
	showIfDelayed();

	if (m_nvim->errorCause() != NeovimConnector::NoError) {
		m_errorWidget->setText(m_nvim->errorString());
		m_errorWidget->showReconnect(m_nvim->canReconnect());
		m_errorWidget->setVisible(true);
	} else if (status != 0) {
		m_errorWidget->setText(QString("Neovim exited with status code (%1)").arg(status));
		m_errorWidget->showReconnect(m_nvim->canReconnect());
		m_errorWidget->setVisible(true);
	} else {
		close();
	}
}
void MainWindow::neovimError(NeovimConnector::NeovimError err)
{
	showIfDelayed();

	switch(err) {
	case NeovimConnector::FailedToStart:
		m_errorWidget->setText("Unable to start nvim: " + m_nvim->errorString());
		break;
	default:
		m_errorWidget->setText(m_nvim->errorString());
	}
	m_errorWidget->showReconnect(m_nvim->canReconnect());
	m_errorWidget->setVisible(true);
}

void MainWindow::neovimSetTitle(const QString &title)
{
	this->setWindowTitle(title);
}

void MainWindow::reconnectNeovim()
{
	if (m_nvim->canReconnect()) {
		init(m_nvim->reconnect());
	}
	m_errorWidget->setVisible(false);
}

void MainWindow::closeEvent(QCloseEvent *ev)
{
	// Never unless the Neovim shell closes too
	if (m_shell->close()) {
		QWidget::closeEvent(ev);
	} else {
		ev->ignore();
	}
}

void MainWindow::neovimWidgetResized(const QSize& newSize)
{
	showIfDelayed();

	if ((windowState() & Qt::WindowMaximized)) {
		if (newSize.width() > width() || newSize.height() > height()) {
			// If the Neovim shell is larger than the main window, resize it
			// to fit
			// TODO: size() is not ideal, if the mainwindow has toolbars, or
			// docks this will be incorrect
			m_shell->resizeNeovim(size());
		}
	} else {
		// Dont use ::adjustSize() here, it does not respect the new sizeHint()
		resize(sizeHint());
	}
}

/**
 * Call show() after a 1s delay or when Neovim connects,
 * whichever comes first
 */
void MainWindow::delayedShow(bool enable)
{
	if (m_nvim->errorCause() != NeovimConnector::NoError) {
		show();
		return;
	}

	m_delayedShow = enable;
	if (enable) {
		QTimer *t = new QTimer(this);
		t->setSingleShot(true);
		t->setInterval(1000);
		connect(t, &QTimer::timeout, this, &QMainWindow::show);
		t->start();
	}
}

void MainWindow::showIfDelayed()
{
	if (m_delayedShow && !isVisible()) {
		this->show();
	}
	m_delayedShow = false;
}

} // Namespace

<|endoftext|>


<commit_before>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "fclaw2d_convenience.h"
#include "amr_forestclaw.H"

int
main (int argc, char **argv)
{
  int			mpiret;
  int			lp;
  MPI_Comm		mpicomm;
  fclaw2d_domain_t	*domain;

  mpiret = MPI_Init (&argc, &argv);
  SC_CHECK_MPI (mpiret);
  mpicomm = MPI_COMM_WORLD;
  lp = SC_LP_PRODUCTION;

  sc_init (mpicomm, 0, 0, NULL, lp);
  p4est_init (NULL, lp);

  // Put this here so that we can read in the minimum level.
  global_parms *gparms = new global_parms();
  gparms->get_inputParams();

  int minlevel = gparms->m_minlevel;
  domain = fclaw2d_domain_new_unitsquare (mpicomm,minlevel);

  fclaw2d_domain_count_levels (domain, lp);

  set_domain_data(domain,gparms);

  amrsetup(domain);
  amrinit(domain);
  amrrun(domain);
  amrreset (domain);

  fclaw2d_domain_destroy (domain);

  sc_finalize ();

  mpiret = MPI_Finalize ();
  SC_CHECK_MPI (mpiret);

  return 0;
}
<commit_msg>Added a few line breaks to see printout from level_count routine.<commit_after>/*
Copyright (c) 2012 Carsten Burstedde, Donna Calhoun
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include "fclaw2d_convenience.h"
#include "amr_forestclaw.H"

int
main (int argc, char **argv)
{
  int			mpiret;
  int			lp;
  MPI_Comm		mpicomm;
  fclaw2d_domain_t	*domain;

  mpiret = MPI_Init (&argc, &argv);
  SC_CHECK_MPI (mpiret);
  mpicomm = MPI_COMM_WORLD;
  lp = SC_LP_PRODUCTION;

  sc_init (mpicomm, 0, 0, NULL, lp);
  p4est_init (NULL, lp);

  // Put this here so that we can read in the minimum level.
  global_parms *gparms = new global_parms();
  gparms->get_inputParams();

  int minlevel = gparms->m_minlevel;
  domain = fclaw2d_domain_new_unitsquare (mpicomm,minlevel);

  printf("\n\n");
  fclaw2d_domain_count_levels (domain, lp);

  set_domain_data(domain,gparms);

  amrsetup(domain);
  amrinit(domain);
  amrrun(domain);
  amrreset (domain);

  fclaw2d_domain_destroy (domain);

  sc_finalize ();

  mpiret = MPI_Finalize ();
  SC_CHECK_MPI (mpiret);

  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AccessiblePageHeaderArea.cxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: kz $ $Date: 2006-07-21 13:06:38 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif

#ifndef _SC_ACCESSIBLEPAGEHEADERAREA_HXX
#include "AccessiblePageHeaderArea.hxx"
#endif
#ifndef _SC_ACCESSIBLETEXT_HXX
#include "AccessibleText.hxx"
#endif
#ifndef SC_ACCESSIBILITYHINTS_HXX
#include "AccessibilityHints.hxx"
#endif
#ifndef SC_UNOGUARD_HXX
#include "unoguard.hxx"
#endif
#ifndef SC_EDITSRC_HXX
#include "editsrc.hxx"
#endif
#include "prevwsh.hxx"
#include "prevloc.hxx"
#ifndef SC_SCRESID_HXX
#include "scresid.hxx"
#endif
#ifndef SC_SC_HRC
#include "sc.hrc"
#endif

#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESTATETYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_
#include <com/sun/star/accessibility/AccessibleEventId.hpp>
#endif

#ifndef _EDITOBJ_HXX
#include <svx/editobj.hxx>
#endif
#ifndef _SVX_ACCESSILE_TEXT_HELPER_HXX_
#include <svx/AccessibleTextHelper.hxx>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX_
#include <unotools/accessiblestatesethelper.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _TOOLKIT_HELPER_CONVERT_HXX_
#include <toolkit/helper/convert.hxx>
#endif

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

    //=====  internal  ========================================================

ScAccessiblePageHeaderArea::ScAccessiblePageHeaderArea(
        const uno::Reference<XAccessible>& rxParent,
        ScPreviewShell* pViewShell,
        const EditTextObject* pEditObj,
        sal_Bool bHeader,
        SvxAdjust eAdjust)
        : ScAccessibleContextBase(rxParent, AccessibleRole::TEXT),
        mpEditObj(pEditObj->Clone()),
        mpTextHelper(NULL),
        mpViewShell(pViewShell),
        mbHeader(bHeader),
        meAdjust(eAdjust)
{
    if (mpViewShell)
        mpViewShell->AddAccessibilityObject(*this);
}

ScAccessiblePageHeaderArea::~ScAccessiblePageHeaderArea(void)
{
    if (!ScAccessibleContextBase::IsDefunc() && !rBHelper.bInDispose)
    {
        // increment refcount to prevent double call off dtor
        osl_incrementInterlockedCount( &m_refCount );
        dispose();
    }
}

void SAL_CALL ScAccessiblePageHeaderArea::disposing()
{
    ScUnoGuard aGuard;
    if (mpViewShell)
    {
        mpViewShell->RemoveAccessibilityObject(*this);
        mpViewShell = NULL;
    }
    if (mpTextHelper)
        DELETEZ(mpTextHelper);
    if (mpEditObj)
        DELETEZ(mpEditObj);

    ScAccessibleContextBase::disposing();
}

//=====  SfxListener  =====================================================

void ScAccessiblePageHeaderArea::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    if (rHint.ISA( SfxSimpleHint ) )
    {
        const SfxSimpleHint& rRef = (const SfxSimpleHint&)rHint;
        // only notify if child exist, otherwise it is not necessary
        if (rRef.GetId() == SC_HINT_ACC_VISAREACHANGED)
        {
            if (mpTextHelper)
                mpTextHelper->UpdateChildren();

            AccessibleEventObject aEvent;
            aEvent.EventId = AccessibleEventId::VISIBLE_DATA_CHANGED;
            aEvent.Source = uno::Reference< XAccessible >(this);
            CommitChange(aEvent);
        }
    }
    ScAccessibleContextBase::Notify(rBC, rHint);
}
    //=====  XAccessibleComponent  ============================================

uno::Reference< XAccessible > SAL_CALL ScAccessiblePageHeaderArea::getAccessibleAtPoint(
        const awt::Point& rPoint )
        throw (uno::RuntimeException)
{
    uno::Reference<XAccessible> xRet;
    if (containsPoint(rPoint))
    {
         ScUnoGuard aGuard;
        IsObjectValid();

        if(!mpTextHelper)
            CreateTextHelper();

        xRet = mpTextHelper->GetAt(rPoint);
    }

    return xRet;
}

    //=====  XAccessibleContext  ==============================================

sal_Int32 SAL_CALL
    ScAccessiblePageHeaderArea::getAccessibleChildCount(void)
                    throw (uno::RuntimeException)
{
    ScUnoGuard aGuard;
    IsObjectValid();
    if (!mpTextHelper)
        CreateTextHelper();
    return mpTextHelper->GetChildCount();
}

uno::Reference< XAccessible > SAL_CALL
    ScAccessiblePageHeaderArea::getAccessibleChild(sal_Int32 nIndex)
        throw (uno::RuntimeException,
        lang::IndexOutOfBoundsException)
{
    ScUnoGuard aGuard;
    IsObjectValid();
    if (!mpTextHelper)
        CreateTextHelper();
    return mpTextHelper->GetChild(nIndex);
}

uno::Reference<XAccessibleStateSet> SAL_CALL
    ScAccessiblePageHeaderArea::getAccessibleStateSet(void)
    throw (uno::RuntimeException)
{
    ScUnoGuard aGuard;
    uno::Reference<XAccessibleStateSet> xParentStates;
    if (getAccessibleParent().is())
    {
        uno::Reference<XAccessibleContext> xParentContext = getAccessibleParent()->getAccessibleContext();
        xParentStates = xParentContext->getAccessibleStateSet();
    }
    utl::AccessibleStateSetHelper* pStateSet = new utl::AccessibleStateSetHelper();
    if (IsDefunc())
        pStateSet->AddState(AccessibleStateType::DEFUNC);
    else
    {
        pStateSet->AddState(AccessibleStateType::ENABLED);
        pStateSet->AddState(AccessibleStateType::MULTI_LINE);
        if (isShowing())
            pStateSet->AddState(AccessibleStateType::SHOWING);
        if (isVisible())
            pStateSet->AddState(AccessibleStateType::VISIBLE);
    }
    return pStateSet;
}

//=====  XServiceInfo  ========================================================

::rtl::OUString SAL_CALL
       ScAccessiblePageHeaderArea::getImplementationName(void)
    throw (uno::RuntimeException)
{
    return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM ("ScAccessiblePageHeaderArea"));
}

uno::Sequence< ::rtl::OUString> SAL_CALL
       ScAccessiblePageHeaderArea::getSupportedServiceNames(void)
    throw (uno::RuntimeException)
{
    uno::Sequence< ::rtl::OUString > aSequence = ScAccessibleContextBase::getSupportedServiceNames();
    sal_Int32 nOldSize(aSequence.getLength());
    aSequence.realloc(nOldSize + 1);
    ::rtl::OUString* pNames = aSequence.getArray();

    pNames[nOldSize] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sheet.AccessiblePageHeaderFooterAreasView"));

    return aSequence;
}

//=====  XTypeProvider  =======================================================

uno::Sequence<sal_Int8> SAL_CALL
    ScAccessiblePageHeaderArea::getImplementationId(void)
    throw (uno::RuntimeException)
{
    ScUnoGuard aGuard;
    IsObjectValid();
    static uno::Sequence<sal_Int8> aId;
    if (aId.getLength() == 0)
    {
        aId.realloc (16);
        rtl_createUuid (reinterpret_cast<sal_uInt8 *>(aId.getArray()), 0, sal_True);
    }
    return aId;
}

//===== internal ==============================================================
rtl::OUString SAL_CALL ScAccessiblePageHeaderArea::createAccessibleDescription(void)
    throw(uno::RuntimeException)
{
    rtl::OUString sDesc;
    switch (meAdjust)
    {
    case SVX_ADJUST_LEFT :
        sDesc = String(ScResId(STR_ACC_LEFTAREA_DESCR));
        break;
    case SVX_ADJUST_RIGHT:
        sDesc = String(ScResId(STR_ACC_RIGHTAREA_DESCR));
        break;
    case SVX_ADJUST_CENTER:
        sDesc = String(ScResId(STR_ACC_CENTERAREA_DESCR));
        break;
    default:
        DBG_ERRORFILE("wrong adjustment found");
    }

    return sDesc;
}

rtl::OUString SAL_CALL ScAccessiblePageHeaderArea::createAccessibleName(void)
    throw (uno::RuntimeException)
{
    rtl::OUString sName;
    switch (meAdjust)
    {
    case SVX_ADJUST_LEFT :
        sName = String(ScResId(STR_ACC_LEFTAREA_NAME));
        break;
    case SVX_ADJUST_RIGHT:
        sName = String(ScResId(STR_ACC_RIGHTAREA_NAME));
        break;
    case SVX_ADJUST_CENTER:
        sName = String(ScResId(STR_ACC_CENTERAREA_NAME));
        break;
    default:
        DBG_ERRORFILE("wrong adjustment found");
    }

    return sName;
}

Rectangle ScAccessiblePageHeaderArea::GetBoundingBoxOnScreen(void) const
    throw(::com::sun::star::uno::RuntimeException)
{
    Rectangle aRect;
    if (mxParent.is())
    {
        uno::Reference<XAccessibleContext> xContext = mxParent->getAccessibleContext();
        uno::Reference<XAccessibleComponent> xComp(xContext, uno::UNO_QUERY);
        if (xComp.is())
        {
            // has the same size and position on screen like the parent
            aRect = Rectangle(VCLPoint(xComp->getLocationOnScreen()), VCLRectangle(xComp->getBounds()).GetSize());
        }
    }
    return aRect;
}

Rectangle ScAccessiblePageHeaderArea::GetBoundingBox(void) const
    throw (::com::sun::star::uno::RuntimeException)
{
    Rectangle aRect;
    if (mxParent.is())
    {
        uno::Reference<XAccessibleContext> xContext = mxParent->getAccessibleContext();
        uno::Reference<XAccessibleComponent> xComp(xContext, uno::UNO_QUERY);
        if (xComp.is())
        {
            // has the same size and position on screen like the parent and so the pos is (0, 0)
            Rectangle aNewRect(Point(0, 0), VCLRectangle(xComp->getBounds()).GetSize());
            aRect = aNewRect;
        }
    }

    return aRect;
}

void ScAccessiblePageHeaderArea::CreateTextHelper()
{
    if (!mpTextHelper)
    {
        ::std::auto_ptr < ScAccessibleTextData > pAccessibleHeaderTextData
            (new ScAccessibleHeaderTextData(mpViewShell, mpEditObj, mbHeader, meAdjust));
        ::std::auto_ptr< SvxEditSource > pEditSource (new ScAccessibilityEditSource(pAccessibleHeaderTextData));

        mpTextHelper = new ::accessibility::AccessibleTextHelper(pEditSource );
        mpTextHelper->SetEventSource(this);
    }
}
<commit_msg>INTEGRATION: CWS dr51 (1.17.86); FILE MERGED 2006/10/30 10:05:42 dr 1.17.86.1: #i68213# set correct event source<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AccessiblePageHeaderArea.cxx,v $
 *
 *  $Revision: 1.18 $
 *
 *  last change: $Author: ihi $ $Date: 2006-12-19 13:26:22 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"

#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif

#ifndef _SC_ACCESSIBLEPAGEHEADERAREA_HXX
#include "AccessiblePageHeaderArea.hxx"
#endif
#ifndef _SC_ACCESSIBLETEXT_HXX
#include "AccessibleText.hxx"
#endif
#ifndef SC_ACCESSIBILITYHINTS_HXX
#include "AccessibilityHints.hxx"
#endif
#ifndef SC_UNOGUARD_HXX
#include "unoguard.hxx"
#endif
#ifndef SC_EDITSRC_HXX
#include "editsrc.hxx"
#endif
#include "prevwsh.hxx"
#include "prevloc.hxx"
#ifndef SC_SCRESID_HXX
#include "scresid.hxx"
#endif
#ifndef SC_SC_HRC
#include "sc.hrc"
#endif

#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLESTATETYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTID_HPP_
#include <com/sun/star/accessibility/AccessibleEventId.hpp>
#endif

#ifndef _EDITOBJ_HXX
#include <svx/editobj.hxx>
#endif
#ifndef _SVX_ACCESSILE_TEXT_HELPER_HXX_
#include <svx/AccessibleTextHelper.hxx>
#endif
#ifndef _RTL_UUID_H_
#include <rtl/uuid.h>
#endif
#ifndef _UTL_ACCESSIBLESTATESETHELPER_HXX_
#include <unotools/accessiblestatesethelper.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _TOOLKIT_HELPER_CONVERT_HXX_
#include <toolkit/helper/convert.hxx>
#endif

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

    //=====  internal  ========================================================

ScAccessiblePageHeaderArea::ScAccessiblePageHeaderArea(
        const uno::Reference<XAccessible>& rxParent,
        ScPreviewShell* pViewShell,
        const EditTextObject* pEditObj,
        sal_Bool bHeader,
        SvxAdjust eAdjust)
        : ScAccessibleContextBase(rxParent, AccessibleRole::TEXT),
        mpEditObj(pEditObj->Clone()),
        mpTextHelper(NULL),
        mpViewShell(pViewShell),
        mbHeader(bHeader),
        meAdjust(eAdjust)
{
    if (mpViewShell)
        mpViewShell->AddAccessibilityObject(*this);
}

ScAccessiblePageHeaderArea::~ScAccessiblePageHeaderArea(void)
{
    if (!ScAccessibleContextBase::IsDefunc() && !rBHelper.bInDispose)
    {
        // increment refcount to prevent double call off dtor
        osl_incrementInterlockedCount( &m_refCount );
        dispose();
    }
}

void SAL_CALL ScAccessiblePageHeaderArea::disposing()
{
    ScUnoGuard aGuard;
    if (mpViewShell)
    {
        mpViewShell->RemoveAccessibilityObject(*this);
        mpViewShell = NULL;
    }
    if (mpTextHelper)
        DELETEZ(mpTextHelper);
    if (mpEditObj)
        DELETEZ(mpEditObj);

    ScAccessibleContextBase::disposing();
}

//=====  SfxListener  =====================================================

void ScAccessiblePageHeaderArea::Notify( SfxBroadcaster& rBC, const SfxHint& rHint )
{
    if (rHint.ISA( SfxSimpleHint ) )
    {
        const SfxSimpleHint& rRef = (const SfxSimpleHint&)rHint;
        // only notify if child exist, otherwise it is not necessary
        if (rRef.GetId() == SC_HINT_ACC_VISAREACHANGED)
        {
            if (mpTextHelper)
                mpTextHelper->UpdateChildren();

            AccessibleEventObject aEvent;
            aEvent.EventId = AccessibleEventId::VISIBLE_DATA_CHANGED;
            aEvent.Source = uno::Reference< XAccessibleContext >(this);
            CommitChange(aEvent);
        }
    }
    ScAccessibleContextBase::Notify(rBC, rHint);
}
    //=====  XAccessibleComponent  ============================================

uno::Reference< XAccessible > SAL_CALL ScAccessiblePageHeaderArea::getAccessibleAtPoint(
        const awt::Point& rPoint )
        throw (uno::RuntimeException)
{
    uno::Reference<XAccessible> xRet;
    if (containsPoint(rPoint))
    {
         ScUnoGuard aGuard;
        IsObjectValid();

        if(!mpTextHelper)
            CreateTextHelper();

        xRet = mpTextHelper->GetAt(rPoint);
    }

    return xRet;
}

    //=====  XAccessibleContext  ==============================================

sal_Int32 SAL_CALL
    ScAccessiblePageHeaderArea::getAccessibleChildCount(void)
                    throw (uno::RuntimeException)
{
    ScUnoGuard aGuard;
    IsObjectValid();
    if (!mpTextHelper)
        CreateTextHelper();
    return mpTextHelper->GetChildCount();
}

uno::Reference< XAccessible > SAL_CALL
    ScAccessiblePageHeaderArea::getAccessibleChild(sal_Int32 nIndex)
        throw (uno::RuntimeException,
        lang::IndexOutOfBoundsException)
{
    ScUnoGuard aGuard;
    IsObjectValid();
    if (!mpTextHelper)
        CreateTextHelper();
    return mpTextHelper->GetChild(nIndex);
}

uno::Reference<XAccessibleStateSet> SAL_CALL
    ScAccessiblePageHeaderArea::getAccessibleStateSet(void)
    throw (uno::RuntimeException)
{
    ScUnoGuard aGuard;
    uno::Reference<XAccessibleStateSet> xParentStates;
    if (getAccessibleParent().is())
    {
        uno::Reference<XAccessibleContext> xParentContext = getAccessibleParent()->getAccessibleContext();
        xParentStates = xParentContext->getAccessibleStateSet();
    }
    utl::AccessibleStateSetHelper* pStateSet = new utl::AccessibleStateSetHelper();
    if (IsDefunc())
        pStateSet->AddState(AccessibleStateType::DEFUNC);
    else
    {
        pStateSet->AddState(AccessibleStateType::ENABLED);
        pStateSet->AddState(AccessibleStateType::MULTI_LINE);
        if (isShowing())
            pStateSet->AddState(AccessibleStateType::SHOWING);
        if (isVisible())
            pStateSet->AddState(AccessibleStateType::VISIBLE);
    }
    return pStateSet;
}

//=====  XServiceInfo  ========================================================

::rtl::OUString SAL_CALL
       ScAccessiblePageHeaderArea::getImplementationName(void)
    throw (uno::RuntimeException)
{
    return rtl::OUString(RTL_CONSTASCII_USTRINGPARAM ("ScAccessiblePageHeaderArea"));
}

uno::Sequence< ::rtl::OUString> SAL_CALL
       ScAccessiblePageHeaderArea::getSupportedServiceNames(void)
    throw (uno::RuntimeException)
{
    uno::Sequence< ::rtl::OUString > aSequence = ScAccessibleContextBase::getSupportedServiceNames();
    sal_Int32 nOldSize(aSequence.getLength());
    aSequence.realloc(nOldSize + 1);
    ::rtl::OUString* pNames = aSequence.getArray();

    pNames[nOldSize] = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sheet.AccessiblePageHeaderFooterAreasView"));

    return aSequence;
}

//=====  XTypeProvider  =======================================================

uno::Sequence<sal_Int8> SAL_CALL
    ScAccessiblePageHeaderArea::getImplementationId(void)
    throw (uno::RuntimeException)
{
    ScUnoGuard aGuard;
    IsObjectValid();
    static uno::Sequence<sal_Int8> aId;
    if (aId.getLength() == 0)
    {
        aId.realloc (16);
        rtl_createUuid (reinterpret_cast<sal_uInt8 *>(aId.getArray()), 0, sal_True);
    }
    return aId;
}

//===== internal ==============================================================
rtl::OUString SAL_CALL ScAccessiblePageHeaderArea::createAccessibleDescription(void)
    throw(uno::RuntimeException)
{
    rtl::OUString sDesc;
    switch (meAdjust)
    {
    case SVX_ADJUST_LEFT :
        sDesc = String(ScResId(STR_ACC_LEFTAREA_DESCR));
        break;
    case SVX_ADJUST_RIGHT:
        sDesc = String(ScResId(STR_ACC_RIGHTAREA_DESCR));
        break;
    case SVX_ADJUST_CENTER:
        sDesc = String(ScResId(STR_ACC_CENTERAREA_DESCR));
        break;
    default:
        DBG_ERRORFILE("wrong adjustment found");
    }

    return sDesc;
}

rtl::OUString SAL_CALL ScAccessiblePageHeaderArea::createAccessibleName(void)
    throw (uno::RuntimeException)
{
    rtl::OUString sName;
    switch (meAdjust)
    {
    case SVX_ADJUST_LEFT :
        sName = String(ScResId(STR_ACC_LEFTAREA_NAME));
        break;
    case SVX_ADJUST_RIGHT:
        sName = String(ScResId(STR_ACC_RIGHTAREA_NAME));
        break;
    case SVX_ADJUST_CENTER:
        sName = String(ScResId(STR_ACC_CENTERAREA_NAME));
        break;
    default:
        DBG_ERRORFILE("wrong adjustment found");
    }

    return sName;
}

Rectangle ScAccessiblePageHeaderArea::GetBoundingBoxOnScreen(void) const
    throw(::com::sun::star::uno::RuntimeException)
{
    Rectangle aRect;
    if (mxParent.is())
    {
        uno::Reference<XAccessibleContext> xContext = mxParent->getAccessibleContext();
        uno::Reference<XAccessibleComponent> xComp(xContext, uno::UNO_QUERY);
        if (xComp.is())
        {
            // has the same size and position on screen like the parent
            aRect = Rectangle(VCLPoint(xComp->getLocationOnScreen()), VCLRectangle(xComp->getBounds()).GetSize());
        }
    }
    return aRect;
}

Rectangle ScAccessiblePageHeaderArea::GetBoundingBox(void) const
    throw (::com::sun::star::uno::RuntimeException)
{
    Rectangle aRect;
    if (mxParent.is())
    {
        uno::Reference<XAccessibleContext> xContext = mxParent->getAccessibleContext();
        uno::Reference<XAccessibleComponent> xComp(xContext, uno::UNO_QUERY);
        if (xComp.is())
        {
            // has the same size and position on screen like the parent and so the pos is (0, 0)
            Rectangle aNewRect(Point(0, 0), VCLRectangle(xComp->getBounds()).GetSize());
            aRect = aNewRect;
        }
    }

    return aRect;
}

void ScAccessiblePageHeaderArea::CreateTextHelper()
{
    if (!mpTextHelper)
    {
        ::std::auto_ptr < ScAccessibleTextData > pAccessibleHeaderTextData
            (new ScAccessibleHeaderTextData(mpViewShell, mpEditObj, mbHeader, meAdjust));
        ::std::auto_ptr< SvxEditSource > pEditSource (new ScAccessibilityEditSource(pAccessibleHeaderTextData));

        mpTextHelper = new ::accessibility::AccessibleTextHelper(pEditSource );
        mpTextHelper->SetEventSource(this);
    }
}
<|endoftext|>