<commit_before>/*
 For more information, please see: http://software.sci.utah.edu

 The MIT License

 Copyright (c) 2012 Scientific Computing and Imaging Institute,
 University of Utah.

 License for the specific language governing rights and limitations under
 Permission is hereby granted, free of charge, to any person obtaining a
 copy of this software and associated documentation files (the "Software"),
 to deal in the Software without restriction, including without limitation
 the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included
 in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 DEALINGS IN THE SOFTWARE.
 */

/// @todo Documentation HardCodedModuleFactory.cc

#include <iostream>
#include <boost/assign.hpp>
#include <boost/foreach.hpp>
#include <Modules/Factory/HardCodedModuleFactory.h>
#include <Dataflow/Network/ModuleDescription.h>
#include <Dataflow/Network/Module.h>
#include <Dataflow/Network/SimpleSourceSink.h>
#include <Modules/Factory/ModuleDescriptionLookup.h>

using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules;
using namespace SCIRun::Modules::Factory;
//
using namespace boost::assign;

ModuleDescriptionLookup::ModuleDescriptionLookup() : includeTestingModules_(false)
{
  /// @todo: is BUILD_TESTING off when we build releases?
#ifdef BUILD_TESTING
  includeTestingModules_ = true;
#endif
  /// @todo: make EVEN MORE generic...macros? xml?
  /// @todo: at least remove duplication of Name,Package,Category here since we should be able to infer from header somehow.

  addEssentialModules();

  addBundleModules();

  /// @todo: possibly use different build setting for these.
  if (includeTestingModules_)
  {
    addTestingModules();
  }

  addBrainSpecificModules();
  addMoreModules();
}

ModuleDescription ModuleDescriptionLookup::lookupDescription(const ModuleLookupInfo& info) const
{
  auto iter = lookup_.find(info);
  if (iter == lookup_.end())
  {
    /// @todo: log
    std::ostringstream ostr;
    ostr << "Error: Undefined module \"" << info.module_name_ << "\"";
    THROW_INVALID_ARGUMENT(ostr.str());
  }
  return iter->second;
}

namespace SCIRun {
  namespace Modules {
    namespace Factory {

      class HardCodedModuleFactoryImpl
      {
      public:
        ModuleDescriptionLookup lookup;
      };

    }}}

HardCodedModuleFactory::HardCodedModuleFactory() : impl_(new HardCodedModuleFactoryImpl)
{
  Module::Builder::use_sink_type(boost::factory<SimpleSink*>());
  Module::Builder::use_source_type(boost::factory<SimpleSource*>());
}

void HardCodedModuleFactory::setStateFactory(SCIRun::Dataflow::Networks::ModuleStateFactoryHandle stateFactory)
{
  stateFactory_ = stateFactory;
  Module::defaultStateFactory_ = stateFactory_;
}

void HardCodedModuleFactory::setAlgorithmFactory(SCIRun::Core::Algorithms::AlgorithmFactoryHandle algoFactory)
{
  Module::defaultAlgoFactory_ = algoFactory;
}

void HardCodedModuleFactory::setReexecutionFactory(SCIRun::Dataflow::Networks::ReexecuteStrategyFactoryHandle reexFactory)
{
  Module::defaultReexFactory_ = reexFactory;
}

ModuleHandle HardCodedModuleFactory::create(const ModuleDescription& desc)
{
  Module::Builder builder;

  if (desc.maker_)
    builder.using_func(desc.maker_);
  else
    builder.with_name(desc.lookupInfo_.module_name_);

  BOOST_FOREACH(const InputPortDescription& input, desc.input_ports_)
  {
    builder.add_input_port(Port::ConstructionParams(input.id, input.datatype, input.isDynamic));
  }
  BOOST_FOREACH(const OutputPortDescription& output, desc.output_ports_)
  {
    builder.add_output_port(Port::ConstructionParams(output.id, output.datatype, output.isDynamic));
  }

  ModuleHandle module = builder.setStateDefaults().build();

  return module;
}

ModuleDescription HardCodedModuleFactory::lookupDescription(const ModuleLookupInfo& info)
{
  return impl_->lookup.lookupDescription(info);
}

const ModuleDescriptionMap& HardCodedModuleFactory::getAllAvailableModuleDescriptions() const
{
  return impl_->lookup.descMap_;
}

const DirectModuleDescriptionLookupMap& HardCodedModuleFactory::getDirectModuleDescriptionLookupMap() const
{
  return impl_->lookup.lookup_;
}

bool SCIRun::Modules::Factory::operator==(const ConnectedPortInfo& lhs, const ConnectedPortInfo& rhs)
{
  return lhs.input == rhs.input && lhs.output == rhs.output;
}

bool SCIRun::Modules::Factory::operator!=(const ConnectedPortInfo& lhs, const ConnectedPortInfo& rhs)
{
  return !(lhs == rhs);
}

bool SCIRun::Modules::Factory::operator<(const ConnectedPortInfo& lhs, const ConnectedPortInfo& rhs)
{
  return true;
}

std::ostream& SCIRun::Modules::Factory::operator<<(std::ostream& o, const ConnectedPortInfo& cpi)
{
  o << "Connected port info: ";
  if (cpi.input.empty())
    o << "[No inputs connected] ";
  else
    for (const auto& p : cpi.input)
    {
      o << "Input[" << p.first << ":" << p.second << "] ";
    }
  if (cpi.output.empty())
    o << "[No outputs connected] ";
  else
    for (const auto& p : cpi.output)
    {
      o << "Output[" << p.first << ":" << p.second << "] ";
    }
  return o;
}

ConnectedPortInfo SCIRun::Modules::Factory::makeConnectedPortInfo(ModuleHandle module)
{
  ConnectedPortInfo cpi;
  if (!module)
    return cpi;
  for (const auto& in : module->inputPorts())
  {
    if (in->nconnections() > 0)
      cpi.input[in->get_typename()]++;
  }
  for (const auto& out : module->outputPorts())
  {
    if (out->nconnections() > 0)
      cpi.output[out->get_typename()]++;
  }
  return cpi;
}

boost::shared_ptr<ModuleReplacementFilter> ModuleReplacementFilterBuilder::build()
{
  ModuleReplacementFilter::ReplaceMap replaceMap;

  for (const auto& infoDesc : descMap_)
  {
    // if (false)
    //   std::cout << infoDesc.first << " --> " << infoDesc.second << std::endl;
    //
    registerModule(replaceMap, infoDesc.first, infoDesc.second.input_ports_, infoDesc.second.output_ports_);
  }

  return boost::make_shared<ModuleReplacementFilter>(std::move(replaceMap));
}

void ModuleReplacementFilterBuilder::registerModule(ModuleReplacementFilter::ReplaceMap& replaceMap,
  const ModuleLookupInfo& info, const InputPortDescriptionList& inputPorts, const OutputPortDescriptionList& outputPorts)
{
  for (const auto& cpi : allPossibleConnectedPortConfigs(inputPorts, outputPorts))
  {
    replaceMap[cpi].push_back(info);
  }
}

namespace
{
  template <typename K, typename V>
  std::map<K,V> unionMaps(const std::map<K,V>& m1, const std::map<K,V>& m2)
  {
    return std::map<K,V>();
  }

  void addOptionsForOneSide(const std::vector<PortDescription>& inputPorts, std::vector<ConnectedPortTypesWithCount>& inputOptions)
  {
    for (const auto& in : inputPorts)
    {
      if (inputOptions.empty())
      {
        inputOptions.push_back({ { in.datatype, 0 } });
        inputOptions.push_back({ { in.datatype, 1 } });
      }
      else
      {
        std::vector<ConnectedPortTypesWithCount> inputOptionsAdditional;
        for (const auto& opt : inputOptions)
        {
          inputOptionsAdditional.push_back(unionMaps(opt, { { in.datatype, 0 } }));
          inputOptionsAdditional.push_back(unionMaps(opt, { { in.datatype, 1 } }));
        }
        std::copy(inputOptionsAdditional.begin(), inputOptionsAdditional.end(), std::back_inserter(inputOptions));
      }
    }
  }
}

std::vector<ConnectedPortInfo> SCIRun::Modules::Factory::allPossibleConnectedPortConfigs(const InputPortDescriptionList& inputPorts,
  const OutputPortDescriptionList& outputPorts)
{
  std::vector<ConnectedPortTypesWithCount> inputOptions, outputOptions;
  addOptionsForOneSide(inputPorts, inputOptions);
  addOptionsForOneSide(outputPorts, outputOptions);

  std::vector<ConnectedPortInfo> cpis;

//NO!: need cartesian product iterator
  std::transform(inputOptions.begin(), inputOptions.end(), outputOptions.begin(), std::back_inserter(cpis),
    [](const ConnectedPortTypesWithCount& in, const ConnectedPortTypesWithCount& out) { return ConnectedPortInfo { in, out }; });

  return cpis;
}

const std::vector<ModuleLookupInfo>& ModuleReplacementFilter::findReplacements(const ConnectedPortInfo& ports) const
{
  auto iter = replaceMap_.find(ports);
  if (iter == replaceMap_.end())
  {
    static const std::vector<ModuleLookupInfo> empty;
    return empty;
  }
  return iter->second;
}
<commit_msg>algo continued<commit_after>/*
 For more information, please see: http://software.sci.utah.edu

 The MIT License

 Copyright (c) 2012 Scientific Computing and Imaging Institute,
 University of Utah.

 License for the specific language governing rights and limitations under
 Permission is hereby granted, free of charge, to any person obtaining a
 copy of this software and associated documentation files (the "Software"),
 to deal in the Software without restriction, including without limitation
 the rights to use, copy, modify, merge, publish, distribute, sublicense,
 and/or sell copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included
 in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 DEALINGS IN THE SOFTWARE.
 */

/// @todo Documentation HardCodedModuleFactory.cc

#include <iostream>
#include <boost/assign.hpp>
#include <boost/foreach.hpp>
#include <Modules/Factory/HardCodedModuleFactory.h>
#include <Dataflow/Network/ModuleDescription.h>
#include <Dataflow/Network/Module.h>
#include <Dataflow/Network/SimpleSourceSink.h>
#include <Modules/Factory/ModuleDescriptionLookup.h>

using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules;
using namespace SCIRun::Modules::Factory;
//
using namespace boost::assign;

