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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbWrapperOutputImageParameter.h"
//#include "itkCastImageFilter.h"
#include "otbVectorRescaleIntensityImageFilter.h"

namespace otb
{
namespace Wrapper
{

OutputImageParameter::OutputImageParameter()
: m_PixelType(ImagePixelType_float)
{
  this->SetName("Output Image");
  this->SetKey("out");

  this->InitializeWriters();

}

OutputImageParameter::~OutputImageParameter()
{
}

void OutputImageParameter::InitializeWriters()
{
  m_Int8Writer = Int8WriterType::New();
  m_UInt8Writer = UInt8WriterType::New();
  m_Int16Writer = Int16WriterType::New();
  m_UInt16Writer = UInt16WriterType::New();
  m_Int32Writer = Int32WriterType::New();
  m_UInt32Writer = UInt32WriterType::New();
  m_FloatWriter = FloatWriterType::New();
  m_DoubleWriter = DoubleWriterType::New();
}

#define otbRescaleAndWriteMacro(OutputImageType, writer)                       \
  {                                                                     \
    typedef VectorRescaleIntensityImageFilter<FloatVectorImageType, OutputImageType> RescaleFilterType; \
    RescaleFilterType::Pointer rescaler = RescaleFilterType::New();     \
    OutputImageType::PixelType outputMinimum(nbChannel);                \
    outputMinimum.Fill(itk::NumericTraits<OutputImageType::InternalPixelType>::min()); \
    OutputImageType::PixelType outputMaximum(nbChannel);                \
    outputMaximum.Fill(itk::NumericTraits<OutputImageType::InternalPixelType>::max()); \
    rescaler->SetOutputMinimum(outputMinimum);                          \
    rescaler->SetOutputMaximum(outputMaximum);                          \
    rescaler->SetAutomaticInputMinMaxComputation( true );               \
    rescaler->SetInput( this->GetImage() );                             \
    writer->SetFileName( this->GetFileName() );                   \
    writer->SetInput(rescaler->GetOutput());                      \
    writer->Update();                                             \
  }

void
OutputImageParameter::Write( )
{
  this->GetImage()->UpdateOutputInformation();
  const unsigned int nbChannel( this->GetImage()->GetNumberOfComponentsPerPixel() );

  switch(m_PixelType )
  {
    case ImagePixelType_int8:
      {
      otbRescaleAndWriteMacro(Int8VectorImageType, m_Int8Writer);
      break;
      }
    case ImagePixelType_uint8:
      {
      otbRescaleAndWriteMacro(UInt8VectorImageType, m_UInt8Writer);
      break;
      }
    case ImagePixelType_int16:
      {
      otbRescaleAndWriteMacro(Int16VectorImageType, m_Int16Writer);
      break;
      }
    case ImagePixelType_uint16:
      {
      otbRescaleAndWriteMacro(UInt16VectorImageType, m_UInt16Writer);
      break;
      }
    case ImagePixelType_int32:
      {
      otbRescaleAndWriteMacro(Int32VectorImageType, m_Int32Writer);
      break;
      }
    case ImagePixelType_uint32:
      {
      otbRescaleAndWriteMacro(UInt32VectorImageType, m_UInt32Writer);
      break;
      }
    case ImagePixelType_float:
      {
      m_FloatWriter->SetFileName( this->GetFileName() );
      m_FloatWriter->SetInput(this->GetImage());
      m_FloatWriter->Modified();
      m_FloatWriter->Update();
      break;
      }
    case ImagePixelType_double:
      {
      otbRescaleAndWriteMacro(DoubleVectorImageType, m_DoubleWriter);
      break;
      }
  }
}

itk::ProcessObject*
OutputImageParameter::GetWriter( )
{
  itk::ProcessObject* writer = 0;
  switch ( GetPixelType() )
  {
    case ImagePixelType_int8:
      writer = m_Int8Writer;
      break;
    case ImagePixelType_uint8:
      writer = m_UInt8Writer;
      break;
    case ImagePixelType_int16:
      writer = m_Int16Writer;
      break;
    case ImagePixelType_uint16:
      writer = m_UInt16Writer;
      break;
    case ImagePixelType_int32:
      writer = m_Int32Writer;
      break;
    case ImagePixelType_uint32:
      writer = m_UInt32Writer;
      break;
    case ImagePixelType_float:
      writer = m_FloatWriter;
      break;
    case ImagePixelType_double:
      writer = m_DoubleWriter;
      break;
  }
  return writer;
}

FloatVectorImageType*
OutputImageParameter::GetValue( )
{
  return m_Image;
}

void
OutputImageParameter::SetValue(FloatVectorImageType* image)
{
  m_Image = image;
  SetActive(true);
}

bool
OutputImageParameter::HasValue() const
{
  std::string filename(this->GetFileName());
  return !filename.empty();
}

}
}
<commit_msg>ENH: supress rescale when writing in double<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "otbWrapperOutputImageParameter.h"
#include "otbVectorRescaleIntensityImageFilter.h"
#include "itkCastImageFilter.h"

namespace otb
{
namespace Wrapper
{

OutputImageParameter::OutputImageParameter()
: m_PixelType(ImagePixelType_float)
{
  this->SetName("Output Image");
  this->SetKey("out");

  this->InitializeWriters();

}

OutputImageParameter::~OutputImageParameter()
{
}

void OutputImageParameter::InitializeWriters()
{
  m_Int8Writer = Int8WriterType::New();
  m_UInt8Writer = UInt8WriterType::New();
  m_Int16Writer = Int16WriterType::New();
  m_UInt16Writer = UInt16WriterType::New();
  m_Int32Writer = Int32WriterType::New();
  m_UInt32Writer = UInt32WriterType::New();
  m_FloatWriter = FloatWriterType::New();
  m_DoubleWriter = DoubleWriterType::New();
}

#define otbRescaleAndWriteMacro(OutputImageType, writer)                       \
  {                                                                     \
    typedef VectorRescaleIntensityImageFilter<FloatVectorImageType, OutputImageType> RescaleFilterType; \
    RescaleFilterType::Pointer rescaler = RescaleFilterType::New();     \
    OutputImageType::PixelType outputMinimum(nbChannel);                \
    outputMinimum.Fill(itk::NumericTraits<OutputImageType::InternalPixelType>::min()); \
    OutputImageType::PixelType outputMaximum(nbChannel);                \
    outputMaximum.Fill(itk::NumericTraits<OutputImageType::InternalPixelType>::max()); \
    rescaler->SetOutputMinimum(outputMinimum);                          \
    rescaler->SetOutputMaximum(outputMaximum);                          \
    rescaler->SetAutomaticInputMinMaxComputation( true );               \
    rescaler->SetInput( this->GetImage() );                             \
    writer->SetFileName( this->GetFileName() );                   \
    writer->SetInput(rescaler->GetOutput());                      \
    writer->Update();                                             \
  }

void
OutputImageParameter::Write( )
{
  this->GetImage()->UpdateOutputInformation();
  const unsigned int nbChannel( this->GetImage()->GetNumberOfComponentsPerPixel() );

  switch(m_PixelType )
  {
    case ImagePixelType_int8:
      {
      otbRescaleAndWriteMacro(Int8VectorImageType, m_Int8Writer);
      break;
      }
    case ImagePixelType_uint8:
      {
      otbRescaleAndWriteMacro(UInt8VectorImageType, m_UInt8Writer);
      break;
      }
    case ImagePixelType_int16:
      {
      otbRescaleAndWriteMacro(Int16VectorImageType, m_Int16Writer);
      break;
      }
    case ImagePixelType_uint16:
      {
      otbRescaleAndWriteMacro(UInt16VectorImageType, m_UInt16Writer);
      break;
      }
    case ImagePixelType_int32:
      {
      otbRescaleAndWriteMacro(Int32VectorImageType, m_Int32Writer);
      break;
      }
    case ImagePixelType_uint32:
      {
      otbRescaleAndWriteMacro(UInt32VectorImageType, m_UInt32Writer);
      break;
      }
    case ImagePixelType_float:
      {
      m_FloatWriter->SetFileName( this->GetFileName() );
      m_FloatWriter->SetInput(this->GetImage());
      m_FloatWriter->Modified();
      m_FloatWriter->Update();
      break;
      }
    case ImagePixelType_double:
      {
      typedef itk::CastImageFilter<FloatVectorImageType, DoubleVectorImageType> CastFilterType;
      CastFilterType::Pointer cast = CastFilterType::New();
      cast->SetInput( this->GetImage() );
      m_DoubleWriter->SetFileName( this->GetFileName() );
      m_DoubleWriter->SetInput(cast->GetOutput());
      m_DoubleWriter->Update();
      break;
      }
  }
}

itk::ProcessObject*
OutputImageParameter::GetWriter( )
{
  itk::ProcessObject* writer = 0;
  switch ( GetPixelType() )
  {
    case ImagePixelType_int8:
      writer = m_Int8Writer;
      break;
    case ImagePixelType_uint8:
      writer = m_UInt8Writer;
      break;
    case ImagePixelType_int16:
      writer = m_Int16Writer;
      break;
    case ImagePixelType_uint16:
      writer = m_UInt16Writer;
      break;
    case ImagePixelType_int32:
      writer = m_Int32Writer;
      break;
    case ImagePixelType_uint32:
      writer = m_UInt32Writer;
      break;
    case ImagePixelType_float:
      writer = m_FloatWriter;
      break;
    case ImagePixelType_double:
      writer = m_DoubleWriter;
      break;
  }
  return writer;
}

FloatVectorImageType*
OutputImageParameter::GetValue( )
{
  return m_Image;
}

void
OutputImageParameter::SetValue(FloatVectorImageType* image)
{
  m_Image = image;
  SetActive(true);
}

bool
OutputImageParameter::HasValue() const
{
  std::string filename(this->GetFileName());
  return !filename.empty();
}

}
}
<|endoftext|>


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

This file is part of the QtMediaHub project on http://www.qtmediahub.com

Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).*
All rights reserved.

Contact:  Girish Ramakrishnan girish@forwardbias.in
Contact:  Nokia Corporation donald.carr@nokia.com
Contact:  Nokia Corporation johannes.zellner@nokia.com

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 Nokia Corporation 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.

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

#include "globalsettings.h"

