<commit_before>#ifndef DUNE_GDT_PROLONGATIONS_L2_HH
#define DUNE_GDT_PROLONGATIONS_L2_HH

#include <dune/gdt/discretefunction/default.hh>

#include "l2-local.hh"
#include "l2-global.hh"

namespace Dune {
namespace GDT {

// forward
template <class GridViewImp, class FieldImp = double>
class L2ProlongationOperator;

namespace internal {

template <class GridViewType, class SourceType, class RangeType>
class L2ProlongationLocalizableOperatorTraits
{
  static_assert(is_const_discrete_function<SourceType>::value, "");
  static_assert(is_discrete_function<RangeType>::value, "");

  template <class G, class S, class R, bool c = true>
  struct Helper
  {
    typedef L2GlobalProlongationLocalizableOperator<G, S, R> type;
  };

  template <class G, class S, class R>
  struct Helper<G, S, R, false>
  {
    typedef L2LocalProlongationLocalizableOperator<G, S, R> type;
  };

public:
  typedef typename Helper<GridViewType, SourceType, RangeType, RangeType::SpaceType::continuous>::type BaseType;
}; // class L2ProlongationLocalizableOperatorTraits

} // namespace internal

template <class GridViewImp, class SourceImp, class RangeImp>
class L2ProlongationLocalizableOperator
    : public internal::L2ProlongationLocalizableOperatorTraits<GridViewImp, SourceImp, RangeImp>::BaseType
{
  typedef
      typename internal::L2ProlongationLocalizableOperatorTraits<GridViewImp, SourceImp, RangeImp>::BaseType BaseType;

public:
  template <class... Args>
  explicit L2ProlongationLocalizableOperator(Args&&... args)
    : BaseType(std::forward<Args>(args)...)
  {
  }
};

template <class GridViewType, class SS, class SV, class RS, class RV>
typename std::enable_if<Stuff::Grid::is_grid_layer<GridViewType>::value,
                        std::unique_ptr<L2ProlongationLocalizableOperator<GridViewType, ConstDiscreteFunction<SS, SV>,
                                                                          DiscreteFunction<RS, RV>>>>::type
make_l2_prolongation_localizable_operator(const GridViewType& grid_view, const ConstDiscreteFunction<SS, SV>& source,
                                          DiscreteFunction<RS, RV>& range, const size_t over_integrate = 0)
{
  return DSC::make_unique<L2ProlongationLocalizableOperator<GridViewType,
                                                            ConstDiscreteFunction<SS, SV>,
                                                            DiscreteFunction<RS, RV>>>(
      over_integrate, grid_view, source, range);
} // ... make_l2_prolongation_localizable_operator(...)

template <class SS, class SV, class RS, class RV>
std::unique_ptr<L2ProlongationLocalizableOperator<typename RS::GridViewType, ConstDiscreteFunction<SS, SV>,
                                                  DiscreteFunction<RS, RV>>>
make_l2_prolongation_localizable_operator(const ConstDiscreteFunction<SS, SV>& source, DiscreteFunction<RS, RV>& range,
                                          const size_t over_integrate = 0)
{
  return DSC::make_unique<L2ProlongationLocalizableOperator<typename RS::GridViewType,
                                                            ConstDiscreteFunction<SS, SV>,
                                                            DiscreteFunction<RS, RV>>>(
      over_integrate, range.space().grid_view(), source, range);
} // ... make_l2_prolongation_localizable_operator(...)

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_PROLONGATIONS_L2_HH
<commit_msg>[prolongations.l2] add L2ProlongationOperator and prolong_l2<commit_after>#ifndef DUNE_GDT_PROLONGATIONS_L2_HH
#define DUNE_GDT_PROLONGATIONS_L2_HH

#include <dune/gdt/discretefunction/default.hh>

#include "l2-local.hh"
#include "l2-global.hh"

namespace Dune {
namespace GDT {

// forward
template <class GridViewImp, class FieldImp = double>
class L2ProlongationOperator;

namespace internal {

template <class GridViewType, class SourceType, class RangeType>
class L2ProlongationLocalizableOperatorTraits
{
  static_assert(is_const_discrete_function<SourceType>::value, "");
  static_assert(is_discrete_function<RangeType>::value, "");

  template <class G, class S, class R, bool c = true>
  struct Helper
  {
    typedef L2GlobalProlongationLocalizableOperator<G, S, R> type;
  };

  template <class G, class S, class R>
  struct Helper<G, S, R, false>
  {
    typedef L2LocalProlongationLocalizableOperator<G, S, R> type;
  };

public:
  typedef typename Helper<GridViewType, SourceType, RangeType, RangeType::SpaceType::continuous>::type BaseType;
}; // class L2ProlongationLocalizableOperatorTraits

template <class GridViewType, class FieldImp = double>
class L2ProlongationOperatorTraits
{
public:
  typedef L2ProlongationOperator<GridViewType, FieldImp> derived_type;
  typedef FieldImp FieldType;
};

} // namespace internal

template <class GridViewImp, class SourceImp, class RangeImp>
class L2ProlongationLocalizableOperator
    : public internal::L2ProlongationLocalizableOperatorTraits<GridViewImp, SourceImp, RangeImp>::BaseType
{
  typedef
      typename internal::L2ProlongationLocalizableOperatorTraits<GridViewImp, SourceImp, RangeImp>::BaseType BaseType;

public:
  template <class... Args>
  explicit L2ProlongationLocalizableOperator(Args&&... args)
    : BaseType(std::forward<Args>(args)...)
  {
  }
};

template <class GridViewType, class SS, class SV, class RS, class RV>
typename std::enable_if<Stuff::Grid::is_grid_layer<GridViewType>::value,
                        std::unique_ptr<L2ProlongationLocalizableOperator<GridViewType, ConstDiscreteFunction<SS, SV>,
                                                                          DiscreteFunction<RS, RV>>>>::type
make_l2_prolongation_localizable_operator(const GridViewType& grid_view, const ConstDiscreteFunction<SS, SV>& source,
                                          DiscreteFunction<RS, RV>& range, const size_t over_integrate = 0)
{
  return DSC::make_unique<L2ProlongationLocalizableOperator<GridViewType,
                                                            ConstDiscreteFunction<SS, SV>,
                                                            DiscreteFunction<RS, RV>>>(
      over_integrate, grid_view, source, range);
} // ... make_l2_prolongation_localizable_operator(...)

template <class SS, class SV, class RS, class RV>
std::unique_ptr<L2ProlongationLocalizableOperator<typename RS::GridViewType, ConstDiscreteFunction<SS, SV>,
                                                  DiscreteFunction<RS, RV>>>
make_l2_prolongation_localizable_operator(const ConstDiscreteFunction<SS, SV>& source, DiscreteFunction<RS, RV>& range,
                                          const size_t over_integrate = 0)
{
  return DSC::make_unique<L2ProlongationLocalizableOperator<typename RS::GridViewType,
                                                            ConstDiscreteFunction<SS, SV>,
                                                            DiscreteFunction<RS, RV>>>(
      over_integrate, range.space().grid_view(), source, range);
} // ... make_l2_prolongation_localizable_operator(...)

template <class GridViewImp, class FieldImp>
class L2ProlongationOperator : public OperatorInterface<internal::L2ProlongationOperatorTraits<GridViewImp, FieldImp>>
{
  typedef OperatorInterface<internal::L2ProlongationOperatorTraits<GridViewImp, FieldImp>> BaseType;

public:
  typedef internal::L2ProlongationOperatorTraits<GridViewImp, FieldImp> Traits;
  typedef GridViewImp GridViewType;
  using typename BaseType::FieldType;

private:
  typedef typename Stuff::Grid::Entity<GridViewType>::Type E;
  typedef typename GridViewType::ctype D;
  static const size_t d = GridViewType::dimension;

public:
  L2ProlongationOperator(const size_t over_integrate, GridViewType grid_view)
    : grid_view_(grid_view)
    , over_integrate_(over_integrate)
  {
  }

  L2ProlongationOperator(GridViewType grid_view)
    : grid_view_(grid_view)
    , over_integrate_(0)
  {
  }

  template <class SS, class SV, class RS, class RV>
  void apply(const ConstDiscreteFunction<SS, SV>& source, DiscreteFunction<RS, RV>& range) const
  {
    redirect<RS::continuous>::apply(grid_view_, source, range, over_integrate_);
  }

  template <class RangeType, class SourceType>
  FieldType apply2(const RangeType& /*range*/, const SourceType& /*source*/) const
  {
    DUNE_THROW(NotImplemented, "Go ahead if you think this makes sense!");
  }

  template <class RangeType, class SourceType>
  void apply_inverse(const RangeType& /*range*/, SourceType& /*source*/,
                     const Stuff::Common::Configuration& /*opts*/) const
  {
    DUNE_THROW(NotImplemented, "Go ahead if you think this makes sense!");
  }

  std::vector<std::string> invert_options() const
  {
    DUNE_THROW(NotImplemented, "Go ahead if you think this makes sense!");
  }

  Stuff::Common::Configuration invert_options(const std::string& /*type*/) const
  {
    DUNE_THROW(NotImplemented, "Go ahead if you think this makes sense!");
  }

private:
  template <bool continuous = true, bool anything = true>
  struct redirect
  {
    template <class SourceType, class RangeType>
    static void apply(const GridViewType& grd_vw, const SourceType& src, RangeType& rng, const size_t over_integrate)
    {
      L2GlobalProlongationLocalizableOperator<GridViewType, SourceType, RangeType>(over_integrate, grd_vw, src, rng)
          .apply();
    }
  };