ModuleDescriptionLookup::ModuleDescriptionLookup() : includeTestingModules_(false)
{
  /// @todo: is BUILD_TESTING off when we build releases?
#ifdef BUILD_TESTING
  includeTestingModules_ = true;
#endif
  /// @todo: make EVEN MORE generic...macros? xml?
  /// @todo: at least remove duplication of Name,Package,Category here since we should be able to infer from header somehow.

  addEssentialModules();

  addBundleModules();

  /// @todo: possibly use different build setting for these.
  if (includeTestingModules_)
  {
    addTestingModules();
  }

  addBrainSpecificModules();
  addMoreModules();
}

ModuleDescription ModuleDescriptionLookup::lookupDescription(const ModuleLookupInfo& info) const
{
  auto iter = lookup_.find(info);
  if (iter == lookup_.end())
  {
    /// @todo: log
    std::ostringstream ostr;
    ostr << "Error: Undefined module \"" << info.module_name_ << "\"";
    THROW_INVALID_ARGUMENT(ostr.str());
  }
  return iter->second;
}

namespace SCIRun {
  namespace Modules {
    namespace Factory {

      class HardCodedModuleFactoryImpl
      {
      public:
        ModuleDescriptionLookup lookup;
      };

    }}}

HardCodedModuleFactory::HardCodedModuleFactory() : impl_(new HardCodedModuleFactoryImpl)
{
  Module::Builder::use_sink_type(boost::factory<SimpleSink*>());
  Module::Builder::use_source_type(boost::factory<SimpleSource*>());
}

void HardCodedModuleFactory::setStateFactory(SCIRun::Dataflow::Networks::ModuleStateFactoryHandle stateFactory)
{
  stateFactory_ = stateFactory;
  Module::defaultStateFactory_ = stateFactory_;
}

void HardCodedModuleFactory::setAlgorithmFactory(SCIRun::Core::Algorithms::AlgorithmFactoryHandle algoFactory)
{
  Module::defaultAlgoFactory_ = algoFactory;
}

void HardCodedModuleFactory::setReexecutionFactory(SCIRun::Dataflow::Networks::ReexecuteStrategyFactoryHandle reexFactory)
{
  Module::defaultReexFactory_ = reexFactory;
}

ModuleHandle HardCodedModuleFactory::create(const ModuleDescription& desc)
{
  Module::Builder builder;

  if (desc.maker_)
    builder.using_func(desc.maker_);
  else
    builder.with_name(desc.lookupInfo_.module_name_);

  BOOST_FOREACH(const InputPortDescription& input, desc.input_ports_)
  {
    builder.add_input_port(Port::ConstructionParams(input.id, input.datatype, input.isDynamic));
  }
  BOOST_FOREACH(const OutputPortDescription& output, desc.output_ports_)
  {
    builder.add_output_port(Port::ConstructionParams(output.id, output.datatype, output.isDynamic));
  }

  ModuleHandle module = builder.setStateDefaults().build();

  return module;
}

ModuleDescription HardCodedModuleFactory::lookupDescription(const ModuleLookupInfo& info)
{
  return impl_->lookup.lookupDescription(info);
}

const ModuleDescriptionMap& HardCodedModuleFactory::getAllAvailableModuleDescriptions() const
{
  return impl_->lookup.descMap_;
}

const DirectModuleDescriptionLookupMap& HardCodedModuleFactory::getDirectModuleDescriptionLookupMap() const
{
  return impl_->lookup.lookup_;
}

bool SCIRun::Modules::Factory::operator==(const ConnectedPortInfo& lhs, const ConnectedPortInfo& rhs)
{
  return lhs.input == rhs.input && lhs.output == rhs.output;
}

bool SCIRun::Modules::Factory::operator!=(const ConnectedPortInfo& lhs, const ConnectedPortInfo& rhs)
{
  return !(lhs == rhs);
}

bool SCIRun::Modules::Factory::operator<(const ConnectedPortInfo& lhs, const ConnectedPortInfo& rhs)
{
  return true;
}

void print(const std::vector<ConnectedPortTypesWithCount>& cptwc)
{
  std::cout << "Connected port info one side: ";
  if (cptwc.empty())
    std::cout << "[Nothing connected] ";
  else
    for (const auto& cpt : cptwc)
    {
      std::cout << "\t";
      for (const auto& p : cpt)
      {
        std::cout << "Port[" << p.first << ":" << p.second << "] ";
      }
      std::cout << std::endl;
    }
  std::cout << std::endl;
}

std::ostream& SCIRun::Modules::Factory::operator<<(std::ostream& o, const ConnectedPortInfo& cpi)
{
  o << "Connected port info: ";
  if (cpi.input.empty())
    o << "[No inputs connected] ";
  else
    for (const auto& p : cpi.input)
    {
      o << "Input[" << p.first << ":" << p.second << "] ";
    }
  if (cpi.output.empty())
    o << "[No outputs connected] ";
  else
    for (const auto& p : cpi.output)
    {
      o << "Output[" << p.first << ":" << p.second << "] ";
    }
  return o;
}

ConnectedPortInfo SCIRun::Modules::Factory::makeConnectedPortInfo(ModuleHandle module)
{
  ConnectedPortInfo cpi;
  if (!module)
    return cpi;
  for (const auto& in : module->inputPorts())
  {
    if (in->nconnections() > 0)
      cpi.input[in->get_typename()]++;
  }
  for (const auto& out : module->outputPorts())
  {
    if (out->nconnections() > 0)
      cpi.output[out->get_typename()]++;
  }
  return cpi;
}

boost::shared_ptr<ModuleReplacementFilter> ModuleReplacementFilterBuilder::build()
{
  ModuleReplacementFilter::ReplaceMap replaceMap;

  for (const auto& infoDesc : descMap_)
  {
    // if (false)
    //   std::cout << infoDesc.first << " --> " << infoDesc.second << std::endl;
    //
    registerModule(replaceMap, infoDesc.first, infoDesc.second.input_ports_, infoDesc.second.output_ports_);
  }

  return boost::make_shared<ModuleReplacementFilter>(std::move(replaceMap));
}

void ModuleReplacementFilterBuilder::registerModule(ModuleReplacementFilter::ReplaceMap& replaceMap,
  const ModuleLookupInfo& info, const InputPortDescriptionList& inputPorts, const OutputPortDescriptionList& outputPorts)
{
  std::cout << "Module: " << info << std::endl;
  for (const auto& cpi : allPossibleConnectedPortConfigs(inputPorts, outputPorts))
  {
    replaceMap[cpi].push_back(info);
  }
}

namespace
{
  template <typename M>
  M unionMaps(const M& m1, const M& m2)
  {
    M sumUnion(m1);
    for (const auto& p : m2)
    {
      sumUnion[p.first] += p.second;
    }
    return sumUnion;
  }

  void addOptionsForOneSide(const std::vector<PortDescription>& inputPorts, std::vector<ConnectedPortTypesWithCount>& inputOptions)
  {
    for (const auto& in : inputPorts)
    {
      if (inputOptions.empty())
      {
        inputOptions.push_back({ { in.datatype, 0 } });
        inputOptions.push_back({ { in.datatype, 1 } });
      }
      else
      {
        std::vector<ConnectedPortTypesWithCount> inputOptionsAdditional;
        for (const auto& opt : inputOptions)
        {
          {
            inputOptionsAdditional.push_back(unionMaps<ConnectedPortTypesWithCount>(opt, { { in.datatype, 0 } }));
            inputOptionsAdditional.push_back(unionMaps<ConnectedPortTypesWithCount>(opt, { { in.datatype, 1 } }));
          }
        }
        std::copy(inputOptionsAdditional.begin(), inputOptionsAdditional.end(), std::back_inserter(inputOptions));
      }
    }
    std::set<ConnectedPortTypesWithCount> all(inputOptions.begin(), inputOptions.end());
    inputOptions.assign(all.begin(), all.end());
  }
}

std::vector<ConnectedPortInfo> SCIRun::Modules::Factory::allPossibleConnectedPortConfigs(const InputPortDescriptionList& inputPorts,
  const OutputPortDescriptionList& outputPorts)
{
  std::vector<ConnectedPortTypesWithCount> inputOptions, outputOptions;

  static int once = 0;
  const int times = 5;

  addOptionsForOneSide(inputPorts, inputOptions);

  if (once < times)
  {
    std::cout << "input side: " << inputOptions.size() << " combos " << std::endl;
    print(inputOptions);
  }

  addOptionsForOneSide(outputPorts, outputOptions);

  if (once < times)
  {
    std::cout << "output side: " << outputOptions.size() << " combos " << std::endl;
    print(outputOptions);
  }

  std::vector<ConnectedPortInfo> cpis;

  for (const auto& in : inputOptions)
  {
    for (const auto& out : outputOptions)
    {
      cpis.push_back({ in, out });
    }
  }

  if (once < times)
  {
    std::copy(cpis.begin(), cpis.end(), std::ostream_iterator<ConnectedPortInfo>(std::cout, "\n "));
    once++;
  }

  return cpis;
}

const std::vector<ModuleLookupInfo>& ModuleReplacementFilter::findReplacements(const ConnectedPortInfo& ports) const
{
  auto iter = replaceMap_.find(ports);
  if (iter == replaceMap_.end())
  {
    static const std::vector<ModuleLookupInfo> empty;
    return empty;
  }
  return iter->second;
}
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2009 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <Modules/Legacy/Fields/GetFieldBoundary.h>
#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundary.h>

using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules::Fields;

GetFieldBoundary::GetFieldBoundary()
  : Module(ModuleLookupInfo("GetFieldBoundary", "NewField", "SCIRun"), false)
{
  algo_ = algoFactory_->create(get_module_name(), getLogger());
}

void
GetFieldBoundary::execute()
{
  FieldHandle field = getRequiredInput(Field);

  // If parameters changed, do algorithm
  if (inputs_changed_ ||
      !oport_cached("BoundaryField") ||
      !oport_cached("Mapping"))
  {
    update_state(Executing);

    FieldHandle ofield;
    MatrixHandle mapping;

    if (!(algo_.run(field,ofield,mapping))) return;

    send_output_handle("BoundaryField", ofield);
    send_output_handle("Mapping", mapping);
  }
}
<commit_msg>Change output function call<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2009 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

#include <Modules/Legacy/Fields/GetFieldBoundary.h>
#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundary.h>

using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules::Fields;

GetFieldBoundary::GetFieldBoundary()
  : Module(ModuleLookupInfo("GetFieldBoundary", "NewField", "SCIRun"), false)
{
  algo_ = algoFactory_->create(get_module_name(), getLogger());
}