GlobalSettings::GlobalSettings(QObject *parent) :
    Settings(parent)
{
    addOptionEntry(GlobalSettings::Skin,                "confluence",   "skin",             "<name> specifies the skin");
    addOptionEntry(GlobalSettings::SkinsPath,           "",             "skinsPath",        "<path> adds path to skins search paths");
    addOptionEntry(GlobalSettings::Keymap,              "stdkeyboard",  "keymap",           "<name> specifies the keymap");
    addOptionEntry(GlobalSettings::KeymapsPath,         "",             "keymapsPath",      "<path> adds path to keymaps search paths");
    addOptionEntry(GlobalSettings::ApplicationsPath,    "",             "appsPath",         "<path> adds path to skins search paths");
    addOptionEntry(GlobalSettings::FullScreen,          "true",         "fullscreen",       "<bool> toggle fullscreen");
    addOptionEntry(GlobalSettings::OverlayMode,         "false",        "overlayMode",      "<bool> toggle overlay mode used for devices with other mediaplayers than QtMultimediaKit");
    addOptionEntry(GlobalSettings::Headless,            "false",        "headless",         "<bool> toggle running with user interface, usable for streaming server usage");
    addOptionEntry(GlobalSettings::Proxy,               "false",        "proxy",            "<bool> use a proxy for network access");
    addOptionEntry(GlobalSettings::ProxyHost,           "localhost",    "proxyHost",        "<hostname> set proxy host, only used with -proxy=true");
    addOptionEntry(GlobalSettings::ProxyPort,           "8080",         "proxyPort",        "<port> set port number for proxy usage, only used with -proxy=true");
    addOptionEntry(GlobalSettings::MultiInstance,       "false",        "multiInstance",    "<bool> allow running multiple instances");
    addOptionEntry(GlobalSettings::Mouse,               "true",         "mouse",            "<bool> toggle mouse cursor");
    addOptionEntry(GlobalSettings::MouseTimeout,        "2",            "mouseTimeout",     "<int> hide idle mouse cursor timeout in seconds");
    addOptionEntry(GlobalSettings::DrivenFPS,           "false",        "drivenFPS",        "<bool> toggle fps counter");
    addOptionEntry(GlobalSettings::StreamingAddress,    "",             "streamingAddress", "<string> specifies the streaming address");
    addOptionEntry(GlobalSettings::StreamingPort,       "1337",         "streamingPort",    "<int> specifies the streaming port");
    addOptionEntry(GlobalSettings::Avahi,               "true",         "avahi",            "<bool> toggle avahi usage");
    addOptionEntry(GlobalSettings::AvahiAdvertize,      "true",         "avahiAdvertize",   "<bool> toggle avahi advertizing");
    addOptionEntry(GlobalSettings::Overscan,            "false",        "overscan",         "<bool> use overscan mode, use also overscanGeometry");
    addOptionEntry(GlobalSettings::OverscanGeometry,    "true",         "overscanGeometry", "<>");
    addOptionEntry(GlobalSettings::IdleTimeout,         "120",          "idleTimeout",      "<int> idle timeout in seconds");
}

bool GlobalSettings::isEnabled(GlobalSettings::Option option) const
{
    return Settings::isEnabled(m_table[option]);
}

QVariant GlobalSettings::value(GlobalSettings::Option option) const
{
    return Settings::value(m_table[option]);
}

const QString GlobalSettings::name(GlobalSettings::Option option) const
{
    return m_table[option];
}

const QString GlobalSettings::doc(GlobalSettings::Option option) const
{
    return Settings::doc(name(option));
}

void GlobalSettings::setValue(GlobalSettings::Option option, const QVariant &value)
{
    insert(m_table[option], value);
    emit valueChanged(m_table[option], value);
}