  template <bool anything>
  struct redirect<false, anything>
  {
    template <class SourceType, class RangeType>
    static void apply(const GridViewType& grd_vw, const SourceType& src, RangeType& rng, const size_t over_integrate)
    {
      L2LocalProlongationLocalizableOperator<GridViewType, SourceType, RangeType>(over_integrate, grd_vw, src, rng)
          .apply();
    }
  };

  GridViewType grid_view_;
  const size_t over_integrate_;
}; // class L2ProlongationOperator

template <class GridViewType>
typename std::enable_if<Stuff::Grid::is_grid_layer<GridViewType>::value,
                        std::unique_ptr<L2ProlongationOperator<GridViewType>>>::type
make_l2_prolongation_operator(const GridViewType& grid_view, const size_t over_integrate = 0)
{
  return DSC::make_unique<L2ProlongationOperator<GridViewType>>(over_integrate, grid_view);
}

template <class GridViewType, class SS, class SV, class RS, class RV>
typename std::enable_if<Stuff::Grid::is_grid_layer<GridViewType>::value, void>::type
prolong_l2(const GridViewType& grid_view, const ConstDiscreteFunction<SS, SV>& source, DiscreteFunction<RS, RV>& range,
           const size_t over_integrate = 0)
{
  make_l2_prolongation_operator(grid_view, over_integrate)->apply(source, range);
}

template <class SS, class SV, class RS, class RV>
void prolong_l2(const ConstDiscreteFunction<SS, SV>& source, DiscreteFunction<RS, RV>& range,
                const size_t over_integrate = 0)
{
  make_l2_prolongation_operator(range.space().grid_view(), over_integrate)->apply(source, range);
}

} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_PROLONGATIONS_L2_HH
<|endoftext|>


<commit_before>// This file is part of the dune-stuff project:
//   https://users.dune-project.org/projects/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_COMMON_FVECTOR_HH
#define DUNE_STUFF_COMMON_FVECTOR_HH

#include <vector>
#include <initializer_list>

#include <dune/common/fvector.hh>

#include <dune/stuff/common/exceptions.hh>

namespace Dune {
namespace Stuff {
namespace Common {

template< class K, int SIZE >
class FieldVector
  : public Dune::FieldVector< K, SIZE >
{
  typedef Dune::FieldVector< K, SIZE > BaseType;
  typedef FieldVector< K, SIZE >       ThisType;

public:
  FieldVector(const size_t sz = SIZE, const K kk = K(0))
    : BaseType(kk)
  {
#ifndef NDEBUG
    if (sz != SIZE)
      DUNE_THROW_COLORFULLY(Exceptions::wrong_input_given,
                            "You are trying to construct a FieldVector< ..., " << SIZE << " > (of "
                            << "static size) with a size of " << sz << "!");
#endif // NDEBUG
  } // ... FieldVector(...)

  FieldVector(const BaseType& other)
    : BaseType(other)
  {}

  FieldVector(const std::vector< K >& vec)
    : BaseType(K(0))
  {
#ifndef NDEBUG
    if (vec.size() != SIZE)
      DUNE_THROW_COLORFULLY(Exceptions::wrong_input_given,
                            "You are trying to construct a FieldVector< ..., " << SIZE << " > (of "
                            << "static size) from a vector of size " << vec.size() << "!");
#endif // NDEBUG
    for (size_t ii = 0; ii < SIZE; ++ii)
      this->operator[](ii) = vec[ii];
  } // FieldVector(...)

  FieldVector(std::initializer_list< K > list)
    : BaseType(K(0))
  {
#ifndef NDEBUG
    if (list.size() != SIZE)
      DUNE_THROW_COLORFULLY(Exceptions::wrong_input_given,
                            "You are trying to construct a FieldVector< ..., " << SIZE << " > (of "
                            << "static size) from a list of size " << list.size() << "!");
#endif // NDEBUG
    size_t ii = 0;
    for (auto element : list) {
      this->operator[](ii) = element;
      ++ii;
    }
  } // FieldVector(...)

  ThisType& operator=(const BaseType& other)
  {
    return BaseType::operator=(other);
  }
}; // class FieldVector

} // namespace Common
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_COMMON_FVECTOR_HH
<commit_msg>[common.fvector] fixed ctor<commit_after>// This file is part of the dune-stuff project:
//   https://users.dune-project.org/projects/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_STUFF_COMMON_FVECTOR_HH
#define DUNE_STUFF_COMMON_FVECTOR_HH

#include <vector>
#include <initializer_list>

#include <dune/common/fvector.hh>

#include <dune/stuff/common/exceptions.hh>

namespace Dune {
namespace Stuff {
namespace Common {

template< class K, int SIZE >
class FieldVector
  : public Dune::FieldVector< K, SIZE >
{
  typedef Dune::FieldVector< K, SIZE > BaseType;
  typedef FieldVector< K, SIZE >       ThisType;

public:
  FieldVector(const K kk = K(0))
    : BaseType(kk)
  {}

  FieldVector(const BaseType& other)
    : BaseType(other)
  {}

  FieldVector(const std::vector< K >& vec)
    : BaseType(K(0))
  {
#ifndef NDEBUG
    if (vec.size() != SIZE)
      DUNE_THROW_COLORFULLY(Exceptions::wrong_input_given,
                            "You are trying to construct a FieldVector< ..., " << SIZE << " > (of "
                            << "static size) from a vector of size " << vec.size() << "!");
#endif // NDEBUG
    for (size_t ii = 0; ii < SIZE; ++ii)
      this->operator[](ii) = vec[ii];
  } // FieldVector(...)

  FieldVector(std::initializer_list< K > list)
    : BaseType(K(0))
  {
#ifndef NDEBUG
    if (list.size() != SIZE)
      DUNE_THROW_COLORFULLY(Exceptions::wrong_input_given,
                            "You are trying to construct a FieldVector< ..., " << SIZE << " > (of "
                            << "static size) from a list of size " << list.size() << "!");
#endif // NDEBUG
    size_t ii = 0;
    for (auto element : list) {
      this->operator[](ii) = element;
      ++ii;
    }
  } // FieldVector(...)

  ThisType& operator=(const BaseType& other)
  {
    return BaseType::operator=(other);
  }
}; // class FieldVector

} // namespace Common
} // namespace Stuff
} // namespace Dune

#endif // DUNE_STUFF_COMMON_FVECTOR_HH
<|endoftext|>


<commit_before>/* GG is a GUI for SDL and OpenGL.
   Copyright (C) 2003 T. Zachary Laine

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public License
   as published by the Free Software Foundation; either version 2.1
   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
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free
   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
   02111-1307 USA

   If you do not wish to comply with the terms of the LGPL please
   contact the author as other terms are available for a fee.

   Zach Laine
   whatwasthataddress@hotmail.com */

/* $Header$ */

#include "SDL/SDLGGApp.h"
#include "GGEventPump.h"

using std::string;

// member functions
SDLGGApp::SDLGGApp(int w/* = 1024*/, int h/* = 768*/, bool calc_FPS/* = false*/, const std::string& app_name/* = "GG"*/) :
    App(app_name),
    m_app_width(w),
    m_app_height(h)
{
}

SDLGGApp::~SDLGGApp()
{
    SDLQuit();
}

SDLGGApp* SDLGGApp::GetApp()
{
    return dynamic_cast<SDLGGApp*>(App::GetApp());
}

void SDLGGApp::Exit(int code)
{
    Logger().fatalStream() << "Initiating Exit (code " << code << " - " << (code ? "error" : "normal") << " termination)";
    SDLQuit();
    exit(code);
}

void SDLGGApp::Wait(int ms)
{
    SDL_Delay(ms);
}

GG::Key SDLGGApp::GGKeyFromSDLKey(const SDL_keysym& key)
{
    GG::Key retval = GG::Key(key.sym);
    bool shift = key.mod & KMOD_SHIFT;
    bool caps_lock = key.mod & KMOD_CAPS;

    // this code works because both SDLKey and GG::Key map (at least
    // partially) to the printable ASCII characters
    if (shift || caps_lock) {
        if (shift != caps_lock && (retval >= 'a' && retval <= 'z')) {
            retval = GG::Key(toupper(retval));
        } else if (shift) { // the caps lock key should not affect these
            // this assumes a US keyboard layout
            switch (retval) {
            case '`': retval = GG::Key('~'); break;
            case '1': retval = GG::Key('!'); break;
            case '2': retval = GG::Key('@'); break;
            case '3': retval = GG::Key('#'); break;
            case '4': retval = GG::Key('$'); break;
            case '5': retval = GG::Key('%'); break;
            case '6': retval = GG::Key('^'); break;
            case '7': retval = GG::Key('&'); break;
            case '8': retval = GG::Key('*'); break;
            case '9': retval = GG::Key('('); break;
            case '0': retval = GG::Key(')'); break;
            case '-': retval = GG::Key('_'); break;
            case '=': retval = GG::Key('+'); break;
            case '[': retval = GG::Key('{'); break;
            case ']': retval = GG::Key('}'); break;
            case '\\': retval = GG::Key('|'); break;
            case ';': retval = GG::Key(':'); break;
            case '\'': retval = GG::Key('"'); break;
            case ',': retval = GG::Key('<'); break;
            case '.': retval = GG::Key('>'); break;
            case '/': retval = GG::Key('?'); break;
            default: break;
            }
        }
    }
    return retval;
}

void SDLGGApp::SDLInit()
{
    const SDL_VideoInfo* vid_info = 0;

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) < 0) {
        Logger().errorStream() << "SDL initialization failed: " << SDL_GetError();
        Exit(1);
    }

#if defined(GG_USE_NET) && GG_USE_NET
    if (SDLNet_Init() < 0) {
        Logger().errorStream() << "SDL Net initialization failed: " << SDLNet_GetError();
        Exit(1);
    }

