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

   The MIT License

   Copyright (c) 2015 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.
   */

#include <Interface/Modules/Factory/ModuleDialogFactory.h>
#include <Interface/Modules/Base/ModuleDialogBasic.h>
#include <Interface/Modules/Testing/SendScalarDialog.h>
#include <Interface/Modules/Testing/ReceiveScalarDialog.h>
#include <Interface/Modules/DataIO/ReadMatrixClassicDialog.h>
#include <Interface/Modules/DataIO/ReadBundleDialog.h>
#include <Interface/Modules/DataIO/WriteMatrixDialog.h>
#include <Interface/Modules/DataIO/ReadFieldDialog.h>
#include <Interface/Modules/DataIO/WriteFieldDialog.h>
#include <Interface/Modules/Math/EvaluateLinearAlgebraUnaryDialog.h>
#include <Interface/Modules/Math/EvaluateLinearAlgebraBinaryDialog.h>
#include <Interface/Modules/Math/ReportMatrixInfoDialog.h>
#include <Interface/Modules/Math/CreateMatrixDialog.h>
#include <Interface/Modules/Math/AppendMatrixDialog.h>
#include <Interface/Modules/Math/SolveLinearSystemDialog.h>
#include <Interface/Modules/Math/SelectSubMatrixDialog.h>
#include <Interface/Modules/Math/ConvertMatrixTypeDialog.h>
#include <Interface/Modules/Math/GetMatrixSliceDialog.h>
#include <Interface/Modules/Math/BuildNoiseColumnMatrixDialog.h>
#include <Interface/Modules/String/CreateStringDialog.h>
#include <Interface/Modules/String/NetworkNotesDialog.h>
#include <Interface/Modules/String/PrintDatatypeDialog.h>
#include <Interface/Modules/Fields/CreateLatVolDialog.h>
#include <Interface/Modules/Fields/EditMeshBoundingBoxDialog.h>
#include <Interface/Modules/Fields/GetDomainBoundaryDialog.h>
#include <Interface/Modules/Fields/ReportFieldInfoDialog.h>
#include <Interface/Modules/Fields/JoinFieldsDialog.h>
#include <Interface/Modules/Fields/SplitFieldByDomainDialog.h>
#include <Interface/Modules/Fields/SplitFieldByConnectedRegionDialog.h>
#include <Interface/Modules/Fields/SetFieldDataDialog.h>
#include <Interface/Modules/Fields/InterfaceWithCleaverDialog.h>
#include <Interface/Modules/Fields/MapFieldDataFromElemToNodeDialog.h>
#include <Interface/Modules/Fields/MapFieldDataFromNodeToElemDialog.h>
#include <Interface/Modules/Fields/CreateFieldDataDialog.h>
#include <Interface/Modules/Fields/CalculateFieldDataDialog.h>
#include <Interface/Modules/Fields/ResampleRegularMeshDialog.h>
#include <Interface/Modules/Fields/FairMeshDialog.h>
#if WITH_TETGEN
#include <Interface/Modules/Fields/InterfaceWithTetGenDialog.h>
#endif
#include <Interface/Modules/Fields/ProjectPointsOntoMeshDialog.h>
#include <Interface/Modules/Fields/CalculateDistanceToFieldDialog.h>
#include <Interface/Modules/Fields/CalculateDistanceToFieldBoundaryDialog.h>
#include <Interface/Modules/Fields/MapFieldDataOntoElemsDialog.h>
#include <Interface/Modules/Fields/MapFieldDataOntoNodesDialog.h>
#include <Interface/Modules/Fields/MapFieldDataFromSourceToDestinationDialog.h>
#include <Interface/Modules/Fields/ClipFieldByFunctionDialog.h>
#include <Interface/Modules/Fields/BuildMappingMatrixDialog.h>
#include <Interface/Modules/Fields/RefineMeshDialog.h>
#include <Interface/Modules/Fields/SetFieldDataToConstantValueDialog.h>
#include <Interface/Modules/Fields/ConvertFieldBasisDialog.h>
#include <Interface/Modules/Fields/SwapFieldDataWithMatrixEntriesDialog.h>
#include <Interface/Modules/Fields/ConvertFieldBasisDialog.h>
#include <Interface/Modules/Fields/ConvertIndicesToFieldDataDialog.h>
#include <Interface/Modules/Fields/RegisterWithCorrespondencesDialog.h>
#include <Interface/Modules/Forward/BuildBEMatrixDialog.h>
#include <Interface/Modules/Inverse/SolveInverseProblemWithTikhonovDialog.h>
#include <Interface/Modules/FiniteElements/ApplyFEMCurrentSourceDialog.h>
#include <Interface/Modules/Visualization/MatrixAsVectorFieldDialog.h>
#include <Interface/Modules/Visualization/ShowStringDialog.h>
#include <Interface/Modules/Visualization/ShowFieldDialog.h>
#include <Interface/Modules/Visualization/ShowFieldGlyphsDialog.h>
#include <Interface/Modules/Visualization/CreateStandardColorMapDialog.h>
#include <Interface/Modules/Visualization/ShowColorMapDialog.h>
#include <Interface/Modules/Visualization/RescaleColorMapDialog.h>
#include <Interface/Modules/Matlab/ImportDatatypesFromMatlabDialog.h>
#include <Interface/Modules/Render/ViewScene.h>
#include <Interface/Modules/Bundle/InsertFieldsIntoBundleDialog.h>
#include <Interface/Modules/Bundle/GetFieldsFromBundleDialog.h>
#include <Interface/Modules/Bundle/ReportBundleInfoDialog.h>
#include <Interface/Modules/Fields/ExtractSimpleIsosurfaceDialog.h>
#include <boost/assign.hpp>
#include <boost/functional/factory.hpp>
#include <boost/foreach.hpp>

using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace boost::assign;

ModuleDialogFactory::ModuleDialogFactory(QWidget* parentToUse,
  ExecutionDisablingServiceFunction disablerAdd,
  ExecutionDisablingServiceFunction disablerRemove) :
  parentToUse_(parentToUse)
{
  addDialogsToMakerMap1();
  addDialogsToMakerMap2();
  ModuleDialogGeneric::setExecutionDisablingServiceFunctionAdd(disablerAdd);
  ModuleDialogGeneric::setExecutionDisablingServiceFunctionRemove(disablerRemove);
}

void ModuleDialogFactory::addDialogsToMakerMap1()
{
  insert(dialogMakerMap_)
    ADD_MODULE_DIALOG(SendScalar, SendScalarDialog)
    ADD_MODULE_DIALOG(ReceiveScalar, ReceiveScalarDialog)
    ADD_MODULE_DIALOG(ReadMatrix, ReadMatrixClassicDialog)
    ADD_MODULE_DIALOG(WriteMatrix, WriteMatrixDialog)
    ADD_MODULE_DIALOG(ReadField, ReadFieldDialog)
    ADD_MODULE_DIALOG(WriteField, WriteFieldDialog)
    ADD_MODULE_DIALOG(ReadBundle, ReadBundleDialog)
    ADD_MODULE_DIALOG(EvaluateLinearAlgebraUnary, EvaluateLinearAlgebraUnaryDialog)
    ADD_MODULE_DIALOG(EvaluateLinearAlgebraBinary, EvaluateLinearAlgebraBinaryDialog)
    ADD_MODULE_DIALOG(ShowString, ShowStringDialog)
    ADD_MODULE_DIALOG(ShowField, ShowFieldDialog)
    ADD_MODULE_DIALOG(ShowFieldGlyphs, ShowFieldGlyphsDialog)
    ADD_MODULE_DIALOG(AppendMatrix, AppendMatrixDialog)
    ADD_MODULE_DIALOG(CreateMatrix, CreateMatrixDialog)
    ADD_MODULE_DIALOG(CreateString, CreateStringDialog)
    ADD_MODULE_DIALOG(NetworkNotes, NetworkNotesDialog)
    ADD_MODULE_DIALOG(PrintDatatype, PrintDatatypeDialog)
    ADD_MODULE_DIALOG(ReportMatrixInfo, ReportMatrixInfoDialog)
    ADD_MODULE_DIALOG(ReportFieldInfo, ReportFieldInfoDialog)
    ADD_MODULE_DIALOG(ReportBundleInfo, ReportBundleInfoDialog)
    ADD_MODULE_DIALOG(MatrixAsVectorField, MatrixAsVectorFieldDialog)
    ADD_MODULE_DIALOG(ViewScene, ViewSceneDialog)
    ADD_MODULE_DIALOG(SolveLinearSystem, SolveLinearSystemDialog)
    ADD_MODULE_DIALOG(CreateLatVol, CreateLatVolDialog)
    ADD_MODULE_DIALOG(CreateStandardColorMap, CreateStandardColorMapDialog)
    ADD_MODULE_DIALOG(GetDomainBoundary, GetDomainBoundaryDialog)
    ADD_MODULE_DIALOG(JoinFields, JoinFieldsDialog)
    ADD_MODULE_DIALOG(InsertFieldsIntoBundle, InsertFieldsIntoBundleDialog)
    ADD_MODULE_DIALOG(GetFieldsFromBundle, GetFieldsFromBundleDialog)
    ADD_MODULE_DIALOG(SplitFieldByDomain, SplitFieldByDomainDialog)
    ADD_MODULE_DIALOG(CreateFieldData, CreateFieldDataDialog)
    ADD_MODULE_DIALOG(CalculateFieldData, CalculateFieldDataDialog)
    ADD_MODULE_DIALOG(SetFieldData, SetFieldDataDialog)
    ADD_MODULE_DIALOG(InterfaceWithCleaver, InterfaceWithCleaverDialog)
    ADD_MODULE_DIALOG(SelectSubMatrix, SelectSubMatrixDialog)
    ADD_MODULE_DIALOG(GetMatrixSlice, GetMatrixSliceDialog)
    ADD_MODULE_DIALOG(MapFieldDataFromElemToNode, MapFieldDataFromElemToNodeDialog)
    ADD_MODULE_DIALOG(InsertFieldsIntoBundle, InsertFieldsIntoBundleDialog)
    ADD_MODULE_DIALOG(GetFieldsFromBundle, GetFieldsFromBundleDialog)
    ADD_MODULE_DIALOG(SplitFieldByDomain, SplitFieldByDomainDialog)
    ADD_MODULE_DIALOG(ConvertMatrixType, ConvertMatrixTypeDialog)
    ADD_MODULE_DIALOG(MapFieldDataFromNodeToElem, MapFieldDataFromNodeToElemDialog)
    ADD_MODULE_DIALOG(ResampleRegularMesh, ResampleRegularMeshDialog)
    ADD_MODULE_DIALOG(FairMesh, FairMeshDialog)
    ADD_MODULE_DIALOG(BuildBEMatrix, BuildBEMatrixDialog)
    ADD_MODULE_DIALOG(ApplyFEMCurrentSource, ApplyFEMCurrentSourceDialog)
    ADD_MODULE_DIALOG(ProjectPointsOntoMesh, ProjectPointsOntoMeshDialog)
    ADD_MODULE_DIALOG(CalculateDistanceToField, CalculateDistanceToFieldDialog)
    ADD_MODULE_DIALOG(CalculateDistanceToFieldBoundary, CalculateDistanceToFieldBoundaryDialog)
#if WITH_TETGEN
    ADD_MODULE_DIALOG(InterfaceWithTetGen, InterfaceWithTetGenDialog)
#endif
    ADD_MODULE_DIALOG(MapFieldDataOntoElements, MapFieldDataOntoElemsDialog)
    ADD_MODULE_DIALOG(MapFieldDataOntoNodes, MapFieldDataOntoNodesDialog)
    ADD_MODULE_DIALOG(MapFieldDataFromSourceToDestination, MapFieldDataFromSourceToDestinationDialog)
    ADD_MODULE_DIALOG(SplitFieldByConnectedRegion, SplitFieldByConnectedRegionDialog)
    ADD_MODULE_DIALOG(ClipFieldByFunction, ClipFieldByFunctionDialog)
    ADD_MODULE_DIALOG(ImportDatatypesFromMatlab, ImportDatatypesFromMatlabDialog)
    ADD_MODULE_DIALOG(RefineMesh, RefineMeshDialog)
    ADD_MODULE_DIALOG(SetFieldDataToConstantValue, SetFieldDataToConstantValueDialog)
    ADD_MODULE_DIALOG(ConvertFieldBasis, ConvertFieldBasisDialog)
    ADD_MODULE_DIALOG(BuildNoiseColumnMatrix, BuildNoiseColumnMatrixDialog)
    ADD_MODULE_DIALOG(SwapFieldDataWithMatrixEntries, SwapFieldDataWithMatrixEntriesDialog)
    ADD_MODULE_DIALOG(BuildMappingMatrix, BuildMappingMatrixDialog)
    ADD_MODULE_DIALOG(EditMeshBoundingBox, EditMeshBoundingBoxDialog)
    ADD_MODULE_DIALOG(ConvertIndicesToFieldData, ConvertIndicesToFieldDataDialog)
    ADD_MODULE_DIALOG(SolveInverseProblemWithTikhonov, SolveInverseProblemWithTikhonovDialog)
    ADD_MODULE_DIALOG(ShowColorMap, ShowColorMapDialog)
    ADD_MODULE_DIALOG(RescaleColorMap, RescaleColorMapDialog)
    ADD_MODULE_DIALOG(ExtractSimpleIsosurface, ExtractSimpleIsosurfaceDialog)
    ADD_MODULE_DIALOG(RegisterWithCorrespondences, RegisterWithCorrespondencesDialog)
    ;
}