void GlobalSettings::addOptionEntry(GlobalSettings::Option option, const QVariant &value, const QString &name, const QString &doc)
{
    m_table[option] = name;
    Settings::addOptionEntry(name, value, doc);
}
<commit_msg>add doc for GlobalSettings::OverscanGeometry,<commit_after>/****************************************************************************

This file is part of the QtMediaHub project on http://www.qtmediahub.com

Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).*
All rights reserved.

Contact:  Girish Ramakrishnan girish@forwardbias.in
Contact:  Nokia Corporation donald.carr@nokia.com
Contact:  Nokia Corporation johannes.zellner@nokia.com

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 Nokia Corporation 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.

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

#include "globalsettings.h"

GlobalSettings::GlobalSettings(QObject *parent) :
    Settings(parent)
{
    addOptionEntry(GlobalSettings::Skin,                "confluence",   "skin",             "<name> specifies the skin");
    addOptionEntry(GlobalSettings::SkinsPath,           "",             "skinsPath",        "<path> adds path to skins search paths");
    addOptionEntry(GlobalSettings::Keymap,              "stdkeyboard",  "keymap",           "<name> specifies the keymap");
    addOptionEntry(GlobalSettings::KeymapsPath,         "",             "keymapsPath",      "<path> adds path to keymaps search paths");
    addOptionEntry(GlobalSettings::ApplicationsPath,    "",             "appsPath",         "<path> adds path to skins search paths");
    addOptionEntry(GlobalSettings::FullScreen,          "true",         "fullscreen",       "<bool> toggle fullscreen");
    addOptionEntry(GlobalSettings::OverlayMode,         "false",        "overlayMode",      "<bool> toggle overlay mode used for devices with other mediaplayers than QtMultimediaKit");
    addOptionEntry(GlobalSettings::Headless,            "false",        "headless",         "<bool> toggle running with user interface, usable for streaming server usage");
    addOptionEntry(GlobalSettings::Proxy,               "false",        "proxy",            "<bool> use a proxy for network access");
    addOptionEntry(GlobalSettings::ProxyHost,           "localhost",    "proxyHost",        "<hostname> set proxy host, only used with -proxy=true");
    addOptionEntry(GlobalSettings::ProxyPort,           "8080",         "proxyPort",        "<port> set port number for proxy usage, only used with -proxy=true");
    addOptionEntry(GlobalSettings::MultiInstance,       "false",        "multiInstance",    "<bool> allow running multiple instances");
    addOptionEntry(GlobalSettings::Mouse,               "true",         "mouse",            "<bool> toggle mouse cursor");
    addOptionEntry(GlobalSettings::MouseTimeout,        "2",            "mouseTimeout",     "<int> hide idle mouse cursor timeout in seconds");
    addOptionEntry(GlobalSettings::DrivenFPS,           "false",        "drivenFPS",        "<bool> toggle fps counter");
    addOptionEntry(GlobalSettings::StreamingAddress,    "",             "streamingAddress", "<string> specifies the streaming address");
    addOptionEntry(GlobalSettings::StreamingPort,       "1337",         "streamingPort",    "<int> specifies the streaming port");
    addOptionEntry(GlobalSettings::Avahi,               "true",         "avahi",            "<bool> toggle avahi usage");
    addOptionEntry(GlobalSettings::AvahiAdvertize,      "true",         "avahiAdvertize",   "<bool> toggle avahi advertizing");
    addOptionEntry(GlobalSettings::Overscan,            "false",        "overscan",         "<bool> use overscan mode, use also overscanGeometry");
    addOptionEntry(GlobalSettings::OverscanGeometry,    "true",         "overscanGeometry", "<int>x<int> set the overscan dimension");   // TODO test this!!!
    addOptionEntry(GlobalSettings::IdleTimeout,         "120",          "idleTimeout",      "<int> idle timeout in seconds");
}

bool GlobalSettings::isEnabled(GlobalSettings::Option option) const
{
    return Settings::isEnabled(m_table[option]);
}

QVariant GlobalSettings::value(GlobalSettings::Option option) const
{
    return Settings::value(m_table[option]);
}

const QString GlobalSettings::name(GlobalSettings::Option option) const
{
    return m_table[option];
}

const QString GlobalSettings::doc(GlobalSettings::Option option) const
{
    return Settings::doc(name(option));
}

void GlobalSettings::setValue(GlobalSettings::Option option, const QVariant &value)
{
    insert(m_table[option], value);
    emit valueChanged(m_table[option], value);
}

void GlobalSettings::addOptionEntry(GlobalSettings::Option option, const QVariant &value, const QString &name, const QString &doc)
{
    m_table[option] = name;
    Settings::addOptionEntry(name, value, doc);
}
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <string>
#include <iostream>
#include <tuple>

#include "cpp_utils/tmp.hpp"

#include "config.hpp"
#include "args.hpp"
#include "budget_exception.hpp"
#include "api.hpp"
#include "currency.hpp"
#include "share.hpp"

//The different modules
#include "debts.hpp"
#include "accounts.hpp"
#include "incomes.hpp"
#include "assets.hpp"
#include "liabilities.hpp"
#include "expenses.hpp"
#include "overview.hpp"
#include "summary.hpp"
#include "earnings.hpp"
#include "help.hpp"
#include "recurring.hpp"
#include "report.hpp"
#include "fortune.hpp"
#include "objectives.hpp"
#include "wishes.hpp"
#include "versioning.hpp"
#include "version.hpp"
#include "predict.hpp"
#include "gc.hpp"
#include "server.hpp"
#include "retirement.hpp"

using namespace budget;

namespace {

typedef std::tuple<
            budget::server_module,
            budget::debt_module,
            budget::expenses_module,
            budget::overview_module,
            budget::summary_module,
            budget::accounts_module,
            budget::incomes_module,
            budget::assets_module,
            budget::liabilities_module,
            budget::earnings_module,
            budget::recurring_module,
            budget::fortune_module,
            budget::report_module,
            budget::objectives_module,
            budget::wishes_module,
            budget::versioning_module,
            budget::version_module,
            budget::predict_module,
            budget::retirement_module,
            budget::gc_module,
            budget::help_module
    > modules_tuple;

template<class T>
struct Void {
    typedef void type;
};

HAS_MEM_FUNC(load, has_load);
HAS_MEM_FUNC(unload, has_unload);
HAS_MEM_FUNC(preload, has_preload);

template<typename Module>
struct need_loading {
    static const bool value = has_load<Module, void(Module::*)()>::value;
};

template<typename Module>
struct need_unloading {
    static const bool value = has_unload<Module, void(Module::*)()>::value;
};

template<typename Module>
struct need_preloading {
    static const bool value = has_preload<Module, void(Module::*)()>::value;
};

HAS_STATIC_FIELD(disable_preloading, has_disable_preloading_field)

template<typename Module, typename Enable = void>
struct disable_preloading {
    static const bool value = false;
};

template<typename Module>
struct disable_preloading<Module, std::enable_if_t<has_disable_preloading_field<module_traits<Module>>::value>> {
    static const bool value = module_traits<Module>::disable_preloading;
};

HAS_STATIC_FIELD(aliases, has_aliases_field)

template<typename Module, typename Enable = void>
struct has_aliases {
    static const bool value = false;
};

template<typename Module>
struct has_aliases<Module, std::enable_if_t<has_aliases_field<module_traits<Module>>::value>> {
    static const bool value = true;
};

struct module_loader {
    template<typename Module, cpp::enable_if_u<need_preloading<Module>::value> = cpp::detail::dummy>
    inline void preload(){
        Module module;
        module.preload();
    }

    template<typename Module, cpp::disable_if_u<need_preloading<Module>::value> = cpp::detail::dummy>
    inline void preload(){
        //NOP
    }

    template<typename Module>
    inline void operator()(){
        preload<Module>();
    }
};

struct module_runner {
    std::vector<std::string> args;
    bool handled = false;

    module_runner(std::vector<std::string>&& args) : args(std::forward<std::vector<std::string>>(args)) {
        //Nothing to init
    }

    template<typename Module, cpp::enable_if_u<need_loading<Module>::value> = cpp::detail::dummy>
    inline void load(Module& module){
       module.load();
    }

    template<typename Module, cpp::disable_if_u<need_loading<Module>::value> = cpp::detail::dummy>
    inline void load(Module&){
        //NOP
    }

    template<typename Module, cpp::enable_if_u<need_unloading<Module>::value> = cpp::detail::dummy>
    inline void unload(Module& module){
       module.unload();
    }

    template<typename Module, cpp::disable_if_u<need_unloading<Module>::value> = cpp::detail::dummy>
    inline void unload(Module&){
        //NOP
    }

    template<typename Module>
    inline void handle_module(){
        //Preload each module that needs it
        if(!disable_preloading<Module>::value){
            module_loader loader;
            cpp::for_each_tuple_t<modules_tuple>(loader);
        }

        Module module;

        load(module);

        module.handle(args);

        unload(module);

        handled = true;
    }

    template<typename Module>
    inline void operator()(){
        if(handled){
            return;
        }

        if(args.empty()){
            if(module_traits<Module>::is_default){
                handle_module<Module>();
            }
        } else if(args[0] == module_traits<Module>::command){
            handle_module<Module>();
        }
    }
};

struct aliases_collector {
    std::vector<std::pair<const char*, const char*>> aliases;

    template<typename Module, cpp::enable_if_u<has_aliases<Module>::value> = cpp::detail::dummy>
    inline void operator()(){
        for(auto& v : module_traits<Module>::aliases){
            aliases.push_back(v);
        }
    }

    template<typename Module, cpp::disable_if_u<has_aliases<Module>::value> = cpp::detail::dummy>
    inline void operator()(){
        //NOP
    }
};

std::string exec_command(const std::string& command) {
    std::stringstream output;

    char buffer[1024];

    FILE* stream = popen(command.c_str(), "r");

    while (fgets(buffer, 1024, stream) != NULL) {
        output << buffer;
    }

    pclose(stream);

    return output.str();
}

bool has_enough_colors(){
    auto colors = exec_command("tput colors");
    colors = colors.substr(0, colors.length() - 1);

    return to_number<int>(colors) > 4;
}

} //end of anonymous namespace

int main(int argc, const char* argv[]) {
    std::locale global_locale("");
    std::locale::global(global_locale);

    if (!load_config()) {
        return 0;
    }

    if (is_server_mode() && (!config_contains("server_url") || !config_contains("server_port"))) {
        std::cout << "error: server_mode=true needs a server_url value and a server_port value" << std::endl;

        return 0;
    }

    if (!has_enough_colors()) {
        std::cout << "WARNING: The terminal does not seem to have enough colors, some command may not work as intended" << std::endl;
    }

    //Collect all aliases
    aliases_collector collector;
    cpp::for_each_tuple_t<modules_tuple>(collector);

    //Parse the command line args
    auto args = parse_args(argc, argv, collector.aliases);

    if(args.size() && args[0] == "server"){
        set_server_running();
    }

    // Restore the caches
    load_currency_cache();
    load_share_price_cache();

    if (!is_server_running() && is_server_mode()) {
        // 1. Ensure that the server is running

        auto res = budget::api_get("/server/up/", false);

        if(!res.success || res.result != "yes"){
            std::cout << "The server is not running, cannot run in server mode" << std::endl;
            return 0;
        }

        std::map<std::string, std::string> params;
        params["version"] = get_version_short();

        auto version_res = budget::api_post("/server/version/support/", params);

        if(!version_res.success || version_res.result != "yes"){
            std::cout << "The server does not support your version, cannot run in server mode" << std::endl;
            std::cout << "You should either upgrade the server or your client" << std::endl;
            return 0;
        }
    } else {
        auto old_data_version = to_number<size_t>(internal_config_value("data_version"));

        if (old_data_version > DATA_VERSION) {
            std::cout << "Unsupported database version, you should update budgetwarrior" << std::endl;

            return 0;
        }

        if (old_data_version < DATA_VERSION) {
            std::cout << "Migrate database..." << std::endl;

            if (old_data_version == 1 && DATA_VERSION >= 2) {
                migrate_recurring_1_to_2();
            }

            if (old_data_version <= 2 && DATA_VERSION >= 3) {
                migrate_wishes_2_to_3();
            }

            if (old_data_version <= 3 && DATA_VERSION >= 4) {
                //migrate_debts_3_to_4();
                migrate_wishes_3_to_4();
            }

            if (old_data_version <= 4 && DATA_VERSION >= 5) {
                migrate_assets_4_to_5();
            }

            if (old_data_version <= 5 && DATA_VERSION >= 6) {
                migrate_assets_5_to_6();
            }

            internal_config_value("data_version") = to_string(DATA_VERSION);

            // We want to make sure the new data version is set in stone!
            save_config();

            std::cout << "done" << std::endl;
        }
    }

    int code = 0;

    try {
        //Run the correct module
        module_runner runner(std::move(args));
        cpp::for_each_tuple_t<modules_tuple>(runner);

        if (!runner.handled) {
            std::cout << "Unhandled command \"" << runner.args[0] << "\"" << std::endl;

            code = 1;
        }
    } catch (const budget_exception& exception) {
        std::cout << exception.message() << std::endl;

        code = 2;
    }

    // Save the caches
    save_currency_cache();
    save_share_price_cache();

    save_config();

    return code;
}
<commit_msg>Set server_is_running faster<commit_after>//=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <string>
#include <iostream>
#include <tuple>

#include "cpp_utils/tmp.hpp"

#include "config.hpp"
#include "args.hpp"
#include "budget_exception.hpp"
#include "api.hpp"
#include "currency.hpp"
#include "share.hpp"

//The different modules
#include "debts.hpp"
#include "accounts.hpp"
#include "incomes.hpp"
#include "assets.hpp"
#include "liabilities.hpp"
#include "expenses.hpp"
#include "overview.hpp"
#include "summary.hpp"
#include "earnings.hpp"
#include "help.hpp"
#include "recurring.hpp"
#include "report.hpp"
#include "fortune.hpp"
#include "objectives.hpp"
#include "wishes.hpp"
#include "versioning.hpp"
#include "version.hpp"
#include "predict.hpp"
#include "gc.hpp"
#include "server.hpp"
#include "retirement.hpp"

using namespace budget;

namespace {

typedef std::tuple<
            budget::server_module,
            budget::debt_module,
            budget::expenses_module,
            budget::overview_module,
            budget::summary_module,
            budget::accounts_module,
            budget::incomes_module,
            budget::assets_module,
            budget::liabilities_module,
            budget::earnings_module,
            budget::recurring_module,
            budget::fortune_module,
            budget::report_module,
            budget::objectives_module,
            budget::wishes_module,
            budget::versioning_module,
            budget::version_module,
            budget::predict_module,
            budget::retirement_module,
            budget::gc_module,
            budget::help_module
    > modules_tuple;

template<class T>
struct Void {
    typedef void type;
};

HAS_MEM_FUNC(load, has_load);
HAS_MEM_FUNC(unload, has_unload);
HAS_MEM_FUNC(preload, has_preload);

template<typename Module>
struct need_loading {
    static const bool value = has_load<Module, void(Module::*)()>::value;
};

template<typename Module>
struct need_unloading {
    static const bool value = has_unload<Module, void(Module::*)()>::value;
};

template<typename Module>
struct need_preloading {
    static const bool value = has_preload<Module, void(Module::*)()>::value;
};

HAS_STATIC_FIELD(disable_preloading, has_disable_preloading_field)

template<typename Module, typename Enable = void>
struct disable_preloading {
    static const bool value = false;
};

template<typename Module>
struct disable_preloading<Module, std::enable_if_t<has_disable_preloading_field<module_traits<Module>>::value>> {
    static const bool value = module_traits<Module>::disable_preloading;
};

HAS_STATIC_FIELD(aliases, has_aliases_field)

template<typename Module, typename Enable = void>
struct has_aliases {
    static const bool value = false;
};

template<typename Module>
struct has_aliases<Module, std::enable_if_t<has_aliases_field<module_traits<Module>>::value>> {
    static const bool value = true;
};

struct module_loader {
    template<typename Module, cpp::enable_if_u<need_preloading<Module>::value> = cpp::detail::dummy>
    inline void preload(){
        Module module;
        module.preload();
    }

    template<typename Module, cpp::disable_if_u<need_preloading<Module>::value> = cpp::detail::dummy>
    inline void preload(){
        //NOP
    }

    template<typename Module>
    inline void operator()(){
        preload<Module>();
    }
};

struct module_runner {
    std::vector<std::string> args;
    bool handled = false;

    module_runner(std::vector<std::string>&& args) : args(std::forward<std::vector<std::string>>(args)) {
        //Nothing to init
    }

    template<typename Module, cpp::enable_if_u<need_loading<Module>::value> = cpp::detail::dummy>
    inline void load(Module& module){
       module.load();
    }

    template<typename Module, cpp::disable_if_u<need_loading<Module>::value> = cpp::detail::dummy>
    inline void load(Module&){
        //NOP
    }

    template<typename Module, cpp::enable_if_u<need_unloading<Module>::value> = cpp::detail::dummy>
    inline void unload(Module& module){
       module.unload();
    }

    template<typename Module, cpp::disable_if_u<need_unloading<Module>::value> = cpp::detail::dummy>
    inline void unload(Module&){
        //NOP
    }

    template<typename Module>
    inline void handle_module(){
        //Preload each module that needs it
        if(!disable_preloading<Module>::value){
            module_loader loader;
            cpp::for_each_tuple_t<modules_tuple>(loader);
        }

        Module module;

        load(module);

        module.handle(args);

        unload(module);

        handled = true;
    }

    template<typename Module>
    inline void operator()(){
        if(handled){
            return;
        }

        if(args.empty()){
            if(module_traits<Module>::is_default){
                handle_module<Module>();
            }
        } else if(args[0] == module_traits<Module>::command){
            handle_module<Module>();
        }
    }
};

struct aliases_collector {
    std::vector<std::pair<const char*, const char*>> aliases;

    template<typename Module, cpp::enable_if_u<has_aliases<Module>::value> = cpp::detail::dummy>
    inline void operator()(){
        for(auto& v : module_traits<Module>::aliases){
            aliases.push_back(v);
        }
    }

    template<typename Module, cpp::disable_if_u<has_aliases<Module>::value> = cpp::detail::dummy>
    inline void operator()(){
        //NOP
    }
};

std::string exec_command(const std::string& command) {
    std::stringstream output;

    char buffer[1024];

    FILE* stream = popen(command.c_str(), "r");

    while (fgets(buffer, 1024, stream) != NULL) {
        output << buffer;
    }

    pclose(stream);

    return output.str();
}

bool has_enough_colors(){
    auto colors = exec_command("tput colors");
    colors = colors.substr(0, colors.length() - 1);

    return to_number<int>(colors) > 4;
}

} //end of anonymous namespace

int main(int argc, const char* argv[]) {
    std::locale global_locale("");
    std::locale::global(global_locale);

    //Collect all aliases
    aliases_collector collector;
    cpp::for_each_tuple_t<modules_tuple>(collector);

    //Parse the command line args
    auto args = parse_args(argc, argv, collector.aliases);

    if(args.size() && args[0] == "server"){
        set_server_running();
    }

    if (!load_config()) {
        return 0;
    }

    if (is_server_mode() && (!config_contains("server_url") || !config_contains("server_port"))) {
        std::cout << "error: server_mode=true needs a server_url value and a server_port value" << std::endl;

        return 0;
    }

    if (!has_enough_colors()) {
        std::cout << "WARNING: The terminal does not seem to have enough colors, some command may not work as intended" << std::endl;
    }

    // Restore the caches
    load_currency_cache();
    load_share_price_cache();

    if (!is_server_running() && is_server_mode()) {
        // 1. Ensure that the server is running

        auto res = budget::api_get("/server/up/", false);

        if(!res.success || res.result != "yes"){
            std::cout << "The server is not running, cannot run in server mode" << std::endl;
            return 0;
        }

        std::map<std::string, std::string> params;
        params["version"] = get_version_short();

        auto version_res = budget::api_post("/server/version/support/", params);

        if(!version_res.success || version_res.result != "yes"){
            std::cout << "The server does not support your version, cannot run in server mode" << std::endl;
            std::cout << "You should either upgrade the server or your client" << std::endl;
            return 0;
        }
    } else {
        auto old_data_version = to_number<size_t>(internal_config_value("data_version"));

        if (old_data_version > DATA_VERSION) {
            std::cout << "Unsupported database version, you should update budgetwarrior" << std::endl;

            return 0;
        }

        if (old_data_version < DATA_VERSION) {
            std::cout << "Migrate database..." << std::endl;

            if (old_data_version == 1 && DATA_VERSION >= 2) {
                migrate_recurring_1_to_2();
            }

            if (old_data_version <= 2 && DATA_VERSION >= 3) {
                migrate_wishes_2_to_3();
            }

            if (old_data_version <= 3 && DATA_VERSION >= 4) {
                //migrate_debts_3_to_4();
                migrate_wishes_3_to_4();
            }

            if (old_data_version <= 4 && DATA_VERSION >= 5) {
                migrate_assets_4_to_5();
            }

            if (old_data_version <= 5 && DATA_VERSION >= 6) {
                migrate_assets_5_to_6();
            }

            internal_config_value("data_version") = to_string(DATA_VERSION);

            // We want to make sure the new data version is set in stone!
            save_config();

            std::cout << "done" << std::endl;
        }
    }

    int code = 0;

    try {
        //Run the correct module
        module_runner runner(std::move(args));
        cpp::for_each_tuple_t<modules_tuple>(runner);

        if (!runner.handled) {
            std::cout << "Unhandled command \"" << runner.args[0] << "\"" << std::endl;

            code = 1;
        }
    } catch (const budget_exception& exception) {
        std::cout << exception.message() << std::endl;

        code = 2;
    }

    // Save the caches
    save_currency_cache();
    save_share_price_cache();

    save_config();

    return code;
}
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) Jürgen Riegel          (juergen.riegel@web.de) 2008     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <gp_Pnt.hxx>
# include <gp_Ax1.hxx>
# include <BRep_Tool.hxx>
# include <TopoDS.hxx>
# include <TopoDS_Vertex.hxx>
# include <BRep_Builder.hxx>
# include <BRepBuilderAPI_MakeVertex.hxx>
# include <Geom_CartesianPoint.hxx>
#endif

#include <Mod/Part/App/TopoShape.h>
#include <Base/VectorPy.h>
#include <Base/Vector3D.h>

#include "PointPy.h"
#include "TopoShapeVertexPy.h"
#include "TopoShapeVertexPy.cpp"

using namespace Part;

// returns a string which represents the object e.g. when printed in python
std::string TopoShapeVertexPy::representation(void) const
{
    std::stringstream str;
    str << "<Vertex object at " << getTopoShapePtr() << ">";

    return str.str();
}

PyObject *TopoShapeVertexPy::PyMake(struct _typeobject *, PyObject *, PyObject *)  // Python wrapper
{
    // create a new instance of TopoShapeVertexPy and the Twin object
    return new TopoShapeVertexPy(new TopoShape);
}

// constructor method
int TopoShapeVertexPy::PyInit(PyObject* args, PyObject* /*kwd*/)
{
    double x=0.0,y=0.0,z=0.0;
    PyObject *object;
    bool success = false;
    if (PyArg_ParseTuple(args, "|ddd", &x,&y,&z)) {
        // do nothing here
        success = true;
    }
    if (!success) {
        PyErr_Clear(); // set by PyArg_ParseTuple()
        if (PyArg_ParseTuple(args,"O!",&(Base::VectorPy::Type), &object)) {
            // Note: must be static_cast, not reinterpret_cast
            Base::Vector3d* ptr = static_cast<Base::VectorPy*>(object)->getVectorPtr();
            x = ptr->x;
            y = ptr->y;
            z = ptr->z;
            success = true;
        }
    }
    if (!success) {
        PyErr_Clear(); // set by PyArg_ParseTuple()
        if (PyArg_ParseTuple(args,"O!",&(PyTuple_Type), &object)) {
            try {
                Py::Tuple tuple(object);
                x = Py::Float(tuple.getItem(0));
                y = Py::Float(tuple.getItem(1));
                z = Py::Float(tuple.getItem(2));
                success = true;
            }
            catch (const Py::Exception&) {
                return -1;
            }
        }
    }
    if (!success) {
        PyErr_Clear(); // set by PyArg_ParseTuple()
        if (PyArg_ParseTuple(args,"O!",&(PointPy::Type), &object)) {
            Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast
                (static_cast<PointPy*>(object)->getGeomPointPtr()->handle());
            gp_Pnt pnt = this_point->Pnt();
            x = pnt.X();
            y = pnt.Y();
            z = pnt.Z();
            success = true;
        }
    }
    if (!success) {
        PyErr_Clear(); // set by PyArg_ParseTuple()
        if (PyArg_ParseTuple(args,"O!",&(Part::TopoShapePy::Type), &object)) {
            TopoShape* ptr = static_cast<TopoShapePy*>(object)->getTopoShapePtr();
            TopoDS_Shape shape = ptr->getShape();
            if (!shape.IsNull() && shape.ShapeType() == TopAbs_VERTEX) {
                TopoShapeVertexPy::PointerType vert = reinterpret_cast<TopoShapeVertexPy::PointerType>(_pcTwinPointer);
                vert->setShape(ptr->getShape());
                return 0;
            }
        }
    }
    if (!success) {
        PyErr_SetString(PyExc_TypeError, "Either three floats, tuple, vector or vertex expected");
        return -1;
    }

    TopoShapeVertexPy::PointerType ptr = reinterpret_cast<TopoShapeVertexPy::PointerType>(_pcTwinPointer);
    BRepBuilderAPI_MakeVertex aBuilder(gp_Pnt(x,y,z));
    TopoDS_Shape s = aBuilder.Vertex();
    ptr->setShape(s);

    return 0;
}