void
GetFieldBoundary::execute()
{
  FieldHandle field = getRequiredInput(Field);

  // If parameters changed, do algorithm
  if (inputs_changed_ ||
      !oport_cached("BoundaryField") ||
      !oport_cached("Mapping"))
  {
    update_state(Executing);

    FieldHandle ofield;
    MatrixHandle mapping;

    if (!(algo_.run(field,ofield,mapping))) return;

    sendOutput(BoundaryField, ofield);
    sendOutput(Mapping, mapping);
  }
}
<|endoftext|>


<commit_before>//===--- ParseRequests.cpp - Parsing Requests -----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Lazy parsing requests
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ParseRequests.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DeclContext.h"
#include "swift/AST/Module.h"
#include "swift/AST/SourceFile.h"
#include "swift/Basic/Defer.h"
#include "swift/Parse/Parser.h"
#include "swift/Subsystems.h"
#include "swift/Syntax/SyntaxArena.h"
#include "swift/Syntax/SyntaxNodes.h"
#include "swift/SyntaxParse/SyntaxTreeCreator.h"

#ifdef SWIFT_SWIFT_PARSER
#include "SwiftParserCompilerSupport.h"
#endif

using namespace swift;

namespace swift {
// Implement the type checker type zone (zone 10).
#define SWIFT_TYPEID_ZONE Parse
#define SWIFT_TYPEID_HEADER "swift/AST/ParseTypeIDZone.def"
#include "swift/Basic/ImplementTypeIDZone.h"
#undef SWIFT_TYPEID_ZONE
#undef SWIFT_TYPEID_HEADER
}

void swift::simple_display(llvm::raw_ostream &out,
                           const FingerprintAndMembers &value) {
  if (value.fingerprint)
    simple_display(out, *value.fingerprint);
  else
    out << "<no fingerprint>";
  out << ", ";
  simple_display(out, value.members);
}

FingerprintAndMembers
ParseMembersRequest::evaluate(Evaluator &evaluator,
                              IterableDeclContext *idc) const {
  SourceFile *sf = idc->getAsGenericContext()->getParentSourceFile();
  ASTContext &ctx = idc->getDecl()->getASTContext();
  auto fileUnit
    = dyn_cast<FileUnit>(idc->getAsGenericContext()->getModuleScopeContext());
  if (!sf) {
    // If there is no parent source file, this is a deserialized or synthesized
    // declaration context, in which case `getMembers()` has all of the members.
    // Filter out the implicitly-generated ones.
    SmallVector<Decl *, 4> members;
    for (auto decl : idc->getMembers()) {
      if (!decl->isImplicit()) {
        members.push_back(decl);
      }
    }

    Optional<Fingerprint> fp = None;
    if (!idc->getDecl()->isImplicit() && fileUnit) {
      fp = fileUnit->loadFingerprint(idc);
    }
    return FingerprintAndMembers{fp, ctx.AllocateCopy(members)};
  }

  unsigned bufferID = *sf->getBufferID();

  // Lexer diagnostics have been emitted during skipping, so we disable lexer's
  // diagnostic engine here.
  Parser parser(bufferID, *sf, /*No Lexer Diags*/nullptr, nullptr, nullptr);
  // Disable libSyntax creation in the delayed parsing.
  parser.SyntaxContext->disable();
  auto declsAndHash = parser.parseDeclListDelayed(idc);
  FingerprintAndMembers fingerprintAndMembers = {declsAndHash.second,
                                                 declsAndHash.first};
  return FingerprintAndMembers{
      fingerprintAndMembers.fingerprint,
      ctx.AllocateCopy(llvm::makeArrayRef(fingerprintAndMembers.members))};
}

BodyAndFingerprint
ParseAbstractFunctionBodyRequest::evaluate(Evaluator &evaluator,
                                           AbstractFunctionDecl *afd) const {
  using BodyKind = AbstractFunctionDecl::BodyKind;

  switch (afd->getBodyKind()) {
  case BodyKind::Deserialized:
  case BodyKind::SILSynthesize:
  case BodyKind::None:
  case BodyKind::Skipped:
    return {};

  case BodyKind::TypeChecked:
  case BodyKind::Parsed:
    return afd->BodyAndFP;

  case BodyKind::Synthesize: {
    BraceStmt *body;
    bool isTypeChecked;

    std::tie(body, isTypeChecked) = (afd->Synthesizer.Fn)(
        afd, afd->Synthesizer.Context);
    assert(body && "cannot synthesize a null body");
    afd->setBodyKind(isTypeChecked ? BodyKind::TypeChecked : BodyKind::Parsed);
    return {body, Fingerprint::ZERO()};
  }

  case BodyKind::Unparsed: {
    // FIXME: How do we configure code completion?
    SourceFile &sf = *afd->getDeclContext()->getParentSourceFile();
    SourceManager &sourceMgr = sf.getASTContext().SourceMgr;
    unsigned bufferID =
        sourceMgr.findBufferContainingLoc(afd->getBodySourceRange().Start);
    Parser parser(bufferID, sf, /*SIL*/ nullptr);
    parser.SyntaxContext->disable();
    auto result = parser.parseAbstractFunctionBodyDelayed(afd);
    afd->setBodyKind(BodyKind::Parsed);
    return result;
  }
  }
  llvm_unreachable("Unhandled BodyKind in switch");
}

//----------------------------------------------------------------------------//
// ParseSourceFileRequest computation.
//----------------------------------------------------------------------------//

/// A thunk that deletes an allocated PersistentParserState. This is needed for
/// us to be able to forward declare a unique_ptr to the state in the AST.
static void deletePersistentParserState(PersistentParserState *state) {
  delete state;
}

SourceFileParsingResult ParseSourceFileRequest::evaluate(Evaluator &evaluator,
                                                         SourceFile *SF) const {
  assert(SF);
  auto &ctx = SF->getASTContext();
  auto bufferID = SF->getBufferID();

  // If there's no buffer, there's nothing to parse.
  if (!bufferID)
    return {};

  std::shared_ptr<SyntaxTreeCreator> sTreeCreator;
  if (SF->shouldBuildSyntaxTree()) {
    sTreeCreator = std::make_shared<SyntaxTreeCreator>(
        ctx.SourceMgr, *bufferID, SF->SyntaxParsingCache, ctx.getSyntaxArena());
  }

  // If we've been asked to silence warnings, do so now. This is needed for
  // secondary files, which can be parsed multiple times.
  auto &diags = ctx.Diags;
  auto didSuppressWarnings = diags.getSuppressWarnings();
  auto shouldSuppress = SF->getParsingOptions().contains(
      SourceFile::ParsingFlags::SuppressWarnings);
  diags.setSuppressWarnings(didSuppressWarnings || shouldSuppress);
  SWIFT_DEFER { diags.setSuppressWarnings(didSuppressWarnings); };

  // If this buffer is for code completion, hook up the state needed by its
  // second pass.
  PersistentParserState *state = nullptr;
  if (ctx.SourceMgr.getCodeCompletionBufferID() == bufferID) {
    state = new PersistentParserState();
    SF->setDelayedParserState({state, &deletePersistentParserState});
  }

  Parser parser(*bufferID, *SF, /*SIL*/ nullptr, state, sTreeCreator);
  PrettyStackTraceParser StackTrace(parser);

  SmallVector<Decl *, 128> decls;
  parser.parseTopLevel(decls);

  Optional<SourceFileSyntax> syntaxRoot;
  if (sTreeCreator) {
    auto rawNode = parser.finalizeSyntaxTree();
    syntaxRoot.emplace(*sTreeCreator->realizeSyntaxRoot(rawNode, *SF));
  }

  Optional<ArrayRef<Token>> tokensRef;
  if (auto tokens = parser.takeTokenReceiver()->finalize())
    tokensRef = ctx.AllocateCopy(*tokens);

#ifdef SWIFT_SWIFT_PARSER
  if ((ctx.LangOpts.hasFeature(Feature::ParserRoundTrip) ||
       ctx.LangOpts.hasFeature(Feature::ParserValidation)) &&
      ctx.SourceMgr.getCodeCompletionBufferID() != bufferID) {
    auto bufferRange = ctx.SourceMgr.getRangeForBuffer(*bufferID);
    unsigned int flags = 0;

    if (ctx.LangOpts.hasFeature(Feature::ParserRoundTrip))
      flags |= SPCC_RoundTrip;

    if (!ctx.Diags.hadAnyError() &&
        ctx.LangOpts.hasFeature(Feature::ParserValidation))
      flags |= SPCC_ParseDiagnostics;

    int roundTripResult =
      swift_parser_consistencyCheck(
        bufferRange.str().data(), bufferRange.getByteLength(),
        SF->getFilename().str().c_str(), flags);

    // FIXME: Produce an error on round-trip failure.
    if (roundTripResult)
      abort();
  }
#endif

  return SourceFileParsingResult{ctx.AllocateCopy(decls), tokensRef,
                                 parser.CurrentTokenHash, syntaxRoot};
}

evaluator::DependencySource ParseSourceFileRequest::readDependencySource(
    const evaluator::DependencyRecorder &e) const {
  return std::get<0>(getStorage());
}

Optional<SourceFileParsingResult>
ParseSourceFileRequest::getCachedResult() const {
  auto *SF = std::get<0>(getStorage());
  auto decls = SF->getCachedTopLevelDecls();
  if (!decls)
    return None;

  Optional<SourceFileSyntax> syntaxRoot;
  if (auto &rootPtr = SF->SyntaxRoot)
    syntaxRoot.emplace(*rootPtr);

  return SourceFileParsingResult{*decls, SF->AllCollectedTokens,
                                 SF->InterfaceHasher, syntaxRoot};
}

void ParseSourceFileRequest::cacheResult(SourceFileParsingResult result) const {
  auto *SF = std::get<0>(getStorage());
  assert(!SF->Decls);
  SF->Decls = result.TopLevelDecls;
  SF->AllCollectedTokens = result.CollectedTokens;
  SF->InterfaceHasher = result.InterfaceHasher;

  if (auto &root = result.SyntaxRoot)
    SF->SyntaxRoot = std::make_unique<SourceFileSyntax>(std::move(*root));

  // Verify the parsed source file.
  verify(*SF);
}

//----------------------------------------------------------------------------//
// CodeCompletionSecondPassRequest computation.
//----------------------------------------------------------------------------//

void swift::simple_display(llvm::raw_ostream &out,
                           const CodeCompletionCallbacksFactory *factory) { }

evaluator::DependencySource
CodeCompletionSecondPassRequest::readDependencySource(
    const evaluator::DependencyRecorder &e) const {
  return std::get<0>(getStorage());
}