ModuleDialogGeneric* ModuleDialogFactory::makeDialog(const std::string& moduleId, ModuleStateHandle state)
{
  BOOST_FOREACH(const DialogMakerMap::value_type& makerPair, dialogMakerMap_)
  {
    //TODO: match full string name; need to strip module id's number
    auto findIndex = moduleId.find(makerPair.first);
    if (findIndex != std::string::npos && moduleId[makerPair.first.size()] == ':')
      return makerPair.second(moduleId, state, parentToUse_);
  }

  return new ModuleDialogBasic(moduleId, parentToUse_);
}
<commit_msg>Add to factory<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2015 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.
   */

#include <Interface/Modules/Factory/ModuleDialogFactory.h>
#include <Interface/Modules/Base/ModuleDialogBasic.h>
#include <Interface/Modules/Testing/SendScalarDialog.h>
#include <Interface/Modules/Testing/ReceiveScalarDialog.h>
#include <Interface/Modules/DataIO/ReadMatrixClassicDialog.h>
#include <Interface/Modules/DataIO/ReadBundleDialog.h>
#include <Interface/Modules/DataIO/WriteMatrixDialog.h>
#include <Interface/Modules/DataIO/ReadFieldDialog.h>
#include <Interface/Modules/DataIO/WriteFieldDialog.h>
#include <Interface/Modules/Math/EvaluateLinearAlgebraUnaryDialog.h>
#include <Interface/Modules/Math/EvaluateLinearAlgebraBinaryDialog.h>
#include <Interface/Modules/Math/EvaluateLinearAlgebraGeneralDialog.h>
#include <Interface/Modules/Math/ReportMatrixInfoDialog.h>
#include <Interface/Modules/Math/CreateMatrixDialog.h>
#include <Interface/Modules/Math/AppendMatrixDialog.h>
#include <Interface/Modules/Math/SolveLinearSystemDialog.h>
#include <Interface/Modules/Math/SelectSubMatrixDialog.h>
#include <Interface/Modules/Math/ConvertMatrixTypeDialog.h>
#include <Interface/Modules/Math/GetMatrixSliceDialog.h>
#include <Interface/Modules/Math/BuildNoiseColumnMatrixDialog.h>
#include <Interface/Modules/String/CreateStringDialog.h>
#include <Interface/Modules/String/NetworkNotesDialog.h>
#include <Interface/Modules/String/PrintDatatypeDialog.h>
#include <Interface/Modules/Fields/CreateLatVolDialog.h>
#include <Interface/Modules/Fields/EditMeshBoundingBoxDialog.h>
#include <Interface/Modules/Fields/GetDomainBoundaryDialog.h>
#include <Interface/Modules/Fields/ReportFieldInfoDialog.h>
#include <Interface/Modules/Fields/JoinFieldsDialog.h>
#include <Interface/Modules/Fields/SplitFieldByDomainDialog.h>
#include <Interface/Modules/Fields/SplitFieldByConnectedRegionDialog.h>
#include <Interface/Modules/Fields/SetFieldDataDialog.h>
#include <Interface/Modules/Fields/InterfaceWithCleaverDialog.h>
#include <Interface/Modules/Fields/MapFieldDataFromElemToNodeDialog.h>
#include <Interface/Modules/Fields/MapFieldDataFromNodeToElemDialog.h>
#include <Interface/Modules/Fields/CreateFieldDataDialog.h>
#include <Interface/Modules/Fields/CalculateFieldDataDialog.h>
#include <Interface/Modules/Fields/ResampleRegularMeshDialog.h>
#include <Interface/Modules/Fields/FairMeshDialog.h>
#if WITH_TETGEN
#include <Interface/Modules/Fields/InterfaceWithTetGenDialog.h>
#endif
#include <Interface/Modules/Fields/ProjectPointsOntoMeshDialog.h>
#include <Interface/Modules/Fields/CalculateDistanceToFieldDialog.h>
#include <Interface/Modules/Fields/CalculateDistanceToFieldBoundaryDialog.h>
#include <Interface/Modules/Fields/MapFieldDataOntoElemsDialog.h>
#include <Interface/Modules/Fields/MapFieldDataOntoNodesDialog.h>
#include <Interface/Modules/Fields/MapFieldDataFromSourceToDestinationDialog.h>
#include <Interface/Modules/Fields/ClipFieldByFunctionDialog.h>
#include <Interface/Modules/Fields/BuildMappingMatrixDialog.h>
#include <Interface/Modules/Fields/RefineMeshDialog.h>
#include <Interface/Modules/Fields/SetFieldDataToConstantValueDialog.h>
#include <Interface/Modules/Fields/ConvertFieldBasisDialog.h>
#include <Interface/Modules/Fields/SwapFieldDataWithMatrixEntriesDialog.h>
#include <Interface/Modules/Fields/ConvertFieldBasisDialog.h>
#include <Interface/Modules/Fields/ConvertIndicesToFieldDataDialog.h>
#include <Interface/Modules/Fields/RegisterWithCorrespondencesDialog.h>
#include <Interface/Modules/Forward/BuildBEMatrixDialog.h>
#include <Interface/Modules/Inverse/SolveInverseProblemWithTikhonovDialog.h>
#include <Interface/Modules/FiniteElements/ApplyFEMCurrentSourceDialog.h>
#include <Interface/Modules/Visualization/MatrixAsVectorFieldDialog.h>
#include <Interface/Modules/Visualization/ShowStringDialog.h>
#include <Interface/Modules/Visualization/ShowFieldDialog.h>
#include <Interface/Modules/Visualization/ShowFieldGlyphsDialog.h>
#include <Interface/Modules/Visualization/CreateStandardColorMapDialog.h>
#include <Interface/Modules/Visualization/ShowColorMapDialog.h>
#include <Interface/Modules/Visualization/RescaleColorMapDialog.h>
#include <Interface/Modules/Matlab/ImportDatatypesFromMatlabDialog.h>
#include <Interface/Modules/Render/ViewScene.h>
#include <Interface/Modules/Bundle/InsertFieldsIntoBundleDialog.h>
#include <Interface/Modules/Bundle/GetFieldsFromBundleDialog.h>
#include <Interface/Modules/Bundle/ReportBundleInfoDialog.h>
#include <Interface/Modules/Fields/ExtractSimpleIsosurfaceDialog.h>
#include <boost/assign.hpp>
#include <boost/functional/factory.hpp>
#include <boost/foreach.hpp>

using namespace SCIRun::Gui;
using namespace SCIRun::Dataflow::Networks;
using namespace boost::assign;

ModuleDialogFactory::ModuleDialogFactory(QWidget* parentToUse,
  ExecutionDisablingServiceFunction disablerAdd,
  ExecutionDisablingServiceFunction disablerRemove) :
  parentToUse_(parentToUse)
{
  addDialogsToMakerMap1();
  addDialogsToMakerMap2();
  ModuleDialogGeneric::setExecutionDisablingServiceFunctionAdd(disablerAdd);
  ModuleDialogGeneric::setExecutionDisablingServiceFunctionRemove(disablerRemove);
}

void ModuleDialogFactory::addDialogsToMakerMap1()
{
  insert(dialogMakerMap_)
    ADD_MODULE_DIALOG(SendScalar, SendScalarDialog)
    ADD_MODULE_DIALOG(ReceiveScalar, ReceiveScalarDialog)
    ADD_MODULE_DIALOG(ReadMatrix, ReadMatrixClassicDialog)
    ADD_MODULE_DIALOG(WriteMatrix, WriteMatrixDialog)
    ADD_MODULE_DIALOG(ReadField, ReadFieldDialog)
    ADD_MODULE_DIALOG(WriteField, WriteFieldDialog)
    ADD_MODULE_DIALOG(ReadBundle, ReadBundleDialog)
    ADD_MODULE_DIALOG(EvaluateLinearAlgebraUnary, EvaluateLinearAlgebraUnaryDialog)
    ADD_MODULE_DIALOG(EvaluateLinearAlgebraBinary, EvaluateLinearAlgebraBinaryDialog)
    ADD_MODULE_DIALOG(EvaluateLinearAlgebraGeneral, EvaluateLinearAlgebraGeneralDialog)
    ADD_MODULE_DIALOG(ShowString, ShowStringDialog)
    ADD_MODULE_DIALOG(ShowField, ShowFieldDialog)
    ADD_MODULE_DIALOG(ShowFieldGlyphs, ShowFieldGlyphsDialog)
    ADD_MODULE_DIALOG(AppendMatrix, AppendMatrixDialog)
    ADD_MODULE_DIALOG(CreateMatrix, CreateMatrixDialog)
    ADD_MODULE_DIALOG(CreateString, CreateStringDialog)
    ADD_MODULE_DIALOG(NetworkNotes, NetworkNotesDialog)
    ADD_MODULE_DIALOG(PrintDatatype, PrintDatatypeDialog)
    ADD_MODULE_DIALOG(ReportMatrixInfo, ReportMatrixInfoDialog)
    ADD_MODULE_DIALOG(ReportFieldInfo, ReportFieldInfoDialog)
    ADD_MODULE_DIALOG(ReportBundleInfo, ReportBundleInfoDialog)
    ADD_MODULE_DIALOG(MatrixAsVectorField, MatrixAsVectorFieldDialog)
    ADD_MODULE_DIALOG(ViewScene, ViewSceneDialog)
    ADD_MODULE_DIALOG(SolveLinearSystem, SolveLinearSystemDialog)
    ADD_MODULE_DIALOG(CreateLatVol, CreateLatVolDialog)
    ADD_MODULE_DIALOG(CreateStandardColorMap, CreateStandardColorMapDialog)
    ADD_MODULE_DIALOG(GetDomainBoundary, GetDomainBoundaryDialog)
    ADD_MODULE_DIALOG(JoinFields, JoinFieldsDialog)
    ADD_MODULE_DIALOG(InsertFieldsIntoBundle, InsertFieldsIntoBundleDialog)
    ADD_MODULE_DIALOG(GetFieldsFromBundle, GetFieldsFromBundleDialog)
    ADD_MODULE_DIALOG(SplitFieldByDomain, SplitFieldByDomainDialog)
    ADD_MODULE_DIALOG(CreateFieldData, CreateFieldDataDialog)
    ADD_MODULE_DIALOG(CalculateFieldData, CalculateFieldDataDialog)
    ADD_MODULE_DIALOG(SetFieldData, SetFieldDataDialog)
    ADD_MODULE_DIALOG(InterfaceWithCleaver, InterfaceWithCleaverDialog)
    ADD_MODULE_DIALOG(SelectSubMatrix, SelectSubMatrixDialog)
    ADD_MODULE_DIALOG(GetMatrixSlice, GetMatrixSliceDialog)
    ADD_MODULE_DIALOG(MapFieldDataFromElemToNode, MapFieldDataFromElemToNodeDialog)
    ADD_MODULE_DIALOG(InsertFieldsIntoBundle, InsertFieldsIntoBundleDialog)
    ADD_MODULE_DIALOG(GetFieldsFromBundle, GetFieldsFromBundleDialog)
    ADD_MODULE_DIALOG(SplitFieldByDomain, SplitFieldByDomainDialog)
    ADD_MODULE_DIALOG(ConvertMatrixType, ConvertMatrixTypeDialog)
    ADD_MODULE_DIALOG(MapFieldDataFromNodeToElem, MapFieldDataFromNodeToElemDialog)
    ADD_MODULE_DIALOG(ResampleRegularMesh, ResampleRegularMeshDialog)
    ADD_MODULE_DIALOG(FairMesh, FairMeshDialog)
    ADD_MODULE_DIALOG(BuildBEMatrix, BuildBEMatrixDialog)
    ADD_MODULE_DIALOG(ApplyFEMCurrentSource, ApplyFEMCurrentSourceDialog)
    ADD_MODULE_DIALOG(ProjectPointsOntoMesh, ProjectPointsOntoMeshDialog)
    ADD_MODULE_DIALOG(CalculateDistanceToField, CalculateDistanceToFieldDialog)
    ADD_MODULE_DIALOG(CalculateDistanceToFieldBoundary, CalculateDistanceToFieldBoundaryDialog)
#if WITH_TETGEN
    ADD_MODULE_DIALOG(InterfaceWithTetGen, InterfaceWithTetGenDialog)
#endif
    ADD_MODULE_DIALOG(MapFieldDataOntoElements, MapFieldDataOntoElemsDialog)
    ADD_MODULE_DIALOG(MapFieldDataOntoNodes, MapFieldDataOntoNodesDialog)
    ADD_MODULE_DIALOG(MapFieldDataFromSourceToDestination, MapFieldDataFromSourceToDestinationDialog)
    ADD_MODULE_DIALOG(SplitFieldByConnectedRegion, SplitFieldByConnectedRegionDialog)
    ADD_MODULE_DIALOG(ClipFieldByFunction, ClipFieldByFunctionDialog)
    ADD_MODULE_DIALOG(ImportDatatypesFromMatlab, ImportDatatypesFromMatlabDialog)
    ADD_MODULE_DIALOG(RefineMesh, RefineMeshDialog)
    ADD_MODULE_DIALOG(SetFieldDataToConstantValue, SetFieldDataToConstantValueDialog)
    ADD_MODULE_DIALOG(ConvertFieldBasis, ConvertFieldBasisDialog)
    ADD_MODULE_DIALOG(BuildNoiseColumnMatrix, BuildNoiseColumnMatrixDialog)
    ADD_MODULE_DIALOG(SwapFieldDataWithMatrixEntries, SwapFieldDataWithMatrixEntriesDialog)
    ADD_MODULE_DIALOG(BuildMappingMatrix, BuildMappingMatrixDialog)
    ADD_MODULE_DIALOG(EditMeshBoundingBox, EditMeshBoundingBoxDialog)
    ADD_MODULE_DIALOG(ConvertIndicesToFieldData, ConvertIndicesToFieldDataDialog)
    ADD_MODULE_DIALOG(SolveInverseProblemWithTikhonov, SolveInverseProblemWithTikhonovDialog)
    ADD_MODULE_DIALOG(ShowColorMap, ShowColorMapDialog)
    ADD_MODULE_DIALOG(RescaleColorMap, RescaleColorMapDialog)
    ADD_MODULE_DIALOG(ExtractSimpleIsosurface, ExtractSimpleIsosurfaceDialog)
    ADD_MODULE_DIALOG(RegisterWithCorrespondences, RegisterWithCorrespondencesDialog)
    ;
}