PyObject* TopoShapeVertexPy::setTolerance(PyObject *args)
{
    double tol;
    if (!PyArg_ParseTuple(args, "d", &tol))
        return 0;
    BRep_Builder aBuilder;
    const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape());
    aBuilder.UpdateVertex(v, tol);
    Py_Return;
}

Py::Float TopoShapeVertexPy::getTolerance(void) const
{
    const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape());
    return Py::Float(BRep_Tool::Tolerance(v));
}

void TopoShapeVertexPy::setTolerance(Py::Float tol)
{
    BRep_Builder aBuilder;
    const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape());
    aBuilder.UpdateVertex(v, (double)tol);
}

Py::Float TopoShapeVertexPy::getX(void) const
{
    const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape());
    return Py::Float(BRep_Tool::Pnt(v).X());
}

Py::Float TopoShapeVertexPy::getY(void) const
{
    const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape());
    return Py::Float(BRep_Tool::Pnt(v).Y());
}

Py::Float TopoShapeVertexPy::getZ(void) const
{
    const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape());
    return Py::Float(BRep_Tool::Pnt(v).Z());
}

Py::Object TopoShapeVertexPy::getPoint(void) const
{
    const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape());
    gp_Pnt p = BRep_Tool::Pnt(v);
    return Py::asObject(new Base::VectorPy(new Base::Vector3d(p.X(),p.Y(),p.Z())));
}

PyObject *TopoShapeVertexPy::getCustomAttributes(const char* /*attr*/) const
{
    return 0;
}

int TopoShapeVertexPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
    return 0;
}
<commit_msg>handle OCC exception when accessing point of a vertex<commit_after>/***************************************************************************
 *   Copyright (c) Jürgen Riegel          (juergen.riegel@web.de) 2008     *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <gp_Pnt.hxx>
# include <gp_Ax1.hxx>
# include <BRep_Tool.hxx>
# include <TopoDS.hxx>
# include <TopoDS_Vertex.hxx>
# include <BRep_Builder.hxx>
# include <BRepBuilderAPI_MakeVertex.hxx>
# include <Geom_CartesianPoint.hxx>
# include <Standard_Failure.hxx>
#endif

#include <Mod/Part/App/TopoShape.h>
#include <Base/VectorPy.h>
#include <Base/Vector3D.h>

#include "PointPy.h"
#include "TopoShapeVertexPy.h"
#include "TopoShapeVertexPy.cpp"

using namespace Part;

// returns a string which represents the object e.g. when printed in python
std::string TopoShapeVertexPy::representation(void) const
{
    std::stringstream str;
    str << "<Vertex object at " << getTopoShapePtr() << ">";

    return str.str();
}

PyObject *TopoShapeVertexPy::PyMake(struct _typeobject *, PyObject *, PyObject *)  // Python wrapper
{
    // create a new instance of TopoShapeVertexPy and the Twin object
    return new TopoShapeVertexPy(new TopoShape);
}

// constructor method
int TopoShapeVertexPy::PyInit(PyObject* args, PyObject* /*kwd*/)
{
    double x=0.0,y=0.0,z=0.0;
    PyObject *object;
    bool success = false;
    if (PyArg_ParseTuple(args, "|ddd", &x,&y,&z)) {
        // do nothing here
        success = true;
    }
    if (!success) {
        PyErr_Clear(); // set by PyArg_ParseTuple()
        if (PyArg_ParseTuple(args,"O!",&(Base::VectorPy::Type), &object)) {
            // Note: must be static_cast, not reinterpret_cast
            Base::Vector3d* ptr = static_cast<Base::VectorPy*>(object)->getVectorPtr();
            x = ptr->x;
            y = ptr->y;
            z = ptr->z;
            success = true;
        }
    }
    if (!success) {
        PyErr_Clear(); // set by PyArg_ParseTuple()
        if (PyArg_ParseTuple(args,"O!",&(PyTuple_Type), &object)) {
            try {
                Py::Tuple tuple(object);
                x = Py::Float(tuple.getItem(0));
                y = Py::Float(tuple.getItem(1));
                z = Py::Float(tuple.getItem(2));
                success = true;
            }
            catch (const Py::Exception&) {
                return -1;
            }
        }
    }
    if (!success) {
        PyErr_Clear(); // set by PyArg_ParseTuple()
        if (PyArg_ParseTuple(args,"O!",&(PointPy::Type), &object)) {
            Handle(Geom_CartesianPoint) this_point = Handle(Geom_CartesianPoint)::DownCast
                (static_cast<PointPy*>(object)->getGeomPointPtr()->handle());
            gp_Pnt pnt = this_point->Pnt();
            x = pnt.X();
            y = pnt.Y();
            z = pnt.Z();
            success = true;
        }
    }
    if (!success) {
        PyErr_Clear(); // set by PyArg_ParseTuple()
        if (PyArg_ParseTuple(args,"O!",&(Part::TopoShapePy::Type), &object)) {
            TopoShape* ptr = static_cast<TopoShapePy*>(object)->getTopoShapePtr();
            TopoDS_Shape shape = ptr->getShape();
            if (!shape.IsNull() && shape.ShapeType() == TopAbs_VERTEX) {
                TopoShapeVertexPy::PointerType vert = reinterpret_cast<TopoShapeVertexPy::PointerType>(_pcTwinPointer);
                vert->setShape(ptr->getShape());
                return 0;
            }
        }
    }
    if (!success) {
        PyErr_SetString(PyExc_TypeError, "Either three floats, tuple, vector or vertex expected");
        return -1;
    }

    TopoShapeVertexPy::PointerType ptr = reinterpret_cast<TopoShapeVertexPy::PointerType>(_pcTwinPointer);
    BRepBuilderAPI_MakeVertex aBuilder(gp_Pnt(x,y,z));
    TopoDS_Shape s = aBuilder.Vertex();
    ptr->setShape(s);

    return 0;
}

PyObject* TopoShapeVertexPy::setTolerance(PyObject *args)
{
    double tol;
    if (!PyArg_ParseTuple(args, "d", &tol))
        return 0;
    BRep_Builder aBuilder;
    const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape());
    aBuilder.UpdateVertex(v, tol);
    Py_Return;
}

Py::Float TopoShapeVertexPy::getTolerance(void) const
{
    const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape());
    return Py::Float(BRep_Tool::Tolerance(v));
}

void TopoShapeVertexPy::setTolerance(Py::Float tol)
{
    BRep_Builder aBuilder;
    const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape());
    aBuilder.UpdateVertex(v, (double)tol);
}

Py::Float TopoShapeVertexPy::getX(void) const
{
    try {
        const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape());
        return Py::Float(BRep_Tool::Pnt(v).X());
    }
    catch (Standard_Failure) {
        Handle(Standard_Failure) e = Standard_Failure::Caught();
        throw Py::RuntimeError(e->GetMessageString());
    }
}

Py::Float TopoShapeVertexPy::getY(void) const
{
    try {
        const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape());
        return Py::Float(BRep_Tool::Pnt(v).Y());
    }
    catch (Standard_Failure) {
        Handle(Standard_Failure) e = Standard_Failure::Caught();
        throw Py::RuntimeError(e->GetMessageString());
    }
}

Py::Float TopoShapeVertexPy::getZ(void) const
{
    try {
        const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape());
        return Py::Float(BRep_Tool::Pnt(v).Z());
    }
    catch (Standard_Failure) {
        Handle(Standard_Failure) e = Standard_Failure::Caught();
        throw Py::RuntimeError(e->GetMessageString());
    }
}

Py::Object TopoShapeVertexPy::getPoint(void) const
{
    try {
        const TopoDS_Vertex& v = TopoDS::Vertex(getTopoShapePtr()->getShape());
        gp_Pnt p = BRep_Tool::Pnt(v);
        return Py::asObject(new Base::VectorPy(new Base::Vector3d(p.X(),p.Y(),p.Z())));
    }
    catch (Standard_Failure) {
        Handle(Standard_Failure) e = Standard_Failure::Caught();
        throw Py::RuntimeError(e->GetMessageString());
    }
}

PyObject *TopoShapeVertexPy::getCustomAttributes(const char* /*attr*/) const
{
    return 0;
}

int TopoShapeVertexPy::setCustomAttributes(const char* /*attr*/, PyObject* /*obj*/)
{
    return 0;
}
<|endoftext|>


<commit_before>#ifndef BUFFER_HPP_INCLUDED
#define BUFFER_HPP_INCLUDED

namespace gst
{
    class RenderState;

    enum class BufferTarget {
        ARRAY,
        ELEMENT_ARRAY
    };

    enum class DataUsage {
        STATIC,
        DYNAMIC
    };

    // The responsibility of this class is to mirror a buffer object on the
    // graphics card.
    class Buffer {
        friend RenderState;
    public:
        // Return buffer target.
        virtual BufferTarget get_target() const = 0;
        // Return buffer data usage.
        virtual DataUsage get_usage() const = 0;
        // Return buffer data size in bytes.
        virtual unsigned int get_size_bytes() const = 0;
        // Return the number of elements in the buffer data.
        virtual unsigned int get_count() const = 0;
    protected:
        // Notify graphics card to bind this buffer.
        virtual void bind() = 0;
        // Sync client state with graphics card.
        virtual void sync() = 0;
    };
}

#endif
<commit_msg>extend buffer interface<commit_after>#ifndef BUFFER_HPP_INCLUDED
#define BUFFER_HPP_INCLUDED

#include "glm.hpp"

#include <vector>

namespace gst
{
    class RenderState;

    // Specifies buffer target.
    enum class BufferTarget {
        ARRAY,
        ELEMENT_ARRAY
    };

    // Specifies expected usage pattern of buffer data.
    enum class DataUsage {
        STATIC,
        DYNAMIC
    };

    // The responsibility of this class is to mirror a buffer object on the
    // graphics card.
    class Buffer {
        friend RenderState;
    public:
        // Set client side data to int array.
        virtual void set_int_array(std::vector<int> const & data) = 0;
        // Set client side data to unsigned int array.
        virtual void set_unsigned_int_array(std::vector<unsigned int> const & data) = 0;
        // Set client side data to float array.
        virtual void set_float_array(std::vector<float> const & data) = 0;
        // Set client side data to vec2 array.
        virtual void set_vec2_array(std::vector<glm::vec2> const & data) = 0;
        // Set client side data to vec3 array.
        virtual void set_vec3_array(std::vector<glm::vec3> const & data) = 0;
        // Set client side data to vec4 array.
        virtual void set_vec4_array(std::vector<glm::vec4> const & data) = 0;
        // Set buffer target.
        virtual void set_target(BufferTarget target) = 0;
        // Set buffer data usage.
        virtual void set_usage(DataUsage usage) = 0;
        // Return buffer target.
        virtual BufferTarget get_target() const = 0;
        // Return buffer data usage.
        virtual DataUsage get_usage() const = 0;
        // Return the number of elements in the buffer data.
        virtual unsigned int get_count() const = 0;
        // Return buffer data size in bytes.
        virtual unsigned int get_size_bytes() const = 0;
    protected:
        // Notify graphics card to bind this buffer.
        virtual void bind() = 0;
        // Sync client state with graphics card.
        virtual void sync() = 0;
    };
}

#endif
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (c) 2004 Jürgen Riegel <juergen.riegel@web.de>              *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <Standard_math.hxx>
# include <Inventor/nodes/SoBaseColor.h>
# include <Inventor/nodes/SoDrawStyle.h>
# include <Inventor/nodes/SoMaterial.h>
# include <Inventor/nodes/SoLineSet.h>
# include <Inventor/nodes/SoPickStyle.h>
# include <Inventor/nodes/SoSeparator.h>
# include <Inventor/nodes/SoVertexProperty.h>
# include <cfloat>
#endif

/// Here the FreeCAD includes sorted by Base,App,Gui......
#include <Base/Console.h>
#include <Base/Parameter.h>
#include <Base/Reader.h>
#include <Base/ViewProj.h>
#include <App/Application.h>
#include <Gui/SoFCBoundingBox.h>

#include "ViewProvider2DObject.h"
#include <Mod/Part/App/PartFeature.h>

using namespace PartGui;
using namespace std;

//**************************************************************************
// Construction/Destruction

const char* ViewProvider2DObject::GridStyleEnums[]= {"Dashed","Light",NULL};
App::PropertyQuantityConstraint::Constraints ViewProvider2DObject::GridSizeRange = {0.001,DBL_MAX,1.0};

PROPERTY_SOURCE(PartGui::ViewProvider2DObject, PartGui::ViewProviderPart)