// Define request evaluation functions for each of the type checker requests.
static AbstractRequestFunction *parseRequestFunctions[] = {
#define SWIFT_REQUEST(Zone, Name, Sig, Caching, LocOptions)                    \
  reinterpret_cast<AbstractRequestFunction *>(&Name::evaluateRequest),
#include "swift/AST/ParseTypeIDZone.def"
#undef SWIFT_REQUEST
};

void swift::registerParseRequestFunctions(Evaluator &evaluator) {
  evaluator.registerRequestFunctions(Zone::Parse,
                                     parseRequestFunctions);
}
<commit_msg>Ignore SIL Files in Swift Syntax Parser Validation<commit_after>//===--- ParseRequests.cpp - Parsing Requests -----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Lazy parsing requests
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ParseRequests.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DeclContext.h"
#include "swift/AST/Module.h"
#include "swift/AST/SourceFile.h"
#include "swift/Basic/Defer.h"
#include "swift/Parse/Parser.h"
#include "swift/Subsystems.h"
#include "swift/Syntax/SyntaxArena.h"
#include "swift/Syntax/SyntaxNodes.h"
#include "swift/SyntaxParse/SyntaxTreeCreator.h"

#ifdef SWIFT_SWIFT_PARSER
#include "SwiftParserCompilerSupport.h"
#endif

using namespace swift;

namespace swift {
// Implement the type checker type zone (zone 10).
#define SWIFT_TYPEID_ZONE Parse
#define SWIFT_TYPEID_HEADER "swift/AST/ParseTypeIDZone.def"
#include "swift/Basic/ImplementTypeIDZone.h"
#undef SWIFT_TYPEID_ZONE
#undef SWIFT_TYPEID_HEADER
}

void swift::simple_display(llvm::raw_ostream &out,
                           const FingerprintAndMembers &value) {
  if (value.fingerprint)
    simple_display(out, *value.fingerprint);
  else
    out << "<no fingerprint>";
  out << ", ";
  simple_display(out, value.members);
}

FingerprintAndMembers
ParseMembersRequest::evaluate(Evaluator &evaluator,
                              IterableDeclContext *idc) const {
  SourceFile *sf = idc->getAsGenericContext()->getParentSourceFile();
  ASTContext &ctx = idc->getDecl()->getASTContext();
  auto fileUnit
    = dyn_cast<FileUnit>(idc->getAsGenericContext()->getModuleScopeContext());
  if (!sf) {
    // If there is no parent source file, this is a deserialized or synthesized
    // declaration context, in which case `getMembers()` has all of the members.
    // Filter out the implicitly-generated ones.
    SmallVector<Decl *, 4> members;
    for (auto decl : idc->getMembers()) {
      if (!decl->isImplicit()) {
        members.push_back(decl);
      }
    }

    Optional<Fingerprint> fp = None;
    if (!idc->getDecl()->isImplicit() && fileUnit) {
      fp = fileUnit->loadFingerprint(idc);
    }
    return FingerprintAndMembers{fp, ctx.AllocateCopy(members)};
  }

  unsigned bufferID = *sf->getBufferID();

  // Lexer diagnostics have been emitted during skipping, so we disable lexer's
  // diagnostic engine here.
  Parser parser(bufferID, *sf, /*No Lexer Diags*/nullptr, nullptr, nullptr);
  // Disable libSyntax creation in the delayed parsing.
  parser.SyntaxContext->disable();
  auto declsAndHash = parser.parseDeclListDelayed(idc);
  FingerprintAndMembers fingerprintAndMembers = {declsAndHash.second,
                                                 declsAndHash.first};
  return FingerprintAndMembers{
      fingerprintAndMembers.fingerprint,
      ctx.AllocateCopy(llvm::makeArrayRef(fingerprintAndMembers.members))};
}

BodyAndFingerprint
ParseAbstractFunctionBodyRequest::evaluate(Evaluator &evaluator,
                                           AbstractFunctionDecl *afd) const {
  using BodyKind = AbstractFunctionDecl::BodyKind;

  switch (afd->getBodyKind()) {
  case BodyKind::Deserialized:
  case BodyKind::SILSynthesize:
  case BodyKind::None:
  case BodyKind::Skipped:
    return {};

  case BodyKind::TypeChecked:
  case BodyKind::Parsed:
    return afd->BodyAndFP;

  case BodyKind::Synthesize: {
    BraceStmt *body;
    bool isTypeChecked;

    std::tie(body, isTypeChecked) = (afd->Synthesizer.Fn)(
        afd, afd->Synthesizer.Context);
    assert(body && "cannot synthesize a null body");
    afd->setBodyKind(isTypeChecked ? BodyKind::TypeChecked : BodyKind::Parsed);
    return {body, Fingerprint::ZERO()};
  }

  case BodyKind::Unparsed: {
    // FIXME: How do we configure code completion?
    SourceFile &sf = *afd->getDeclContext()->getParentSourceFile();
    SourceManager &sourceMgr = sf.getASTContext().SourceMgr;
    unsigned bufferID =
        sourceMgr.findBufferContainingLoc(afd->getBodySourceRange().Start);
    Parser parser(bufferID, sf, /*SIL*/ nullptr);
    parser.SyntaxContext->disable();
    auto result = parser.parseAbstractFunctionBodyDelayed(afd);
    afd->setBodyKind(BodyKind::Parsed);
    return result;
  }
  }
  llvm_unreachable("Unhandled BodyKind in switch");
}

//----------------------------------------------------------------------------//
// ParseSourceFileRequest computation.
//----------------------------------------------------------------------------//

/// A thunk that deletes an allocated PersistentParserState. This is needed for
/// us to be able to forward declare a unique_ptr to the state in the AST.
static void deletePersistentParserState(PersistentParserState *state) {
  delete state;
}

SourceFileParsingResult ParseSourceFileRequest::evaluate(Evaluator &evaluator,
                                                         SourceFile *SF) const {
  assert(SF);
  auto &ctx = SF->getASTContext();
  auto bufferID = SF->getBufferID();

  // If there's no buffer, there's nothing to parse.
  if (!bufferID)
    return {};

  std::shared_ptr<SyntaxTreeCreator> sTreeCreator;
  if (SF->shouldBuildSyntaxTree()) {
    sTreeCreator = std::make_shared<SyntaxTreeCreator>(
        ctx.SourceMgr, *bufferID, SF->SyntaxParsingCache, ctx.getSyntaxArena());
  }

  // If we've been asked to silence warnings, do so now. This is needed for
  // secondary files, which can be parsed multiple times.
  auto &diags = ctx.Diags;
  auto didSuppressWarnings = diags.getSuppressWarnings();
  auto shouldSuppress = SF->getParsingOptions().contains(
      SourceFile::ParsingFlags::SuppressWarnings);
  diags.setSuppressWarnings(didSuppressWarnings || shouldSuppress);
  SWIFT_DEFER { diags.setSuppressWarnings(didSuppressWarnings); };

  // If this buffer is for code completion, hook up the state needed by its
  // second pass.
  PersistentParserState *state = nullptr;
  if (ctx.SourceMgr.getCodeCompletionBufferID() == bufferID) {
    state = new PersistentParserState();
    SF->setDelayedParserState({state, &deletePersistentParserState});
  }

  Parser parser(*bufferID, *SF, /*SIL*/ nullptr, state, sTreeCreator);
  PrettyStackTraceParser StackTrace(parser);

  SmallVector<Decl *, 128> decls;
  parser.parseTopLevel(decls);

  Optional<SourceFileSyntax> syntaxRoot;
  if (sTreeCreator) {
    auto rawNode = parser.finalizeSyntaxTree();
    syntaxRoot.emplace(*sTreeCreator->realizeSyntaxRoot(rawNode, *SF));
  }

  Optional<ArrayRef<Token>> tokensRef;
  if (auto tokens = parser.takeTokenReceiver()->finalize())
    tokensRef = ctx.AllocateCopy(*tokens);

#ifdef SWIFT_SWIFT_PARSER
  if ((ctx.LangOpts.hasFeature(Feature::ParserRoundTrip) ||
       ctx.LangOpts.hasFeature(Feature::ParserValidation)) &&
      ctx.SourceMgr.getCodeCompletionBufferID() != bufferID &&
      SF->Kind != SourceFileKind::SIL) {
    auto bufferRange = ctx.SourceMgr.getRangeForBuffer(*bufferID);
    unsigned int flags = 0;

    if (ctx.LangOpts.hasFeature(Feature::ParserRoundTrip))
      flags |= SPCC_RoundTrip;

    if (!ctx.Diags.hadAnyError() &&
        ctx.LangOpts.hasFeature(Feature::ParserValidation))
      flags |= SPCC_ParseDiagnostics;

    int roundTripResult =
      swift_parser_consistencyCheck(
        bufferRange.str().data(), bufferRange.getByteLength(),
        SF->getFilename().str().c_str(), flags);

    // FIXME: Produce an error on round-trip failure.
    if (roundTripResult)
      abort();
  }
#endif

  return SourceFileParsingResult{ctx.AllocateCopy(decls), tokensRef,
                                 parser.CurrentTokenHash, syntaxRoot};
}

evaluator::DependencySource ParseSourceFileRequest::readDependencySource(
    const evaluator::DependencyRecorder &e) const {
  return std::get<0>(getStorage());
}

Optional<SourceFileParsingResult>
ParseSourceFileRequest::getCachedResult() const {
  auto *SF = std::get<0>(getStorage());
  auto decls = SF->getCachedTopLevelDecls();
  if (!decls)
    return None;

  Optional<SourceFileSyntax> syntaxRoot;
  if (auto &rootPtr = SF->SyntaxRoot)
    syntaxRoot.emplace(*rootPtr);

  return SourceFileParsingResult{*decls, SF->AllCollectedTokens,
                                 SF->InterfaceHasher, syntaxRoot};
}

void ParseSourceFileRequest::cacheResult(SourceFileParsingResult result) const {
  auto *SF = std::get<0>(getStorage());
  assert(!SF->Decls);
  SF->Decls = result.TopLevelDecls;
  SF->AllCollectedTokens = result.CollectedTokens;
  SF->InterfaceHasher = result.InterfaceHasher;

  if (auto &root = result.SyntaxRoot)
    SF->SyntaxRoot = std::make_unique<SourceFileSyntax>(std::move(*root));

  // Verify the parsed source file.
  verify(*SF);
}

//----------------------------------------------------------------------------//
// CodeCompletionSecondPassRequest computation.
//----------------------------------------------------------------------------//

void swift::simple_display(llvm::raw_ostream &out,
                           const CodeCompletionCallbacksFactory *factory) { }

evaluator::DependencySource
CodeCompletionSecondPassRequest::readDependencySource(
    const evaluator::DependencyRecorder &e) const {
  return std::get<0>(getStorage());
}