ModuleDialogGeneric* ModuleDialogFactory::makeDialog(const std::string& moduleId, ModuleStateHandle state)
{
  BOOST_FOREACH(const DialogMakerMap::value_type& makerPair, dialogMakerMap_)
  {
    //TODO: match full string name; need to strip module id's number
    auto findIndex = moduleId.find(makerPair.first);
    if (findIndex != std::string::npos && moduleId[makerPair.first.size()] == ':')
      return makerPair.second(moduleId, state, parentToUse_);
  }

  return new ModuleDialogBasic(moduleId, parentToUse_);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: service2_impl.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2003-06-30 15:13:19 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  the BSD license.
 *
 *  Copyright (c) 2003 by Sun Microsystems, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *  1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *  3. Neither the name of Sun Microsystems, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 *  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 *  TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 *  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *************************************************************************/

#include <cppuhelper/implbase3.hxx> // "3" implementing three interfaces
#include <cppuhelper/factory.hxx>
#include <cppuhelper/implementationentry.hxx>

#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <my_module/XSomething.hpp>

using namespace ::rtl; // for OUString
using namespace ::com::sun::star; // for odk interfaces
using namespace ::com::sun::star::uno; // for basic types

namespace my_sc_impl
{

extern Sequence< OUString > SAL_CALL  getSupportedServiceNames_MyService1Impl();
extern OUString SAL_CALL getImplementationName_MyService1Impl();
extern Reference< XInterface > SAL_CALL create_MyService1Impl(
                                        Reference< XComponentContext > const & xContext )
                                            SAL_THROW( () );

static Sequence< OUString > getSupportedServiceNames_MyService2Impl()
{
    static Sequence < OUString > *pNames = 0;
    if( ! pNames )
    {
//      MutexGuard guard( Mutex::getGlobalMutex() );
        if( !pNames )
        {
            static Sequence< OUString > seqNames(1);
            seqNames.getArray()[0] = OUString(RTL_CONSTASCII_USTRINGPARAM("my_module.MyService2"));
            pNames = &seqNames;
        }
    }
    return *pNames;
}

static OUString getImplementationName_MyService2Impl()
{
    static OUString *pImplName = 0;
    if( ! pImplName )
    {
//      MutexGuard guard( Mutex::getGlobalMutex() );
        if( ! pImplName )
        {
            static OUString implName( RTL_CONSTASCII_USTRINGPARAM("my_module.my_sc_implementation.MyService2") );
            pImplName = &implName;
        }
    }
    return *pImplName;
}

class MyService2Impl : public ::cppu::WeakImplHelper3<
      ::my_module::XSomething, lang::XServiceInfo, lang::XInitialization >
{
    OUString m_arg;
public:
    // focus on three given interfaces,
    // no need to implement XInterface, XTypeProvider, XWeak

    // XInitialization will be called upon createInstanceWithArguments[AndContext]()
    virtual void SAL_CALL initialize( Sequence< Any > const & args )
        throw (Exception);
    // XSomething
    virtual OUString SAL_CALL methodOne( OUString const & str )
        throw (RuntimeException);
    // XServiceInfo
    virtual OUString SAL_CALL getImplementationName()
        throw (RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( OUString const & serviceName )
        throw (RuntimeException);
    virtual Sequence< OUString > SAL_CALL getSupportedServiceNames()
        throw (RuntimeException);
};
// XInitialization implemention
void MyService2Impl::initialize( Sequence< Any > const & args )
    throw (Exception)
{
    if (1 != args.getLength())
    {
        throw lang::IllegalArgumentException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("give a string instanciating this component!") ),
            (::cppu::OWeakObject *)this, // resolve to XInterface reference
            0 ); // argument pos
    }
    if (! (args[ 0 ] >>= m_arg))
    {
        throw lang::IllegalArgumentException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("no string given as argument!") ),
            (::cppu::OWeakObject *)this, // resolve to XInterface reference
            0 ); // argument pos
    }
}
// XSomething implementation
OUString MyService2Impl::methodOne( OUString const & str )
    throw (RuntimeException)
{
    return OUString( RTL_CONSTASCII_USTRINGPARAM(
        "called methodOne() of MyService2 implementation: ") ) + m_arg + str;
}
// XServiceInfo implementation
OUString MyService2Impl::getImplementationName()
    throw (RuntimeException)
{
    // unique implementation name
    return OUString( RTL_CONSTASCII_USTRINGPARAM("my_module.my_sc_impl.MyService2") );
}
sal_Bool MyService2Impl::supportsService( OUString const & serviceName )
    throw (RuntimeException)
{
    // this object only supports one service, so the test is simple
    return serviceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM("my_module.MyService2") );
}
Sequence< OUString > MyService2Impl::getSupportedServiceNames()
    throw (RuntimeException)
{
    return getSupportedServiceNames_MyService2Impl();
}

Reference< XInterface > SAL_CALL create_MyService2Impl(
    Reference< XComponentContext > const & xContext )
    SAL_THROW( () )
{
    return static_cast< lang::XTypeProvider * >( new MyService2Impl() );
}

}

/* shared lib exports implemented without helpers in service_impl1.cxx */
namespace my_sc_impl
{
static struct ::cppu::ImplementationEntry s_component_entries [] =
{
    {
        create_MyService1Impl, getImplementationName_MyService1Impl,
        getSupportedServiceNames_MyService1Impl, ::cppu::createSingleComponentFactory,
        0, 0
    },
    {
        create_MyService2Impl, getImplementationName_MyService2Impl,
        getSupportedServiceNames_MyService2Impl, ::cppu::createSingleComponentFactory,
        0, 0
    },
    { 0, 0, 0, 0, 0, 0 }
};
}

extern "C"
{
void SAL_CALL component_getImplementationEnvironment(
    sal_Char const ** ppEnvTypeName, uno_Environment ** ppEnv )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
sal_Bool SAL_CALL component_writeInfo(
    lang::XMultiServiceFactory * xMgr, registry::XRegistryKey * xRegistry )
{
    return ::cppu::component_writeInfoHelper(
        xMgr, xRegistry, ::my_sc_impl::s_component_entries );
}
void * SAL_CALL component_getFactory(
    sal_Char const * implName, lang::XMultiServiceFactory * xMgr,
    registry::XRegistryKey * xRegistry )
{
    return ::cppu::component_getFactoryHelper(
        implName, xMgr, xRegistry, ::my_sc_impl::s_component_entries );
}
}

<commit_msg>INTEGRATION: CWS sdksample (1.3.124); FILE MERGED 2004/08/03 15:33:01 dbo 1.3.124.2: revised sample code Issue number: Submitted by: Reviewed by: 2004/06/30 09:10:25 jsc 1.3.124.1: #i29308# use of new UNO features<commit_after>/*************************************************************************
 *
 *  $RCSfile: service2_impl.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-01-31 16:13:51 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  the BSD license.
 *
 *  Copyright (c) 2003 by Sun Microsystems, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *  1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *  3. Neither the name of Sun Microsystems, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 *  OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 *  TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 *  USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *************************************************************************/

#include <cppuhelper/implbase3.hxx> // "3" implementing three interfaces
#include <cppuhelper/factory.hxx>
#include <cppuhelper/implementationentry.hxx>

#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XInitialization.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <my_module/XSomething.hpp>

using namespace ::rtl; // for OUString
using namespace ::com::sun::star; // for odk interfaces
using namespace ::com::sun::star::uno; // for basic types

namespace my_sc_impl
{

extern Sequence< OUString > SAL_CALL  getSupportedServiceNames_MyService1Impl();
extern OUString SAL_CALL getImplementationName_MyService1Impl();
extern Reference< XInterface > SAL_CALL create_MyService1Impl(
    Reference< XComponentContext > const & xContext )
    SAL_THROW( () );

static Sequence< OUString > getSupportedServiceNames_MyService2Impl()
{
    Sequence<OUString> names(1);
    names[0] = OUString(RTL_CONSTASCII_USTRINGPARAM("my_module.MyService2"));
    return names;
}

static OUString getImplementationName_MyService2Impl()
{
    return OUString( RTL_CONSTASCII_USTRINGPARAM(
                         "my_module.my_sc_implementation.MyService2") );
}

class MyService2Impl : public ::cppu::WeakImplHelper3<
      ::my_module::XSomething, lang::XServiceInfo, lang::XInitialization >
{
    OUString m_sData;
public:
    // focus on three given interfaces,
    // no need to implement XInterface, XTypeProvider, XWeak

    // XInitialization will be called upon
    // createInstanceWithArguments[AndContext]()
    virtual void SAL_CALL initialize( Sequence< Any > const & args )
        throw (Exception);
    // XSomething
    virtual OUString SAL_CALL methodOne( OUString const & str )
        throw (RuntimeException);
    virtual OUString SAL_CALL methodTwo( )
        throw (RuntimeException);
    // XServiceInfo
    virtual OUString SAL_CALL getImplementationName()
        throw (RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( OUString const & serviceName )
        throw (RuntimeException);
    virtual Sequence< OUString > SAL_CALL getSupportedServiceNames()
        throw (RuntimeException);
};

// XInitialization implemention
void MyService2Impl::initialize( Sequence< Any > const & args )
    throw (Exception)
{
    if (args.getLength() != 1)
    {
        throw lang::IllegalArgumentException(
            OUString( RTL_CONSTASCII_USTRINGPARAM(
                          "give a string instanciating this component!") ),
            // resolve to XInterface reference:
            static_cast< ::cppu::OWeakObject * >(this),
            0 ); // argument pos
    }
    if (! (args[ 0 ] >>= m_sData))
    {
        throw lang::IllegalArgumentException(
            OUString( RTL_CONSTASCII_USTRINGPARAM(
                          "no string given as argument!") ),
            // resolve to XInterface reference:
            static_cast< ::cppu::OWeakObject * >(this),
            0 ); // argument pos
    }
}

// XSomething implementation
OUString MyService2Impl::methodOne( OUString const & str )
    throw (RuntimeException)
{
    m_sData = str;
    return OUString( RTL_CONSTASCII_USTRINGPARAM(
        "called methodOne() of MyService2 implementation: ") ) + m_sData;
}

OUString MyService2Impl::methodTwo( )
    throw (RuntimeException)
{
    return OUString( RTL_CONSTASCII_USTRINGPARAM(
        "called methodTwo() of MyService2 implementation: ") ) + m_sData;
}

// XServiceInfo implementation
OUString MyService2Impl::getImplementationName()
    throw (RuntimeException)
{
    // unique implementation name
    return OUString( RTL_CONSTASCII_USTRINGPARAM(
                         "my_module.my_sc_impl.MyService2") );
}

sal_Bool MyService2Impl::supportsService( OUString const & serviceName )
    throw (RuntimeException)
{
    // this object only supports one service, so the test is simple
    return serviceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM(
                                         "my_module.MyService2") );
}

Sequence< OUString > MyService2Impl::getSupportedServiceNames()
    throw (RuntimeException)
{
    return getSupportedServiceNames_MyService2Impl();
}

Reference< XInterface > SAL_CALL create_MyService2Impl(
    Reference< XComponentContext > const & xContext )
    SAL_THROW( () )
{
    return static_cast< ::cppu::OWeakObject * >( new MyService2Impl );
}

}