ViewProvider2DObject::ViewProvider2DObject()
{
    ADD_PROPERTY_TYPE(ShowGrid,(false),"Grid",(App::PropertyType)(App::Prop_None),"Switch the grid on/off");
    ADD_PROPERTY_TYPE(GridSize,(10),"Grid",(App::PropertyType)(App::Prop_None),"Gap size of the grid");
    ADD_PROPERTY_TYPE(GridStyle,((long)0),"Grid",(App::PropertyType)(App::Prop_None),"Appearance style of the grid");
    ADD_PROPERTY_TYPE(TightGrid,(true),"Grid",(App::PropertyType)(App::Prop_None),"Switch the tight grid mode on/off");
    ADD_PROPERTY_TYPE(GridSnap,(false),"Grid",(App::PropertyType)(App::Prop_None),"Switch the grid snap on/off");

    GridRoot = new SoSeparator();
    GridRoot->ref();
    MinX = MinY = -100;
    MaxX = MaxY = 100;
    GridStyle.setEnums(GridStyleEnums);
    GridSize.setConstraints(&GridSizeRange);

    pcRoot->addChild(GridRoot);

    sPixmap = "PartFeatureImport";
}

ViewProvider2DObject::~ViewProvider2DObject()
{
     GridRoot->unref();
}

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

SoSeparator* ViewProvider2DObject::createGrid(void)
{
    //double dx = 10 * GridSize.getValue();                       // carpet size
    //double dy = 10 * GridSize.getValue();
    // float Size = (MaxX-MinX > MaxY-MinY) ? MaxX-MinX : MaxY-MinY;
    float Step = GridSize.getValue(); //pow(10,floor(log10(Size/5.0)));
    float MiX, MaX, MiY, MaY;
    if (TightGrid.getValue()) {
        MiX = MinX - (MaxX-MinX)*0.2f;
        MaX = MaxX + (MaxX-MinX)*0.2f;
        MiY = MinY - (MaxY-MinY)*0.2f;
        MaY = MaxY + (MaxY-MinY)*0.2f;
    }
    else {
        // make sure that nine of the numbers are exactly zero because log(0)
        // is not defined
        float xMin = std::abs(MinX) < FLT_EPSILON ? 0.01f : MinX;
        float xMax = std::abs(MaxX) < FLT_EPSILON ? 0.01f : MaxX;
        float yMin = std::abs(MinY) < FLT_EPSILON ? 0.01f : MinY;
        float yMax = std::abs(MaxY) < FLT_EPSILON ? 0.01f : MaxY;
        MiX = -exp(ceil(log(std::abs(xMin))));
        MiX = std::min<float>(MiX,(float)-exp(ceil(log(std::abs(0.1f*xMax)))));
        MaX = exp(ceil(log(std::abs(xMax))));
        MaX = std::max<float>(MaX,(float)exp(ceil(log(std::abs(0.1f*xMin)))));
        MiY = -exp(ceil(log(std::abs(yMin))));
        MiY = std::min<float>(MiY,(float)-exp(ceil(log(std::abs(0.1f*yMax)))));
        MaY = exp(ceil(log(std::abs(yMax))));
        MaY = std::max<float>(MaY,(float)exp(ceil(log(std::abs(0.1f*yMin)))));
    }
    //Round the values otherwise grid is not aligned with center
    MiX = floor(MiX / Step) * Step;
    MaX = ceil(MaX / Step) * Step;
    MiY = floor(MiY / Step) * Step;
    MaY = ceil(MaY / Step) * Step;

    double zGrid = 0.0;                     // carpet-grid separation

    SoGroup *parent = new Gui::SoSkipBoundingGroup();
    GridRoot->removeAllChildren();
    GridRoot->addChild(parent);
    SoBaseColor *mycolor;
    SoVertexProperty *vts;

   // carpet
 /* mycolor = new SoBaseColor;
    mycolor->rgb.setValue(0.2f, 0.7f, 0.7f);
    parent->addChild(mycolor);

    vts = new SoVertexProperty;
    vts->vertex.set1Value(0, -0.5*dx, -1.5*dy,  0.5*zGrid);
    vts->vertex.set1Value(1, -0.5*dx, -1.5*dy, -0.5*zGrid);
    vts->vertex.set1Value(2,  0.5*dx, -1.5*dy,  0.5*zGrid);
    vts->vertex.set1Value(3,  0.5*dx, -1.5*dy, -0.5*zGrid);

    SoQuadMesh *carpet = new SoQuadMesh;
    carpet->verticesPerColumn = 2;
    carpet->verticesPerRow = 2;
    carpet->vertexProperty = vts;
    parent->addChild(carpet);*/

    // gridlines
    mycolor = new SoBaseColor;
    mycolor->rgb.setValue(0.7f, 0.7f ,0.7f);
    parent->addChild(mycolor);

    if (GridStyle.getValue() == 0) {
        ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Part");
        int pattern = hGrp->GetInt("GridLinePattern", 0x0f0f);
        SoDrawStyle* DefaultStyle = new SoDrawStyle;
        DefaultStyle->lineWidth = 1;
        DefaultStyle->linePattern = pattern;
        parent->addChild(DefaultStyle);
    }
    else {
        SoMaterial* LightStyle = new SoMaterial;
        LightStyle->transparency = 0.7f;
        parent->addChild(LightStyle);
    }

    SoPickStyle* PickStyle = new SoPickStyle;
    PickStyle->style = SoPickStyle::UNPICKABLE;
    parent->addChild(PickStyle);

    SoLineSet *grid = new SoLineSet;
    vts = new SoVertexProperty;
    grid->vertexProperty = vts;

    // vertical lines
    int vlines = static_cast<int>((MaX - MiX) / Step + 0.5f);

    // horizontal lines
    int hlines = static_cast<int>((MaY - MiY) / Step + 0.5f);

    int lines = vlines + hlines;

    // set the grid indices
    grid->numVertices.setNum(lines);
    int32_t* vertices = grid->numVertices.startEditing();
    for (int i=0; i<lines; i++)
        vertices[i] = 2;
    grid->numVertices.finishEditing();

    // set the grid coordinates
    vts->vertex.setNum(2*lines);
    SbVec3f* coords = vts->vertex.startEditing();

    // vertical lines
    int i_offset_x = static_cast<int>(MiX / Step);
    for (int i=0; i<vlines; i++) {
        coords[2*i].setValue((i+i_offset_x)*Step, MiY, zGrid);
        coords[2*i+1].setValue((i+i_offset_x)*Step, MaY, zGrid);
    }

    // horizontal lines
    int i_offset_y = static_cast<int>(MiY / Step);
    for (int i=vlines; i<lines; i++) {
        coords[2*i].setValue(MiX, (i-vlines+i_offset_y)*Step, zGrid);
        coords[2*i+1].setValue(MaX, (i-vlines+i_offset_y)*Step, zGrid);
    }
    vts->vertex.finishEditing();

    parent->addChild(vts);
    parent->addChild(grid);

    return GridRoot;
}

void ViewProvider2DObject::updateData(const App::Property* prop)
{
    ViewProviderPart::updateData(prop);

    if (prop->getTypeId() == Part::PropertyPartShape::getClassTypeId()) {
        Base::BoundBox3d bbox = static_cast<const Part::PropertyPartShape*>(prop)->getBoundingBox();
        if (!bbox.IsValid()) return;
        GridRoot->removeAllChildren();
        Base::Placement place = static_cast<const Part::PropertyPartShape*>(prop)->getComplexData()->getPlacement();
        place.invert();
        Base::ViewProjMatrix proj(place.toMatrix());
        Base::BoundBox2d bbox2d = bbox.ProjectBox(&proj);
        this->MinX = bbox2d.MinX;
        this->MaxX = bbox2d.MaxX;
        this->MinY = bbox2d.MinY;
        this->MaxY = bbox2d.MaxY;
        if (ShowGrid.getValue()) {
            createGrid();
        }
    }
}

void ViewProvider2DObject::onChanged(const App::Property* prop)
{
    // call father
    ViewProviderPart::onChanged(prop);

    if (prop == &ShowGrid) {
        if (ShowGrid.getValue())
            createGrid();
        else
            GridRoot->removeAllChildren();
    }
    if ((prop == &GridSize) || (prop == &GridStyle) || (prop == &TightGrid)) {
        if (ShowGrid.getValue()) {
            GridRoot->removeAllChildren();
            createGrid();
        }
    }
}

void ViewProvider2DObject::Restore(Base::XMLReader &reader)
{
    reader.readElement("Properties");
    int Cnt = reader.getAttributeAsInteger("Count");

    for (int i=0 ;i<Cnt ;i++) {
        reader.readElement("Property");
        const char* PropName = reader.getAttribute("name");
        const char* TypeName = reader.getAttribute("type");
        App::Property* prop = getPropertyByName(PropName);

        try {
            if (prop && strcmp(prop->getTypeId().getName(), TypeName) == 0) {
                prop->Restore(reader);
            }
            else if (prop) {
                Base::Type inputType = Base::Type::fromName(TypeName);
                if (prop->getTypeId().isDerivedFrom(App::PropertyFloat::getClassTypeId()) &&
                    inputType.isDerivedFrom(App::PropertyFloat::getClassTypeId())) {
                    // Do not directly call the property's Restore method in case the implmentation
                    // has changed. So, create a temporary PropertyFloat object and assign the value.
                    App::PropertyFloat floatProp;
                    floatProp.Restore(reader);
                    static_cast<App::PropertyFloat*>(prop)->setValue(floatProp.getValue());
                }
            }
        }
        catch (const Base::XMLParseException&) {
            throw; // re-throw
        }
        catch (const Base::Exception &e) {
            Base::Console().Error("%s\n", e.what());
        }
        catch (const std::exception &e) {
            Base::Console().Error("%s\n", e.what());
        }
        catch (const char* e) {
            Base::Console().Error("%s\n", e);
        }
#ifndef FC_DEBUG
        catch (...) {
            Base::Console().Error("Primitive::Restore: Unknown C++ exception thrown");
        }
#endif

        reader.readEndElement("Property");
    }
    reader.readEndElement("Properties");
}

void ViewProvider2DObject::attach(App::DocumentObject *pcFeat)
{
    ViewProviderPart::attach(pcFeat);

    if (ShowGrid.getValue())
        createGrid();
}

bool ViewProvider2DObject::setEdit(int)
{
    return false;
}

void ViewProvider2DObject::unsetEdit(int)
{

}