// Define request evaluation functions for each of the type checker requests.
static AbstractRequestFunction *parseRequestFunctions[] = {
#define SWIFT_REQUEST(Zone, Name, Sig, Caching, LocOptions)                    \
  reinterpret_cast<AbstractRequestFunction *>(&Name::evaluateRequest),
#include "swift/AST/ParseTypeIDZone.def"
#undef SWIFT_REQUEST
};

void swift::registerParseRequestFunctions(Evaluator &evaluator) {
  evaluator.registerRequestFunctions(Zone::Parse,
                                     parseRequestFunctions);
}
<|endoftext|>


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

#include <google/protobuf/io/coded_stream.h>
#include <libfuzzer/libfuzzer_macro.h>

#include <atomic>
#include <cstdint>
#include <iosfwd>
#include <memory>
#include <string>
#include <utility>

#include "App.h"
#include "CallTreeView.h"
#include "DataView.h"
#include "DataViewTypes.h"
#include "OrbitBase/ThreadPool.h"
#include "OrbitClientData/ModuleManager.h"
#include "OrbitClientModel/CaptureDeserializer.h"
#include "OrbitClientModel/CaptureSerializer.h"
#include "SamplingReport.h"
#include "StringManager.h"
#include "TimeGraph.h"
#include "absl/flags/flag.h"
#include "capture_data.pb.h"
#include "google/protobuf/io/zero_copy_stream_impl_lite.h"

// Hack: This is declared in a header we include here
// and the definition needs to take place somewhere.
ABSL_FLAG(bool, devmode, false, "Enable developer mode in the client's UI");
ABSL_FLAG(bool, local, false, "Connects to local instance of OrbitService");
ABSL_FLAG(uint16_t, sampling_rate, 1000, "Frequency of callstack sampling in samples per second");
ABSL_FLAG(bool, frame_pointer_unwinding, false, "Use frame pointers for unwinding");
ABSL_FLAG(bool, enable_frame_pointer_validator, false, "Enable validation of frame pointers");
ABSL_FLAG(bool, show_return_values, false, "Show return values on time slices");
ABSL_FLAG(bool, enable_tracepoint_feature, false,
          "Enable the setting of the panel of kernel tracepoints");

DEFINE_PROTO_FUZZER(const orbit_client_protos::CaptureDeserializerFuzzerInfo& info) {
  std::string buffer{};
  {
    google::protobuf::io::StringOutputStream stream{&buffer};
    google::protobuf::io::CodedOutputStream coded_stream{&stream};
    orbit_client_protos::CaptureHeader capture_header{};
    capture_header.set_version("1.55");

    capture_serializer::WriteMessage(&capture_header, &coded_stream);
    capture_serializer::WriteMessage(&info.capture_info(), &coded_stream);
    for (const auto& timer : info.timers()) {
      capture_serializer::WriteMessage(&timer, &coded_stream);
    }
  }

  std::unique_ptr<OrbitApp> app = OrbitApp::Create(nullptr);

  app->SetCaptureStartedCallback([]() {});
  app->SetCaptureStoppedCallback([]() {});
  app->SetCaptureFailedCallback([]() {});
  app->SetCaptureClearedCallback([]() {});
  app->SetOpenCaptureCallback([]() {});
  app->SetOpenCaptureFailedCallback([]() {});
  app->SetOpenCaptureFinishedCallback([]() {});
  app->SetSelectLiveTabCallback([]() {});
  app->SetErrorMessageCallback([](const std::string& /*title*/, const std::string& /*text*/) {});
  app->SetRefreshCallback([](DataViewType /*type*/) {});
  app->SetSamplingReportCallback(
      [](DataView* /*view*/, std::shared_ptr<SamplingReport> /*report*/) {});
  app->SetTopDownViewCallback([](std::unique_ptr<CallTreeView> /*view*/) {});
  app->SetBottomUpViewCallback([](std::unique_ptr<CallTreeView> /*view*/) {});

  TimeGraph time_graph{14, app.get()};
  GCurrentTimeGraph = &time_graph;
  app->ClearCapture();

  // NOLINTNEXTLINE
  std::istringstream input_stream{std::move(buffer)};
  std::atomic<bool> cancellation_requested = false;

  orbit_client_data::ModuleManager module_manager;
  capture_deserializer::Load(input_stream, "", app.get(), &module_manager, &cancellation_requested);

  app->GetThreadPool()->ShutdownAndWait();
}
<commit_msg>Address lint warning in CaptureDeserializerLoadFuzzer<commit_after>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <google/protobuf/io/coded_stream.h>
#include <libfuzzer/libfuzzer_macro.h>

#include <atomic>
#include <cstdint>
#include <iosfwd>
#include <memory>
#include <string>
#include <utility>

#include "App.h"
#include "CallTreeView.h"
#include "DataView.h"
#include "DataViewTypes.h"
#include "OrbitBase/ThreadPool.h"
#include "OrbitClientData/ModuleManager.h"
#include "OrbitClientModel/CaptureDeserializer.h"
#include "OrbitClientModel/CaptureSerializer.h"
#include "SamplingReport.h"
#include "StringManager.h"
#include "TimeGraph.h"
#include "absl/flags/flag.h"
#include "capture_data.pb.h"
#include "google/protobuf/io/zero_copy_stream_impl_lite.h"

// Hack: This is declared in a header we include here
// and the definition needs to take place somewhere.
ABSL_FLAG(bool, devmode, false, "Enable developer mode in the client's UI");
ABSL_FLAG(bool, local, false, "Connects to local instance of OrbitService");
ABSL_FLAG(uint16_t, sampling_rate, 1000, "Frequency of callstack sampling in samples per second");
ABSL_FLAG(bool, frame_pointer_unwinding, false, "Use frame pointers for unwinding");
ABSL_FLAG(bool, enable_frame_pointer_validator, false, "Enable validation of frame pointers");
ABSL_FLAG(bool, show_return_values, false, "Show return values on time slices");
ABSL_FLAG(bool, enable_tracepoint_feature, false,
          "Enable the setting of the panel of kernel tracepoints");

DEFINE_PROTO_FUZZER(const orbit_client_protos::CaptureDeserializerFuzzerInfo& info) {
  std::string buffer{};
  {
    google::protobuf::io::StringOutputStream stream{&buffer};
    google::protobuf::io::CodedOutputStream coded_stream{&stream};
    orbit_client_protos::CaptureHeader capture_header{};
    capture_header.set_version("1.55");

    capture_serializer::WriteMessage(&capture_header, &coded_stream);
    capture_serializer::WriteMessage(&info.capture_info(), &coded_stream);
    for (const auto& timer : info.timers()) {
      capture_serializer::WriteMessage(&timer, &coded_stream);
    }
  }

  std::unique_ptr<OrbitApp> app = OrbitApp::Create(nullptr);

  app->SetCaptureStartedCallback([]() {});
  app->SetCaptureStoppedCallback([]() {});
  app->SetCaptureFailedCallback([]() {});
  app->SetCaptureClearedCallback([]() {});
  app->SetOpenCaptureCallback([]() {});
  app->SetOpenCaptureFailedCallback([]() {});
  app->SetOpenCaptureFinishedCallback([]() {});
  app->SetSelectLiveTabCallback([]() {});
  app->SetErrorMessageCallback([](const std::string& /*title*/, const std::string& /*text*/) {});
  app->SetRefreshCallback([](DataViewType /*type*/) {});
  app->SetSamplingReportCallback(
      [](DataView* /*view*/, const std::shared_ptr<SamplingReport>& /*report*/) {});
  app->SetTopDownViewCallback([](std::unique_ptr<CallTreeView> /*view*/) {});
  app->SetBottomUpViewCallback([](std::unique_ptr<CallTreeView> /*view*/) {});

  TimeGraph time_graph{14, app.get()};
  GCurrentTimeGraph = &time_graph;
  app->ClearCapture();

  // NOLINTNEXTLINE
  std::istringstream input_stream{std::move(buffer)};
  std::atomic<bool> cancellation_requested = false;

  orbit_client_data::ModuleManager module_manager;
  capture_deserializer::Load(input_stream, "", app.get(), &module_manager, &cancellation_requested);

  app->GetThreadPool()->ShutdownAndWait();
}
<|endoftext|>


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

#ifndef _COLLECTION_HXX
#define _COLLECTION_HXX

#include "enumeration.hxx"

#include <cppuhelper/implbase3.hxx>
#include <com/sun/star/container/ElementExistException.hpp>
#include <com/sun/star/container/NoSuchElementException.hpp>
#include <com/sun/star/container/XEnumeration.hpp>
#include <com/sun/star/container/XIndexReplace.hpp>
#include <com/sun/star/container/XSet.hpp>
#include <com/sun/star/container/XContainer.hpp>
#include <com/sun/star/container/XContainerListener.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#include <com/sun/star/lang/WrappedTargetException.hpp>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/uno/Type.hxx>
#include <vector>
#include <algorithm>

typedef cppu::WeakImplHelper3<
    com::sun::star::container::XIndexReplace,
    com::sun::star::container::XSet,
    com::sun::star::container::XContainer>
Collection_t;

template<class ELEMENT_TYPE>
class Collection : public Collection_t
{
public:
    typedef ELEMENT_TYPE T;
    typedef com::sun::star::uno::Reference<com::sun::star::container::XContainerListener> XContainerListener_t;
    typedef std::vector<XContainerListener_t> Listeners_t;

protected:
    std::vector<T> maItems;
    Listeners_t maListeners;

public:

    Collection() {}
    virtual ~Collection() {}

    const T& getItem( sal_Int32 n ) const
    {
        OSL_ENSURE( isValidIndex(n), "invalid index" );
        OSL_ENSURE( isValid( maItems[n] ), "invalid item found" );
        return maItems[n];
    }

    void setItem( sal_Int32 n, const T& t)
    {
        OSL_ENSURE( isValidIndex(n), "invalid index" );
        OSL_ENSURE( isValid ( t ), "invalid item" );

        T& aRef = maItems[ n ];
        _elementReplaced( n, t );
        _remove( aRef );
        aRef = t;
        _insert( t );
    }

    bool hasItem( const T& t ) const
    {
        return maItems.end() != std::find( maItems.begin(), maItems.end(), t );
    }

    sal_Int32 addItem( const T& t )
    {
        OSL_ENSURE( !hasItem( t ), "item to be added already present" );
        OSL_ENSURE( isValid( t ), "invalid item" );

        maItems.push_back( t );
        _insert( t );
        _elementInserted( maItems.size() - 1 );
        return ( maItems.size() - 1 );
    }