    if (FE_Init() < 0) {
        Logger().errorStream() << "FastEvents initialization failed: " << FE_GetError();
        Exit(1);
    }
#endif // GG_USE_NET

    vid_info = SDL_GetVideoInfo();

    if (!vid_info) {
        Logger().errorStream() << "Video info query failed: " << SDL_GetError();
        Exit(1);
    }

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    if (SDL_SetVideoMode(m_app_width, m_app_height, 16, SDL_OPENGL) == 0) {
        Logger().errorStream() << "Video mode set failed: " << SDL_GetError();
        Exit(1);
    }

#if defined(GG_USE_NET) && GG_USE_NET
    if (NET2_Init() < 0) {
        Logger().errorStream() << "SDL Net2 initialization failed: " << NET2_GetError();
        Exit(1);
    }
#endif // GG_USE_NET

    SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
    EnableMouseDragRepeat(SDL_DEFAULT_REPEAT_DELAY / 2, SDL_DEFAULT_REPEAT_INTERVAL / 2);

    Logger().debugStream() << "SDLInit() complete.";
    GLInit();
}

void SDLGGApp::GLInit()
{
    double ratio = m_app_width / (float)(m_app_height);

    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glEnable(GL_BLEND);
    glShadeModel(GL_SMOOTH);
    glClearColor(0, 0, 0, 0);
    glViewport(0, 0, m_app_width - 1, m_app_height - 1);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(50.0, ratio, 1.0, 10.0);

    Logger().debugStream() << "GLInit() complete.";
}

void SDLGGApp::HandleSystemEvents(int& last_mouse_event_time)
{
    // handle events
    SDL_Event event;
#if defined(GG_USE_NET) && GG_USE_NET
    while (0 < FE_PollEvent(&event)) {
#else
    while (0 < SDL_PollEvent(&event)) {
#endif // GG_USE_NET
        if (event.type  == SDL_MOUSEBUTTONDOWN || event.type  == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEMOTION)
            last_mouse_event_time = Ticks();

        bool send_to_gg = false;
        EventType gg_event;
        GG::Key key = GGKeyFromSDLKey(event.key.keysym);
        Uint32 key_mods = SDL_GetModState();
#ifdef __APPLE__
        GG::Pt mouse_pos(event.motion.x, m_app_height - event.motion.y);
        GG::Pt mouse_rel(event.motion.xrel, -event.motion.yrel);
#else
        GG::Pt mouse_pos(event.motion.x, event.motion.y);
        GG::Pt mouse_rel(event.motion.xrel, event.motion.yrel);
#endif

        switch (event.type) {
        case SDL_KEYDOWN:
            if (key < GG::GGK_NUMLOCK)
                send_to_gg = true;
            gg_event = KEYPRESS;
            break;
        case SDL_MOUSEMOTION:
            send_to_gg = true;
            gg_event = MOUSEMOVE;
            break;
        case SDL_MOUSEBUTTONDOWN:
            send_to_gg = true;
            switch (event.button.button) {
                case SDL_BUTTON_LEFT:      gg_event = LPRESS; break;
                case SDL_BUTTON_MIDDLE:    gg_event = MPRESS; break;
                case SDL_BUTTON_RIGHT:     gg_event = RPRESS; break;
                case SDL_BUTTON_WHEELUP:   gg_event = MOUSEWHEEL; mouse_rel = GG::Pt(0, 1); break;
                case SDL_BUTTON_WHEELDOWN: gg_event = MOUSEWHEEL; mouse_rel = GG::Pt(0, -1); break;
            }
            key_mods = SDL_GetModState();
            break;
        case SDL_MOUSEBUTTONUP:
            send_to_gg = true;
            switch (event.button.button) {
                case SDL_BUTTON_LEFT:   gg_event = LRELEASE; break;
                case SDL_BUTTON_MIDDLE: gg_event = MRELEASE; break;
                case SDL_BUTTON_RIGHT:  gg_event = RRELEASE; break;
            }
            key_mods = SDL_GetModState();
            break;
        }

        if (send_to_gg)
            HandleGGEvent(gg_event, key, key_mods, mouse_pos, mouse_rel);
        else
            HandleNonGGEvent(event);
    }
}

void SDLGGApp::HandleNonGGEvent(const SDL_Event& event)
{
    switch (event.type) {
    case SDL_QUIT:
        Exit(0);
        break;
    }
}

void SDLGGApp::RenderBegin()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

void SDLGGApp::RenderEnd()
{
    SDL_GL_SwapBuffers();
}

void SDLGGApp::SDLQuit()
{
    FinalCleanup();
#if defined(GG_USE_NET) && GG_USE_NET
    NET2_Quit();
    FE_Quit();
    SDLNet_Quit();
#endif // GG_USE_NET
    SDL_Quit();
    Logger().debugStream() << "SDLQuit() complete.";
}

void SDLGGApp::Run()
{
    try {
        SDLInit();
        Initialize();
        GG::EventPump pump;
        pump();
    } catch (const std::invalid_argument& exception) {
        Logger().fatal("std::invalid_argument Exception caught in App::Run(): " + string(exception.what()));
        Exit(1);
    } catch (const std::runtime_error& exception) {
        Logger().fatal("std::runtime_error Exception caught in App::Run(): " + string(exception.what()));
        Exit(1);
    } catch (const GG::GGException& exception) {
        Logger().fatal("GG::GGException (subclass " + string(exception.what()) + ") caught in App::Run(): " + exception.Message());
        Exit(1);
    }
}

<commit_msg>Demoted normal-termination logging from FATAL to DEBUG.<commit_after>/* GG is a GUI for SDL and OpenGL.
   Copyright (C) 2003 T. Zachary Laine

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public License
   as published by the Free Software Foundation; either version 2.1
   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
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free
   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
   02111-1307 USA

   If you do not wish to comply with the terms of the LGPL please
   contact the author as other terms are available for a fee.

   Zach Laine
   whatwasthataddress@hotmail.com */

/* $Header$ */

#include "SDL/SDLGGApp.h"
#include "GGEventPump.h"

using std::string;

// member functions
SDLGGApp::SDLGGApp(int w/* = 1024*/, int h/* = 768*/, bool calc_FPS/* = false*/, const std::string& app_name/* = "GG"*/) :
    App(app_name),
    m_app_width(w),
    m_app_height(h)
{
}

SDLGGApp::~SDLGGApp()
{
    SDLQuit();
}

SDLGGApp* SDLGGApp::GetApp()
{
    return dynamic_cast<SDLGGApp*>(App::GetApp());
}

void SDLGGApp::Exit(int code)
{
    if (code)
        Logger().fatalStream() << "Initiating Exit (code " << code << " - error termination)";
    else
        Logger().debugStream() << "Initiating Exit (normal termination)";
    SDLQuit();
    exit(code);
}

void SDLGGApp::Wait(int ms)
{
    SDL_Delay(ms);
}

GG::Key SDLGGApp::GGKeyFromSDLKey(const SDL_keysym& key)
{
    GG::Key retval = GG::Key(key.sym);
    bool shift = key.mod & KMOD_SHIFT;
    bool caps_lock = key.mod & KMOD_CAPS;

    // this code works because both SDLKey and GG::Key map (at least
    // partially) to the printable ASCII characters
    if (shift || caps_lock) {
        if (shift != caps_lock && (retval >= 'a' && retval <= 'z')) {
            retval = GG::Key(toupper(retval));
        } else if (shift) { // the caps lock key should not affect these
            // this assumes a US keyboard layout
            switch (retval) {
            case '`': retval = GG::Key('~'); break;
            case '1': retval = GG::Key('!'); break;
            case '2': retval = GG::Key('@'); break;
            case '3': retval = GG::Key('#'); break;
            case '4': retval = GG::Key('$'); break;
            case '5': retval = GG::Key('%'); break;
            case '6': retval = GG::Key('^'); break;
            case '7': retval = GG::Key('&'); break;
            case '8': retval = GG::Key('*'); break;
            case '9': retval = GG::Key('('); break;
            case '0': retval = GG::Key(')'); break;
            case '-': retval = GG::Key('_'); break;
            case '=': retval = GG::Key('+'); break;
            case '[': retval = GG::Key('{'); break;
            case ']': retval = GG::Key('}'); break;
            case '\\': retval = GG::Key('|'); break;
            case ';': retval = GG::Key(':'); break;
            case '\'': retval = GG::Key('"'); break;
            case ',': retval = GG::Key('<'); break;
            case '.': retval = GG::Key('>'); break;
            case '/': retval = GG::Key('?'); break;
            default: break;
            }
        }
    }
    return retval;
}

void SDLGGApp::SDLInit()
{
    const SDL_VideoInfo* vid_info = 0;

    if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) < 0) {
        Logger().errorStream() << "SDL initialization failed: " << SDL_GetError();
        Exit(1);
    }

#if defined(GG_USE_NET) && GG_USE_NET
    if (SDLNet_Init() < 0) {
        Logger().errorStream() << "SDL Net initialization failed: " << SDLNet_GetError();
        Exit(1);
    }