std::vector<std::string> ViewProvider2DObject::getDisplayModes(void) const
{
    // get the modes of the father
    std::vector<std::string> StrList = ViewProviderGeometryObject::getDisplayModes();

    // add your own modes
    StrList.push_back("Flat Lines");
    //StrList.push_back("Shaded");
    StrList.push_back("Wireframe");
    StrList.push_back("Points");

    return StrList;
}

const char* ViewProvider2DObject::getDefaultDisplayMode() const
{
  return "Wireframe";
}

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

namespace Gui {
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(PartGui::ViewProvider2DObjectPython, PartGui::ViewProvider2DObject)
/// @endcond

// explicit template instantiation
template class PartGuiExport ViewProviderPythonFeatureT<PartGui::ViewProvider2DObject>;
}
<commit_msg>fixes #0002745: The Disappearing Grid<commit_after>/***************************************************************************
 *   Copyright (c) 2004 Jürgen Riegel <juergen.riegel@web.de>              *
 *                                                                         *
 *   This file is part of the FreeCAD CAx development system.              *
 *                                                                         *
 *   This library is free software; you can redistribute it and/or         *
 *   modify it under the terms of the GNU Library General Public           *
 *   License as published by the Free Software Foundation; either          *
 *   version 2 of the License, or (at your option) any later version.      *
 *                                                                         *
 *   This library  is distributed in the hope that it will be useful,      *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU Library General Public License for more details.                  *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this library; see the file COPYING.LIB. If not,    *
 *   write to the Free Software Foundation, Inc., 59 Temple Place,         *
 *   Suite 330, Boston, MA  02111-1307, USA                                *
 *                                                                         *
 ***************************************************************************/

#include "PreCompiled.h"

#ifndef _PreComp_
# include <Standard_math.hxx>
# include <Inventor/nodes/SoBaseColor.h>
# include <Inventor/nodes/SoDepthBuffer.h>
# include <Inventor/nodes/SoDrawStyle.h>
# include <Inventor/nodes/SoMaterial.h>
# include <Inventor/nodes/SoLineSet.h>
# include <Inventor/nodes/SoPickStyle.h>
# include <Inventor/nodes/SoSeparator.h>
# include <Inventor/nodes/SoVertexProperty.h>
# include <cfloat>
#endif

/// Here the FreeCAD includes sorted by Base,App,Gui......
#include <Base/Console.h>
#include <Base/Parameter.h>
#include <Base/Reader.h>
#include <Base/ViewProj.h>
#include <App/Application.h>
#include <Gui/SoFCBoundingBox.h>

#include "ViewProvider2DObject.h"
#include <Mod/Part/App/PartFeature.h>

using namespace PartGui;
using namespace std;

//**************************************************************************
// Construction/Destruction

const char* ViewProvider2DObject::GridStyleEnums[]= {"Dashed","Light",NULL};
App::PropertyQuantityConstraint::Constraints ViewProvider2DObject::GridSizeRange = {0.001,DBL_MAX,1.0};

PROPERTY_SOURCE(PartGui::ViewProvider2DObject, PartGui::ViewProviderPart)

ViewProvider2DObject::ViewProvider2DObject()
{
    ADD_PROPERTY_TYPE(ShowGrid,(false),"Grid",(App::PropertyType)(App::Prop_None),"Switch the grid on/off");
    ADD_PROPERTY_TYPE(GridSize,(10),"Grid",(App::PropertyType)(App::Prop_None),"Gap size of the grid");
    ADD_PROPERTY_TYPE(GridStyle,((long)0),"Grid",(App::PropertyType)(App::Prop_None),"Appearance style of the grid");
    ADD_PROPERTY_TYPE(TightGrid,(true),"Grid",(App::PropertyType)(App::Prop_None),"Switch the tight grid mode on/off");
    ADD_PROPERTY_TYPE(GridSnap,(false),"Grid",(App::PropertyType)(App::Prop_None),"Switch the grid snap on/off");

    GridRoot = new SoSeparator();
    GridRoot->ref();
    GridRoot->setName("GridRoot");
    MinX = MinY = -100;
    MaxX = MaxY = 100;
    GridStyle.setEnums(GridStyleEnums);
    GridSize.setConstraints(&GridSizeRange);

    pcRoot->addChild(GridRoot);

    sPixmap = "PartFeatureImport";
}

ViewProvider2DObject::~ViewProvider2DObject()
{
     GridRoot->unref();
}

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

SoSeparator* ViewProvider2DObject::createGrid(void)
{
    //double dx = 10 * GridSize.getValue();                       // carpet size
    //double dy = 10 * GridSize.getValue();
    // float Size = (MaxX-MinX > MaxY-MinY) ? MaxX-MinX : MaxY-MinY;
    float Step = GridSize.getValue(); //pow(10,floor(log10(Size/5.0)));
    float MiX, MaX, MiY, MaY;
    if (TightGrid.getValue()) {
        MiX = MinX - (MaxX-MinX)*0.2f;
        MaX = MaxX + (MaxX-MinX)*0.2f;
        MiY = MinY - (MaxY-MinY)*0.2f;
        MaY = MaxY + (MaxY-MinY)*0.2f;
    }
    else {
        // make sure that nine of the numbers are exactly zero because log(0)
        // is not defined
        float xMin = std::abs(MinX) < FLT_EPSILON ? 0.01f : MinX;
        float xMax = std::abs(MaxX) < FLT_EPSILON ? 0.01f : MaxX;
        float yMin = std::abs(MinY) < FLT_EPSILON ? 0.01f : MinY;
        float yMax = std::abs(MaxY) < FLT_EPSILON ? 0.01f : MaxY;
        MiX = -exp(ceil(log(std::abs(xMin))));
        MiX = std::min<float>(MiX,(float)-exp(ceil(log(std::abs(0.1f*xMax)))));
        MaX = exp(ceil(log(std::abs(xMax))));
        MaX = std::max<float>(MaX,(float)exp(ceil(log(std::abs(0.1f*xMin)))));
        MiY = -exp(ceil(log(std::abs(yMin))));
        MiY = std::min<float>(MiY,(float)-exp(ceil(log(std::abs(0.1f*yMax)))));
        MaY = exp(ceil(log(std::abs(yMax))));
        MaY = std::max<float>(MaY,(float)exp(ceil(log(std::abs(0.1f*yMin)))));
    }
    //Round the values otherwise grid is not aligned with center
    MiX = floor(MiX / Step) * Step;
    MaX = ceil(MaX / Step) * Step;
    MiY = floor(MiY / Step) * Step;
    MaY = ceil(MaY / Step) * Step;

    double zGrid = 0.0;                     // carpet-grid separation

    SoGroup *parent = new Gui::SoSkipBoundingGroup();
    GridRoot->removeAllChildren();
    GridRoot->addChild(parent);
    SoBaseColor *mycolor;
    SoVertexProperty *vts;

   // carpet
 /* mycolor = new SoBaseColor;
    mycolor->rgb.setValue(0.2f, 0.7f, 0.7f);
    parent->addChild(mycolor);

    vts = new SoVertexProperty;
    vts->vertex.set1Value(0, -0.5*dx, -1.5*dy,  0.5*zGrid);
    vts->vertex.set1Value(1, -0.5*dx, -1.5*dy, -0.5*zGrid);
    vts->vertex.set1Value(2,  0.5*dx, -1.5*dy,  0.5*zGrid);
    vts->vertex.set1Value(3,  0.5*dx, -1.5*dy, -0.5*zGrid);

    SoQuadMesh *carpet = new SoQuadMesh;
    carpet->verticesPerColumn = 2;
    carpet->verticesPerRow = 2;
    carpet->vertexProperty = vts;
    parent->addChild(carpet);*/

    SoDepthBuffer *depth = new SoDepthBuffer;
    depth->function = SoDepthBuffer::ALWAYS;
    parent->addChild(depth);

    // gridlines
    mycolor = new SoBaseColor;
    mycolor->rgb.setValue(0.7f, 0.7f ,0.7f);
    parent->addChild(mycolor);

    if (GridStyle.getValue() == 0) {
        ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/Mod/Part");
        int pattern = hGrp->GetInt("GridLinePattern", 0x0f0f);
        SoDrawStyle* DefaultStyle = new SoDrawStyle;
        DefaultStyle->lineWidth = 1;
        DefaultStyle->linePattern = pattern;
        parent->addChild(DefaultStyle);
    }
    else {
        SoMaterial* LightStyle = new SoMaterial;
        LightStyle->transparency = 0.7f;
        parent->addChild(LightStyle);
    }

    SoPickStyle* PickStyle = new SoPickStyle;
    PickStyle->style = SoPickStyle::UNPICKABLE;
    parent->addChild(PickStyle);

    SoLineSet *grid = new SoLineSet;
    vts = new SoVertexProperty;
    grid->vertexProperty = vts;

    // vertical lines
    int vlines = static_cast<int>((MaX - MiX) / Step + 0.5f);

    // horizontal lines
    int hlines = static_cast<int>((MaY - MiY) / Step + 0.5f);

    int lines = vlines + hlines;

    // set the grid indices
    grid->numVertices.setNum(lines);
    int32_t* vertices = grid->numVertices.startEditing();
    for (int i=0; i<lines; i++)
        vertices[i] = 2;
    grid->numVertices.finishEditing();

    // set the grid coordinates
    vts->vertex.setNum(2*lines);
    SbVec3f* coords = vts->vertex.startEditing();

    // vertical lines
    int i_offset_x = static_cast<int>(MiX / Step);
    for (int i=0; i<vlines; i++) {
        coords[2*i].setValue((i+i_offset_x)*Step, MiY, zGrid);
        coords[2*i+1].setValue((i+i_offset_x)*Step, MaY, zGrid);
    }

    // horizontal lines
    int i_offset_y = static_cast<int>(MiY / Step);
    for (int i=vlines; i<lines; i++) {
        coords[2*i].setValue(MiX, (i-vlines+i_offset_y)*Step, zGrid);
        coords[2*i+1].setValue(MaX, (i-vlines+i_offset_y)*Step, zGrid);
    }
    vts->vertex.finishEditing();

    parent->addChild(vts);
    parent->addChild(grid);

    return GridRoot;
}

void ViewProvider2DObject::updateData(const App::Property* prop)
{
    ViewProviderPart::updateData(prop);

    if (prop->getTypeId() == Part::PropertyPartShape::getClassTypeId()) {
        Base::BoundBox3d bbox = static_cast<const Part::PropertyPartShape*>(prop)->getBoundingBox();
        if (!bbox.IsValid()) return;
        GridRoot->removeAllChildren();
        Base::Placement place = static_cast<const Part::PropertyPartShape*>(prop)->getComplexData()->getPlacement();
        place.invert();
        Base::ViewProjMatrix proj(place.toMatrix());
        Base::BoundBox2d bbox2d = bbox.ProjectBox(&proj);
        this->MinX = bbox2d.MinX;
        this->MaxX = bbox2d.MaxX;
        this->MinY = bbox2d.MinY;
        this->MaxY = bbox2d.MaxY;
        if (ShowGrid.getValue()) {
            createGrid();
        }
    }
}