    void removeItem( const T& t )
    {
        OSL_ENSURE( hasItem( t ), "item to be removed not present" );
        OSL_ENSURE( isValid( t ), "an invalid item, funny that!" );

        _elementRemoved( t );
        _remove( t );
        maItems.erase( std::find( maItems.begin(), maItems.end(), t ) );
    }

    bool hasItems() const
    {
        return maItems.size() != 0;
    }

    sal_Int32 countItems() const
    {
        return static_cast<sal_Int32>( maItems.size() );
    }

    bool isValidIndex( sal_Int32 n ) const
    {
        return n >= 0  &&  n < static_cast<sal_Int32>( maItems.size() );
    }

    // the following method may be overriden by sub-classes for
    // customized behaviour

    /// called before insertion to determine whether item is valid
    virtual bool isValid( const T& ) const { return true; }

protected:

    // the following methods may be overriden by sub-classes for
    // customized behaviour

    /// called after item has been inserted into the collection
    virtual void _insert( const T& ) { }

    /// called before item is removed from the collection
    virtual void _remove( const T& ) { }

public:

    typedef com::sun::star::uno::Type Type_t;
    typedef com::sun::star::uno::Any Any_t;
    typedef com::sun::star::uno::RuntimeException RuntimeException_t;
    typedef com::sun::star::lang::IllegalArgumentException IllegalArgumentException_t;
    typedef com::sun::star::container::NoSuchElementException NoSuchElementException_t;
    typedef com::sun::star::lang::IndexOutOfBoundsException IndexOutOfBoundsException_t;
    typedef com::sun::star::uno::Reference<com::sun::star::container::XEnumeration> XEnumeration_t;
    typedef com::sun::star::lang::WrappedTargetException WrappedTargetException_t;
    typedef com::sun::star::container::ElementExistException ElementExistException_t;

    // XElementAccess
    virtual Type_t SAL_CALL getElementType()
        throw( RuntimeException_t )
    {
        return getCppuType( static_cast<T*>( NULL ) );
    }

    virtual sal_Bool SAL_CALL hasElements()
        throw( RuntimeException_t )
    {
        return hasItems();
    }

    // XIndexAccess : XElementAccess
    virtual sal_Int32 SAL_CALL getCount()
        throw( RuntimeException_t )
    {
        return countItems();
    }

    virtual Any_t SAL_CALL getByIndex( sal_Int32 nIndex )
        throw( IndexOutOfBoundsException_t,
               WrappedTargetException_t,
               RuntimeException_t)
    {
        if( isValidIndex( nIndex ) )
            return com::sun::star::uno::makeAny( getItem( nIndex ) );
        else
            throw IndexOutOfBoundsException_t();
    }

    // XIndexReplace : XIndexAccess
    virtual void SAL_CALL replaceByIndex( sal_Int32 nIndex,
                                          const Any_t& aElement )
        throw( IllegalArgumentException_t,
               IndexOutOfBoundsException_t,
               WrappedTargetException_t,
               RuntimeException_t)
    {
        T t;
        if( isValidIndex( nIndex) )
            if( ( aElement >>= t )  &&  isValid( t ) )
                setItem( nIndex, t );
            else
                throw IllegalArgumentException_t();
        else
            throw IndexOutOfBoundsException_t();
    }

    // XEnumerationAccess : XElementAccess
    virtual XEnumeration_t SAL_CALL createEnumeration()
        throw( RuntimeException_t )
    {
        return new Enumeration( this );
    }

    // XSet : XEnumerationAccess
    virtual sal_Bool SAL_CALL has( const Any_t& aElement )
        throw( RuntimeException_t )
    {
        T t;
        return ( aElement >>= t ) ? hasItem( t ) : sal_False;
    }

    virtual void SAL_CALL insert( const Any_t& aElement )
        throw( IllegalArgumentException_t,
               ElementExistException_t,
               RuntimeException_t )
    {
        T t;
        if( ( aElement >>= t )  &&  isValid( t ) )
            if( ! hasItem( t ) )
                addItem( t );
            else
                throw ElementExistException_t();
        else
            throw IllegalArgumentException_t();
    }

    virtual void SAL_CALL remove( const Any_t& aElement )
        throw( IllegalArgumentException_t,
               NoSuchElementException_t,
               RuntimeException_t )
    {
        T t;
        if( aElement >>= t )
            if( hasItem( t ) )
                removeItem( t );
            else
                throw NoSuchElementException_t();
        else
            throw IllegalArgumentException_t();
    }

    // XContainer
    virtual void SAL_CALL addContainerListener(
        const XContainerListener_t& xListener )
        throw( RuntimeException_t )
    {
        OSL_ENSURE( xListener.is(), "need listener!" );
        if( std::find( maListeners.begin(), maListeners.end(), xListener)
            == maListeners.end() )
            maListeners.push_back( xListener );
    }

    virtual void SAL_CALL removeContainerListener(
        const XContainerListener_t& xListener )
        throw( RuntimeException_t )
    {
        OSL_ENSURE( xListener.is(), "need listener!" );
        Listeners_t::iterator aIter =
            std::find( maListeners.begin(), maListeners.end(), xListener );
        if( aIter != maListeners.end() )
            maListeners.erase( aIter );
    }

protected:

    // call listeners:
    void _elementInserted( sal_Int32 nPos )
    {
        OSL_ENSURE( isValidIndex(nPos), "invalid index" );
        com::sun::star::container::ContainerEvent aEvent(
            static_cast<com::sun::star::container::XIndexReplace*>( this ),
            com::sun::star::uno::makeAny( nPos ),
            com::sun::star::uno::makeAny( getItem( nPos ) ),
            com::sun::star::uno::Any() );
        for( Listeners_t::iterator aIter = maListeners.begin();
             aIter != maListeners.end();
             aIter++ )
        {
            (*aIter)->elementInserted( aEvent );
        }
    }

    void _elementRemoved( const T& aOld )
    {
        com::sun::star::container::ContainerEvent aEvent(
            static_cast<com::sun::star::container::XIndexReplace*>( this ),
            com::sun::star::uno::Any(),
            com::sun::star::uno::makeAny( aOld ),
            com::sun::star::uno::Any() );
        for( Listeners_t::iterator aIter = maListeners.begin();
             aIter != maListeners.end();
             aIter++ )
        {
            (*aIter)->elementRemoved( aEvent );
        }
    }

    void _elementReplaced( const sal_Int32 nPos, const T& aNew )
    {
        OSL_ENSURE( isValidIndex(nPos), "invalid index" );
        com::sun::star::container::ContainerEvent aEvent(
            static_cast<com::sun::star::container::XIndexReplace*>( this ),
            com::sun::star::uno::makeAny( nPos ),
            com::sun::star::uno::makeAny( getItem( nPos ) ),
            com::sun::star::uno::makeAny( aNew ) );
        for( Listeners_t::iterator aIter = maListeners.begin();
             aIter != maListeners.end();
             aIter++ )
        {
            (*aIter)->elementReplaced( aEvent );
        }
    }

};

#endif

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Prefer prefix ++/-- operators for non-primitive types<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#ifndef _COLLECTION_HXX
#define _COLLECTION_HXX

#include "enumeration.hxx"

#include <cppuhelper/implbase3.hxx>
#include <com/sun/star/container/ElementExistException.hpp>
#include <com/sun/star/container/NoSuchElementException.hpp>
#include <com/sun/star/container/XEnumeration.hpp>
#include <com/sun/star/container/XIndexReplace.hpp>
#include <com/sun/star/container/XSet.hpp>
#include <com/sun/star/container/XContainer.hpp>
#include <com/sun/star/container/XContainerListener.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#include <com/sun/star/lang/WrappedTargetException.hpp>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/uno/Type.hxx>
#include <vector>
#include <algorithm>

typedef cppu::WeakImplHelper3<
    com::sun::star::container::XIndexReplace,
    com::sun::star::container::XSet,
    com::sun::star::container::XContainer>
Collection_t;

template<class ELEMENT_TYPE>
class Collection : public Collection_t
{
public:
    typedef ELEMENT_TYPE T;
    typedef com::sun::star::uno::Reference<com::sun::star::container::XContainerListener> XContainerListener_t;
    typedef std::vector<XContainerListener_t> Listeners_t;

protected:
    std::vector<T> maItems;
    Listeners_t maListeners;

public:

    Collection() {}
    virtual ~Collection() {}

    const T& getItem( sal_Int32 n ) const
    {
        OSL_ENSURE( isValidIndex(n), "invalid index" );
        OSL_ENSURE( isValid( maItems[n] ), "invalid item found" );
        return maItems[n];
    }

    void setItem( sal_Int32 n, const T& t)
    {
        OSL_ENSURE( isValidIndex(n), "invalid index" );
        OSL_ENSURE( isValid ( t ), "invalid item" );

        T& aRef = maItems[ n ];
        _elementReplaced( n, t );
        _remove( aRef );
        aRef = t;
        _insert( t );
    }

    bool hasItem( const T& t ) const
    {
        return maItems.end() != std::find( maItems.begin(), maItems.end(), t );
    }

    sal_Int32 addItem( const T& t )
    {
        OSL_ENSURE( !hasItem( t ), "item to be added already present" );
        OSL_ENSURE( isValid( t ), "invalid item" );

        maItems.push_back( t );
        _insert( t );
        _elementInserted( maItems.size() - 1 );
        return ( maItems.size() - 1 );
    }

    void removeItem( const T& t )
    {
        OSL_ENSURE( hasItem( t ), "item to be removed not present" );
        OSL_ENSURE( isValid( t ), "an invalid item, funny that!" );

        _elementRemoved( t );
        _remove( t );
        maItems.erase( std::find( maItems.begin(), maItems.end(), t ) );
    }

    bool hasItems() const
    {
        return maItems.size() != 0;
    }

    sal_Int32 countItems() const
    {
        return static_cast<sal_Int32>( maItems.size() );
    }

    bool isValidIndex( sal_Int32 n ) const
    {
        return n >= 0  &&  n < static_cast<sal_Int32>( maItems.size() );
    }

    // the following method may be overriden by sub-classes for
    // customized behaviour

    /// called before insertion to determine whether item is valid
    virtual bool isValid( const T& ) const { return true; }

protected:

    // the following methods may be overriden by sub-classes for
    // customized behaviour

    /// called after item has been inserted into the collection
    virtual void _insert( const T& ) { }

    /// called before item is removed from the collection
    virtual void _remove( const T& ) { }

public:

    typedef com::sun::star::uno::Type Type_t;
    typedef com::sun::star::uno::Any Any_t;
    typedef com::sun::star::uno::RuntimeException RuntimeException_t;
    typedef com::sun::star::lang::IllegalArgumentException IllegalArgumentException_t;
    typedef com::sun::star::container::NoSuchElementException NoSuchElementException_t;
    typedef com::sun::star::lang::IndexOutOfBoundsException IndexOutOfBoundsException_t;
    typedef com::sun::star::uno::Reference<com::sun::star::container::XEnumeration> XEnumeration_t;
    typedef com::sun::star::lang::WrappedTargetException WrappedTargetException_t;
    typedef com::sun::star::container::ElementExistException ElementExistException_t;

    // XElementAccess
    virtual Type_t SAL_CALL getElementType()
        throw( RuntimeException_t )
    {
        return getCppuType( static_cast<T*>( NULL ) );
    }

    virtual sal_Bool SAL_CALL hasElements()
        throw( RuntimeException_t )
    {
        return hasItems();
    }

    // XIndexAccess : XElementAccess
    virtual sal_Int32 SAL_CALL getCount()
        throw( RuntimeException_t )
    {
        return countItems();
    }

    virtual Any_t SAL_CALL getByIndex( sal_Int32 nIndex )
        throw( IndexOutOfBoundsException_t,
               WrappedTargetException_t,
               RuntimeException_t)
    {
        if( isValidIndex( nIndex ) )
            return com::sun::star::uno::makeAny( getItem( nIndex ) );
        else
            throw IndexOutOfBoundsException_t();
    }

    // XIndexReplace : XIndexAccess
    virtual void SAL_CALL replaceByIndex( sal_Int32 nIndex,
                                          const Any_t& aElement )
        throw( IllegalArgumentException_t,
               IndexOutOfBoundsException_t,
               WrappedTargetException_t,
               RuntimeException_t)
    {
        T t;
        if( isValidIndex( nIndex) )
            if( ( aElement >>= t )  &&  isValid( t ) )
                setItem( nIndex, t );
            else
                throw IllegalArgumentException_t();
        else
            throw IndexOutOfBoundsException_t();
    }

    // XEnumerationAccess : XElementAccess
    virtual XEnumeration_t SAL_CALL createEnumeration()
        throw( RuntimeException_t )
    {
        return new Enumeration( this );
    }

    // XSet : XEnumerationAccess
    virtual sal_Bool SAL_CALL has( const Any_t& aElement )
        throw( RuntimeException_t )
    {
        T t;
        return ( aElement >>= t ) ? hasItem( t ) : sal_False;
    }

    virtual void SAL_CALL insert( const Any_t& aElement )
        throw( IllegalArgumentException_t,
               ElementExistException_t,
               RuntimeException_t )
    {
        T t;
        if( ( aElement >>= t )  &&  isValid( t ) )
            if( ! hasItem( t ) )
                addItem( t );
            else
                throw ElementExistException_t();
        else
            throw IllegalArgumentException_t();
    }

    virtual void SAL_CALL remove( const Any_t& aElement )
        throw( IllegalArgumentException_t,
               NoSuchElementException_t,
               RuntimeException_t )
    {
        T t;
        if( aElement >>= t )
            if( hasItem( t ) )
                removeItem( t );
            else
                throw NoSuchElementException_t();
        else
            throw IllegalArgumentException_t();
    }

    // XContainer
    virtual void SAL_CALL addContainerListener(
        const XContainerListener_t& xListener )
        throw( RuntimeException_t )
    {
        OSL_ENSURE( xListener.is(), "need listener!" );
        if( std::find( maListeners.begin(), maListeners.end(), xListener)
            == maListeners.end() )
            maListeners.push_back( xListener );
    }

    virtual void SAL_CALL removeContainerListener(
        const XContainerListener_t& xListener )
        throw( RuntimeException_t )
    {
        OSL_ENSURE( xListener.is(), "need listener!" );
        Listeners_t::iterator aIter =
            std::find( maListeners.begin(), maListeners.end(), xListener );
        if( aIter != maListeners.end() )
            maListeners.erase( aIter );
    }

protected:

    // call listeners:
    void _elementInserted( sal_Int32 nPos )
    {
        OSL_ENSURE( isValidIndex(nPos), "invalid index" );
        com::sun::star::container::ContainerEvent aEvent(
            static_cast<com::sun::star::container::XIndexReplace*>( this ),
            com::sun::star::uno::makeAny( nPos ),
            com::sun::star::uno::makeAny( getItem( nPos ) ),
            com::sun::star::uno::Any() );
        for( Listeners_t::iterator aIter = maListeners.begin();
             aIter != maListeners.end();
             ++aIter )
        {
            (*aIter)->elementInserted( aEvent );
        }
    }

    void _elementRemoved( const T& aOld )
    {
        com::sun::star::container::ContainerEvent aEvent(
            static_cast<com::sun::star::container::XIndexReplace*>( this ),
            com::sun::star::uno::Any(),
            com::sun::star::uno::makeAny( aOld ),
            com::sun::star::uno::Any() );
        for( Listeners_t::iterator aIter = maListeners.begin();
             aIter != maListeners.end();
             ++aIter )
        {
            (*aIter)->elementRemoved( aEvent );
        }
    }

    void _elementReplaced( const sal_Int32 nPos, const T& aNew )
    {
        OSL_ENSURE( isValidIndex(nPos), "invalid index" );
        com::sun::star::container::ContainerEvent aEvent(
            static_cast<com::sun::star::container::XIndexReplace*>( this ),
            com::sun::star::uno::makeAny( nPos ),
            com::sun::star::uno::makeAny( getItem( nPos ) ),
            com::sun::star::uno::makeAny( aNew ) );
        for( Listeners_t::iterator aIter = maListeners.begin();
             aIter != maListeners.end();
             ++aIter )
        {
            (*aIter)->elementReplaced( aEvent );
        }
    }

};

#endif

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


<commit_before>/*************************************************************************
 *
 *  $RCSfile: submission.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2004-11-16 10:57:00 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SUBMISSION_HXX
#define _SUBMISSION_HXX

// includes for parent classes
#include <cppuhelper/implbase2.hxx>
#include <propertysetbase.hxx>
#include <com/sun/star/util/XModifyBroadcaster.hpp>
#include <com/sun/star/container/XNamed.hpp>
#include <com/sun/star/xml/dom/events/XEventListener.hpp>
#include <com/sun/star/lang/XUnoTunnel.hpp>
#include <com/sun/star/xml/dom/XNode.hpp>
#include <com/sun/star/xml/dom/XDocument.hpp>
#include <com/sun/star/xml/dom/XDocumentFragment.hpp>
#include <com/sun/star/xml/xpath/XXPathObject.hpp>
#include <com/sun/star/xforms/XSubmission.hpp>

// includes for member variables
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include <computedexpression.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

// forward declaractions
namespace com { namespace sun { namespace star {
    namespace xforms { class XModel; }
    namespace uno { class Any; }
    namespace beans { class UnknownPropertyException;
                      class PropertyVetoException; }
    namespace lang { class IllegalArgumentException;
                     class WrappedTargetException; }
} } }
namespace xforms { class Model; }
namespace comphelper { class PropertySetInfo; }

namespace xforms
{

/** An XForms submission.
 *
 * See http://www.w3.org/TR/xforms/ for more information.
 */
typedef cppu::ImplInheritanceHelper2<
    PropertySetBase,
    com::sun::star::lang::XUnoTunnel,
    com::sun::star::xforms::XSubmission
> Submission_t;

class Submission : public Submission_t
{
    // submission properties
    rtl::OUString msID;
    rtl::OUString msBind;
    ComputedExpression maRef;
    rtl::OUString msAction;
    rtl::OUString msMethod;
    rtl::OUString msVersion;
    bool mbIndent;
    rtl::OUString msMediaType;
    rtl::OUString msEncoding;
    bool mbOmitXmlDeclaration;
    bool mbStandalone;
    rtl::OUString msCDataSectionElement;
    rtl::OUString msReplace;
    rtl::OUString msSeparator;
    com::sun::star::uno::Sequence< rtl::OUString > msIncludeNamespacePrefixes;

private:

    /// the Model to which this Submission belongs; may be NULL
    com::sun::star::uno::Reference<com::sun::star::xforms::XModel> mxModel;

    // this will extract the document from the model that will be submitted
    com::sun::star::uno::Reference< com::sun::star::xml::dom::XDocumentFragment >
        createSubmissionDocument(const com::sun::star::uno::Reference< com::sun::star::xml::xpath::XXPathObject >& aObject,
                                 sal_Bool bRemoveWSNodes = sal_False);

    com::sun::star::uno::Reference<com::sun::star::lang::XMultiServiceFactory > m_aFactory;
public:
    Submission();
    virtual ~Submission() throw();

    //
    // property methods: get/set value
    //

    /// get XForms model
    com::sun::star::uno::Reference<com::sun::star::xforms::XModel>
        getModel() const;

    /// set XForms model
    void setModel(
        const com::sun::star::uno::Reference<com::sun::star::xforms::XModel>& );

    rtl::OUString getID() const;         /// get ID for this submission
    void setID( const rtl::OUString& );  /// set ID for this submission

    rtl::OUString getBind() const;
    void setBind( const rtl::OUString& );

    rtl::OUString getRef() const;
    void setRef( const rtl::OUString& );

    rtl::OUString getAction() const;
    void setAction( const rtl::OUString& );

    rtl::OUString getMethod() const;
    void setMethod( const rtl::OUString& );

    rtl::OUString getVersion() const;
    void setVersion( const rtl::OUString& );

    bool getIndent() const;
    void setIndent( bool );

    rtl::OUString getMediaType() const;
    void setMediaType( const rtl::OUString& );

    rtl::OUString getEncoding() const;
    void setEncoding( const rtl::OUString& );

    bool getOmitXmlDeclaration() const;
    void setOmitXmlDeclaration( bool );

    bool getStandalone() const;
    void setStandalone( bool );

    rtl::OUString getCDataSectionElement() const;
    void setCDataSectionElement( const rtl::OUString& );

    rtl::OUString getReplace() const;
    void setReplace( const rtl::OUString& );

    rtl::OUString getSeparator() const;
    void setSeparator( const rtl::OUString& );

    com::sun::star::uno::Sequence< rtl::OUString > getIncludeNamespacePrefixes() const;
    void setIncludeNamespacePrefixes( const rtl::OUString& );

    /** perform the submission
     * @returns if submission was successful */
    bool doSubmit( const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& aHandler );