    if (FE_Init() < 0) {
        Logger().errorStream() << "FastEvents initialization failed: " << FE_GetError();
        Exit(1);
    }
#endif // GG_USE_NET

    vid_info = SDL_GetVideoInfo();

    if (!vid_info) {
        Logger().errorStream() << "Video info query failed: " << SDL_GetError();
        Exit(1);
    }

    SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

    if (SDL_SetVideoMode(m_app_width, m_app_height, 16, SDL_OPENGL) == 0) {
        Logger().errorStream() << "Video mode set failed: " << SDL_GetError();
        Exit(1);
    }

#if defined(GG_USE_NET) && GG_USE_NET
    if (NET2_Init() < 0) {
        Logger().errorStream() << "SDL Net2 initialization failed: " << NET2_GetError();
        Exit(1);
    }
#endif // GG_USE_NET

    SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
    EnableMouseDragRepeat(SDL_DEFAULT_REPEAT_DELAY / 2, SDL_DEFAULT_REPEAT_INTERVAL / 2);

    Logger().debugStream() << "SDLInit() complete.";
    GLInit();
}

void SDLGGApp::GLInit()
{
    double ratio = m_app_width / (float)(m_app_height);

    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    glEnable(GL_BLEND);
    glShadeModel(GL_SMOOTH);
    glClearColor(0, 0, 0, 0);
    glViewport(0, 0, m_app_width - 1, m_app_height - 1);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(50.0, ratio, 1.0, 10.0);

    Logger().debugStream() << "GLInit() complete.";
}

void SDLGGApp::HandleSystemEvents(int& last_mouse_event_time)
{
    // handle events
    SDL_Event event;
#if defined(GG_USE_NET) && GG_USE_NET
    while (0 < FE_PollEvent(&event)) {
#else
    while (0 < SDL_PollEvent(&event)) {
#endif // GG_USE_NET
        if (event.type  == SDL_MOUSEBUTTONDOWN || event.type  == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEMOTION)
            last_mouse_event_time = Ticks();

        bool send_to_gg = false;
        EventType gg_event;
        GG::Key key = GGKeyFromSDLKey(event.key.keysym);
        Uint32 key_mods = SDL_GetModState();
#ifdef __APPLE__
        GG::Pt mouse_pos(event.motion.x, m_app_height - event.motion.y);
        GG::Pt mouse_rel(event.motion.xrel, -event.motion.yrel);
#else
        GG::Pt mouse_pos(event.motion.x, event.motion.y);
        GG::Pt mouse_rel(event.motion.xrel, event.motion.yrel);
#endif

        switch (event.type) {
        case SDL_KEYDOWN:
            if (key < GG::GGK_NUMLOCK)
                send_to_gg = true;
            gg_event = KEYPRESS;
            break;
        case SDL_MOUSEMOTION:
            send_to_gg = true;
            gg_event = MOUSEMOVE;
            break;
        case SDL_MOUSEBUTTONDOWN:
            send_to_gg = true;
            switch (event.button.button) {
                case SDL_BUTTON_LEFT:      gg_event = LPRESS; break;
                case SDL_BUTTON_MIDDLE:    gg_event = MPRESS; break;
                case SDL_BUTTON_RIGHT:     gg_event = RPRESS; break;
                case SDL_BUTTON_WHEELUP:   gg_event = MOUSEWHEEL; mouse_rel = GG::Pt(0, 1); break;
                case SDL_BUTTON_WHEELDOWN: gg_event = MOUSEWHEEL; mouse_rel = GG::Pt(0, -1); break;
            }
            key_mods = SDL_GetModState();
            break;
        case SDL_MOUSEBUTTONUP:
            send_to_gg = true;
            switch (event.button.button) {
                case SDL_BUTTON_LEFT:   gg_event = LRELEASE; break;
                case SDL_BUTTON_MIDDLE: gg_event = MRELEASE; break;
                case SDL_BUTTON_RIGHT:  gg_event = RRELEASE; break;
            }
            key_mods = SDL_GetModState();
            break;
        }

        if (send_to_gg)
            HandleGGEvent(gg_event, key, key_mods, mouse_pos, mouse_rel);
        else
            HandleNonGGEvent(event);
    }
}

void SDLGGApp::HandleNonGGEvent(const SDL_Event& event)
{
    switch (event.type) {
    case SDL_QUIT:
        Exit(0);
        break;
    }
}

void SDLGGApp::RenderBegin()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

void SDLGGApp::RenderEnd()
{
    SDL_GL_SwapBuffers();
}

void SDLGGApp::SDLQuit()
{
    FinalCleanup();
#if defined(GG_USE_NET) && GG_USE_NET
    NET2_Quit();
    FE_Quit();
    SDLNet_Quit();
#endif // GG_USE_NET
    SDL_Quit();
    Logger().debugStream() << "SDLQuit() complete.";
}

void SDLGGApp::Run()
{
    try {
        SDLInit();
        Initialize();
        GG::EventPump pump;
        pump();
    } catch (const std::invalid_argument& exception) {
        Logger().fatal("std::invalid_argument Exception caught in App::Run(): " + string(exception.what()));
        Exit(1);
    } catch (const std::runtime_error& exception) {
        Logger().fatal("std::runtime_error Exception caught in App::Run(): " + string(exception.what()));
        Exit(1);
    } catch (const GG::GGException& exception) {
        Logger().fatal("GG::GGException (subclass " + string(exception.what()) + ") caught in App::Run(): " + exception.Message());
        Exit(1);
    }
}

<|endoftext|>


<commit_before>#include "solver.hpp"

namespace eq {

void Solver::addVar(int& ref)
{
	intVars.emplace_back(&ref, solver.MakeIntVar(minInt, maxInt));
}

void Solver::apply()
{
	/// @todo Should undo this after solving
	auto success_amount= solver.MakeSum(successAmounts)->Var();
	auto optimizer= solver.MakeMaximize(success_amount, 100);

	std::vector<op::IntVar*> vars;
	for (auto&& v : intVars) {
		vars.push_back(v.model);
	}
	auto db= solver.MakePhase(vars, op::Solver::CHOOSE_FIRST_UNBOUND, op::Solver::ASSIGN_CENTER_VALUE);

	solver.NewSearch(db, optimizer);
	if (solver.NextSolution()) {
		// Apparently last solution is the one which has the best success amount
		do {
			// Apply solution to actual variables
			for (auto&& v : intVars) {
				ensure(v.actual && v.model);
				*v.actual= v.model->Value();
				//std::cout << "Solution: " << v.model->Value() << std::endl;
			}
		} while (solver.NextSolution());
	} else {
		/// @todo Throw
		std::cout << "Solving error, failure count: " << solver.failures() << std::endl;
	}

	solver.EndSearch();
}

Solver::VarInfo<int>& Solver::getVarInfo(const int& ref)
{
	for (auto&& m : intVars) {
		if (m.actual == &ref)
			return m;
	}

	throw std::runtime_error{"var not found"};
}

void Solver::tryEraseVarInfo(const int& ref)
{
	auto it= std::find_if(intVars.begin(), intVars.end(),
		[&ref] (const VarInfo<int>& info)
		{
			return info.actual == &ref;
		});

	if (it != intVars.end())
		intVars.erase(it);
}

void Solver::addSuccessVar(op::IntVar* success, detail::Priority p)
{
	ensure(!p.hard());
	ensure(success);
	auto prod= solver.MakeProd(success, p.value())->Var();
	successAmounts.push_back(prod);
}

} // eq
<commit_msg>Replaced op::OptimizeVar with custom MaximizeVar<commit_after>#include "solver.hpp"

namespace eq {
namespace detail {

/// Custom optimizer for or-tools solver
/// Optimizes for solution which has biggest value for given IntVar
/// Needs only 32 steps for int32 range, while or-tools MakeMaximize needs 4 billion
/// @note May miss the absolute maximum. This can be prevented by using 64 steps
class MaximizeVar : public op::SearchMonitor {
public:
	MaximizeVar(op::Solver& solver, op::IntVar* var)
		: SearchMonitor(&solver), var_(var) { }
	virtual ~MaximizeVar() { }

	int64 best() const { return best_; }

	op::IntVar* Var() const { return var_; }

	virtual void EnterSearch()
	{
		has_init_solution_= false;
		best_= kint64min;
	}

	virtual void RestartSearch() { ApplyBound(); }
	virtual void RefuteDecision(op::Decision* d) { ApplyBound(); }

	virtual bool AtSolution()
	{
		int64 val= var_->Value();
		if (!has_init_solution_ || val > best_)
			best_= val;
		has_init_solution_= true;
	}

	virtual bool AcceptSolution()
	{
		int64 val= var_->Value();
		if (!has_init_solution_)
			return true;
		else
			return val > best_;
	}

	virtual std::string Print() const { return ""; }
	virtual std::string DebugString() const { return ""; }

	virtual void Accept(op::ModelVisitor* const visitor) const
	{
		visitor->BeginVisitExtension(op::ModelVisitor::kObjectiveExtension);
		visitor->VisitIntegerExpressionArgument(
				op::ModelVisitor::kExpressionArgument,
				var_);
		visitor->EndVisitExtension(op::ModelVisitor::kObjectiveExtension);
	}

	void ApplyBound()
	{
		if (has_init_solution_) {
			var_->SetMin(best_ + 1);
		}
	}

private:
	op::IntVar* const var_= nullptr;
	int64 best_= 0;
	bool has_init_solution_= false;

	DISALLOW_COPY_AND_ASSIGN(MaximizeVar);
};

} // detail

void Solver::addVar(int& ref)
{
	intVars.emplace_back(&ref, solver.MakeIntVar(minInt, maxInt));
}

void Solver::apply()
{
	/// @todo Should undo this after solving
	auto success_amount= solver.MakeSum(successAmounts)->Var();
	auto optimizer= solver.RevAlloc(new detail::MaximizeVar(solver, success_amount));

	std::vector<op::IntVar*> vars;
	for (auto&& v : intVars) {
		vars.push_back(v.model);
	}
	auto db= solver.MakePhase(vars, op::Solver::CHOOSE_FIRST_UNBOUND, op::Solver::ASSIGN_CENTER_VALUE);

	solver.NewSearch(db, optimizer);
	if (solver.NextSolution()) {
		// Apparently last solution is the one which has the best success amount
		do {
			// Apply solution to actual variables
			for (auto&& v : intVars) {
				ensure(v.actual && v.model);
				*v.actual= v.model->Value();
				//std::cout << "Solution: " << v.model->Value() << std::endl;
			}
		} while (solver.NextSolution());
	} else {
		/// @todo Throw
		std::cout << "Solving error, failure count: " << solver.failures() << std::endl;
	}

	solver.EndSearch();
}

Solver::VarInfo<int>& Solver::getVarInfo(const int& ref)
{
	for (auto&& m : intVars) {
		if (m.actual == &ref)
			return m;
	}

	throw std::runtime_error{"var not found"};
}

void Solver::tryEraseVarInfo(const int& ref)
{
	auto it= std::find_if(intVars.begin(), intVars.end(),
		[&ref] (const VarInfo<int>& info)
		{
			return info.actual == &ref;
		});

	if (it != intVars.end())
		intVars.erase(it);
}

void Solver::addSuccessVar(op::IntVar* success, detail::Priority p)
{
	ensure(!p.hard());
	ensure(success);
	auto prod= solver.MakeProd(success, p.value())->Var();
	successAmounts.push_back(prod);
}

} // eq
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2003-2007 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders 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.
 *
 * Authors: Gabe Black
 */

/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * 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
 * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * 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.
 *
 * Authors: Gabe Black
 */

#include "arch/x86/intregfile.hh"
#include "base/misc.hh"
#include "sim/serialize.hh"

#include <string.h>

using namespace X86ISA;
using namespace std;

class Checkpoint;

string X86ISA::getIntRegName(RegIndex index)
{
    //These might appear to be out of order, but they match
    //the encoding for the registers. Who knows why the indexes
    //are out of order
    static std::string intRegName[NumIntArchRegs] =
        {"rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
         "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"};
    return intRegName[index];
}

int IntRegFile::flattenIndex(int reg)
{
    return reg;
}

void IntRegFile::clear()
{
    memset(regs, 0, sizeof(IntReg) * NumIntRegs);
}

IntReg IntRegFile::readReg(int intReg)
{
    return regs[intReg];
}

void IntRegFile::setReg(int intReg, const IntReg &val)
{
    regs[intReg] = val;
}

void IntRegFile::serialize(std::ostream &os)
{
    SERIALIZE_ARRAY(regs, NumIntRegs);
}

void IntRegFile::unserialize(Checkpoint *cp, const std::string &section)
{
    UNSERIALIZE_ARRAY(regs, NumIntRegs);
}
<commit_msg>Add some dprintfs<commit_after>/*
 * Copyright (c) 2003-2007 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders 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.
 *
 * Authors: Gabe Black
 */

/*
 * Copyright (c) 2007 The Hewlett-Packard Development Company
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms,
 * with or without modification, are permitted provided that the
 * following conditions are met:
 *
 * The software must be used only for Non-Commercial Use which means any
 * use which is NOT directed to receiving any direct monetary
 * compensation for, or commercial advantage from such use.  Illustrative
 * examples of non-commercial use are academic research, personal study,
 * teaching, education and corporate research & development.
 * Illustrative examples of commercial use are distributing products for
 * commercial advantage and providing services using the software for
 * commercial advantage.
 *
 * If you wish to use this software or functionality therein that may be
 * covered by patents for commercial use, please contact:
 *     Director of Intellectual Property Licensing
 *     Office of Strategy and Technology
 *     Hewlett-Packard Company
 *     1501 Page Mill Road
 *     Palo Alto, California  94304
 *
 * 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
 * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.  No right of
 * sublicense is granted herewith.  Derivatives of the software and
 * output created using the software may be prepared, but only for
 * Non-Commercial Uses.  Derivatives of the software may be shared with
 * others provided: (i) the others agree to abide by the list of
 * conditions herein which includes the Non-Commercial Use restrictions;
 * and (ii) such Derivatives of the software include the above copyright
 * notice to acknowledge the contribution from this software where
 * applicable, this list of conditions and the disclaimer below.
 *
 * 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.
 *
 * Authors: Gabe Black
 */

#include "arch/x86/intregfile.hh"
#include "base/misc.hh"
#include "base/trace.hh"
#include "sim/serialize.hh"

#include <string.h>

using namespace X86ISA;
using namespace std;

class Checkpoint;

string X86ISA::getIntRegName(RegIndex index)
{
    //These might appear to be out of order, but they match
    //the encoding for the registers. Who knows why the indexes
    //are out of order
    static std::string intRegName[NumIntArchRegs] =
        {"rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
         "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"};
    return intRegName[index];
}

int IntRegFile::flattenIndex(int reg)
{
    return reg;
}

void IntRegFile::clear()
{
    memset(regs, 0, sizeof(IntReg) * NumIntRegs);
}

IntReg IntRegFile::readReg(int intReg)
{
    DPRINTF(X86, "Read int reg %d and got value %#x\n", intReg, regs[intReg]);
    return regs[intReg];
}

void IntRegFile::setReg(int intReg, const IntReg &val)
{
    DPRINTF(X86, "Setting int reg %d to value %#x\n", intReg, val);
    regs[intReg] = val;
}

void IntRegFile::serialize(std::ostream &os)
{
    SERIALIZE_ARRAY(regs, NumIntRegs);
}

void IntRegFile::unserialize(Checkpoint *cp, const std::string &section)
{
    UNSERIALIZE_ARRAY(regs, NumIntRegs);
}
<|endoftext|>


<commit_before>/*
 * Copyright © 2012 Intel Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 *
 * Author: Benjamin Segovia <benjamin.segovia@intel.com>
 */

#include "utest_file_map.hpp"
#include "CL/cl.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <stdio.h>

int
cl_file_map_init(cl_file_map_t *fm)
{
  assert(fm);
  memset(fm,0,sizeof(*fm));
  return CL_SUCCESS;
}

void
cl_file_map_destroy(cl_file_map_t *fm)
{
  if (fm->mapped) {
    munmap(fm->start, fm->size);
    fm->start = fm->stop = 0;
    fm->size = 0;
    fm->mapped = CL_FALSE;
  }
  if(fm->fd) {
    close(fm->fd);
    fm->fd = 0;
  }
  free(fm->name);
  memset(fm,0,sizeof(*fm));
}

void
cl_file_map_delete(cl_file_map_t *fm)
{
  if (fm == NULL)
    return;
  cl_file_map_destroy(fm);
  free(fm);
}

cl_file_map_t*
cl_file_map_new(void)
{
  cl_file_map_t *fm = NULL;

  if ((fm = (cl_file_map_t *) calloc(1, sizeof(cl_file_map_t))) == NULL)
    goto error;
  if (cl_file_map_init(fm) != CL_SUCCESS)
    goto error;

exit:
  return fm;
error:
  cl_file_map_delete(fm);
  fm = NULL;
  goto exit;
}

int
cl_file_map_open(cl_file_map_t *fm, const char *name)
{
  int err = CL_FILE_MAP_SUCCESS;

  /* Open the file */
  fm->fd = open(name, O_RDONLY);
  if(fm->fd <= 0) {
    err = CL_FILE_MAP_FILE_NOT_FOUND;
    goto error;
  }
  if ((fm->name = (char*) calloc(strlen(name) + 1, sizeof(char))) == NULL)
    goto error;
  sprintf(fm->name, "%s", name);

  /* Map it */
  fm->size = lseek(fm->fd, 0, SEEK_END);
  lseek(fm->fd, 0, SEEK_SET);
  fm->start = mmap(0, fm->size, PROT_READ, MAP_SHARED, fm->fd, 0);
  if(fm->start == NULL) {
    err = CL_FILE_MAP_FAILED_TO_MMAP;
    goto error;
  }

  fm->stop = ((char *) fm->start) + fm->size;
  fm->mapped = CL_TRUE;

exit:
  return err;
error:
  cl_file_map_destroy(fm);
  goto exit;
}

<commit_msg>Fix the problem by kernel file open in utest<commit_after>/*
 * Copyright © 2012 Intel Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 *
 * Author: Benjamin Segovia <benjamin.segovia@intel.com>
 */

#include "utest_file_map.hpp"
#include "CL/cl.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <stdio.h>

int
cl_file_map_init(cl_file_map_t *fm)
{
  assert(fm);
  memset(fm,0,sizeof(*fm));
  return CL_SUCCESS;
}

void
cl_file_map_destroy(cl_file_map_t *fm)
{
  if (fm->mapped) {
    munmap(fm->start, fm->size);
    fm->start = fm->stop = 0;
    fm->size = 0;
    fm->mapped = CL_FALSE;
  }
  if(fm->fd) {
    close(fm->fd);
    fm->fd = 0;
  }
  free(fm->name);
  memset(fm,0,sizeof(*fm));
}

void
cl_file_map_delete(cl_file_map_t *fm)
{
  if (fm == NULL)
    return;
  cl_file_map_destroy(fm);
  free(fm);
}

cl_file_map_t*
cl_file_map_new(void)
{
  cl_file_map_t *fm = NULL;

  if ((fm = (cl_file_map_t *) calloc(1, sizeof(cl_file_map_t))) == NULL)
    goto error;
  if (cl_file_map_init(fm) != CL_SUCCESS)
    goto error;

exit:
  return fm;
error:
  cl_file_map_delete(fm);
  fm = NULL;
  goto exit;
}

int
cl_file_map_open(cl_file_map_t *fm, const char *name)
{
  int err = CL_FILE_MAP_SUCCESS;

  /* Open the file */
  fm->fd = open(name, O_RDONLY);
  if(fm->fd < 0) {
    err = CL_FILE_MAP_FILE_NOT_FOUND;
    goto error;
  }
  if ((fm->name = (char*) calloc(strlen(name) + 1, sizeof(char))) == NULL)
    goto error;
  sprintf(fm->name, "%s", name);

  /* Map it */
  fm->size = lseek(fm->fd, 0, SEEK_END);
  lseek(fm->fd, 0, SEEK_SET);
  fm->start = mmap(0, fm->size, PROT_READ, MAP_SHARED, fm->fd, 0);
  if(fm->start == NULL) {
    err = CL_FILE_MAP_FAILED_TO_MMAP;
    goto error;
  }

  fm->stop = ((char *) fm->start) + fm->size;
  fm->mapped = CL_TRUE;

exit:
  return err;
error:
  cl_file_map_destroy(fm);
  goto exit;
}

<|endoftext|>


<commit_before>/*
    This file is part of kdepim.

    Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>
    Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>

    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., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "kmailchanges.h"

#include <kapplication.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kemailsettings.h>
#include <identitymanager.h>
#include <identity.h>
#include <kdebug.h>
#include <kstringhandler.h>

static const char* s_folderContentsType[] = {
  I18N_NOOP( "Calendar" ),
  I18N_NOOP( "Contacts" ),
  I18N_NOOP( "Notes" ),
  I18N_NOOP( "Tasks" ),
  I18N_NOOP( "Journal" ) };

CreateImapAccount::CreateImapAccount( const QString &accountName, const QString &title )
  : KConfigPropagator::Change( title ),
    mAccountName( accountName ), mEnableSieve( false ), mEnableSavePassword( true ),
    mEncryption( None ), mAuthenticationSend( PLAIN ), mSmtpPort( 25 ),
    mExistingAccountId( -1 ), mExistingTransportId( -1 ),
    mCustomWriter( 0 )
{
}

CreateImapAccount::~CreateImapAccount()
{
  delete mCustomWriter;
}

void CreateImapAccount::setServer( const QString &s )
{
  mServer = s;
}

void CreateImapAccount::setUser( const QString &s )
{
  mUser = s;
}

void CreateImapAccount::setPassword( const QString &s )
{
  mPassword = s;
}

void CreateImapAccount::setRealName( const QString &s )
{
  mRealName = s;
}

void CreateImapAccount::setEmail( const QString &s )
{
  mEmail = s;
}

void CreateImapAccount::enableSieve( bool b )
{
  mEnableSieve = b;
}

void CreateImapAccount::setSieveVacationFileName( const QString& f )
{
  mSieveVacationFileName = f;
}

void CreateImapAccount::enableSavePassword( bool b )
{
  mEnableSavePassword = b;
}

void CreateImapAccount::setEncryption(
  CreateImapAccount::Encryption e )
{
  mEncryption = e;
}

void CreateImapAccount::setDefaultDomain(const QString &d)
{
  mDefaultDomain = d;
}

void CreateImapAccount::setAuthenticationSend(
  CreateImapAccount::Authentication a )
{
  mAuthenticationSend = a;
}

void CreateImapAccount::setSmtpPort( int port )
{
  mSmtpPort = port;
}

void CreateImapAccount::setExistingAccountId( int id )
{
  mExistingAccountId = id;
}

void CreateImapAccount::setExistingTransportId( int id )
{
  mExistingTransportId = id;
}

void CreateImapAccount::setCustomWriter(
  CreateImapAccount::CustomWriter *writer )
{
  mCustomWriter = writer;
}

CreateDisconnectedImapAccount::CreateDisconnectedImapAccount(const QString & accountName) :
    CreateImapAccount( accountName, i18n("Create Disconnected IMAP Account for KMail") ),
    mLocalSubscription( false )
{
}

void CreateDisconnectedImapAccount::apply()
{
  if ( mEmail.isEmpty() ) mEmail = mUser + "@" + mServer;

  KConfig c( "kmailrc" );
  c.setGroup( "General" );
  c.writeEntry( "Default domain", mDefaultDomain );
  int accountId;
  if ( mExistingAccountId < 0 ) {
    uint accCnt = c.readNumEntry( "accounts", 0 );
    accountId = accCnt + 1;
    c.writeEntry( "accounts", accountId );
  } else {
    accountId = mExistingAccountId;
  }
  int transportId;
  if ( mExistingTransportId < 0 ) {
    uint transCnt = c.readNumEntry( "transports", 0 );
    transportId = transCnt + 1;
    c.writeEntry( "transports", transportId );
  } else {
    transportId = mExistingTransportId;
  }

  c.setGroup( QString("Account %1").arg( accountId ) );
  int uid;
  if ( mExistingAccountId < 0 ) {
    uid = kapp->random();
    c.writeEntry( "Folder", uid );
  } else {
    uid = c.readNumEntry( "Folder" );
  }
  c.writeEntry( "Id", uid );
  c.writeEntry( "Type", "cachedimap");
  c.writeEntry( "auth", "*");
  c.writeEntry( "Name", mAccountName );
  c.writeEntry( "host", mServer );
  c.writeEntry( "port", "993" );

  // in case the user wants to get rid of some groupware folders
  c.writeEntry( "locally-subscribed-folders", mLocalSubscription );

  c.writeEntry( "login", mUser );

  c.writeEntry( "sieve-support", mEnableSieve ? "true" : "false" );
  if ( !mSieveVacationFileName.isEmpty() )
    c.writeEntry( "sieve-vacation-filename", mSieveVacationFileName );

  if ( mEncryption == SSL ) {
    c.writeEntry( "use-ssl", true );
  } else if ( mEncryption == TLS ) {
    c.writeEntry( "use-tls", true );
  }

  c.setGroup( QString("Folder-%1").arg( uid ) );
  c.writeEntry( "isOpen", true );

  if ( mEnableSavePassword ) {
    c.writeEntry( "pass", KStringHandler::obscure( mPassword ) );
    c.writeEntry( "store-passwd", true );
  }

  c.setGroup( QString("Transport %1").arg( transportId ) );
  c.writeEntry( "name", mAccountName );
  c.writeEntry( "host", mServer );
  c.writeEntry( "type", "smtp" );
  c.writeEntry( "port", mSmtpPort );
  if ( mEncryption == SSL ) {
    c.writeEntry( "encryption", "SSL" );
  } else if ( mEncryption == TLS ) {
    c.writeEntry( "encryption", "TLS" );
  }
  c.writeEntry( "auth", true );
  if ( mAuthenticationSend == PLAIN ) {
    c.writeEntry( "authtype", "PLAIN" );
  } else if ( mAuthenticationSend == LOGIN ) {
    c.writeEntry( "authtype", "LOGIN" );
  }
  c.writeEntry( "user", mUser );
  if ( mEnableSavePassword ) {
    c.writeEntry( "pass", KStringHandler::obscure( mPassword ) );
    c.writeEntry( "storepass", "true" );
  }

  // Write email in "default kcontrol settings", used by IdentityManager
  // if it has to create a default identity.
  KEMailSettings es;
  es.setSetting( KEMailSettings::RealName, mRealName );
  es.setSetting( KEMailSettings::EmailAddress, mEmail );

  KPIM::IdentityManager identityManager;
  if ( !identityManager.allEmails().contains( mEmail ) ) {
    // Not sure how to name the identity. First one is "Default", next one mAccountName, but then...
    // let's use the server name after that.
    QString accountName = mAccountName;
    const QStringList identities = identityManager.identities();
    if ( identities.find( accountName ) != identities.end() ) {
      accountName = mServer;
      int i = 2;
      // And if there's already one, number them
      while ( identities.find( accountName ) != identities.end() ) {
        accountName = mServer + " " + QString::number( i++ );
      }
    }

    KPIM::Identity& identity = identityManager.newFromScratch( accountName );
    identity.setFullName( mRealName );
    identity.setEmailAddr( mEmail );
    identityManager.commit();
  }

  if ( mCustomWriter ) {
    mCustomWriter->writeFolder( c, uid );
    mCustomWriter->writeIds( accountId, transportId );
  }
}

CreateOnlineImapAccount::CreateOnlineImapAccount(const QString & accountName) :
    CreateImapAccount( accountName, i18n("Create Online IMAP Account for KMail") )
{
}

void CreateOnlineImapAccount::apply()
{
  KConfig c( "kmailrc" );
  c.setGroup( "General" );
  uint accCnt = c.readNumEntry( "accounts", 0 );
  c.writeEntry( "accounts", accCnt+1 );

  c.setGroup( QString("Account %1").arg(accCnt+1) );
  int uid = kapp->random();
  c.writeEntry( "Folder", uid );
  c.writeEntry( "Id", uid );
  c.writeEntry( "Type", "imap" );
  c.writeEntry( "auth", true );
  c.writeEntry( "Name", mAccountName );
  c.writeEntry( "host", mServer );

  c.writeEntry( "login", mUser );

  if ( mEnableSavePassword ) {
    c.writeEntry( "pass", KStringHandler::obscure( mPassword ) );
    c.writeEntry( "store-passwd", true );
  }
  c.writeEntry( "port", "993" );

  if ( mEncryption == SSL ) {
    c.writeEntry( "encryption", "SSL" );
  } else if ( mEncryption == TLS ) {
    c.writeEntry( "encryption", "TLS" );
  }

  if ( mAuthenticationSend == PLAIN ) {
    c.writeEntry( "authtype", "PLAIN" );
  } else if ( mAuthenticationSend == LOGIN ) {
    c.writeEntry( "authtype", "LOGIN" );
  }

  c.writeEntry( "sieve-support", mEnableSieve );

  // locally unsubscribe the default folders
  c.writeEntry( "locally-subscribed-folders", true );
  QString groupwareFolders = QString("/INBOX/%1/,/INBOX/%2/,/INBOX/%3/,/INBOX/%4/,/INBOX/%5/")
      .arg( i18n(s_folderContentsType[0]) ).arg( i18n(s_folderContentsType[1]) )
      .arg( i18n(s_folderContentsType[2]) ).arg( i18n(s_folderContentsType[3]) )
      .arg( i18n(s_folderContentsType[4]) );
  c.writeEntry( "locallyUnsubscribedFolders", groupwareFolders );

  c.setGroup( QString("Folder-%1").arg( uid ) );
  c.writeEntry( "isOpen", true );
}
<commit_msg>Actually writing the password looks like a good idea.<commit_after>/*
    This file is part of kdepim.

    Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>
    Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>

    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., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "kmailchanges.h"

#include <kapplication.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kemailsettings.h>
#include <identitymanager.h>
#include <identity.h>
#include <kdebug.h>
#include <kstringhandler.h>

static const char* s_folderContentsType[] = {
  I18N_NOOP( "Calendar" ),
  I18N_NOOP( "Contacts" ),
  I18N_NOOP( "Notes" ),
  I18N_NOOP( "Tasks" ),
  I18N_NOOP( "Journal" ) };

CreateImapAccount::CreateImapAccount( const QString &accountName, const QString &title )
  : KConfigPropagator::Change( title ),
    mAccountName( accountName ), mEnableSieve( false ), mEnableSavePassword( true ),
    mEncryption( None ), mAuthenticationSend( PLAIN ), mSmtpPort( 25 ),
    mExistingAccountId( -1 ), mExistingTransportId( -1 ),
    mCustomWriter( 0 )
{
}

CreateImapAccount::~CreateImapAccount()
{
  delete mCustomWriter;
}

void CreateImapAccount::setServer( const QString &s )
{
  mServer = s;
}

void CreateImapAccount::setUser( const QString &s )
{
  mUser = s;
}

void CreateImapAccount::setPassword( const QString &s )
{
  mPassword = s;
}

void CreateImapAccount::setRealName( const QString &s )
{
  mRealName = s;
}

void CreateImapAccount::setEmail( const QString &s )
{
  mEmail = s;
}

void CreateImapAccount::enableSieve( bool b )
{
  mEnableSieve = b;
}

void CreateImapAccount::setSieveVacationFileName( const QString& f )
{
  mSieveVacationFileName = f;
}

void CreateImapAccount::enableSavePassword( bool b )
{
  mEnableSavePassword = b;
}

void CreateImapAccount::setEncryption(
  CreateImapAccount::Encryption e )
{
  mEncryption = e;
}

void CreateImapAccount::setDefaultDomain(const QString &d)
{
  mDefaultDomain = d;
}

void CreateImapAccount::setAuthenticationSend(
  CreateImapAccount::Authentication a )
{
  mAuthenticationSend = a;
}

void CreateImapAccount::setSmtpPort( int port )
{
  mSmtpPort = port;
}

void CreateImapAccount::setExistingAccountId( int id )
{
  mExistingAccountId = id;
}

void CreateImapAccount::setExistingTransportId( int id )
{
  mExistingTransportId = id;
}

void CreateImapAccount::setCustomWriter(
  CreateImapAccount::CustomWriter *writer )
{
  mCustomWriter = writer;
}

CreateDisconnectedImapAccount::CreateDisconnectedImapAccount(const QString & accountName) :
    CreateImapAccount( accountName, i18n("Create Disconnected IMAP Account for KMail") ),
    mLocalSubscription( false )
{
}

void CreateDisconnectedImapAccount::apply()
{
  if ( mEmail.isEmpty() ) mEmail = mUser + "@" + mServer;

  KConfig c( "kmailrc" );
  c.setGroup( "General" );
  c.writeEntry( "Default domain", mDefaultDomain );
  int accountId;
  if ( mExistingAccountId < 0 ) {
    uint accCnt = c.readNumEntry( "accounts", 0 );
    accountId = accCnt + 1;
    c.writeEntry( "accounts", accountId );
  } else {
    accountId = mExistingAccountId;
  }
  int transportId;
  if ( mExistingTransportId < 0 ) {
    uint transCnt = c.readNumEntry( "transports", 0 );
    transportId = transCnt + 1;
    c.writeEntry( "transports", transportId );
  } else {
    transportId = mExistingTransportId;
  }

  c.setGroup( QString("Account %1").arg( accountId ) );
  int uid;
  if ( mExistingAccountId < 0 ) {
    uid = kapp->random();
    c.writeEntry( "Folder", uid );
  } else {
    uid = c.readNumEntry( "Folder" );
  }
  c.writeEntry( "Id", uid );
  c.writeEntry( "Type", "cachedimap");
  c.writeEntry( "auth", "*");
  c.writeEntry( "Name", mAccountName );
  c.writeEntry( "host", mServer );
  c.writeEntry( "port", "993" );

  // in case the user wants to get rid of some groupware folders
  c.writeEntry( "locally-subscribed-folders", mLocalSubscription );

  c.writeEntry( "login", mUser );

  c.writeEntry( "sieve-support", mEnableSieve ? "true" : "false" );
  if ( !mSieveVacationFileName.isEmpty() )
    c.writeEntry( "sieve-vacation-filename", mSieveVacationFileName );

  if ( mEncryption == SSL ) {
    c.writeEntry( "use-ssl", true );
  } else if ( mEncryption == TLS ) {
    c.writeEntry( "use-tls", true );
  }

  if ( mEnableSavePassword ) {
    c.writeEntry( "pass", KStringHandler::obscure( mPassword ) );
    c.writeEntry( "store-passwd", true );
  }

  c.setGroup( QString("Folder-%1").arg( uid ) );
  c.writeEntry( "isOpen", true );

  if ( mEnableSavePassword ) {
    c.writeEntry( "pass", KStringHandler::obscure( mPassword ) );
    c.writeEntry( "store-passwd", true );
  }

  c.setGroup( QString("Transport %1").arg( transportId ) );
  c.writeEntry( "name", mAccountName );
  c.writeEntry( "host", mServer );
  c.writeEntry( "type", "smtp" );
  c.writeEntry( "port", mSmtpPort );
  if ( mEncryption == SSL ) {
    c.writeEntry( "encryption", "SSL" );
  } else if ( mEncryption == TLS ) {
    c.writeEntry( "encryption", "TLS" );
  }
  c.writeEntry( "auth", true );
  if ( mAuthenticationSend == PLAIN ) {
    c.writeEntry( "authtype", "PLAIN" );
  } else if ( mAuthenticationSend == LOGIN ) {
    c.writeEntry( "authtype", "LOGIN" );
  }
  c.writeEntry( "user", mUser );
  if ( mEnableSavePassword ) {
    c.writeEntry( "pass", KStringHandler::obscure( mPassword ) );
    c.writeEntry( "storepass", true );
  }

  // Write email in "default kcontrol settings", used by IdentityManager
  // if it has to create a default identity.
  KEMailSettings es;
  es.setSetting( KEMailSettings::RealName, mRealName );
  es.setSetting( KEMailSettings::EmailAddress, mEmail );

  KPIM::IdentityManager identityManager;
  if ( !identityManager.allEmails().contains( mEmail ) ) {
    // Not sure how to name the identity. First one is "Default", next one mAccountName, but then...
    // let's use the server name after that.
    QString accountName = mAccountName;
    const QStringList identities = identityManager.identities();
    if ( identities.find( accountName ) != identities.end() ) {
      accountName = mServer;
      int i = 2;
      // And if there's already one, number them
      while ( identities.find( accountName ) != identities.end() ) {
        accountName = mServer + " " + QString::number( i++ );
      }
    }

    KPIM::Identity& identity = identityManager.newFromScratch( accountName );
    identity.setFullName( mRealName );
    identity.setEmailAddr( mEmail );
    identityManager.commit();
  }

  if ( mCustomWriter ) {
    mCustomWriter->writeFolder( c, uid );
    mCustomWriter->writeIds( accountId, transportId );
  }
}

CreateOnlineImapAccount::CreateOnlineImapAccount(const QString & accountName) :
    CreateImapAccount( accountName, i18n("Create Online IMAP Account for KMail") )
{
}

void CreateOnlineImapAccount::apply()
{
  KConfig c( "kmailrc" );
  c.setGroup( "General" );
  uint accCnt = c.readNumEntry( "accounts", 0 );
  c.writeEntry( "accounts", accCnt+1 );

  c.setGroup( QString("Account %1").arg(accCnt+1) );
  int uid = kapp->random();
  c.writeEntry( "Folder", uid );
  c.writeEntry( "Id", uid );
  c.writeEntry( "Type", "imap" );
  c.writeEntry( "auth", true );
  c.writeEntry( "Name", mAccountName );
  c.writeEntry( "host", mServer );

  c.writeEntry( "login", mUser );

  if ( mEnableSavePassword ) {
    c.writeEntry( "pass", KStringHandler::obscure( mPassword ) );
    c.writeEntry( "store-passwd", true );
  }
  c.writeEntry( "port", "993" );

  if ( mEncryption == SSL ) {
    c.writeEntry( "encryption", "SSL" );
  } else if ( mEncryption == TLS ) {
    c.writeEntry( "encryption", "TLS" );
  }

  if ( mAuthenticationSend == PLAIN ) {
    c.writeEntry( "authtype", "PLAIN" );
  } else if ( mAuthenticationSend == LOGIN ) {
    c.writeEntry( "authtype", "LOGIN" );
  }

  c.writeEntry( "sieve-support", mEnableSieve );

  // locally unsubscribe the default folders
  c.writeEntry( "locally-subscribed-folders", true );
  QString groupwareFolders = QString("/INBOX/%1/,/INBOX/%2/,/INBOX/%3/,/INBOX/%4/,/INBOX/%5/")
      .arg( i18n(s_folderContentsType[0]) ).arg( i18n(s_folderContentsType[1]) )
      .arg( i18n(s_folderContentsType[2]) ).arg( i18n(s_folderContentsType[3]) )
      .arg( i18n(s_folderContentsType[4]) );
  c.writeEntry( "locallyUnsubscribedFolders", groupwareFolders );

  c.setGroup( QString("Folder-%1").arg( uid ) );
  c.writeEntry( "isOpen", true );
}
<|endoftext|>


<commit_before>/*
    This file is part of kdepim.

    Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>

    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 "kmailchanges.h"
#include "kolabconfig.h"

#include <kapplication.h>
#include <klocale.h>

class CreateDisconnectedImapAccount : public KConfigPropagator::Change
{
  public:
    CreateDisconnectedImapAccount()
      : KConfigPropagator::Change( i18n("Create Disconnected IMAP Account for KMail") )
    {
    }

    // This sucks as this is a 1:1 copy from KMAccount::encryptStr()
    static QString encryptStr(const QString& aStr)
    {
      QString result;
      for (uint i = 0; i < aStr.length(); i++)
        result += (aStr[i].unicode() < 0x20) ? aStr[i] :
          QChar(0x1001F - aStr[i].unicode());
      return result;

    }

    void apply()
    {
      KConfig c( "kmailrc" );
      c.setGroup( "General" );
      uint accCnt = c.readNumEntry( "accounts", 0 );
      c.writeEntry( "accounts", accCnt+1 );
      uint transCnt = c.readNumEntry( "transports", 0 );
      c.writeEntry( "transports", transCnt+1 );

      c.setGroup( QString("Account %1").arg(accCnt+1) );
      int uid = kapp->random();
      c.writeEntry( "Folder", uid );
      c.writeEntry( "Id", uid );
      c.writeEntry( "Type", "cachedimap");
      c.writeEntry( "auth", "*");
      c.writeEntry( "Name", "Kolab Server" );
      c.writeEntry( "host", KolabConfig::self()->server() );

      c.writeEntry( "login", KolabConfig::self()->user() );

      if ( KolabConfig::self()->savePassword() )
        c.writeEntry( "pass", encryptStr(KolabConfig::self()->password()) );

      c.setGroup( QString("Transport %1").arg(transCnt+1) );
      c.writeEntry( "name", "Kolab Server" );
      c.writeEntry( "host", KolabConfig::self()->server() );

      // ### Should be done using the KPIM identity manager

      if ( !c.hasGroup("Identity") )
      {
        c.setGroup( "Identity" );
      }
      else
      {
        int i = 0;
        while (c.hasGroup(QString("Identity #%1").arg(i)))
          ++i;

        c.setGroup( QString("Identity #%1").arg(++i) );
      }

      QString user = KolabConfig::self()->user();
      int pos = user.find( "@" );
      if ( pos > 0 ) user = user.left( pos );

      c.writeEntry("Email Address", user+"@"+KolabConfig::self()->server() );
      c.writeEntry("Name", KolabConfig::self()->realName() );
      c.writeEntry("uoid", kapp->random() );

      // This needs to be done here, since it reference just just generated id
      c.setGroup( "IMAP Resource" );
      c.writeEntry("Folder Parent", uid);
   }

};

void createKMailChanges( KConfigPropagator::Change::List& changes )
{
  KConfigPropagator::ChangeConfig *c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "Groupware";
  c->name = "Enabled";
  c->value = "true";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "Groupware";
  c->name = "AutoAccept";
  c->value = "false";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "Groupware";
  c->name = "AutoDeclConflict";
  c->value = "false";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "Groupware";
  c->name = "LegacyMangleFromToHeaders";
  c->value = "false";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "IMAP Resource";
  c->name = "Enabled";
  c->value = "true";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "IMAP Resource";
  c->name = "TheIMAPResourceEnabled";
  c->value = "true";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "IMAP Resource";
  c->name = "Folder Language";
  c->value = "0"; // TODO: Fix the language
  changes.append( c );

  changes.append( new CreateDisconnectedImapAccount );
}
<commit_msg>Fixed "store-passwd" option no set, fixed folder-parent option name<commit_after>/*
    This file is part of kdepim.

    Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>

    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 "kmailchanges.h"
#include "kolabconfig.h"

#include <kapplication.h>
#include <klocale.h>

class CreateDisconnectedImapAccount : public KConfigPropagator::Change
{
  public:
    CreateDisconnectedImapAccount()
      : KConfigPropagator::Change( i18n("Create Disconnected IMAP Account for KMail") )
    {
    }

    // This sucks as this is a 1:1 copy from KMAccount::encryptStr()
    static QString encryptStr(const QString& aStr)
    {
      QString result;
      for (uint i = 0; i < aStr.length(); i++)
        result += (aStr[i].unicode() < 0x20) ? aStr[i] :
          QChar(0x1001F - aStr[i].unicode());
      return result;

    }

    void apply()
    {
      KConfig c( "kmailrc" );
      c.setGroup( "General" );
      uint accCnt = c.readNumEntry( "accounts", 0 );
      c.writeEntry( "accounts", accCnt+1 );
      uint transCnt = c.readNumEntry( "transports", 0 );
      c.writeEntry( "transports", transCnt+1 );

      c.setGroup( QString("Account %1").arg(accCnt+1) );
      int uid = kapp->random();
      c.writeEntry( "Folder", uid );
      c.writeEntry( "Id", uid );
      c.writeEntry( "Type", "cachedimap");
      c.writeEntry( "auth", "*");
      c.writeEntry( "Name", "Kolab Server" );
      c.writeEntry( "host", KolabConfig::self()->server() );

      c.writeEntry( "login", KolabConfig::self()->user() );

      if ( KolabConfig::self()->savePassword() ) {
        c.writeEntry( "pass", encryptStr(KolabConfig::self()->password()) );
        c.writeEntry( "store-passwd", true );
      }

      c.setGroup( QString("Transport %1").arg(transCnt+1) );
      c.writeEntry( "name", "Kolab Server" );
      c.writeEntry( "host", KolabConfig::self()->server() );

      // ### Should be done using the KPIM identity manager

      if ( !c.hasGroup("Identity") )
      {
        c.setGroup( "Identity" );
      }
      else
      {
        int i = 0;
        while (c.hasGroup(QString("Identity #%1").arg(i)))
          ++i;

        c.setGroup( QString("Identity #%1").arg(++i) );
      }

      QString user = KolabConfig::self()->user();
      int pos = user.find( "@" );
      if ( pos > 0 ) user = user.left( pos );

      c.writeEntry("Email Address", user+"@"+KolabConfig::self()->server() );
      c.writeEntry("Name", KolabConfig::self()->realName() );
      c.writeEntry("uoid", kapp->random() );

      // This needs to be done here, since it reference just just generated id
      c.setGroup( "IMAP Resource" );
      c.writeEntry("TheIMAPResourceFolderParent", QString(".%1.directory/INBOX").arg( uid ));
   }

};

void createKMailChanges( KConfigPropagator::Change::List& changes )
{
  KConfigPropagator::ChangeConfig *c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "Groupware";
  c->name = "Enabled";
  c->value = "true";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "Groupware";
  c->name = "AutoAccept";
  c->value = "false";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "Groupware";
  c->name = "AutoDeclConflict";
  c->value = "false";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "Groupware";
  c->name = "LegacyMangleFromToHeaders";
  c->value = "false";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "IMAP Resource";
  c->name = "Enabled";
  c->value = "true";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "IMAP Resource";
  c->name = "TheIMAPResourceEnabled";
  c->value = "true";
  changes.append( c );

  c = new KConfigPropagator::ChangeConfig;
  c->file = "kmailrc";
  c->group = "IMAP Resource";
  c->name = "Folder Language";
  c->value = "0"; // TODO: Fix the language
  changes.append( c );

  changes.append( new CreateDisconnectedImapAccount );
}
<|endoftext|>