void ViewProvider2DObject::onChanged(const App::Property* prop)
{
    // call father
    ViewProviderPart::onChanged(prop);

    if (prop == &ShowGrid) {
        if (ShowGrid.getValue())
            createGrid();
        else
            GridRoot->removeAllChildren();
    }
    if ((prop == &GridSize) || (prop == &GridStyle) || (prop == &TightGrid)) {
        if (ShowGrid.getValue()) {
            GridRoot->removeAllChildren();
            createGrid();
        }
    }
}

void ViewProvider2DObject::Restore(Base::XMLReader &reader)
{
    reader.readElement("Properties");
    int Cnt = reader.getAttributeAsInteger("Count");

    for (int i=0 ;i<Cnt ;i++) {
        reader.readElement("Property");
        const char* PropName = reader.getAttribute("name");
        const char* TypeName = reader.getAttribute("type");
        App::Property* prop = getPropertyByName(PropName);

        try {
            if (prop && strcmp(prop->getTypeId().getName(), TypeName) == 0) {
                prop->Restore(reader);
            }
            else if (prop) {
                Base::Type inputType = Base::Type::fromName(TypeName);
                if (prop->getTypeId().isDerivedFrom(App::PropertyFloat::getClassTypeId()) &&
                    inputType.isDerivedFrom(App::PropertyFloat::getClassTypeId())) {
                    // Do not directly call the property's Restore method in case the implmentation
                    // has changed. So, create a temporary PropertyFloat object and assign the value.
                    App::PropertyFloat floatProp;
                    floatProp.Restore(reader);
                    static_cast<App::PropertyFloat*>(prop)->setValue(floatProp.getValue());
                }
            }
        }
        catch (const Base::XMLParseException&) {
            throw; // re-throw
        }
        catch (const Base::Exception &e) {
            Base::Console().Error("%s\n", e.what());
        }
        catch (const std::exception &e) {
            Base::Console().Error("%s\n", e.what());
        }
        catch (const char* e) {
            Base::Console().Error("%s\n", e);
        }
#ifndef FC_DEBUG
        catch (...) {
            Base::Console().Error("Primitive::Restore: Unknown C++ exception thrown");
        }
#endif

        reader.readEndElement("Property");
    }
    reader.readEndElement("Properties");
}

void ViewProvider2DObject::attach(App::DocumentObject *pcFeat)
{
    ViewProviderPart::attach(pcFeat);

    if (ShowGrid.getValue())
        createGrid();
}

bool ViewProvider2DObject::setEdit(int)
{
    return false;
}

void ViewProvider2DObject::unsetEdit(int)
{

}

std::vector<std::string> ViewProvider2DObject::getDisplayModes(void) const
{
    // get the modes of the father
    std::vector<std::string> StrList = ViewProviderGeometryObject::getDisplayModes();

    // add your own modes
    StrList.push_back("Flat Lines");
    //StrList.push_back("Shaded");
    StrList.push_back("Wireframe");
    StrList.push_back("Points");

    return StrList;
}

const char* ViewProvider2DObject::getDefaultDisplayMode() const
{
  return "Wireframe";
}

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

namespace Gui {
/// @cond DOXERR
PROPERTY_SOURCE_TEMPLATE(PartGui::ViewProvider2DObjectPython, PartGui::ViewProvider2DObject)
/// @endcond

// explicit template instantiation
template class PartGuiExport ViewProviderPythonFeatureT<PartGui::ViewProvider2DObject>;
}
<|endoftext|>


<commit_before>#ifndef MAIN_HPP
#define MAIN_HPP

#include <iosfwd>

#include "control.hpp"
#include "system.hpp"
#include "math.hpp"

/**
 * Entry point of the program
 * @param argc Number of args (1+)
 * @param argv Array of args (starting with self)
 * @return Zero if and only if exiting without failure
 */
int main(int argc, const char **argv);

#endif
<commit_msg>Added definition to inhibit GLFW from importing GL while GL3W does the same<commit_after>#ifndef MAIN_HPP
#define MAIN_HPP

#include <iosfwd>

#define GLFW_INCLUDE_NONE

#include "control.hpp"
#include "system.hpp"
#include "math.hpp"

/**
 * Entry point of the program
 * @param argc Number of args (1+)
 * @param argv Array of args (starting with self)
 * @return Zero if and only if exiting without failure
 */
int main(int argc, const char **argv);

#endif
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  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. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#include "XalanNumberFormat.hpp"
#include "DOMStringHelper.hpp"

XalanNumberFormat::XalanNumberFormat() :
	m_isGroupingUsed(false),
	m_groupingSeparator(XALAN_STATIC_UCODE_STRING(",")),
	m_groupingSize(3)	// Default to US values
{
}

XalanNumberFormat::~XalanNumberFormat()
{
}

XalanDOMString
XalanNumberFormat::format(double		theValue)
{
	// $$$ ToDo: Fix this!
	return applyGrouping(DoubleToDOMString(theValue));
}

XalanDOMString
XalanNumberFormat::format(int	theValue)
{
	// $$$ ToDo: Fix this!
	return applyGrouping(LongToDOMString(theValue));
}

XalanDOMString
XalanNumberFormat::format(unsigned int	theValue)
{
	// $$$ ToDo: Fix this!
	return applyGrouping(UnsignedLongToDOMString(theValue));
}

XalanDOMString
XalanNumberFormat::format(long	theValue)
{
	// $$$ ToDo: Fix this!
	return applyGrouping(LongToDOMString(theValue));
}

XalanDOMString
XalanNumberFormat::applyGrouping(const XalanDOMString& value)
/*
 * Convert a string value using the currently active values for grouping size
 * and separator; returns the converted string
 */
{
	if (!m_isGroupingUsed) return value;
	if (m_groupingSize == 0) return value;
	int len = value.length();
	if (len == 0) return value;

	const unsigned int	bufsize = len + len/m_groupingSize + 1;

	XalanDOMChar* const		buffer = new XalanDOMChar[bufsize];

	XalanDOMChar*			p = buffer + bufsize - 1;

	*p-- = 0;	// null terminate

	for (unsigned int i = 0, ix = len - 1; i < len; i++, ix--)
	{
		const XalanDOMChar		c = charAt(value, ix);

		if (i && !(i% m_groupingSize))
		{
			// Could be a multiple character separator??
			for (int j= m_groupingSeparator.length()-1; j>=0; j--)
				*p-- = charAt(m_groupingSeparator, j);
		}

		*p-- = c;
	}

	XalanDOMString s(++p);

	delete [] buffer;

	return s;
}

XalanDOMString
XalanNumberFormat::format(unsigned long	theValue)
{
	// $$$ ToDo: Fix this!
	return UnsignedLongToDOMString(theValue);
}

bool
XalanNumberFormat::isGroupingUsed() const
{
	return m_isGroupingUsed;
}

void
XalanNumberFormat::setGroupingUsed(bool bUsed)
{
	m_isGroupingUsed = bUsed;
}

void
XalanNumberFormat::setGroupingSize(unsigned long	size)
{
	assert(size > 0);

	m_groupingSize = size;
}

void
XalanNumberFormat::setGroupingSeparator(const XalanDOMString&	s)
{
	m_groupingSeparator = s;
}
<commit_msg>Fixed signed/unsigned mismatch.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  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. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#include "XalanNumberFormat.hpp"
#include "DOMStringHelper.hpp"

XalanNumberFormat::XalanNumberFormat() :
	m_isGroupingUsed(false),
	m_groupingSeparator(XALAN_STATIC_UCODE_STRING(",")),
	m_groupingSize(3)	// Default to US values
{
}

XalanNumberFormat::~XalanNumberFormat()
{
}

XalanDOMString
XalanNumberFormat::format(double		theValue)
{
	// $$$ ToDo: Fix this!
	return applyGrouping(DoubleToDOMString(theValue));
}

XalanDOMString
XalanNumberFormat::format(int	theValue)
{
	// $$$ ToDo: Fix this!
	return applyGrouping(LongToDOMString(theValue));
}

XalanDOMString
XalanNumberFormat::format(unsigned int	theValue)
{
	// $$$ ToDo: Fix this!
	return applyGrouping(UnsignedLongToDOMString(theValue));
}

XalanDOMString
XalanNumberFormat::format(long	theValue)
{
	// $$$ ToDo: Fix this!
	return applyGrouping(LongToDOMString(theValue));
}

XalanDOMString
XalanNumberFormat::applyGrouping(const XalanDOMString& value)
/*
 * Convert a string value using the currently active values for grouping size
 * and separator; returns the converted string
 */
{
	if (!m_isGroupingUsed) return value;
	if (m_groupingSize == 0) return value;
	const unsigned int len = length(value);
	if (len == 0) return value;

	const unsigned int	bufsize = len + len/m_groupingSize + 1;

	XalanDOMChar* const		buffer = new XalanDOMChar[bufsize];

	XalanDOMChar*			p = buffer + bufsize - 1;

	*p-- = 0;	// null terminate

	for (unsigned int i = 0, ix = len - 1; i < len; i++, ix--)
	{
		const XalanDOMChar		c = charAt(value, ix);

		if (i && !(i% m_groupingSize))
		{
			// Could be a multiple character separator??
			for (int j= m_groupingSeparator.length()-1; j>=0; j--)
				*p-- = charAt(m_groupingSeparator, j);
		}

		*p-- = c;
	}

	XalanDOMString s(++p);

	delete [] buffer;

	return s;
}

XalanDOMString
XalanNumberFormat::format(unsigned long	theValue)
{
	// $$$ ToDo: Fix this!
	return UnsignedLongToDOMString(theValue);
}

bool
XalanNumberFormat::isGroupingUsed() const
{
	return m_isGroupingUsed;
}

void
XalanNumberFormat::setGroupingUsed(bool bUsed)
{
	m_isGroupingUsed = bUsed;
}

void
XalanNumberFormat::setGroupingSize(unsigned long	size)
{
	assert(size > 0);

	m_groupingSize = size;
}

void
XalanNumberFormat::setGroupingSeparator(const XalanDOMString&	s)
{
	m_groupingSeparator = s;
}
<|endoftext|>