    /// release the model (note: Binding is unusable without model)
    void releaseModel();

    // helpers for UNO tunnel
    static com::sun::star::uno::Sequence<sal_Int8> getUnoTunnelID();
    static Submission* getSubmission( const com::sun::star::uno::Reference<com::sun::star::beans::XPropertySet>& );

private:

    /// check whether object is live, and throw suitable exception if not
    /// (to be used be API methods before acting on the object)
    void liveCheck()
        throw( com::sun::star::uno::RuntimeException );

    /// get the model implementation
    xforms::Model* getModelImpl() const;
    xforms::Model* getModelImpl( const com::sun::star::uno::Reference<com::sun::star::xforms::XModel>& xModel ) const;

protected:

    //
    // XPropertySet & friends:
    //   implement abstract methods from PropertySetHelper
    //

    virtual void _setPropertyValues(
        const comphelper::PropertyMapEntry** ppEntries,
        const com::sun::star::uno::Any* pValues )
        throw( com::sun::star::beans::UnknownPropertyException,
               com::sun::star::beans::PropertyVetoException,
               com::sun::star::lang::IllegalArgumentException,
               com::sun::star::lang::WrappedTargetException );

    virtual void _getPropertyValues(
        const comphelper::PropertyMapEntry** ppEntries,
        com::sun::star::uno::Any* pValue )
        throw( com::sun::star::beans::UnknownPropertyException,
               com::sun::star::lang::WrappedTargetException );

private:
    static comphelper::PropertySetInfo* _getPropertySetInfo();

public:

    //
    // XNamed:
    //   get/set name
    //

    virtual rtl::OUString SAL_CALL getName()
        throw( com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL setName( const rtl::OUString& )
        throw( com::sun::star::uno::RuntimeException );

    //
    // XUnoTunnel
    //

    virtual sal_Int64 SAL_CALL getSomething(
        const com::sun::star::uno::Sequence<sal_Int8>& )
        throw( com::sun::star::uno::RuntimeException );

    //
    // XSubmission
    //

    virtual void SAL_CALL submit(  )
        throw ( com::sun::star::util::VetoException,
                com::sun::star::lang::WrappedTargetException,
                com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL submitWithInteraction(
        const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& aHandler )
        throw ( com::sun::star::util::VetoException,
                com::sun::star::lang::WrappedTargetException,
                com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL addSubmissionVetoListener(
        const ::com::sun::star::uno::Reference< ::com::sun::star::form::submission::XSubmissionVetoListener >& listener )
        throw (::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeSubmissionVetoListener(
        const ::com::sun::star::uno::Reference< ::com::sun::star::form::submission::XSubmissionVetoListener >& listener )
        throw (::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);

    //
    // XPropertySet
    // (need to disambiguate this)

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
};

} // namespace xforms

#endif
<commit_msg>INTEGRATION: CWS eforms4 (1.2.6); FILE MERGED 2005/03/16 10:32:42 lo 1.2.6.2: #i36288# replace after submission 2004/12/28 09:38:30 fs 1.2.6.1: #i39451# derive from another PropertySet helper class, which also allows listener handling<commit_after>/*************************************************************************
 *
 *  $RCSfile: submission.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-23 11:38:52 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SUBMISSION_HXX
#define _SUBMISSION_HXX

// includes for parent classes
#include <cppuhelper/implbase2.hxx>
#include <propertysetbase.hxx>
#include <com/sun/star/util/XModifyBroadcaster.hpp>
#include <com/sun/star/container/XNamed.hpp>
#include <com/sun/star/xml/dom/events/XEventListener.hpp>
#include <com/sun/star/lang/XUnoTunnel.hpp>
#include <com/sun/star/xml/dom/XNode.hpp>
#include <com/sun/star/xml/dom/XDocument.hpp>
#include <com/sun/star/xml/dom/XDocumentFragment.hpp>
#include <com/sun/star/xml/xpath/XXPathObject.hpp>
#include <com/sun/star/xforms/XSubmission.hpp>

// includes for member variables
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include <computedexpression.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>

// forward declaractions
namespace com { namespace sun { namespace star {
    namespace xforms { class XModel; }
    namespace uno { class Any; }
    namespace beans { class UnknownPropertyException;
                      class PropertyVetoException; }
    namespace lang { class IllegalArgumentException;
                     class WrappedTargetException; }
} } }
namespace xforms { class Model; }

namespace xforms
{

/** An XForms submission.
 *
 * See http://www.w3.org/TR/xforms/ for more information.
 */
typedef cppu::ImplInheritanceHelper2<
    PropertySetBase,
    com::sun::star::lang::XUnoTunnel,
    com::sun::star::xforms::XSubmission
> Submission_t;

class Submission : public Submission_t
{
    // submission properties
    rtl::OUString msID;
    rtl::OUString msBind;
    ComputedExpression maRef;
    rtl::OUString msAction;
    rtl::OUString msMethod;
    rtl::OUString msVersion;
    bool mbIndent;
    rtl::OUString msMediaType;
    rtl::OUString msEncoding;
    bool mbOmitXmlDeclaration;
    bool mbStandalone;
    rtl::OUString msCDataSectionElement;
    rtl::OUString msReplace;
    rtl::OUString msSeparator;
    com::sun::star::uno::Sequence< rtl::OUString > msIncludeNamespacePrefixes;

private:

    /// the Model to which this Submission belongs; may be NULL
    com::sun::star::uno::Reference<com::sun::star::xforms::XModel> mxModel;

    // this will extract the document from the model that will be submitted
    com::sun::star::uno::Reference< com::sun::star::xml::dom::XDocumentFragment >
        createSubmissionDocument(const com::sun::star::uno::Reference< com::sun::star::xml::xpath::XXPathObject >& aObject,
                                 sal_Bool bRemoveWSNodes = sal_False);
    com::sun::star::uno::Reference< com::sun::star::xml::dom::XDocument >
        getInstanceDocument(const com::sun::star::uno::Reference< com::sun::star::xml::xpath::XXPathObject >& aObject);

    com::sun::star::uno::Reference<com::sun::star::lang::XMultiServiceFactory > m_aFactory;
public:
    Submission();
    virtual ~Submission() throw();

    //
    // property methods: get/set value
    //

    /// get XForms model
    com::sun::star::uno::Reference<com::sun::star::xforms::XModel>
        getModel() const;

    /// set XForms model
    void setModel(
        const com::sun::star::uno::Reference<com::sun::star::xforms::XModel>& );

    rtl::OUString getID() const;         /// get ID for this submission
    void setID( const rtl::OUString& );  /// set ID for this submission

    rtl::OUString getBind() const;
    void setBind( const rtl::OUString& );

    rtl::OUString getRef() const;
    void setRef( const rtl::OUString& );

    rtl::OUString getAction() const;
    void setAction( const rtl::OUString& );

    rtl::OUString getMethod() const;
    void setMethod( const rtl::OUString& );

    rtl::OUString getVersion() const;
    void setVersion( const rtl::OUString& );

    bool getIndent() const;
    void setIndent( bool );

    rtl::OUString getMediaType() const;
    void setMediaType( const rtl::OUString& );

    rtl::OUString getEncoding() const;
    void setEncoding( const rtl::OUString& );

    bool getOmitXmlDeclaration() const;
    void setOmitXmlDeclaration( bool );

    bool getStandalone() const;
    void setStandalone( bool );

    rtl::OUString getCDataSectionElement() const;
    void setCDataSectionElement( const rtl::OUString& );

    rtl::OUString getReplace() const;
    void setReplace( const rtl::OUString& );

    rtl::OUString getSeparator() const;
    void setSeparator( const rtl::OUString& );

    com::sun::star::uno::Sequence< rtl::OUString > getIncludeNamespacePrefixes() const;
    void setIncludeNamespacePrefixes( const com::sun::star::uno::Sequence< rtl::OUString >& );

    /** perform the submission
     * @returns if submission was successful */
    bool doSubmit( const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& aHandler );

    /// release the model (note: Binding is unusable without model)
    void releaseModel();

    // helpers for UNO tunnel
    static com::sun::star::uno::Sequence<sal_Int8> getUnoTunnelID();
    static Submission* getSubmission( const com::sun::star::uno::Reference<com::sun::star::beans::XPropertySet>& );

private:

    /// check whether object is live, and throw suitable exception if not
    /// (to be used be API methods before acting on the object)
    void liveCheck()
        throw( com::sun::star::uno::RuntimeException );

    /// get the model implementation
    xforms::Model* getModelImpl() const;
    xforms::Model* getModelImpl( const com::sun::star::uno::Reference<com::sun::star::xforms::XModel>& xModel ) const;

protected:

    //
    // XPropertySet & friends:
    //   implement abstract methods from PropertySetHelper
    //

    virtual sal_Bool SAL_CALL convertFastPropertyValue(
        com::sun::star::uno::Any& rConvertedValue,
        com::sun::star::uno::Any& rOldValue,
        sal_Int32 nHandle,
        const com::sun::star::uno::Any& rValue )
        throw ( com::sun::star::lang::IllegalArgumentException );

private:
    void initializePropertySet();

public:

    //
    // XNamed:
    //   get/set name
    //

    virtual rtl::OUString SAL_CALL getName()
        throw( com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL setName( const rtl::OUString& )
        throw( com::sun::star::uno::RuntimeException );

    //
    // XUnoTunnel
    //

    virtual sal_Int64 SAL_CALL getSomething(
        const com::sun::star::uno::Sequence<sal_Int8>& )
        throw( com::sun::star::uno::RuntimeException );

    //
    // XSubmission
    //

    virtual void SAL_CALL submit(  )
        throw ( com::sun::star::util::VetoException,
                com::sun::star::lang::WrappedTargetException,
                com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL submitWithInteraction(
        const ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionHandler >& aHandler )
        throw ( com::sun::star::util::VetoException,
                com::sun::star::lang::WrappedTargetException,
                com::sun::star::uno::RuntimeException );
    virtual void SAL_CALL addSubmissionVetoListener(
        const ::com::sun::star::uno::Reference< ::com::sun::star::form::submission::XSubmissionVetoListener >& listener )
        throw (::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeSubmissionVetoListener(
        const ::com::sun::star::uno::Reference< ::com::sun::star::form::submission::XSubmissionVetoListener >& listener )
        throw (::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException);

    //
    // XPropertySet
    // (need to disambiguate this)

    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addPropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& xListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removePropertyChangeListener( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertyChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeVetoableChangeListener( const ::rtl::OUString& PropertyName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XVetoableChangeListener >& aListener ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
};

} // namespace xforms

#endif
<|endoftext|>