/* shared lib exports implemented without helpers in service_impl1.cxx */
namespace my_sc_impl
{
static struct ::cppu::ImplementationEntry s_component_entries [] =
{
    {
        create_MyService1Impl, getImplementationName_MyService1Impl,
        getSupportedServiceNames_MyService1Impl,
        ::cppu::createSingleComponentFactory,
        0, 0
    },
    {
        create_MyService2Impl, getImplementationName_MyService2Impl,
        getSupportedServiceNames_MyService2Impl,
        ::cppu::createSingleComponentFactory,
        0, 0
    },
    { 0, 0, 0, 0, 0, 0 }
};
}

extern "C"
{
void SAL_CALL component_getImplementationEnvironment(
    sal_Char const ** ppEnvTypeName, uno_Environment ** ppEnv )
{
    *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
sal_Bool SAL_CALL component_writeInfo(
    lang::XMultiServiceFactory * xMgr, registry::XRegistryKey * xRegistry )
{
    return ::cppu::component_writeInfoHelper(
        xMgr, xRegistry, ::my_sc_impl::s_component_entries );
}
void * SAL_CALL component_getFactory(
    sal_Char const * implName, lang::XMultiServiceFactory * xMgr,
    registry::XRegistryKey * xRegistry )
{
    return ::cppu::component_getFactoryHelper(
        implName, xMgr, xRegistry, ::my_sc_impl::s_component_entries );
}
}

<|endoftext|>


<commit_before>#include <cassert>

#include "Tools/Exception/exception.hpp"
#include "Tools/Display/rang_format/rang_format.h"

#include "Terminal_std.hpp"

using namespace aff3ct;
using namespace aff3ct::tools;

const char        aff3ct::tools::Terminal_std::line_separator        = '-';
const std::string aff3ct::tools::Terminal_std::col_separator         = "|";
const std::string aff3ct::tools::Terminal_std::group_separator       = "||";
const std::string aff3ct::tools::Terminal_std::spaced_scol_separator = " |";
const std::string aff3ct::tools::Terminal_std::spaced_dcol_separator = " ||";
const std::string aff3ct::tools::Terminal_std::data_tag              = "  ";
const rang::style aff3ct::tools::Terminal_std::legend_style          = rang::style::bold;
const rang::style aff3ct::tools::Terminal_std::report_style          = rang::style::bold;

#ifdef _WIN32
const int aff3ct::tools::Terminal_std::column_width = 11;
#else
const int aff3ct::tools::Terminal_std::column_width = 10;
#endif

Terminal_std
::Terminal_std(std::vector<Reporter*>& reporters)
: Terminal(), reporters(reporters)
{
}

Terminal_std
::~Terminal_std()
{
}

void Terminal_std
::legend(std::ostream &stream) const
{
	std::vector<const Reporter::group_t*> cols_groups;

	for(auto& r : this->reporters)
		if (r != nullptr)
			for (auto& g : r->get_groups())
				cols_groups.push_back(&g);
		else
			throw tools::runtime_error(__FILE__, __LINE__, __func__, "'this->reporters' contains null pointer.");

	std::ios::fmtflags f(stream.flags());

	// stream << "# " << "----------------------------------------------||---------------------------------" << std::endl; // line 1
	// stream << "# " << "          cols_groups[0].first.first          ||   cols_groups[1].first.first    " << std::endl; // line 2
	// stream << "# " << "          cols_groups[0].first.second         ||   cols_groups[1].first.second   " << std::endl; // line 3
	// stream << "# " << "----------------------------------------------||---------------------------------" << std::endl; // line 4
	// stream << "# " << "----------|-----------|-----------|-----------||----------|----------|-----------" << std::endl; // line 5
	// stream << "# " << "   (1.1)  |    (2.1)  |    (3.1)  |    (4.1)  ||   (5.1)  |   (6.1)  |   (7.1)   " << std::endl; // line 6
	// stream << "# " << "   (1.2)  |    (2.2)  |    (3.2)  |    (4.2)  ||   (5.2)  |   (6.2)  |   (7.2)   " << std::endl; // line 7
	// stream << "# " << "----------|-----------|-----------|-----------||----------|----------|-----------" << std::endl; // line 8
	// note (1.1) is "cols_groups[0].second[0].first"
	// note (1.2) is "cols_groups[0].second[0].second"
	// note (2.1) is "cols_groups[0].second[1].first"
	// note (2.2) is "cols_groups[0].second[1].second"
	// note (3.1) is "cols_groups[0].second[2].first"
	// note (3.2) is "cols_groups[0].second[2].second"
	// note (4.1) is "cols_groups[0].second[3].first"
	// note (4.2) is "cols_groups[0].second[3].second"
	// note (5.1) is "cols_groups[1].second[0].first"
	// note (5.2) is "cols_groups[1].second[0].second"
	// note (6.1) is "cols_groups[1].second[1].first"
	// note (6.2) is "cols_groups[1].second[1].second"
	// note (7.1) is "cols_groups[1].second[2].first"
	// note (7.2) is "cols_groups[1].second[2].second"

	assert(!cols_groups.empty());

	// print line 1 of the table
	stream << rang::tag::comment;
	for (unsigned i = 0; i < cols_groups.size(); i++)
	{
		assert(!cols_groups[i]->second.empty());

		const unsigned group_width = get_group_width(*cols_groups[i]);
		const auto n_separators = group_width + extra_spaces(cols_groups[i]->first, group_width);

		stream << legend_style << std::string(n_separators, line_separator) << rang::style::reset ;

		if (i < (cols_groups.size() -1)) // print group separator except for last
			stream << legend_style << group_separator << rang::style::reset ;
	}
	stream << std::endl;

	// print line 2 and 3 of the table (group title lines)
	for (auto l = 0; l < 2; l++)
	{
		stream << rang::tag::comment;
		for (unsigned i = 0; i < cols_groups.size(); i++)
		{
			const auto& text = l == 0 ? cols_groups[i]->first.first : cols_groups[i]->first.second;

			const unsigned group_width = get_group_width(*cols_groups[i]);
			int n_spaces = (int)group_width - (int)text.size();

			if (text.size() != std::max(cols_groups[i]->first.first.size(), cols_groups[i]->first.second.size()))
				n_spaces += extra_spaces(cols_groups[i]->first, group_width);

			const unsigned n_spaces_left  = (n_spaces >= 0) ? (unsigned)n_spaces/2 : 0;
			const unsigned n_spaces_right = (n_spaces >= 0) ? n_spaces - n_spaces_left : 0;

			stream << legend_style << std::string(n_spaces_left,  ' ') << rang::style::reset;
			stream << legend_style << text << rang::style::reset;
			stream << legend_style << std::string(n_spaces_right, ' ') << rang::style::reset;

			if (i < (cols_groups.size() -1)) // print group separator except for last
				stream << legend_style << group_separator << rang::style::reset;
		}
		stream << std::endl;
	}

	// print line 4 of the table
	stream << rang::tag::comment;
	for (unsigned i = 0; i < cols_groups.size(); i++)
	{
		const unsigned group_width = get_group_width(*cols_groups[i]);
		const auto n_separators = group_width + extra_spaces(cols_groups[i]->first, group_width);

		stream << legend_style << std::string(n_separators, line_separator) << rang::style::reset;

		if (i < (cols_groups.size() -1)) // print group separator except for last
			stream << legend_style << group_separator << rang::style::reset;
	}
	stream << std::endl;

	// print line 5 of the table
	stream << rang::tag::comment;
	for (unsigned i = 0; i < cols_groups.size(); i++)
	{
		const unsigned group_width = get_group_width(*cols_groups[i]);
		const auto n_extra = extra_spaces(cols_groups[i]->first, group_width);

		for (unsigned j = 0; j < cols_groups[i]->second.size(); j++)
		{
			auto n_separators = column_width;
			if (j == 0)
				n_separators += n_extra;

			stream << legend_style << std::string(n_separators, line_separator) << rang::style::reset;
			if (j < (cols_groups[i]->second.size() -1)) // print column separator except for last
				stream << legend_style << col_separator << rang::style::reset;
		}

		if (i < (cols_groups.size() -1)) // print group separator except for last
			stream << legend_style << group_separator << rang::style::reset;
	}
	stream << std::endl;

	// print line 6 and 7 of the table (column title lines)
	for (auto l = 0; l < 2; l++)
	{
		stream << rang::tag::comment;
		for (unsigned i = 0; i < cols_groups.size(); i++)
		{
			const unsigned group_width = get_group_width(*cols_groups[i]);
			const auto n_extra = extra_spaces(cols_groups[i]->first, group_width);

			for (unsigned j = 0; j < cols_groups[i]->second.size(); j++)
			{
				const auto& text = l == 0 ? cols_groups[i]->second[j].first : cols_groups[i]->second[j].second;
				int n_spaces = (int)column_width - (int)text.size() -1;

				if (j == 0)
					n_spaces += n_extra;

				if (n_spaces > 0)
					stream << legend_style << std::string(n_spaces,  ' ') << rang::style::reset;

				stream << legend_style << text + " " << rang::style::reset;

				if (j < (cols_groups[i]->second.size() -1)) // print column separator except for last
					stream << legend_style << col_separator << rang::style::reset;
			}

			if (i < (cols_groups.size() -1)) // print group separator except for last
				stream << legend_style << group_separator << rang::style::reset;
		}
		stream << std::endl;
	}

	// print line 8 of the table
	stream << rang::tag::comment;
	for (unsigned i = 0; i < cols_groups.size(); i++)
	{
		const unsigned group_width = get_group_width(*cols_groups[i]);
		const auto n_extra = extra_spaces(cols_groups[i]->first, group_width);

		for (unsigned j = 0; j < cols_groups[i]->second.size(); j++)
		{
			auto n_separators = column_width;
			if (j == 0)
				n_separators += n_extra;

			stream << legend_style << std::string(n_separators, line_separator) << rang::style::reset;
			if (j < (cols_groups[i]->second.size() -1)) // print column separator except for last
				stream << legend_style << col_separator << rang::style::reset;
		}

		if (i < (cols_groups.size() -1)) // print group separator except for last
			stream << legend_style << group_separator << rang::style::reset;
	}
	stream << std::endl;

	stream.flags(f);
}

void Terminal_std
::report(std::ostream &stream, bool final)
{
	std::ios::fmtflags f(stream.flags());

	stream << "\r" << data_tag;

	for (unsigned r = 0; r < this->reporters.size(); r++)
		if (this->reporters[r] != nullptr)
		{
			auto  report = this->reporters[r]->report(final);
			auto& groups = this->reporters[r]->get_groups();

			assert(report.size() == groups.size());

			for (unsigned g = 0; g < groups.size(); g++)
			{
				assert(report[g].size() == groups[g].second.size());

				stream << report_style << std::string(extra_spaces(groups[g]), ' ') << rang::style::reset;

				for (unsigned c = 0; c < report[g].size(); c++)
				{
					auto& text = report[g][c];

					if (text.size() < column_width)
					{
						text += " ";
						text.insert(0, column_width - text.size(), ' ');
					}

					stream << text;

					if (c != (report[g].size() - 1))
						stream << report_style << col_separator << rang::style::reset;
				}

				if (g != (groups.size() - 1))
					stream << report_style << group_separator << rang::style::reset;
			}

			if (r != (this->reporters.size() - 1))
				stream << report_style << group_separator << rang::style::reset;
		}
		else
			throw tools::runtime_error(__FILE__, __LINE__, __func__, "'this->reporters' contains null pointer.");

	if (final)
	{
		stream << (Terminal::is_interrupt() ? " x" : "  ") << std::endl;
	}
	else
	{
		stream << rang::style::bold << rang::fg::green << (real_time_state++ < 2 ? " *" : "  ") << rang::style::reset << "\r";
		real_time_state %= (uint8_t)4;
	}

	stream.flags(f);
	stream.flush();
}

// get extra spaces if text is too long for the given group width
unsigned Terminal_std
::extra_spaces(const Reporter::title_t& text, const unsigned group_width)
{
	const unsigned longest_text = (unsigned)std::max(text.first.size(), text.second.size());
	return (longest_text > group_width) ? longest_text - group_width : 0;
}

unsigned Terminal_std
::extra_spaces(const Reporter::group_t& group)
{
	return extra_spaces(group.first, get_group_width(group));
}

unsigned Terminal_std
::get_group_width(const Reporter::group_t& group)
{
	return (unsigned)(group.second.size() * (column_width + 1) -1); // add a col separator between each except for the last
}<commit_msg>Remove \r at the end of the temp report's line<commit_after>#include <cassert>

#include "Tools/Exception/exception.hpp"
#include "Tools/Display/rang_format/rang_format.h"

#include "Terminal_std.hpp"

using namespace aff3ct;
using namespace aff3ct::tools;

const char        aff3ct::tools::Terminal_std::line_separator        = '-';
const std::string aff3ct::tools::Terminal_std::col_separator         = "|";
const std::string aff3ct::tools::Terminal_std::group_separator       = "||";
const std::string aff3ct::tools::Terminal_std::spaced_scol_separator = " |";
const std::string aff3ct::tools::Terminal_std::spaced_dcol_separator = " ||";
const std::string aff3ct::tools::Terminal_std::data_tag              = "  ";
const rang::style aff3ct::tools::Terminal_std::legend_style          = rang::style::bold;
const rang::style aff3ct::tools::Terminal_std::report_style          = rang::style::bold;

#ifdef _WIN32
const int aff3ct::tools::Terminal_std::column_width = 11;
#else
const int aff3ct::tools::Terminal_std::column_width = 10;
#endif

Terminal_std
::Terminal_std(std::vector<Reporter*>& reporters)
: Terminal(), reporters(reporters)
{
}

Terminal_std
::~Terminal_std()
{
}

void Terminal_std
::legend(std::ostream &stream) const
{
	std::vector<const Reporter::group_t*> cols_groups;

	for(auto& r : this->reporters)
		if (r != nullptr)
			for (auto& g : r->get_groups())
				cols_groups.push_back(&g);
		else
			throw tools::runtime_error(__FILE__, __LINE__, __func__, "'this->reporters' contains null pointer.");

	std::ios::fmtflags f(stream.flags());

	// stream << "# " << "----------------------------------------------||---------------------------------" << std::endl; // line 1
	// stream << "# " << "          cols_groups[0].first.first          ||   cols_groups[1].first.first    " << std::endl; // line 2
	// stream << "# " << "          cols_groups[0].first.second         ||   cols_groups[1].first.second   " << std::endl; // line 3
	// stream << "# " << "----------------------------------------------||---------------------------------" << std::endl; // line 4
	// stream << "# " << "----------|-----------|-----------|-----------||----------|----------|-----------" << std::endl; // line 5
	// stream << "# " << "   (1.1)  |    (2.1)  |    (3.1)  |    (4.1)  ||   (5.1)  |   (6.1)  |   (7.1)   " << std::endl; // line 6
	// stream << "# " << "   (1.2)  |    (2.2)  |    (3.2)  |    (4.2)  ||   (5.2)  |   (6.2)  |   (7.2)   " << std::endl; // line 7
	// stream << "# " << "----------|-----------|-----------|-----------||----------|----------|-----------" << std::endl; // line 8
	// note (1.1) is "cols_groups[0].second[0].first"
	// note (1.2) is "cols_groups[0].second[0].second"
	// note (2.1) is "cols_groups[0].second[1].first"
	// note (2.2) is "cols_groups[0].second[1].second"
	// note (3.1) is "cols_groups[0].second[2].first"
	// note (3.2) is "cols_groups[0].second[2].second"
	// note (4.1) is "cols_groups[0].second[3].first"
	// note (4.2) is "cols_groups[0].second[3].second"
	// note (5.1) is "cols_groups[1].second[0].first"
	// note (5.2) is "cols_groups[1].second[0].second"
	// note (6.1) is "cols_groups[1].second[1].first"
	// note (6.2) is "cols_groups[1].second[1].second"
	// note (7.1) is "cols_groups[1].second[2].first"
	// note (7.2) is "cols_groups[1].second[2].second"

	assert(!cols_groups.empty());

	// print line 1 of the table
	stream << rang::tag::comment;
	for (unsigned i = 0; i < cols_groups.size(); i++)
	{
		assert(!cols_groups[i]->second.empty());

		const unsigned group_width = get_group_width(*cols_groups[i]);
		const auto n_separators = group_width + extra_spaces(cols_groups[i]->first, group_width);

		stream << legend_style << std::string(n_separators, line_separator) << rang::style::reset ;

		if (i < (cols_groups.size() -1)) // print group separator except for last
			stream << legend_style << group_separator << rang::style::reset ;
	}
	stream << std::endl;

	// print line 2 and 3 of the table (group title lines)
	for (auto l = 0; l < 2; l++)
	{
		stream << rang::tag::comment;
		for (unsigned i = 0; i < cols_groups.size(); i++)
		{
			const auto& text = l == 0 ? cols_groups[i]->first.first : cols_groups[i]->first.second;

			const unsigned group_width = get_group_width(*cols_groups[i]);
			int n_spaces = (int)group_width - (int)text.size();

			if (text.size() != std::max(cols_groups[i]->first.first.size(), cols_groups[i]->first.second.size()))
				n_spaces += extra_spaces(cols_groups[i]->first, group_width);

			const unsigned n_spaces_left  = (n_spaces >= 0) ? (unsigned)n_spaces/2 : 0;
			const unsigned n_spaces_right = (n_spaces >= 0) ? n_spaces - n_spaces_left : 0;

			stream << legend_style << std::string(n_spaces_left,  ' ') << rang::style::reset;
			stream << legend_style << text << rang::style::reset;
			stream << legend_style << std::string(n_spaces_right, ' ') << rang::style::reset;

			if (i < (cols_groups.size() -1)) // print group separator except for last
				stream << legend_style << group_separator << rang::style::reset;
		}
		stream << std::endl;
	}

	// print line 4 of the table
	stream << rang::tag::comment;
	for (unsigned i = 0; i < cols_groups.size(); i++)
	{
		const unsigned group_width = get_group_width(*cols_groups[i]);
		const auto n_separators = group_width + extra_spaces(cols_groups[i]->first, group_width);

		stream << legend_style << std::string(n_separators, line_separator) << rang::style::reset;

		if (i < (cols_groups.size() -1)) // print group separator except for last
			stream << legend_style << group_separator << rang::style::reset;
	}
	stream << std::endl;

	// print line 5 of the table
	stream << rang::tag::comment;
	for (unsigned i = 0; i < cols_groups.size(); i++)
	{
		const unsigned group_width = get_group_width(*cols_groups[i]);
		const auto n_extra = extra_spaces(cols_groups[i]->first, group_width);

		for (unsigned j = 0; j < cols_groups[i]->second.size(); j++)
		{
			auto n_separators = column_width;
			if (j == 0)
				n_separators += n_extra;

			stream << legend_style << std::string(n_separators, line_separator) << rang::style::reset;
			if (j < (cols_groups[i]->second.size() -1)) // print column separator except for last
				stream << legend_style << col_separator << rang::style::reset;
		}

		if (i < (cols_groups.size() -1)) // print group separator except for last
			stream << legend_style << group_separator << rang::style::reset;
	}
	stream << std::endl;

	// print line 6 and 7 of the table (column title lines)
	for (auto l = 0; l < 2; l++)
	{
		stream << rang::tag::comment;
		for (unsigned i = 0; i < cols_groups.size(); i++)
		{
			const unsigned group_width = get_group_width(*cols_groups[i]);
			const auto n_extra = extra_spaces(cols_groups[i]->first, group_width);

			for (unsigned j = 0; j < cols_groups[i]->second.size(); j++)
			{
				const auto& text = l == 0 ? cols_groups[i]->second[j].first : cols_groups[i]->second[j].second;
				int n_spaces = (int)column_width - (int)text.size() -1;

				if (j == 0)
					n_spaces += n_extra;

				if (n_spaces > 0)
					stream << legend_style << std::string(n_spaces,  ' ') << rang::style::reset;

				stream << legend_style << text + " " << rang::style::reset;

				if (j < (cols_groups[i]->second.size() -1)) // print column separator except for last
					stream << legend_style << col_separator << rang::style::reset;
			}

			if (i < (cols_groups.size() -1)) // print group separator except for last
				stream << legend_style << group_separator << rang::style::reset;
		}
		stream << std::endl;
	}

	// print line 8 of the table
	stream << rang::tag::comment;
	for (unsigned i = 0; i < cols_groups.size(); i++)
	{
		const unsigned group_width = get_group_width(*cols_groups[i]);
		const auto n_extra = extra_spaces(cols_groups[i]->first, group_width);

		for (unsigned j = 0; j < cols_groups[i]->second.size(); j++)
		{
			auto n_separators = column_width;
			if (j == 0)
				n_separators += n_extra;

			stream << legend_style << std::string(n_separators, line_separator) << rang::style::reset;
			if (j < (cols_groups[i]->second.size() -1)) // print column separator except for last
				stream << legend_style << col_separator << rang::style::reset;
		}

		if (i < (cols_groups.size() -1)) // print group separator except for last
			stream << legend_style << group_separator << rang::style::reset;
	}
	stream << std::endl;

	stream.flags(f);
}

void Terminal_std
::report(std::ostream &stream, bool final)
{
	std::ios::fmtflags f(stream.flags());

	stream << "\r" << data_tag;

	for (unsigned r = 0; r < this->reporters.size(); r++)
		if (this->reporters[r] != nullptr)
		{
			auto  report = this->reporters[r]->report(final);
			auto& groups = this->reporters[r]->get_groups();

			assert(report.size() == groups.size());

			for (unsigned g = 0; g < groups.size(); g++)
			{
				assert(report[g].size() == groups[g].second.size());

				stream << report_style << std::string(extra_spaces(groups[g]), ' ') << rang::style::reset;

				for (unsigned c = 0; c < report[g].size(); c++)
				{
					auto& text = report[g][c];

					if (text.size() < column_width)
					{
						text += " ";
						text.insert(0, column_width - text.size(), ' ');
					}

					stream << text;

					if (c != (report[g].size() - 1))
						stream << report_style << col_separator << rang::style::reset;
				}

				if (g != (groups.size() - 1))
					stream << report_style << group_separator << rang::style::reset;
			}

			if (r != (this->reporters.size() - 1))
				stream << report_style << group_separator << rang::style::reset;
		}
		else
			throw tools::runtime_error(__FILE__, __LINE__, __func__, "'this->reporters' contains null pointer.");

	if (final)
	{
		stream << (Terminal::is_interrupt() ? " x" : "  ") << std::endl;
	}
	else
	{
		stream << rang::style::bold << rang::fg::green << (real_time_state++ < 2 ? " *" : "  ") << rang::style::reset;
		real_time_state %= (uint8_t)4;
	}

	stream.flags(f);
	stream.flush();
}

// get extra spaces if text is too long for the given group width
unsigned Terminal_std
::extra_spaces(const Reporter::title_t& text, const unsigned group_width)
{
	const unsigned longest_text = (unsigned)std::max(text.first.size(), text.second.size());
	return (longest_text > group_width) ? longest_text - group_width : 0;
}

unsigned Terminal_std
::extra_spaces(const Reporter::group_t& group)
{
	return extra_spaces(group.first, get_group_width(group));
}

unsigned Terminal_std
::get_group_width(const Reporter::group_t& group)
{
	return (unsigned)(group.second.size() * (column_width + 1) -1); // add a col separator between each except for the last
}<|endoftext|>


<commit_before>/**
* @file       SerialNumberSignatureOfKnowledge.cpp
*
* @brief      SerialNumberSignatureOfKnowledge class for the Zerocoin library.
*
* @author     Ian Miers, Christina Garman and Matthew Green
* @date       June 2013
*
* @copyright  Copyright 2013 Ian Miers, Christina Garman and Matthew Green
* @license    This project is released under the MIT license.
**/
// Copyright (c) 2017 The PIVX developers

#include <streams.h>
#include "SerialNumberSignatureOfKnowledge.h"

namespace libzerocoin {

SerialNumberSignatureOfKnowledge::SerialNumberSignatureOfKnowledge(const ZerocoinParams* p): params(p) { }

// Use one 256 bit seed and concatenate 4 unique 256 bit hashes to make a 1024 bit hash
CBigNum SeedTo1024(uint256 hashSeed) {
    CHashWriter hasher(0,0);
    hasher << hashSeed;

    vector<unsigned char> vResult;
    vector<unsigned char> vHash = CBigNum(hasher.GetHash()).getvch();
    vResult.insert(vResult.end(), vHash.begin(), vHash.end());
    for (int i = 0; i < 3; i ++) {
        hasher << vResult;
        vHash = CBigNum(hasher.GetHash()).getvch();
        vResult.insert(vResult.end(), vHash.begin(), vHash.end());
    }

    CBigNum bnResult;
    bnResult.setvch(vResult);
    return bnResult;
}

SerialNumberSignatureOfKnowledge::SerialNumberSignatureOfKnowledge(const
        ZerocoinParams* p, const PrivateCoin& coin, const Commitment& commitmentToCoin,
        uint256 msghash):params(p),
	s_notprime(p->zkp_iterations),
	sprime(p->zkp_iterations) {

	// Sanity check: verify that the order of the "accumulatedValueCommitmentGroup" is
	// equal to the modulus of "coinCommitmentGroup". Otherwise we will produce invalid
	// proofs.
	if (params->coinCommitmentGroup.modulus != params->serialNumberSoKCommitmentGroup.groupOrder) {
		throw std::runtime_error("Groups are not structured correctly.");
	}

	CBigNum a = params->coinCommitmentGroup.g;
	CBigNum b = params->coinCommitmentGroup.h;
	CBigNum g = params->serialNumberSoKCommitmentGroup.g;
	CBigNum h = params->serialNumberSoKCommitmentGroup.h;

	CHashWriter hasher(0,0);
	hasher << *params << commitmentToCoin.getCommitmentValue() << coin.getSerialNumber() << msghash;

	vector<CBigNum> r(params->zkp_iterations);
	vector<CBigNum> v_seed(params->zkp_iterations);
    vector<CBigNum> v_expanded(params->zkp_iterations);
	vector<CBigNum> c(params->zkp_iterations);

	for(uint32_t i=0; i < params->zkp_iterations; i++) {
		r[i] = CBigNum::randBignum(params->coinCommitmentGroup.groupOrder);

        //use a random 256 bit seed that expands to 1024 bit for v[i]
        while (true) {
            uint256 hashRand = CBigNum::randBignum(CBigNum(~uint256(0))).getuint256();
            CBigNum bnExpanded = SeedTo1024(hashRand);

            if(bnExpanded > params->serialNumberSoKCommitmentGroup.groupOrder)
                continue;

            v_seed[i] = CBigNum(hashRand);
            v_expanded[i] = bnExpanded;
            break;
        }
	}

	for(uint32_t i=0; i < params->zkp_iterations; i++) {
		// compute g^{ {a^x b^r} h^v} mod p2
		c[i] = challengeCalculation(coin.getSerialNumber(), r[i], v_expanded[i]);
	}

	// We can't hash data in parallel either
	// because OPENMP cannot not guarantee loops
	// execute in order.
	for(uint32_t i=0; i < params->zkp_iterations; i++) {
		hasher << c[i];
	}
	this->hash = hasher.GetHash();
	unsigned char *hashbytes =  (unsigned char*) &hash;

	for(uint32_t i = 0; i < params->zkp_iterations; i++) {
		int bit = i % 8;
		int byte = i / 8;

		bool challenge_bit = ((hashbytes[byte] >> bit) & 0x01);
		if (challenge_bit) {
			s_notprime[i]       = r[i];
			sprime[i]           = v_seed[i];
		} else {
			s_notprime[i]       = r[i] - coin.getRandomness();
			sprime[i]           = v_expanded[i] - (commitmentToCoin.getRandomness() *
			                              b.pow_mod(r[i] - coin.getRandomness(), params->serialNumberSoKCommitmentGroup.groupOrder));
		}
	}
}

inline CBigNum SerialNumberSignatureOfKnowledge::challengeCalculation(const CBigNum& a_exp,const CBigNum& b_exp,
        const CBigNum& h_exp) const {

	CBigNum a = params->coinCommitmentGroup.g;
	CBigNum b = params->coinCommitmentGroup.h;
	CBigNum g = params->serialNumberSoKCommitmentGroup.g;
	CBigNum h = params->serialNumberSoKCommitmentGroup.h;

	CBigNum exponent = (a.pow_mod(a_exp, params->serialNumberSoKCommitmentGroup.groupOrder)
	                   * b.pow_mod(b_exp, params->serialNumberSoKCommitmentGroup.groupOrder)) % params->serialNumberSoKCommitmentGroup.groupOrder;

	return (g.pow_mod(exponent, params->serialNumberSoKCommitmentGroup.modulus) * h.pow_mod(h_exp, params->serialNumberSoKCommitmentGroup.modulus)) % params->serialNumberSoKCommitmentGroup.modulus;
}

bool SerialNumberSignatureOfKnowledge::Verify(const CBigNum& coinSerialNumber, const CBigNum& valueOfCommitmentToCoin,
        const uint256 msghash, bool isInParamsValidationRange) const {
	CBigNum a = params->coinCommitmentGroup.g;
	CBigNum b = params->coinCommitmentGroup.h;
	CBigNum g = params->serialNumberSoKCommitmentGroup.g;
	CBigNum h = params->serialNumberSoKCommitmentGroup.h;

    //// Params validation.
    if(isInParamsValidationRange) {
        // Check that the serial is within the max size
        if (!IsValidSerial(params, coinSerialNumber))
            return error("Invalid serial range");

        // Check that the commitment is in the correct group
        if (!IsValidCommitmentToCoinRange(params, valueOfCommitmentToCoin))
            return error("Invalid commitment to coin range");
    }

    //// Verification
    CHashWriter hasher(0,0);
	hasher << *params << valueOfCommitmentToCoin << coinSerialNumber << msghash;

	vector<CBigNum> tprime(params->zkp_iterations);
	unsigned char *hashbytes = (unsigned char*) &this->hash;

	try {
		for (uint32_t i = 0; i < params->zkp_iterations; i++) {
			int bit = i % 8;
			int byte = i / 8;
			bool challenge_bit = ((hashbytes[byte] >> bit) & 0x01);
			if (challenge_bit) {
			    CBigNum bn = SeedTo1024(sprime[i].getuint256());
                if (bn > params->serialNumberSoKCommitmentGroup.groupOrder && isInParamsValidationRange)
                    return error("SoK Verify() :: sprime in pos %d not in valid range", i);
                tprime[i] = challengeCalculation(coinSerialNumber, s_notprime[i], bn);
            } else {
                CBigNum exp = b.pow_mod(s_notprime[i], params->serialNumberSoKCommitmentGroup.groupOrder);
                tprime[i] = ((valueOfCommitmentToCoin.pow_mod(exp, params->serialNumberSoKCommitmentGroup.modulus) %
                              params->serialNumberSoKCommitmentGroup.modulus) *
                             (h.pow_mod(sprime[i], params->serialNumberSoKCommitmentGroup.modulus) %
                              params->serialNumberSoKCommitmentGroup.modulus)) %
                            params->serialNumberSoKCommitmentGroup.modulus;
            }
        }
        for (uint32_t i = 0; i < params->zkp_iterations; i++) {
            hasher << tprime[i];
        }
        return hasher.GetHash() == hash;
    }catch (std::range_error e){
        return error("SoK Verify() :: sprime invalid range.");
    }
}

} /* namespace libzerocoin */
<commit_msg>fix tabs in SoK<commit_after>/**
* @file       SerialNumberSignatureOfKnowledge.cpp
*
* @brief      SerialNumberSignatureOfKnowledge class for the Zerocoin library.
*
* @author     Ian Miers, Christina Garman and Matthew Green
* @date       June 2013
*
* @copyright  Copyright 2013 Ian Miers, Christina Garman and Matthew Green
* @license    This project is released under the MIT license.
**/
// Copyright (c) 2017 The PIVX developers

#include <streams.h>
#include "SerialNumberSignatureOfKnowledge.h"

namespace libzerocoin {

SerialNumberSignatureOfKnowledge::SerialNumberSignatureOfKnowledge(const ZerocoinParams* p): params(p) { }

// Use one 256 bit seed and concatenate 4 unique 256 bit hashes to make a 1024 bit hash
CBigNum SeedTo1024(uint256 hashSeed) {
    CHashWriter hasher(0,0);
    hasher << hashSeed;

    vector<unsigned char> vResult;
    vector<unsigned char> vHash = CBigNum(hasher.GetHash()).getvch();
    vResult.insert(vResult.end(), vHash.begin(), vHash.end());
    for (int i = 0; i < 3; i ++) {
        hasher << vResult;
        vHash = CBigNum(hasher.GetHash()).getvch();
        vResult.insert(vResult.end(), vHash.begin(), vHash.end());
    }

    CBigNum bnResult;
    bnResult.setvch(vResult);
    return bnResult;
}

SerialNumberSignatureOfKnowledge::SerialNumberSignatureOfKnowledge(const
        ZerocoinParams* p, const PrivateCoin& coin, const Commitment& commitmentToCoin, uint256 msghash):
                params(p),
                s_notprime(p->zkp_iterations),
                sprime(p->zkp_iterations)
{
    // Sanity check: verify that the order of the "accumulatedValueCommitmentGroup" is
    // equal to the modulus of "coinCommitmentGroup". Otherwise we will produce invalid proofs.
    if (params->coinCommitmentGroup.modulus != params->serialNumberSoKCommitmentGroup.groupOrder)
        throw std::runtime_error("Groups are not structured correctly.");

    CBigNum a = params->coinCommitmentGroup.g;
    CBigNum b = params->coinCommitmentGroup.h;
    CBigNum g = params->serialNumberSoKCommitmentGroup.g;
    CBigNum h = params->serialNumberSoKCommitmentGroup.h;

    CHashWriter hasher(0,0);
    hasher << *params << commitmentToCoin.getCommitmentValue() << coin.getSerialNumber() << msghash;

    vector<CBigNum> r(params->zkp_iterations);
    vector<CBigNum> v_seed(params->zkp_iterations);
    vector<CBigNum> v_expanded(params->zkp_iterations);
    vector<CBigNum> c(params->zkp_iterations);

    for(uint32_t i=0; i < params->zkp_iterations; i++) {
        r[i] = CBigNum::randBignum(params->coinCommitmentGroup.groupOrder);

        //use a random 256 bit seed that expands to 1024 bit for v[i]
        while (true) {
            uint256 hashRand = CBigNum::randBignum(CBigNum(~uint256(0))).getuint256();
            CBigNum bnExpanded = SeedTo1024(hashRand);

            if(bnExpanded > params->serialNumberSoKCommitmentGroup.groupOrder)
                continue;

            v_seed[i] = CBigNum(hashRand);
            v_expanded[i] = bnExpanded;
            break;
        }
    }

    for(uint32_t i=0; i < params->zkp_iterations; i++) {
        // compute g^{ {a^x b^r} h^v} mod p2
        c[i] = challengeCalculation(coin.getSerialNumber(), r[i], v_expanded[i]);
    }

    // We can't hash data in parallel either
    // because OPENMP cannot not guarantee loops
    // execute in order.
    for(uint32_t i=0; i < params->zkp_iterations; i++)
        hasher << c[i];

    this->hash = hasher.GetHash();
    unsigned char *hashbytes =  (unsigned char*) &hash;

    for(uint32_t i = 0; i < params->zkp_iterations; i++) {
        int bit = i % 8;
        int byte = i / 8;

        bool challenge_bit = ((hashbytes[byte] >> bit) & 0x01);
        if (challenge_bit) {
            s_notprime[i]       = r[i];
            sprime[i]           = v_seed[i];
        } else {
            s_notprime[i]       = r[i] - coin.getRandomness();
            sprime[i]           = v_expanded[i] - (commitmentToCoin.getRandomness() *
                    b.pow_mod(r[i] - coin.getRandomness(), params->serialNumberSoKCommitmentGroup.groupOrder));
        }
    }
}

inline CBigNum SerialNumberSignatureOfKnowledge::challengeCalculation(const CBigNum& a_exp,const CBigNum& b_exp,
        const CBigNum& h_exp) const {

    CBigNum a = params->coinCommitmentGroup.g;
    CBigNum b = params->coinCommitmentGroup.h;
    CBigNum g = params->serialNumberSoKCommitmentGroup.g;
    CBigNum h = params->serialNumberSoKCommitmentGroup.h;

    CBigNum exponent = (a.pow_mod(a_exp, params->serialNumberSoKCommitmentGroup.groupOrder) *
            b.pow_mod(b_exp, params->serialNumberSoKCommitmentGroup.groupOrder)) % params->serialNumberSoKCommitmentGroup.groupOrder;

    return (g.pow_mod(exponent, params->serialNumberSoKCommitmentGroup.modulus) * h.pow_mod(h_exp, params->serialNumberSoKCommitmentGroup.modulus)) % params->serialNumberSoKCommitmentGroup.modulus;
}

bool SerialNumberSignatureOfKnowledge::Verify(const CBigNum& coinSerialNumber, const CBigNum& valueOfCommitmentToCoin,
        const uint256 msghash, bool isInParamsValidationRange) const {
    CBigNum a = params->coinCommitmentGroup.g;
    CBigNum b = params->coinCommitmentGroup.h;
    CBigNum g = params->serialNumberSoKCommitmentGroup.g;
    CBigNum h = params->serialNumberSoKCommitmentGroup.h;

    //// Params validation.
    if(isInParamsValidationRange) {
        // Check that the serial is within the max size
        if (!IsValidSerial(params, coinSerialNumber))
            return error("Invalid serial range");

        // Check that the commitment is in the correct group
        if (!IsValidCommitmentToCoinRange(params, valueOfCommitmentToCoin))
            return error("Invalid commitment to coin range");
    }

    //// Verification
    CHashWriter hasher(0,0);
    hasher << *params << valueOfCommitmentToCoin << coinSerialNumber << msghash;

    vector<CBigNum> tprime(params->zkp_iterations);
    unsigned char *hashbytes = (unsigned char*) &this->hash;

    try {
        for (uint32_t i = 0; i < params->zkp_iterations; i++) {
            int bit = i % 8;
            int byte = i / 8;
            bool challenge_bit = ((hashbytes[byte] >> bit) & 0x01);
            if (challenge_bit) {
                CBigNum bn = SeedTo1024(sprime[i].getuint256());
                if (bn > params->serialNumberSoKCommitmentGroup.groupOrder && isInParamsValidationRange)
                    return error("SoK Verify() :: sprime in pos %d not in valid range", i);
                tprime[i] = challengeCalculation(coinSerialNumber, s_notprime[i], bn);
            } else {
                CBigNum exp = b.pow_mod(s_notprime[i], params->serialNumberSoKCommitmentGroup.groupOrder);
                tprime[i] = ((valueOfCommitmentToCoin.pow_mod(exp, params->serialNumberSoKCommitmentGroup.modulus) %
                              params->serialNumberSoKCommitmentGroup.modulus) *
                             (h.pow_mod(sprime[i], params->serialNumberSoKCommitmentGroup.modulus) %
                              params->serialNumberSoKCommitmentGroup.modulus)) %
                            params->serialNumberSoKCommitmentGroup.modulus;
            }
        }
        for (uint32_t i = 0; i < params->zkp_iterations; i++) {
            hasher << tprime[i];
        }
        return hasher.GetHash() == hash;
    }catch (std::range_error e){
        return error("SoK Verify() :: sprime invalid range.");
    }
}

} /* namespace libzerocoin */
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Compositor.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
**     of its contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "waylandsurfaceitem.h"
#include "waylandsurfacenode.h"
#include "waylandsurface.h"
#include "waylandcompositor.h"
#include "waylandinput.h"

#include "wlsurface.h"
#include "wlextendedsurface.h"

#include <QtGui/QKeyEvent>
#include <QtGui/QGuiApplication>
#include <QtGui/QScreen>

#include <QtQuick/QSGSimpleRectNode>
#include <QtQuick/QQuickCanvas>

#include <QtCore/QMutexLocker>
#include <QtCore/QMutex>

class WaylandSurfaceTextureProvider : public QSGTextureProvider
{
    Q_OBJECT

public:
    WaylandSurfaceTextureProvider() : t(0) { }
    ~WaylandSurfaceTextureProvider() { delete t; }

    QSGTexture *texture() const {
        if (t)
            t->setFiltering(smooth ? QSGTexture::Linear : QSGTexture::Nearest);
        return t;
    }

    bool smooth;
    QSGTexture *t;

public slots:
    void invalidate()
    {
        delete t;
        t = 0;
    }
};

QMutex *WaylandSurfaceItem::mutex = 0;

WaylandSurfaceItem::WaylandSurfaceItem(QQuickItem *parent)
    : QQuickItem(parent)
    , m_surface(0)
    , m_provider(0)
    , m_node(0)
    , m_paintEnabled(true)
    , m_useTextureAlpha(false)
    , m_clientRenderingEnabled(false)
    , m_touchEventsEnabled(false)
{
    if (!mutex)
        mutex = new QMutex;
}

WaylandSurfaceItem::WaylandSurfaceItem(WaylandSurface *surface, QQuickItem *parent)
    : QQuickItem(parent)
    , m_surface(0)
    , m_provider(0)
    , m_node(0)
    , m_paintEnabled(true)
    , m_useTextureAlpha(false)
    , m_clientRenderingEnabled(false)
    , m_touchEventsEnabled(false)
{
    init(surface);
}

void WaylandSurfaceItem::init(WaylandSurface *surface)
{
    if (!surface)
        return;

    if (m_surface) {
        m_surface->setSurfaceItem(0);
    }

    m_surface = surface;
    m_surface->setSurfaceItem(this);
    if (m_clientRenderingEnabled) {
        m_surface->sendOnScreenVisibilityChange(m_clientRenderingEnabled);
    }

    setWidth(surface->size().width());
    setHeight(surface->size().height());

    setSmooth(true);
    setFlag(ItemHasContents);
    setAcceptedMouseButtons(Qt::LeftButton | Qt::MiddleButton | Qt::RightButton |
        Qt::ExtraButton1 | Qt::ExtraButton2 | Qt::ExtraButton3 | Qt::ExtraButton4 |
        Qt::ExtraButton5 | Qt::ExtraButton6 | Qt::ExtraButton7 | Qt::ExtraButton8 |
        Qt::ExtraButton9 | Qt::ExtraButton10 | Qt::ExtraButton11 |
        Qt::ExtraButton12 | Qt::ExtraButton13);
    setAcceptHoverEvents(true);
    connect(surface, SIGNAL(mapped()), this, SLOT(surfaceMapped()));
    connect(surface, SIGNAL(unmapped()), this, SLOT(surfaceUnmapped()));
    connect(surface, SIGNAL(destroyed(QObject *)), this, SLOT(surfaceDestroyed(QObject *)));
    connect(surface, SIGNAL(damaged(const QRect &)), this, SLOT(surfaceDamaged(const QRect &)));
    connect(surface, SIGNAL(parentChanged(WaylandSurface*,WaylandSurface*)),
            this, SLOT(parentChanged(WaylandSurface*,WaylandSurface*)));
    connect(surface, SIGNAL(sizeChanged()), this, SLOT(updateSize()));
    connect(surface, SIGNAL(posChanged()), this, SLOT(updatePosition()));

    m_damaged = false;
    m_yInverted = surface ? surface->isYInverted() : true;
}

WaylandSurfaceItem::~WaylandSurfaceItem()
{
    QMutexLocker locker(mutex);
    if (m_node)
        m_node->setItem(0);
    if (m_surface)
        m_surface->setSurfaceItem(0);
    if (m_provider)
        m_provider->deleteLater();
}

void WaylandSurfaceItem::setSurface(WaylandSurface *surface)
{
    if (surface == m_surface)
        return;

    init(surface);
    emit surfaceChanged();
}

bool WaylandSurfaceItem::isYInverted() const
{
    return m_yInverted;
}

QSGTextureProvider *WaylandSurfaceItem::textureProvider() const
{
    const_cast<WaylandSurfaceItem *>(this)->ensureProvider();
    return m_provider;
}

void WaylandSurfaceItem::ensureProvider()
{
    if (!m_provider) {
        m_provider = new WaylandSurfaceTextureProvider();
        connect(canvas(), SIGNAL(sceneGraphInvalidated()), m_provider, SLOT(invalidate()), Qt::DirectConnection);
    }
}

void WaylandSurfaceItem::mousePressEvent(QMouseEvent *event)
{
    if (m_surface) {
        WaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice();
        if (inputDevice->mouseFocus() != m_surface)
            inputDevice->setMouseFocus(m_surface, event->pos(), event->globalPos());
        inputDevice->sendMousePressEvent(event->button(), toSurface(event->pos()), event->globalPos());
    }
}

void WaylandSurfaceItem::mouseMoveEvent(QMouseEvent *event)
{
    if (m_surface){
        WaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice();
        inputDevice->sendMouseMoveEvent(m_surface, toSurface(event->pos()), event->globalPos());
    }
}

void WaylandSurfaceItem::mouseReleaseEvent(QMouseEvent *event)
{
    if (m_surface){
        WaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice();
        inputDevice->sendMouseReleaseEvent(event->button(), toSurface(event->pos()), event->globalPos());
    }
}

void WaylandSurfaceItem::wheelEvent(QWheelEvent *event)
{
    if (m_surface) {
        WaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice();
        inputDevice->sendMouseWheelEvent(event->orientation(), event->delta());
    }
}

void WaylandSurfaceItem::keyPressEvent(QKeyEvent *event)
{
    if (m_surface && hasFocus()) {
        WaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice();
        inputDevice->sendFullKeyEvent(event);
    }
}

void WaylandSurfaceItem::keyReleaseEvent(QKeyEvent *event)
{
    if (m_surface && hasFocus()) {
        WaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice();
        inputDevice->sendFullKeyEvent(event);
    }
}

void WaylandSurfaceItem::touchEvent(QTouchEvent *event)
{
    if (m_touchEventsEnabled && m_surface) {
        WaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice();
        event->accept();
        if (inputDevice->mouseFocus() != m_surface) {
            QPoint pointPos;
            QList<QTouchEvent::TouchPoint> points = event->touchPoints();
            if (!points.isEmpty())
                pointPos = points.at(0).pos().toPoint();
            inputDevice->setMouseFocus(m_surface, pointPos, pointPos);
        }
        inputDevice->sendFullTouchEvent(event);
    } else {
        event->ignore();
    }
}

void WaylandSurfaceItem::takeFocus()
{
    setFocus(true);

    if (m_surface) {
        WaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice();
        inputDevice->setKeyboardFocus(m_surface);
    }
}

QPoint WaylandSurfaceItem::toSurface(const QPointF &pos) const
{
    return pos.toPoint();
}

void WaylandSurfaceItem::surfaceMapped()
{
    setPaintEnabled(true);
}

void WaylandSurfaceItem::surfaceUnmapped()
{
    setPaintEnabled(false);
}

void WaylandSurfaceItem::surfaceDestroyed(QObject *)
{
    m_surface = 0;
}

void WaylandSurfaceItem::setDamagedFlag(bool on)
{
    m_damaged = on;
}

void WaylandSurfaceItem::surfaceDamaged(const QRect &)
{
    m_damaged = true;
    if (m_surface) {
        bool inverted = m_surface->isYInverted();
        if (inverted  != m_yInverted) {
            m_yInverted = inverted;
            emit yInvertedChanged();
        }
    }
    emit textureChanged();
    update();
}

void WaylandSurfaceItem::parentChanged(WaylandSurface *newParent, WaylandSurface *oldParent)
{
    Q_UNUSED(oldParent);

    WaylandSurfaceItem *item = newParent? newParent->surfaceItem():0;
    setParentItem(item);

    if (newParent) {
        setPaintEnabled(true);
        setVisible(true);
        setOpacity(1);
        setEnabled(true);
    }
}

void WaylandSurfaceItem::updateSize()
{
    setSize(m_surface->size());
}

void WaylandSurfaceItem::updatePosition()
{
    setPos(m_surface->pos());
}

bool WaylandSurfaceItem::paintEnabled() const
{
    return m_paintEnabled;
}

void WaylandSurfaceItem::setPaintEnabled(bool enabled)
{
    m_paintEnabled = enabled;
    update();
}

void WaylandSurfaceItem::updateTexture()
{
    ensureProvider();
    QSGTexture *texture = m_provider->t;
    if (m_damaged) {
        m_damaged = false;
        QSGTexture *oldTexture = texture;
        if (m_surface->type() == WaylandSurface::Texture) {
            QOpenGLContext *context = QOpenGLContext::currentContext();
            QQuickCanvas::CreateTextureOptions opt = 0;
            if (useTextureAlpha()) {
                opt |= QQuickCanvas::TextureHasAlphaChannel;
            }
            texture = canvas()->createTextureFromId(m_surface->texture(context), m_surface->size(), opt);
        } else {
            texture = canvas()->createTextureFromImage(m_surface->image());
        }
        texture->bind();
        delete oldTexture;
    }

    m_provider->t = texture;
    m_provider->smooth = smooth();
}

QSGNode *WaylandSurfaceItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
{
    if (!m_surface) {
        delete oldNode;
        return 0;
    }

    updateTexture();
    if (!m_provider->t || !m_paintEnabled) {
        delete oldNode;
        return 0;
    }

    WaylandSurfaceNode *node = static_cast<WaylandSurfaceNode *>(oldNode);

    if (!node) {
        node = new WaylandSurfaceNode(this);
    }

    node->updateTexture();

    if (surface()->isYInverted()) {
        node->setRect(0, height(), width(), -height());
    } else {
        node->setRect(0, 0, width(), height());
    }

    node->setTextureUpdated(true);

    return node;
}

void WaylandSurfaceItem::setUseTextureAlpha(bool useTextureAlpha)
{
    m_useTextureAlpha = useTextureAlpha;

    if ((flags() & ItemHasContents) != 0) {
        update();
    }
}

void WaylandSurfaceItem::setClientRenderingEnabled(bool enabled)
{
    if (m_clientRenderingEnabled != enabled) {
        m_clientRenderingEnabled = enabled;

        if (m_surface) {
            m_surface->sendOnScreenVisibilityChange(enabled);
        }

        emit clientRenderingEnabledChanged();
    }
}

void WaylandSurfaceItem::setTouchEventsEnabled(bool enabled)
{
    if (m_touchEventsEnabled != enabled) {
        m_touchEventsEnabled = enabled;
        emit touchEventsEnabledChanged();
    }
}

#include "waylandsurfaceitem.moc"
<commit_msg>Changing from QQuickCanvas to QQuickWindow<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Compositor.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names
**     of its contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "waylandsurfaceitem.h"
#include "waylandsurfacenode.h"
#include "waylandsurface.h"
#include "waylandcompositor.h"
#include "waylandinput.h"

#include "wlsurface.h"
#include "wlextendedsurface.h"

#include <QtGui/QKeyEvent>
#include <QtGui/QGuiApplication>
#include <QtGui/QScreen>

#include <QtQuick/QSGSimpleRectNode>
#include <QtQuick/QQuickWindow>

#include <QtCore/QMutexLocker>
#include <QtCore/QMutex>

class WaylandSurfaceTextureProvider : public QSGTextureProvider
{
    Q_OBJECT

public:
    WaylandSurfaceTextureProvider() : t(0) { }
    ~WaylandSurfaceTextureProvider() { delete t; }

    QSGTexture *texture() const {
        if (t)
            t->setFiltering(smooth ? QSGTexture::Linear : QSGTexture::Nearest);
        return t;
    }

    bool smooth;
    QSGTexture *t;

public slots:
    void invalidate()
    {
        delete t;
        t = 0;
    }
};

QMutex *WaylandSurfaceItem::mutex = 0;

WaylandSurfaceItem::WaylandSurfaceItem(QQuickItem *parent)
    : QQuickItem(parent)
    , m_surface(0)
    , m_provider(0)
    , m_node(0)
    , m_paintEnabled(true)
    , m_useTextureAlpha(false)
    , m_clientRenderingEnabled(false)
    , m_touchEventsEnabled(false)
{
    if (!mutex)
        mutex = new QMutex;
}

WaylandSurfaceItem::WaylandSurfaceItem(WaylandSurface *surface, QQuickItem *parent)
    : QQuickItem(parent)
    , m_surface(0)
    , m_provider(0)
    , m_node(0)
    , m_paintEnabled(true)
    , m_useTextureAlpha(false)
    , m_clientRenderingEnabled(false)
    , m_touchEventsEnabled(false)
{
    init(surface);
}

void WaylandSurfaceItem::init(WaylandSurface *surface)
{
    if (!surface)
        return;

    if (m_surface) {
        m_surface->setSurfaceItem(0);
    }

    m_surface = surface;
    m_surface->setSurfaceItem(this);
    if (m_clientRenderingEnabled) {
        m_surface->sendOnScreenVisibilityChange(m_clientRenderingEnabled);
    }

    setWidth(surface->size().width());
    setHeight(surface->size().height());

    setSmooth(true);
    setFlag(ItemHasContents);
    setAcceptedMouseButtons(Qt::LeftButton | Qt::MiddleButton | Qt::RightButton |
        Qt::ExtraButton1 | Qt::ExtraButton2 | Qt::ExtraButton3 | Qt::ExtraButton4 |
        Qt::ExtraButton5 | Qt::ExtraButton6 | Qt::ExtraButton7 | Qt::ExtraButton8 |
        Qt::ExtraButton9 | Qt::ExtraButton10 | Qt::ExtraButton11 |
        Qt::ExtraButton12 | Qt::ExtraButton13);
    setAcceptHoverEvents(true);
    connect(surface, SIGNAL(mapped()), this, SLOT(surfaceMapped()));
    connect(surface, SIGNAL(unmapped()), this, SLOT(surfaceUnmapped()));
    connect(surface, SIGNAL(destroyed(QObject *)), this, SLOT(surfaceDestroyed(QObject *)));
    connect(surface, SIGNAL(damaged(const QRect &)), this, SLOT(surfaceDamaged(const QRect &)));
    connect(surface, SIGNAL(parentChanged(WaylandSurface*,WaylandSurface*)),
            this, SLOT(parentChanged(WaylandSurface*,WaylandSurface*)));
    connect(surface, SIGNAL(sizeChanged()), this, SLOT(updateSize()));
    connect(surface, SIGNAL(posChanged()), this, SLOT(updatePosition()));

    m_damaged = false;
    m_yInverted = surface ? surface->isYInverted() : true;
}

WaylandSurfaceItem::~WaylandSurfaceItem()
{
    QMutexLocker locker(mutex);
    if (m_node)
        m_node->setItem(0);
    if (m_surface)
        m_surface->setSurfaceItem(0);
    if (m_provider)
        m_provider->deleteLater();
}

void WaylandSurfaceItem::setSurface(WaylandSurface *surface)
{
    if (surface == m_surface)
        return;

    init(surface);
    emit surfaceChanged();
}

bool WaylandSurfaceItem::isYInverted() const
{
    return m_yInverted;
}

QSGTextureProvider *WaylandSurfaceItem::textureProvider() const
{
    const_cast<WaylandSurfaceItem *>(this)->ensureProvider();
    return m_provider;
}

void WaylandSurfaceItem::ensureProvider()
{
    if (!m_provider) {
        m_provider = new WaylandSurfaceTextureProvider();
        connect(window(), SIGNAL(sceneGraphInvalidated()), m_provider, SLOT(invalidate()), Qt::DirectConnection);
    }
}

void WaylandSurfaceItem::mousePressEvent(QMouseEvent *event)
{
    if (m_surface) {
        WaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice();
        if (inputDevice->mouseFocus() != m_surface)
            inputDevice->setMouseFocus(m_surface, event->pos(), event->globalPos());
        inputDevice->sendMousePressEvent(event->button(), toSurface(event->pos()), event->globalPos());
    }
}

void WaylandSurfaceItem::mouseMoveEvent(QMouseEvent *event)
{
    if (m_surface){
        WaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice();
        inputDevice->sendMouseMoveEvent(m_surface, toSurface(event->pos()), event->globalPos());
    }
}

void WaylandSurfaceItem::mouseReleaseEvent(QMouseEvent *event)
{
    if (m_surface){
        WaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice();
        inputDevice->sendMouseReleaseEvent(event->button(), toSurface(event->pos()), event->globalPos());
    }
}

void WaylandSurfaceItem::wheelEvent(QWheelEvent *event)
{
    if (m_surface) {
        WaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice();
        inputDevice->sendMouseWheelEvent(event->orientation(), event->delta());
    }
}

void WaylandSurfaceItem::keyPressEvent(QKeyEvent *event)
{
    if (m_surface && hasFocus()) {
        WaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice();
        inputDevice->sendFullKeyEvent(event);
    }
}

void WaylandSurfaceItem::keyReleaseEvent(QKeyEvent *event)
{
    if (m_surface && hasFocus()) {
        WaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice();
        inputDevice->sendFullKeyEvent(event);
    }
}

void WaylandSurfaceItem::touchEvent(QTouchEvent *event)
{
    if (m_touchEventsEnabled && m_surface) {
        WaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice();
        event->accept();
        if (inputDevice->mouseFocus() != m_surface) {
            QPoint pointPos;
            QList<QTouchEvent::TouchPoint> points = event->touchPoints();
            if (!points.isEmpty())
                pointPos = points.at(0).pos().toPoint();
            inputDevice->setMouseFocus(m_surface, pointPos, pointPos);
        }
        inputDevice->sendFullTouchEvent(event);
    } else {
        event->ignore();
    }
}

void WaylandSurfaceItem::takeFocus()
{
    setFocus(true);

    if (m_surface) {
        WaylandInputDevice *inputDevice = m_surface->compositor()->defaultInputDevice();
        inputDevice->setKeyboardFocus(m_surface);
    }
}

QPoint WaylandSurfaceItem::toSurface(const QPointF &pos) const
{
    return pos.toPoint();
}

void WaylandSurfaceItem::surfaceMapped()
{
    setPaintEnabled(true);
}

void WaylandSurfaceItem::surfaceUnmapped()
{
    setPaintEnabled(false);
}

void WaylandSurfaceItem::surfaceDestroyed(QObject *)
{
    m_surface = 0;
}

void WaylandSurfaceItem::setDamagedFlag(bool on)
{
    m_damaged = on;
}

void WaylandSurfaceItem::surfaceDamaged(const QRect &)
{
    m_damaged = true;
    if (m_surface) {
        bool inverted = m_surface->isYInverted();
        if (inverted  != m_yInverted) {
            m_yInverted = inverted;
            emit yInvertedChanged();
        }
    }
    emit textureChanged();
    update();
}

void WaylandSurfaceItem::parentChanged(WaylandSurface *newParent, WaylandSurface *oldParent)
{
    Q_UNUSED(oldParent);

    WaylandSurfaceItem *item = newParent? newParent->surfaceItem():0;
    setParentItem(item);

    if (newParent) {
        setPaintEnabled(true);
        setVisible(true);
        setOpacity(1);
        setEnabled(true);
    }
}

void WaylandSurfaceItem::updateSize()
{
    setSize(m_surface->size());
}

void WaylandSurfaceItem::updatePosition()
{
    setPos(m_surface->pos());
}

bool WaylandSurfaceItem::paintEnabled() const
{
    return m_paintEnabled;
}

void WaylandSurfaceItem::setPaintEnabled(bool enabled)
{
    m_paintEnabled = enabled;
    update();
}

void WaylandSurfaceItem::updateTexture()
{
    ensureProvider();
    QSGTexture *texture = m_provider->t;
    if (m_damaged) {
        m_damaged = false;
        QSGTexture *oldTexture = texture;
        if (m_surface->type() == WaylandSurface::Texture) {
            QOpenGLContext *context = QOpenGLContext::currentContext();
            QQuickWindow::CreateTextureOptions opt = 0;
            if (useTextureAlpha()) {
                opt |= QQuickWindow::TextureHasAlphaChannel;
            }
            texture = window()->createTextureFromId(m_surface->texture(context), m_surface->size(), opt);
        } else {
            texture = window()->createTextureFromImage(m_surface->image());
        }
        texture->bind();
        delete oldTexture;
    }

    m_provider->t = texture;
    m_provider->smooth = smooth();
}

QSGNode *WaylandSurfaceItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *)
{
    if (!m_surface) {
        delete oldNode;
        return 0;
    }

    updateTexture();
    if (!m_provider->t || !m_paintEnabled) {
        delete oldNode;
        return 0;
    }

    WaylandSurfaceNode *node = static_cast<WaylandSurfaceNode *>(oldNode);

    if (!node) {
        node = new WaylandSurfaceNode(this);
    }

    node->updateTexture();

    if (surface()->isYInverted()) {
        node->setRect(0, height(), width(), -height());
    } else {
        node->setRect(0, 0, width(), height());
    }

    node->setTextureUpdated(true);

    return node;
}

void WaylandSurfaceItem::setUseTextureAlpha(bool useTextureAlpha)
{
    m_useTextureAlpha = useTextureAlpha;

    if ((flags() & ItemHasContents) != 0) {
        update();
    }
}

void WaylandSurfaceItem::setClientRenderingEnabled(bool enabled)
{
    if (m_clientRenderingEnabled != enabled) {
        m_clientRenderingEnabled = enabled;

        if (m_surface) {
            m_surface->sendOnScreenVisibilityChange(enabled);
        }

        emit clientRenderingEnabledChanged();
    }
}

void WaylandSurfaceItem::setTouchEventsEnabled(bool enabled)
{
    if (m_touchEventsEnabled != enabled) {
        m_touchEventsEnabled = enabled;
        emit touchEventsEnabledChanged();
    }
}

#include "waylandsurfaceitem.moc"
<|endoftext|>