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

    Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>

    This program is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include <interfaces/bodypartformatter.h>
#include <interfaces/bodypart.h>
#include <interfaces/bodyparturlhandler.h>
#include <khtmlparthtmlwriter.h>

#include <libkcal/calendarlocal.h>
#include <libkcal/icalformat.h>
#include <libkcal/attendee.h>
#include <libkcal/incidence.h>
#include <libkcal/incidenceformatter.h>

#include <kpimprefs.h> // for the timezone

#include <kmail/callback.h>
#include <kmail/kmmessage.h>
#include <kmail/kmcommands.h>

#include <email.h>

#include <kglobal.h>
#include <klocale.h>
#include <kstringhandler.h>
#include <kglobalsettings.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <kdcopservicestarter.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kapplication.h>
#include <ktempfile.h>

#include <qurl.h>
#include <qdir.h>
#include <qtextstream.h>

#include <kdepimmacros.h>

#include <dcopclient.h>
#include <dcopref.h>

using namespace KCal;

namespace {

class KMInvitationFormatterHelper : public KCal::InvitationFormatterHelper
{
  public:
    KMInvitationFormatterHelper( KMail::Interface::BodyPart *bodyPart ) : mBodyPart( bodyPart ) {}
    virtual QString generateLinkURL( const QString &id ) { return mBodyPart->makeLink( id ); }
  private:
    KMail::Interface::BodyPart *mBodyPart;
};

class Formatter : public KMail::Interface::BodyPartFormatter
{
  public:
    Result format( KMail::Interface::BodyPart *bodyPart,
                   KMail::HtmlWriter *writer ) const
    {
      if ( !writer )
        // Guard against crashes in createReply()
        return Ok;
      CalendarLocal cl( KPimPrefs::timezone() );
      KMInvitationFormatterHelper helper( bodyPart );
      QString source;
      /* If the bodypart does not have a charset specified, we need to fall back to
         utf8, not the KMail fallback encoding, so get the contents as binary and decode
         explicitely. */
      if ( bodyPart->contentTypeParameter( "charset").isEmpty() ) {
        const QByteArray &ba = bodyPart->asBinary();
        source = QString::fromUtf8(ba);
      } else {
        source = bodyPart->asText();
      }
      QString html = IncidenceFormatter::formatICalInvitation( source, &cl, &helper );

      if ( html.isEmpty() ) return AsIcon;
      writer->queue( html );

      return Ok;
    }
};

class UrlHandler : public KMail::Interface::BodyPartURLHandler
{
  public:
    UrlHandler()
    {
      kdDebug() << "UrlHandler() (iCalendar)" << endl;
    }

    Incidence* icalToString( const QString& iCal ) const
    {
      CalendarLocal calendar( KPimPrefs::timezone() ) ;
      ICalFormat format;
      ScheduleMessage *message =
        format.parseScheduleMessage( &calendar, iCal );
      if ( !message )
        //TODO: Error message?
        return 0;
      return dynamic_cast<Incidence*>( message->event() );
    }

    Attendee *findMyself( Incidence* incidence, const QString& receiver ) const
    {
      Attendee::List attendees = incidence->attendees();
      Attendee::List::ConstIterator it;
      Attendee* myself = 0;
      // Find myself. There will always be all attendees listed, even if
      // only I need to answer it.
      if ( attendees.count() == 1 )
        // Only one attendee, that must be me
        myself = *attendees.begin();
      else {
        for ( it = attendees.begin(); it != attendees.end(); ++it ) {
          // match only the email part, not the name
          if( KPIM::compareEmail( (*it)->email(), receiver, false ) ) {
            // We are the current one, and even the receiver, note
            // this and quit searching.
            myself = (*it);
            break;
          }
        }
      }
      return myself;
    }

    static bool heuristicalRSVP( Incidence *incidence )
    {
      bool rsvp = true; // better send superfluously than not at all
      Attendee::List attendees = incidence->attendees();
      Attendee::List::ConstIterator it;
      for ( it = attendees.begin(); it != attendees.end(); ++it ) {
        if ( it == attendees.begin() ) {
          rsvp = (*it)->RSVP(); // use what the first one has
        } else {
          if ( (*it)->RSVP() != rsvp ) {
            rsvp = true; // they differ, default
            break;
          }
        }
      }
      return rsvp;
    }

    static Attendee::Role heuristicalRole( Incidence *incidence )
    {
      Attendee::Role role = Attendee::OptParticipant;
      Attendee::List attendees = incidence->attendees();
      Attendee::List::ConstIterator it;
      for ( it = attendees.begin(); it != attendees.end(); ++it ) {
        if ( it == attendees.begin() ) {
          role = (*it)->role(); // use what the first one has
        } else {
          if ( (*it)->role() != role ) {
            role = Attendee::OptParticipant; // they differ, default
            break;
          }
        }
      }
      return role;

    }

    void setStatusOnMyself( Incidence* incidence, Attendee* myself,
                            Attendee::PartStat status, const QString &receiver ) const
    {
      Attendee* newMyself = 0;
      QString name;
      QString email;
      KPIM::getNameAndMail( receiver, name, email );
      if ( name.isEmpty() && myself ) name = myself->name();
      if ( email.isEmpty()&& myself ) email = myself->email();
      Q_ASSERT( !email.isEmpty() ); // delivery must be possible
      newMyself = new Attendee( name,
                                email,
                                true, // RSVP, otherwise we would not be here
                                status,
                                myself ? myself->role() : heuristicalRole( incidence ),
                                myself ? myself->uid() : QString::null );

      // Make sure only ourselves is in the event
      incidence->clearAttendees();
      if( newMyself )
        incidence->addAttendee( newMyself );
    }

    bool mail( Incidence* incidence, KMail::Callback& callback ) const
    {
      ICalFormat format;
      format.setTimeZone( KPimPrefs::timezone(), false );
      QString msg = format.createScheduleMessage( incidence,
                                                  Scheduler::Reply );
      QString subject;
      if ( !incidence->summary().isEmpty() )
        subject = i18n( "Answer: %1" ).arg( incidence->summary() );
      else
        subject = i18n( "Answer: Incidence with no summary" );
      return callback.mailICal( incidence->organizer().fullName(), msg, subject );
    }

    bool saveFile( const QString& receiver, const QString& iCal,
                   const QString& type ) const
    {
      KTempFile file( locateLocal( "data", "korganizer/income." + type + '/',
                                   true ) );
      QTextStream* ts = file.textStream();
      if ( !ts ) {
        KMessageBox::error( 0, i18n("Could not save file to KOrganizer") );
        return false;
      }
      ts->setEncoding( QTextStream::UnicodeUTF8 );
      (*ts) << receiver << '\n' << iCal;
      file.close();

      // Now ensure that korganizer is running; otherwise start it, to prevent surprises
      // (https://intevation.de/roundup/kolab/issue758)
      QString error;
      QCString dcopService;
      int result = KDCOPServiceStarter::self()->findServiceFor( "DCOP/Organizer", QString::null, QString::null, &error, &dcopService );
      if ( result == 0 ) {
        // OK, so korganizer (or kontact) is running. Now ensure the object we want is available
        // [that's not the case when kontact was already running, but korganizer not loaded into it...]
        static const char* const dcopObjectId = "KOrganizerIface";
        QCString dummy;
        if ( !kapp->dcopClient()->findObject( dcopService, dcopObjectId, "", QByteArray(), dummy, dummy ) ) {
          DCOPRef ref( dcopService, dcopService ); // talk to the KUniqueApplication or its kontact wrapper
          DCOPReply reply = ref.call( "load()" );
          if ( reply.isValid() && (bool)reply ) {
            kdDebug() << "Loaded " << dcopService << " successfully" << endl;
            Q_ASSERT( kapp->dcopClient()->findObject( dcopService, dcopObjectId, "", QByteArray(), dummy, dummy ) );
          } else
            kdWarning() << "Error loading " << dcopService << endl;
        }

        // We don't do anything with it, we just need it to be running so that it handles
        // the incoming directory.
      }
      else
        kdWarning() << "Couldn't start DCOP/Organizer: " << dcopService << " " << error << endl;

      return true;
    }

    bool handleInvitation( const QString& iCal, Attendee::PartStat status,
                           KMail::Callback &callback ) const
    {
      bool ok = true;
      const QString receiver = callback.receiver();
      if ( receiver.isEmpty() )
        // Must be some error. Still return true though, since we did handle it
        return true;

      // First, save it for KOrganizer to handle
      QString dir;
      if ( status == Attendee::Accepted ) dir = "accepted";
      else if ( status == Attendee::Tentative  ) dir = "tentative";
      else if ( status == Attendee::Declined ) dir = "cancel";
      else return true; // unknown status

      saveFile( receiver, iCal, dir );

      // Now produce the return message
      Incidence* incidence = icalToString( iCal );

      if( !incidence ) return false;
      Attendee *myself = findMyself( incidence, receiver );
      if ( ( myself && myself->RSVP() ) || heuristicalRSVP( incidence ) ) {
        setStatusOnMyself( incidence, myself, status, receiver );
        ok =  mail( incidence, callback );
      } else {
        ( new KMDeleteMsgCommand( callback.getMsg()->getMsgSerNum() ) )->start();
      }
      delete incidence;
      return ok;
    }

    bool handleIgnore( const QString&, KMail::Callback& c ) const
    {
      // simply move the message to trash
      ( new KMDeleteMsgCommand( c.getMsg()->getMsgSerNum() ) )->start();
      return true;
    }

    bool handleClick( KMail::Interface::BodyPart *part,
                      const QString &path, KMail::Callback& c ) const
    {
      QString iCal = part->asText();
      bool result = false;
      if ( path == "accept" )
        result = handleInvitation( iCal, Attendee::Accepted, c );
      if ( path == "accept_conditionally" )
        result = handleInvitation( iCal, Attendee::Tentative, c );
      if ( path == "ignore" )
        result = handleIgnore( iCal, c );
      if ( path == "decline" )
        result = handleInvitation( iCal, Attendee::Declined, c );
      if ( path == "reply" || path == "cancel" ) {
        // These should just be saved with their type as the dir
        if ( saveFile( "Receiver Not Searched", iCal, path ) ) {
          ( new KMDeleteMsgCommand( c.getMsg()->getMsgSerNum() ) )->start();
          result = true;
        }
      }
      if ( result )
        c.closeIfSecondaryWindow();
      return result;
    }

    bool handleContextMenuRequest( KMail::Interface::BodyPart *,
                                   const QString &,
                                   const QPoint & ) const
    {
      return false;
    }

    QString statusBarMessage( KMail::Interface::BodyPart *,
                              const QString &path ) const
    {
      if ( !path.isEmpty() ) {
        if ( path == "accept" )
          return i18n("Accept incidence");
        if ( path == "accept_conditionally" )
          return i18n( "Accept incidence conditionally" );
        if ( path == "ignore" )
          return i18n( "Throw mail away" );
        if ( path == "decline" )
          return i18n( "Decline incidence" );
        if ( path == "check_calendar" )
          return i18n("Check my calendar..." );
        if ( path == "reply" )
          return i18n( "Enter incidence into my calendar" );
        if ( path == "cancel" )
          return i18n( "Remove incidence from my calendar" );
      }

      return QString::null;
    }
};

class Plugin : public KMail::Interface::BodyPartFormatterPlugin
{
  public:
    const KMail::Interface::BodyPartFormatter *bodyPartFormatter( int idx ) const
    {
      if ( idx == 0 ) return new Formatter();
      else return 0;
    }

    const char *type( int idx ) const
    {
      if ( idx == 0 ) return "text";
      else return 0;
    }

    const char *subtype( int idx ) const
    {
      if ( idx == 0 ) return "calendar";
      else return 0;
    }

    const KMail::Interface::BodyPartURLHandler * urlHandler( int idx ) const
    {
      if ( idx == 0 ) return new UrlHandler();
      else return 0;
    }
};

}

extern "C"
KDE_EXPORT KMail::Interface::BodyPartFormatterPlugin *
libkmail_bodypartformatter_text_calendar_create_bodypart_formatter_plugin()
{
  KGlobal::locale()->insertCatalogue( "kmail_text_calendar_plugin" );
  return new Plugin();
}
<commit_msg>Allow to delegate iCal invitations according to RFC 2446. <commit_after>/*
    This file is part of kdepim.

    Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>

    This program is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include <interfaces/bodypartformatter.h>
#include <interfaces/bodypart.h>
#include <interfaces/bodyparturlhandler.h>
#include <khtmlparthtmlwriter.h>

#include <libkcal/calendarlocal.h>
#include <libkcal/icalformat.h>
#include <libkcal/attendee.h>
#include <libkcal/incidence.h>
#include <libkcal/incidenceformatter.h>

#include <kpimprefs.h> // for the timezone

#include <kmail/callback.h>
#include <kmail/kmmessage.h>
#include <kmail/kmcommands.h>

#include <email.h>

#include <kglobal.h>
#include <kinputdialog.h>
#include <klocale.h>
#include <kstringhandler.h>
#include <kglobalsettings.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <kdcopservicestarter.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kapplication.h>
#include <ktempfile.h>

#include <qurl.h>
#include <qdir.h>
#include <qtextstream.h>

#include <kdepimmacros.h>

#include <dcopclient.h>
#include <dcopref.h>

using namespace KCal;

namespace {

class KMInvitationFormatterHelper : public KCal::InvitationFormatterHelper
{
  public:
    KMInvitationFormatterHelper( KMail::Interface::BodyPart *bodyPart ) : mBodyPart( bodyPart ) {}
    virtual QString generateLinkURL( const QString &id ) { return mBodyPart->makeLink( id ); }
  private:
    KMail::Interface::BodyPart *mBodyPart;
};

class Formatter : public KMail::Interface::BodyPartFormatter
{
  public:
    Result format( KMail::Interface::BodyPart *bodyPart,
                   KMail::HtmlWriter *writer ) const
    {
      if ( !writer )
        // Guard against crashes in createReply()
        return Ok;
      CalendarLocal cl( KPimPrefs::timezone() );
      KMInvitationFormatterHelper helper( bodyPart );
      QString source;
      /* If the bodypart does not have a charset specified, we need to fall back to
         utf8, not the KMail fallback encoding, so get the contents as binary and decode
         explicitely. */
      if ( bodyPart->contentTypeParameter( "charset").isEmpty() ) {
        const QByteArray &ba = bodyPart->asBinary();
        source = QString::fromUtf8(ba);
      } else {
        source = bodyPart->asText();
      }
      QString html = IncidenceFormatter::formatICalInvitation( source, &cl, &helper );

      if ( html.isEmpty() ) return AsIcon;
      writer->queue( html );

      return Ok;
    }
};

class UrlHandler : public KMail::Interface::BodyPartURLHandler
{
  public:
    UrlHandler()
    {
      kdDebug() << "UrlHandler() (iCalendar)" << endl;
    }

    Incidence* icalToString( const QString& iCal ) const
    {
      CalendarLocal calendar( KPimPrefs::timezone() ) ;
      ICalFormat format;
      ScheduleMessage *message =
        format.parseScheduleMessage( &calendar, iCal );
      if ( !message )
        //TODO: Error message?
        return 0;
      return dynamic_cast<Incidence*>( message->event() );
    }

    Attendee *findMyself( Incidence* incidence, const QString& receiver ) const
    {
      Attendee::List attendees = incidence->attendees();
      Attendee::List::ConstIterator it;
      Attendee* myself = 0;
      // Find myself. There will always be all attendees listed, even if
      // only I need to answer it.
      if ( attendees.count() == 1 )
        // Only one attendee, that must be me
        myself = *attendees.begin();
      else {
        for ( it = attendees.begin(); it != attendees.end(); ++it ) {
          // match only the email part, not the name
          if( KPIM::compareEmail( (*it)->email(), receiver, false ) ) {
            // We are the current one, and even the receiver, note
            // this and quit searching.
            myself = (*it);
            break;
          }
        }
      }
      return myself;
    }

    static bool heuristicalRSVP( Incidence *incidence )
    {
      bool rsvp = true; // better send superfluously than not at all
      Attendee::List attendees = incidence->attendees();
      Attendee::List::ConstIterator it;
      for ( it = attendees.begin(); it != attendees.end(); ++it ) {
        if ( it == attendees.begin() ) {
          rsvp = (*it)->RSVP(); // use what the first one has
        } else {
          if ( (*it)->RSVP() != rsvp ) {
            rsvp = true; // they differ, default
            break;
          }
        }
      }
      return rsvp;
    }

    static Attendee::Role heuristicalRole( Incidence *incidence )
    {
      Attendee::Role role = Attendee::OptParticipant;
      Attendee::List attendees = incidence->attendees();
      Attendee::List::ConstIterator it;
      for ( it = attendees.begin(); it != attendees.end(); ++it ) {
        if ( it == attendees.begin() ) {
          role = (*it)->role(); // use what the first one has
        } else {
          if ( (*it)->role() != role ) {
            role = Attendee::OptParticipant; // they differ, default
            break;
          }
        }
      }
      return role;

    }

    Attendee* setStatusOnMyself( Incidence* incidence, Attendee* myself,
                            Attendee::PartStat status, const QString &receiver ) const
    {
      Attendee* newMyself = 0;
      QString name;
      QString email;
      KPIM::getNameAndMail( receiver, name, email );
      if ( name.isEmpty() && myself ) name = myself->name();
      if ( email.isEmpty()&& myself ) email = myself->email();
      Q_ASSERT( !email.isEmpty() ); // delivery must be possible
      newMyself = new Attendee( name,
                                email,
                                true, // RSVP, otherwise we would not be here
                                status,
                                myself ? myself->role() : heuristicalRole( incidence ),
                                myself ? myself->uid() : QString::null );

      // Make sure only ourselves is in the event
      incidence->clearAttendees();
      if( newMyself )
        incidence->addAttendee( newMyself );
      return newMyself;
    }

    bool mail( Incidence* incidence, KMail::Callback& callback, Scheduler::Method method = Scheduler::Reply, const QString &to = QString::null ) const
    {
      ICalFormat format;
      format.setTimeZone( KPimPrefs::timezone(), false );
      QString msg = format.createScheduleMessage( incidence, method );
      QString subject;
      if ( !incidence->summary().isEmpty() )
        subject = i18n( "Answer: %1" ).arg( incidence->summary() );
      else
        subject = i18n( "Answer: Incidence with no summary" );
      QString recv = to;
      if ( recv.isEmpty() )
        recv = incidence->organizer().fullName();
      return callback.mailICal( recv, msg, subject );
    }

    bool saveFile( const QString& receiver, const QString& iCal,
                   const QString& type ) const
    {
      KTempFile file( locateLocal( "data", "korganizer/income." + type + '/',
                                   true ) );
      QTextStream* ts = file.textStream();
      if ( !ts ) {
        KMessageBox::error( 0, i18n("Could not save file to KOrganizer") );
        return false;
      }
      ts->setEncoding( QTextStream::UnicodeUTF8 );
      (*ts) << receiver << '\n' << iCal;
      file.close();

      // Now ensure that korganizer is running; otherwise start it, to prevent surprises
      // (https://intevation.de/roundup/kolab/issue758)
      QString error;
      QCString dcopService;
      int result = KDCOPServiceStarter::self()->findServiceFor( "DCOP/Organizer", QString::null, QString::null, &error, &dcopService );
      if ( result == 0 ) {
        // OK, so korganizer (or kontact) is running. Now ensure the object we want is available
        // [that's not the case when kontact was already running, but korganizer not loaded into it...]
        static const char* const dcopObjectId = "KOrganizerIface";
        QCString dummy;
        if ( !kapp->dcopClient()->findObject( dcopService, dcopObjectId, "", QByteArray(), dummy, dummy ) ) {
          DCOPRef ref( dcopService, dcopService ); // talk to the KUniqueApplication or its kontact wrapper
          DCOPReply reply = ref.call( "load()" );
          if ( reply.isValid() && (bool)reply ) {
            kdDebug() << "Loaded " << dcopService << " successfully" << endl;
            Q_ASSERT( kapp->dcopClient()->findObject( dcopService, dcopObjectId, "", QByteArray(), dummy, dummy ) );
          } else
            kdWarning() << "Error loading " << dcopService << endl;
        }

        // We don't do anything with it, we just need it to be running so that it handles
        // the incoming directory.
      }
      else
        kdWarning() << "Couldn't start DCOP/Organizer: " << dcopService << " " << error << endl;

      return true;
    }

    bool handleInvitation( const QString& iCal, Attendee::PartStat status,
                           KMail::Callback &callback ) const
    {
      bool ok = true;
      const QString receiver = callback.receiver();
      if ( receiver.isEmpty() )
        // Must be some error. Still return true though, since we did handle it
        return true;

      // First, save it for KOrganizer to handle
      QString dir;
      if ( status == Attendee::Accepted ) dir = "accepted";
      else if ( status == Attendee::Tentative  ) dir = "tentative";
      else if ( status == Attendee::Declined ) dir = "cancel";
      else if ( status == Attendee::Delegated ) dir = "delegated";
      else return true; // unknown status

      saveFile( receiver, iCal, dir );

      QString delegateString;
      if ( status == Attendee::Delegated ) {
        // TODO: add real attendee selector
        bool ok = false;
        delegateString = KInputDialog::getText( "Select Delegate", "Delegate:", QString::null, &ok );
        if ( delegateString.isEmpty() || !ok )
          return true;
      }

      // Now produce the return message
      Incidence* incidence = icalToString( iCal );

      if( !incidence ) return false;
      Attendee *myself = findMyself( incidence, receiver );
      if ( ( myself && myself->RSVP() ) || heuristicalRSVP( incidence ) ) {
        Attendee* newMyself = setStatusOnMyself( incidence, myself, status, receiver );
        if ( newMyself && status == Attendee::Delegated )
          newMyself->setDelegate( delegateString );
        ok =  mail( incidence, callback );
      } else {
        ( new KMDeleteMsgCommand( callback.getMsg()->getMsgSerNum() ) )->start();
      }
      delete incidence;

      // create invitation for the delegate
      if ( status == Attendee::Delegated ) {
        incidence = icalToString( iCal );
        myself = findMyself( incidence, receiver );
        Attendee *newMyself = setStatusOnMyself( incidence, myself, status, receiver );
        newMyself->setDelegate( delegateString );
        QString name, email;
        KPIM::getNameAndMail( delegateString, name, email );
        Attendee *delegate = new Attendee( name, email, true );
        delegate->setDelegator( receiver );
        incidence->addAttendee( delegate );
        ok = mail( incidence, callback, Scheduler::Request, delegateString );
      }
      return ok;
    }

    bool handleIgnore( const QString&, KMail::Callback& c ) const
    {
      // simply move the message to trash
      ( new KMDeleteMsgCommand( c.getMsg()->getMsgSerNum() ) )->start();
      return true;
    }

    bool handleClick( KMail::Interface::BodyPart *part,
                      const QString &path, KMail::Callback& c ) const
    {
      QString iCal = part->asText();
      bool result = false;
      if ( path == "accept" )
        result = handleInvitation( iCal, Attendee::Accepted, c );
      if ( path == "accept_conditionally" )
        result = handleInvitation( iCal, Attendee::Tentative, c );
      if ( path == "ignore" )
        result = handleIgnore( iCal, c );
      if ( path == "decline" )
        result = handleInvitation( iCal, Attendee::Declined, c );
      if ( path == "delegate" )
        result = handleInvitation( iCal, Attendee::Delegated, c );
      if ( path == "forward" )
        kdDebug() << k_funcinfo << "forwarding not yet implemented" << endl;
      if ( path == "reply" || path == "cancel" ) {
        // These should just be saved with their type as the dir
        if ( saveFile( "Receiver Not Searched", iCal, path ) ) {
          ( new KMDeleteMsgCommand( c.getMsg()->getMsgSerNum() ) )->start();
          result = true;
        }
      }
      if ( result )
        c.closeIfSecondaryWindow();
      return result;
    }

    bool handleContextMenuRequest( KMail::Interface::BodyPart *,
                                   const QString &,
                                   const QPoint & ) const
    {
      return false;
    }

    QString statusBarMessage( KMail::Interface::BodyPart *,
                              const QString &path ) const
    {
      if ( !path.isEmpty() ) {
        if ( path == "accept" )
          return i18n("Accept incidence");
        if ( path == "accept_conditionally" )
          return i18n( "Accept incidence conditionally" );
        if ( path == "ignore" )
          return i18n( "Throw mail away" );
        if ( path == "decline" )
          return i18n( "Decline incidence" );
        if ( path == "check_calendar" )
          return i18n("Check my calendar..." );
        if ( path == "reply" )
          return i18n( "Enter incidence into my calendar" );
        if ( path == "delegate" )
          return i18n( "Delegate incidence" );
        if ( path == "forward" )
          return i18n( "Forward incidence" );
        if ( path == "cancel" )
          return i18n( "Remove incidence from my calendar" );
      }

      return QString::null;
    }
};

class Plugin : public KMail::Interface::BodyPartFormatterPlugin
{
  public:
    const KMail::Interface::BodyPartFormatter *bodyPartFormatter( int idx ) const
    {
      if ( idx == 0 ) return new Formatter();
      else return 0;
    }

    const char *type( int idx ) const
    {
      if ( idx == 0 ) return "text";
      else return 0;
    }

    const char *subtype( int idx ) const
    {
      if ( idx == 0 ) return "calendar";
      else return 0;
    }

    const KMail::Interface::BodyPartURLHandler * urlHandler( int idx ) const
    {
      if ( idx == 0 ) return new UrlHandler();
      else return 0;
    }
};

}

extern "C"
KDE_EXPORT KMail::Interface::BodyPartFormatterPlugin *
libkmail_bodypartformatter_text_calendar_create_bodypart_formatter_plugin()
{
  KGlobal::locale()->insertCatalogue( "kmail_text_calendar_plugin" );
  return new Plugin();
}
<|endoftext|>


<commit_before>#ifndef AB_LEB128_HPP_
#define AB_LEB128_HPP_

#include <cstddef>
#include <cstdint>
#include <istream>

namespace Ab {

class ReaderError : public std::runtime_error {
public:
	using std::runtime_error::runtime_error;
};

class BadNumber : public ReaderError {
public:
	BadNumber() : ReaderError{"Could not decode number"} {}
};

struct ReaderInput {
	ReaderInput(std::istream& in) : in_{in}, offset_{0} {}

	ReaderInput(const ReaderInput& other) : ReaderInput{other.in_} {}

	auto get() -> std::uint8_t {
		std::uint8_t x = in_.get();
		offset_ += in_.gcount();
		return x;
	}

	auto read(char* buffer, std::streamsize bytes) -> void {
		in_.read(buffer, bytes);

		if (in_.gcount() != bytes)
			throw ReaderError("didn't read all the bytes like we were hoping");
		// TODO:

		offset_ += bytes;
	}

	auto offset() const -> std::size_t { return offset_; }

	auto stream() -> std::istream& { return in_; }

private:
	std::istream& in_;
	std::size_t offset_;
};

template <typename Integer, std::size_t bytes = sizeof(Integer)>
inline auto readNumber(ReaderInput& in) -> Integer {
	Integer result = 0;
	auto buffer    = (char*)&result;
	in.read(buffer, bytes);
	return result;
}

inline auto leb128(ReaderInput& in) -> std::int64_t {
	const std::uint8_t FLAG = 0b1000'0000;
	const std::uint8_t MASK = 0b0111'1111;
	const std::uint8_t SIGN = 0b0100'0000;

	std::uint64_t result = 0;
	std::size_t shift    = 0;
	std::uint8_t byte    = 0;

	do {
		if (shift > 63)
			throw BadNumber();

		byte = in.get();
		result |= std::uint64_t(byte & MASK) << shift;
		shift += 7;

	} while (byte & FLAG && (shift < 64) && !in.stream().eof());

	if (byte & SIGN) {
		result |= ~std::uint64_t(0) << shift;
	}

	return result;
}

inline auto leb128(std::istream& s) -> std::int64_t {
	ReaderInput in(s);
	return leb128(in);
}

/// Read a uleb128 from a buffer. Reads up to n characters
inline auto uleb128(ReaderInput& in) -> std::uint64_t {
	constexpr std::uint8_t FLAG = 0b1000'0000;
	constexpr std::uint8_t MASK = 0b0111'1111;

	std::uint64_t result = 0;
	std::size_t shift    = 0;
	std::uint8_t byte    = 0;

	do {
		if (shift > 63)
			throw BadNumber();

		byte = in.get();
		result |= std::uint64_t(byte & MASK) << shift;
		shift += 7;
	} while ((byte & FLAG) != 0 && shift < 64 && !in.stream().eof());

	return result;
}

inline auto uleb128(std::istream& s) -> std::int64_t {
	ReaderInput in(s);
	return uleb128(in);
}

inline auto varuint32(ReaderInput& in) -> std::uint64_t { return uleb128(in); }

}  // namespace Ab

#endif  // AB_LEB128_HPP_
<commit_msg>Switch from trailing return types to leading return types<commit_after>#ifndef AB_LEB128_HPP_
#define AB_LEB128_HPP_

#include <cstddef>
#include <cstdint>
#include <istream>

namespace Ab {

class ReaderError : public std::runtime_error {
public:
	using std::runtime_error::runtime_error;
};

class BadNumber : public ReaderError {
public:
	BadNumber() : ReaderError{"Could not decode number"} {}
};

struct ReaderInput {
	ReaderInput(std::istream& in) : in_{in}, offset_{0} {}

	ReaderInput(const ReaderInput& other) : ReaderInput{other.in_} {}

	std::uint8_t get() {
		std::uint8_t x = in_.get();
		offset_ += in_.gcount();
		return x;
	}

	void read(char* buffer, std::streamsize bytes) {
		in_.read(buffer, bytes);

		if (in_.gcount() != bytes)
			throw ReaderError("didn't read all the bytes like we were hoping");
		// TODO:

		offset_ += bytes;
	}

	std::size_t offset() const { return offset_; }

	std::istream& stream() const { return in_; }

private:
	std::istream& in_;
	std::size_t offset_;
};

template <typename Integer, std::size_t bytes = sizeof(Integer)>
Integer readNumber(ReaderInput& in) {
	Integer result = 0;
	auto buffer    = (char*)&result;
	in.read(buffer, bytes);
	return result;
}

inline std::int64_t leb128(ReaderInput& in) {
	const std::uint8_t FLAG = 0b1000'0000;
	const std::uint8_t MASK = 0b0111'1111;
	const std::uint8_t SIGN = 0b0100'0000;

	std::uint64_t result = 0;
	std::size_t shift    = 0;
	std::uint8_t byte    = 0;

	do {
		if (shift > 63)
			throw BadNumber();

		byte = in.get();
		result |= std::uint64_t(byte & MASK) << shift;
		shift += 7;

	} while (byte & FLAG && (shift < 64) && !in.stream().eof());

	if (byte & SIGN) {
		result |= ~std::uint64_t(0) << shift;
	}

	return result;
}

inline std::int64_t leb128(std::istream& s) {
	ReaderInput in(s);
	return leb128(in);
}

/// Read a uleb128 from a buffer. Reads up to n characters
inline std::uint64_t uleb128(ReaderInput& in) {
	constexpr std::uint8_t FLAG = 0b1000'0000;
	constexpr std::uint8_t MASK = 0b0111'1111;

	std::uint64_t result = 0;
	std::size_t shift    = 0;
	std::uint8_t byte    = 0;

	do {
		if (shift > 63)
			throw BadNumber();

		byte = in.get();
		result |= std::uint64_t(byte & MASK) << shift;
		shift += 7;
	} while ((byte & FLAG) != 0 && shift < 64 && !in.stream().eof());

	return result;
}

inline std::int64_t uleb128(std::istream& s) {
	ReaderInput in(s);
	return uleb128(in);
}

inline std::uint64_t varuint32(ReaderInput& in) { return uleb128(in); }

}  // namespace Ab

#endif  // AB_LEB128_HPP_
<|endoftext|>


<commit_before>#pragma once
//=========================================================================//
/*!	@file
	@brief	RX グループ・SCI/SPI I/O 制御 @n
			※現在、実装中で「未完」となっている。
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=========================================================================//
#include "common/renesas.hpp"
#include "common/vect.h"

/// F_PCLKB はボーレートパラメーター計算に必要で、設定が無いとエラーにします。
#ifndef F_PCLKB
#  error "sci_spi_io.hpp requires F_PCLKB to be defined"
#endif

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  SCI/SPI I/O 制御クラス
		@param[in]	SCI		SCI 型
		@param[in]	RBF		受信バッファクラス
		@param[in]	SBF		送信バッファクラス
		@param[in]	PSEL	ポート選択
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class SCI, class RBF, class SBF, port_map::option PSEL = port_map::option::FIRST>
	class sci_spi_io {

		static RBF	recv_;
		static SBF	send_;

		uint8_t		level_;

		// ※マルチタスクの場合適切な実装をする
		void sleep_() noexcept { asm("nop"); }

#if 0
		static INTERRUPT_FUNC void recv_task_()
		{
			bool err = false;
			if(SCI::SSR.ORER()) {	///< 受信オーバランエラー状態確認
				SCI::SSR.ORER = 0;	///< 受信オーバランエラークリア
				err = true;
			}
			///< フレーミングエラー/パリティエラー状態確認
			if(SCI::SSR() & (SCI::SSR.FER.b() | SCI::SSR.PER.b())) {
				// エラーフラグの消去
				SCI::SSR.FER = 0;
				SCI::SSR.PER = 0;
				err = true;
			}
			volatile uint8_t data = SCI::RDR();
			if(!err) {
				recv_.put(data);
			}
		}

		static INTERRUPT_FUNC void send_task_()
		{
#if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N)
			if(send_.length() > 0) {
				SCI::TDR = send_.get();
			}
			if(send_.length() == 0) {
				SCI::SCR.TIE = 0;
				send_stall_ = true;
			}
#else
			SCI::TDR = send_.get();
			if(send_.length() == 0) {
				SCI::SCR.TEIE = 0;
			}
#endif
		}

		void set_vector_(ICU::VECTOR rx_vec, ICU::VECTOR tx_vec) noexcept
		{
			if(level_) {
				set_interrupt_task(recv_task_, static_cast<uint32_t>(rx_vec));
				set_interrupt_task(send_task_, static_cast<uint32_t>(tx_vec));
			} else {
				set_interrupt_task(nullptr, static_cast<uint32_t>(rx_vec));
				set_interrupt_task(nullptr, static_cast<uint32_t>(tx_vec));
			}
		}

		void set_intr_() noexcept
		{
#if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N)
			set_vector_(SCI::get_rx_vec(), SCI::get_tx_vec());
#else
			set_vector_(SCI::get_rx_vec(), SCI::get_te_vec());
#endif
			icu_mgr::set_level(SCI::get_peripheral(), level_);
		}
#endif

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
		*/
		//-----------------------------------------------------------------//
		sci_spi_io() noexcept : level_(0) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  簡易 SPI を有効にする
			@param[in]	bps	ビットレート
			@param[in]	level	割り込みレベル（０の場合ポーリング）
			@return エラーなら「false」
		*/
		//-----------------------------------------------------------------//
		bool start(uint32_t bps, uint8_t level = 0) noexcept
		{
			level_ = level;

			power_cfg::turn(SCI::get_peripheral());

			SCI::SCR = 0x00;			// TE, RE disable.

			uint32_t brr = F_PCLKB / bps / 2;
			if(brr & 1) { brr >>= 1; ++brr; }
			else { brr >>= 1; }
			uint8_t cks = 0;
			while(brr > 256) {
				brr >>= 2;
				++cks;
			}
			if(cks > 3 || brr > 256) return false;

			set_intr_();

			// LSB(0), MSB(1) first
			SCI::SCMR.SDIR = 1;

			SCI::SIMR1.IICM = 0;
			SCI::SMR = cks | SCI::SMR.CM.b();
			SCI::SPMR.SSE = 0;		///< SS 端子制御しない「０」

			if(master) {
				SCI::SPMR.MSS = 0;
			} else {
				SCI::SPMR.MSS = 1;
			}

			// クロックタイミング種別選択
			SCI::SPMR.CKPOL = 0;
			SCI::SPMR.CKPH  = 0;

			if(brr) --brr;
			SCI::BRR = static_cast<uint8_t>(brr);

			uint8_t scr = 0;
			if(master) {
				scr = SCI::SCR.CKE.b(0b01);
			} else {
				scr = SCI::SCR.CKE.b(0b10);
			}

			if(level_) {
				SCI::SCR = SCI::SCR.RIE.b() | SCI::SCR.TE.b() | SCI::SCR.RE.b() | scr;
			} else {
				SCI::SCR = SCI::SCR.TE.b() | SCI::SCR.RE.b() | scr;
			}

			return true;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  送受信（SPI）
			@param[in]	ch	送信データ
			@return	受信データ
		*/
		//-----------------------------------------------------------------//
		inline uint8_t xchg(uint8_t ch = 0xff) noexcept
		{
			if(level_) {
				return 0;
			} else {
				SCI::TDR = ch;
				while(recv_length() == 0) sleep_();
				return SCI::RDR();
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  ブロック送信（SPI）
			@param[in]	src	送信ソース
			@param[in]	siz	送信サイズ
		*/
		//-----------------------------------------------------------------//
		void send(const void* src, uint32_t siz) noexcept
		{
			const uint8_t* p = static_cast<const uint8_t*>(src);
			auto end = p + siz;
			while(p < end) {
				xchg(*p);
				++p;
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  ブロック受信（SPI）
			@param[out]	dst	受信先
			@param[in]	siz	受信サイズ
		*/
		//-----------------------------------------------------------------//
		void recv(void* dst, uint32_t siz) noexcept
		{
			uint8_t* p = static_cast<uint8_t*>(dst);
			auto end = p + siz;
			while(p < end) {
				*p = xchg();
				++p;
			}
		}
	};

	// テンプレート関数、実態の定義
	template<class SCI, class RBF, class SBF, port_map::option PSEL>
		RBF sci_spi_io<SCI, RBF, SBF, PSEL>::recv_;
	template<class SCI, class RBF, class SBF, port_map::option PSEL>
		SBF sci_spi_io<SCI, RBF, SBF, PSEL>::send_;
}
<commit_msg>update: set_task API for icu_mgr class<commit_after>#pragma once
//=========================================================================//
/*!	@file
	@brief	RX グループ・SCI/SPI I/O 制御 @n
			※現在、実装中で「未完」となっている。
    @author 平松邦仁 (hira@rvf-rc45.net)
	@copyright	Copyright (C) 2018 Kunihito Hiramatsu @n
				Released under the MIT license @n
				https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=========================================================================//
#include "common/renesas.hpp"
#include "common/vect.h"

/// F_PCLKB はボーレートパラメーター計算に必要で、設定が無いとエラーにします。
#ifndef F_PCLKB
#  error "sci_spi_io.hpp requires F_PCLKB to be defined"
#endif

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  SCI/SPI I/O 制御クラス
		@param[in]	SCI		SCI 型
		@param[in]	RBF		受信バッファクラス
		@param[in]	SBF		送信バッファクラス
		@param[in]	PSEL	ポート選択
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <class SCI, class RBF, class SBF, port_map::option PSEL = port_map::option::FIRST>
	class sci_spi_io {

		static RBF	recv_;
		static SBF	send_;

		uint8_t		level_;

		// ※マルチタスクの場合適切な実装をする
		void sleep_() noexcept { asm("nop"); }

#if 0
		static INTERRUPT_FUNC void recv_task_()
		{
			bool err = false;
			if(SCI::SSR.ORER()) {	///< 受信オーバランエラー状態確認
				SCI::SSR.ORER = 0;	///< 受信オーバランエラークリア
				err = true;
			}
			///< フレーミングエラー/パリティエラー状態確認
			if(SCI::SSR() & (SCI::SSR.FER.b() | SCI::SSR.PER.b())) {
				// エラーフラグの消去
				SCI::SSR.FER = 0;
				SCI::SSR.PER = 0;
				err = true;
			}
			volatile uint8_t data = SCI::RDR();
			if(!err) {
				recv_.put(data);
			}
		}

		static INTERRUPT_FUNC void send_task_()
		{
#if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N)
			if(send_.length() > 0) {
				SCI::TDR = send_.get();
			}
			if(send_.length() == 0) {
				SCI::SCR.TIE = 0;
				send_stall_ = true;
			}
#else
			SCI::TDR = send_.get();
			if(send_.length() == 0) {
				SCI::SCR.TEIE = 0;
			}
#endif
		}

		void set_vector_(ICU::VECTOR rx_vec, ICU::VECTOR tx_vec) noexcept
		{
			if(level_) {
				icu_mgr::set_task(rx_vec, recv_task_);
				icu_mgr::set_task(tx_vec, send_task_);
			} else {
				icu_mgr::set_task(rx_vec, nullptr);
				icu_mgr::set_task(tx_vec, nullptr);
			}
		}

		void set_intr_() noexcept
		{
#if defined(SIG_RX64M) || defined(SIG_RX71M) || defined(SIG_RX65N)
			set_vector_(SCI::get_rx_vec(), SCI::get_tx_vec());
#else
			set_vector_(SCI::get_rx_vec(), SCI::get_te_vec());
#endif
			icu_mgr::set_level(SCI::get_peripheral(), level_);
		}
#endif

	public:
		//-----------------------------------------------------------------//
		/*!
			@brief  コンストラクター
		*/
		//-----------------------------------------------------------------//
		sci_spi_io() noexcept : level_(0) { }

		//-----------------------------------------------------------------//
		/*!
			@brief  簡易 SPI を有効にする
			@param[in]	bps	ビットレート
			@param[in]	level	割り込みレベル（０の場合ポーリング）
			@return エラーなら「false」
		*/
		//-----------------------------------------------------------------//
		bool start(uint32_t bps, uint8_t level = 0) noexcept
		{
			level_ = level;

			power_cfg::turn(SCI::get_peripheral());

			SCI::SCR = 0x00;			// TE, RE disable.

			uint32_t brr = F_PCLKB / bps / 2;
			if(brr & 1) { brr >>= 1; ++brr; }
			else { brr >>= 1; }
			uint8_t cks = 0;
			while(brr > 256) {
				brr >>= 2;
				++cks;
			}
			if(cks > 3 || brr > 256) return false;

			set_intr_();

			// LSB(0), MSB(1) first
			SCI::SCMR.SDIR = 1;

			SCI::SIMR1.IICM = 0;
			SCI::SMR = cks | SCI::SMR.CM.b();
			SCI::SPMR.SSE = 0;		///< SS 端子制御しない「０」

			if(master) {
				SCI::SPMR.MSS = 0;
			} else {
				SCI::SPMR.MSS = 1;
			}

			// クロックタイミング種別選択
			SCI::SPMR.CKPOL = 0;
			SCI::SPMR.CKPH  = 0;

			if(brr) --brr;
			SCI::BRR = static_cast<uint8_t>(brr);

			uint8_t scr = 0;
			if(master) {
				scr = SCI::SCR.CKE.b(0b01);
			} else {
				scr = SCI::SCR.CKE.b(0b10);
			}

			if(level_) {
				SCI::SCR = SCI::SCR.RIE.b() | SCI::SCR.TE.b() | SCI::SCR.RE.b() | scr;
			} else {
				SCI::SCR = SCI::SCR.TE.b() | SCI::SCR.RE.b() | scr;
			}

			return true;
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  送受信（SPI）
			@param[in]	ch	送信データ
			@return	受信データ
		*/
		//-----------------------------------------------------------------//
		inline uint8_t xchg(uint8_t ch = 0xff) noexcept
		{
			if(level_) {
				return 0;
			} else {
				SCI::TDR = ch;
				while(recv_length() == 0) sleep_();
				return SCI::RDR();
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  ブロック送信（SPI）
			@param[in]	src	送信ソース
			@param[in]	siz	送信サイズ
		*/
		//-----------------------------------------------------------------//
		void send(const void* src, uint32_t siz) noexcept
		{
			const uint8_t* p = static_cast<const uint8_t*>(src);
			auto end = p + siz;
			while(p < end) {
				xchg(*p);
				++p;
			}
		}

		//-----------------------------------------------------------------//
		/*!
			@brief  ブロック受信（SPI）
			@param[out]	dst	受信先
			@param[in]	siz	受信サイズ
		*/
		//-----------------------------------------------------------------//
		void recv(void* dst, uint32_t siz) noexcept
		{
			uint8_t* p = static_cast<uint8_t*>(dst);
			auto end = p + siz;
			while(p < end) {
				*p = xchg();
				++p;
			}
		}
	};

	// テンプレート関数、実態の定義
	template<class SCI, class RBF, class SBF, port_map::option PSEL>
		RBF sci_spi_io<SCI, RBF, SBF, PSEL>::recv_;
	template<class SCI, class RBF, class SBF, port_map::option PSEL>
		SBF sci_spi_io<SCI, RBF, SBF, PSEL>::send_;
}
<|endoftext|>


<commit_before>// TransformTools.cpp
/*
 * Copyright (c) 2009, Dan Heeks
 * This program is released under the BSD license. See the file COPYING for
 * details.
 */

#include "stdafx.h"
#include "TransformTools.h"
#include "MarkedList.h"
#include "HLine.h"
#include "HILine.h"

static double from[3];
static double centre[3];

static void on_move_translate(const double* to)
{
	wxGetApp().m_drag_matrix.SetTranslationPart(gp_Vec(make_point(from), make_point(to)));
	wxGetApp().Repaint(true);
}

//static
void TransformTools::RemoveUncopyable()
{
	std::list<HeeksObj*> uncopyable_objects;
	for(std::list<HeeksObj*>::const_iterator It = wxGetApp().m_marked_list->list().begin(); It != wxGetApp().m_marked_list->list().end(); It++)
	{
		HeeksObj* object = *It;
		if(!object->CanBeCopied())uncopyable_objects.push_back(object);
	}
	if(uncopyable_objects.size() > 0)wxGetApp().m_marked_list->Remove(uncopyable_objects, true);
}

//static
void TransformTools::Translate(bool copy)
{
	// pick items
	if(wxGetApp().m_marked_list->size() == 0){
		wxGetApp().PickObjects(_("Pick objects to move"));
	}
	if(wxGetApp().m_marked_list->size() == 0)return;

	// get number of copies
	int ncopies = 1;
	if(copy)
	{
		// check for uncopyable objects
		RemoveUncopyable();
		if(wxGetApp().m_marked_list->size() == 0)return;

		// input "number of copies"
		double number_of_copies = 1.0;
		wxGetApp().InputDouble(_("Enter number of copies"), _("number of copies"), number_of_copies);
		ncopies = (int)(number_of_copies + 0.5);
		if(ncopies < 1)return;
	}

	// clear the selection
	std::list<HeeksObj *> selected_items = wxGetApp().m_marked_list->list();
	wxGetApp().m_marked_list->Clear(true);

	// pick "from" position
	if(!wxGetApp().PickPosition(_("Click position to move from"), from))return;

	// pick "to" position
	wxGetApp().CreateTransformGLList(selected_items, false);
	wxGetApp().m_drag_matrix = gp_Trsf();
	if(!copy)
	{
		for(std::list<HeeksObj*>::const_iterator It = selected_items.begin(); It != selected_items.end(); It++){
			HeeksObj* object = *It;
			if(object->m_visible)wxGetApp().m_hidden_for_drag.push_back(object);
			object->m_visible = false;
		}
	}
	double to[3];
	wxGetApp().PickPosition(_("Click position to move to"), to, on_move_translate);
	if(!copy)
	{
		for(std::list<HeeksObj*>::iterator It = wxGetApp().m_hidden_for_drag.begin(); It != wxGetApp().m_hidden_for_drag.end(); It++)
		{
			HeeksObj* object = *It;
			object->m_visible = true;
		}
		wxGetApp().m_hidden_for_drag.clear();
	}
	wxGetApp().DestroyTransformGLList();

	// transform the objects
	if(copy)
	{
		for(int i = 0; i<ncopies; i++)
		{
			gp_Trsf mat;
			mat.SetTranslationPart(make_vector(make_point(from), make_point(to)) * (i + 1));
			double m[16];
			extract(mat, m);
			for(std::list<HeeksObj*>::iterator It = selected_items.begin(); It != selected_items.end(); It++)
			{
				HeeksObj* object = *It;
				HeeksObj* new_object = object->MakeACopy();
				object->Owner()->Add(new_object, NULL);
				new_object->ModifyByMatrix(m);
			}
		}
		wxGetApp().m_marked_list->Clear(true);
	}
	else
	{
		gp_Trsf mat;
		mat.SetTranslationPart(make_vector(make_point(from), make_point(to)));
		double m[16];
		extract(mat, m);
		wxGetApp().Transform(selected_items, m);
	}
}

//static
void TransformTools::Rotate(bool copy, bool allow3DRotation)
{
	//rotation axis - Z axis by default
	gp_Dir axis_Dir = gp_Dir(0,0,1);
	gp_Pnt line_Pos = gp_Pnt(0,0,0);

	// pick items
	if(wxGetApp().m_marked_list->size() == 0){
		wxGetApp().PickObjects(_("Pick objects to rotate"));
	}
	if(wxGetApp().m_marked_list->size() == 0)return;

	// get number of copies
	int ncopies = 1;
	if(copy)
	{
		// check for uncopyable objects
		RemoveUncopyable();
		if(wxGetApp().m_marked_list->size() == 0)return;

		// input "number of copies"
		double number_of_copies = 1.0;
		wxGetApp().InputDouble(_("Enter number of copies"), _("number of copies"), number_of_copies);
		ncopies = (int)(number_of_copies + 0.5);
		if(ncopies < 1)return;
	}

	// clear the selection
	std::list<HeeksObj *> selected_items = wxGetApp().m_marked_list->list();
	wxGetApp().m_marked_list->Clear(true);

	if(allow3DRotation)
	{
		// pick a line to use as rotation axis
		bool line_found = false;
		gp_Lin line;
		int save_filter = wxGetApp().m_marked_list->m_filter;
		wxGetApp().PickObjects(_("Pick line for rotation axis"), MARKING_FILTER_LINE | MARKING_FILTER_ILINE, true);
		wxGetApp().m_marked_list->m_filter = save_filter;
		for(std::list<HeeksObj *>::const_iterator It = wxGetApp().m_marked_list->list().begin(); It != wxGetApp().m_marked_list->list().end(); It++)
		{
			HeeksObj* object = *It;
			if(object->GetType() == LineType)
			{
				line = ((HLine*)object)->GetLine();
				line_found = true;
			}
			else if(object->GetType() == ILineType)
			{
				line = ((HILine*)object)->GetLine();
				line_found = true;
			}
		}
		if(!line_found)return;
		axis_Dir=line.Direction();
		line_Pos= line.Location();
	}
	else
	{
		// pick "centre" position
		if(!wxGetApp().PickPosition(_("Click centre position to rotate about"), centre))return;
		line_Pos.SetXYZ(gp_XYZ(centre[0],centre[1],centre[2]));
	}

	// enter angle
	double angle = 45.0;
	if(!wxGetApp().InputDouble(_("Enter angle to rotate by"), _("angle"), angle))return;

	// transform the objects
	if(copy)
	{
		for(int i = 0; i<ncopies; i++)
		{
			gp_Trsf mat;
			mat.SetRotation(gp_Ax1(line_Pos, axis_Dir), angle * Pi/180 * (i+1));
			double m[16];
			extract(mat, m);
			for(std::list<HeeksObj*>::iterator It = selected_items.begin(); It != selected_items.end(); It++)
			{
				HeeksObj* object = *It;
				HeeksObj* new_object = object->MakeACopy();
				object->Owner()->Add(new_object, NULL);
				object->ModifyByMatrix(m);
			}
		}
		wxGetApp().m_marked_list->Clear(true);
	}
	else
	{
		gp_Trsf mat;
		mat.SetRotation(gp_Ax1(line_Pos, axis_Dir), angle * Pi/180);
		double m[16];
		extract(mat, m);
		wxGetApp().Transform(selected_items, m);
	}
}

//static
void TransformTools::Mirror(bool copy)
{
	// pick items
	if(wxGetApp().m_marked_list->size() == 0){
		wxGetApp().PickObjects(_("Pick objects to mirror"));
	}
	if(wxGetApp().m_marked_list->size() == 0)return;

	if(copy)
	{
		// check for uncopyable objects
		RemoveUncopyable();
		if(wxGetApp().m_marked_list->size() == 0)return;

		// input "number of copies"
		double number_of_copies = 1.0;
		wxGetApp().InputDouble(_("Enter number of copies"), _("number of copies"), number_of_copies);
		int ncopies = (int)(number_of_copies + 0.5);
		if(ncopies < 1)return;
	}

	// clear the selection
	std::list<HeeksObj *> selected_items = wxGetApp().m_marked_list->list();
	wxGetApp().m_marked_list->Clear(true);

	// pick a line to mirror about
	bool line_found = false;
	gp_Lin line;
	int save_filter = wxGetApp().m_marked_list->m_filter;
	wxGetApp().PickObjects(_("Pick line to mirror about"), MARKING_FILTER_LINE | MARKING_FILTER_ILINE, true);
	wxGetApp().m_marked_list->m_filter = save_filter;
	for(std::list<HeeksObj *>::const_iterator It = wxGetApp().m_marked_list->list().begin(); It != wxGetApp().m_marked_list->list().end(); It++)
	{
		HeeksObj* object = *It;
		if(object->GetType() == LineType)
		{
			line = ((HLine*)object)->GetLine();
			line_found = true;
		}
		else if(object->GetType() == ILineType)
		{
			line = ((HILine*)object)->GetLine();
			line_found = true;
		}
	}
	if(!line_found)return;

	// transform the objects
	gp_Trsf mat;
	mat.SetMirror(gp_Ax1(line.Location(), line.Direction()));
	double m[16];
	extract(mat, m);

	if(copy)
	{
		for(std::list<HeeksObj*>::iterator It = selected_items.begin(); It != selected_items.end(); It++)
		{
			HeeksObj* object = *It;
			HeeksObj* new_object = object->MakeACopy();
			object->Owner()->Add(new_object, NULL);
			new_object->ModifyByMatrix(m);
		}
		wxGetApp().m_marked_list->Clear(true);
	}
	else
	{
		wxGetApp().Transform(selected_items, m);
	}
}

void TransformTools::Scale(bool copy)
{
	// pick items
	if(wxGetApp().m_marked_list->size() == 0){
		wxGetApp().PickObjects(_("Pick objects to scale"));
	}
	if(wxGetApp().m_marked_list->size() == 0)return;

	// get number of copies
	int ncopies = 1;
	if(copy)
	{
		// check for uncopyable objects
		RemoveUncopyable();
		if(wxGetApp().m_marked_list->size() == 0)return;

		// input "number of copies"
		double number_of_copies = 1.0;
		wxGetApp().InputDouble(_("Enter number of copies"), _("number of copies"), number_of_copies);
		ncopies = (int)(number_of_copies + 0.5);
		if(ncopies < 1)return;
	}

	// clear the selection
	std::list<HeeksObj *> selected_items = wxGetApp().m_marked_list->list();
	wxGetApp().m_marked_list->Clear(true);

	// pick "centre" position
	if(!wxGetApp().PickPosition(_("Click centre position to scale about"), centre))return;

	// enter scale factor
	double scale = 2.0;
	if(!wxGetApp().InputDouble(_("Enter scale factor"), _("scale factor"), scale))return;

	// transform the objects
	if(copy)
	{
		for(int i = 0; i<ncopies; i++)
		{
			gp_Trsf mat;
			mat.SetScale(make_point(centre), scale * (i+1));
			double m[16];
			extract(mat, m);
			for(std::list<HeeksObj*>::iterator It = selected_items.begin(); It != selected_items.end(); It++)
			{
				HeeksObj* object = *It;
				HeeksObj* new_object = object->MakeACopy();
				object->Owner()->Add(new_object, NULL);
				new_object->ModifyByMatrix(m);
			}
		}
		wxGetApp().m_marked_list->Clear(true);
	}
	else
	{
		gp_Trsf mat;
		mat.SetScale(make_point(centre), scale);
		double m[16];
		extract(mat, m);
		wxGetApp().Transform(selected_items, m);
	}
}
<commit_msg>Fixed problem where multiple copies of a rotated object were not all being rotated from the same reference angle.  (there was a cumulative error)<commit_after>// TransformTools.cpp
/*
 * Copyright (c) 2009, Dan Heeks
 * This program is released under the BSD license. See the file COPYING for
 * details.
 */

#include "stdafx.h"
#include "TransformTools.h"
#include "MarkedList.h"
#include "HLine.h"
#include "HILine.h"

static double from[3];
static double centre[3];

static void on_move_translate(const double* to)
{
	wxGetApp().m_drag_matrix.SetTranslationPart(gp_Vec(make_point(from), make_point(to)));
	wxGetApp().Repaint(true);
}

//static
void TransformTools::RemoveUncopyable()
{
	std::list<HeeksObj*> uncopyable_objects;
	for(std::list<HeeksObj*>::const_iterator It = wxGetApp().m_marked_list->list().begin(); It != wxGetApp().m_marked_list->list().end(); It++)
	{
		HeeksObj* object = *It;
		if(!object->CanBeCopied())uncopyable_objects.push_back(object);
	}
	if(uncopyable_objects.size() > 0)wxGetApp().m_marked_list->Remove(uncopyable_objects, true);
}

//static
void TransformTools::Translate(bool copy)
{
	// pick items
	if(wxGetApp().m_marked_list->size() == 0){
		wxGetApp().PickObjects(_("Pick objects to move"));
	}
	if(wxGetApp().m_marked_list->size() == 0)return;

	// get number of copies
	int ncopies = 1;
	if(copy)
	{
		// check for uncopyable objects
		RemoveUncopyable();
		if(wxGetApp().m_marked_list->size() == 0)return;

		// input "number of copies"
		double number_of_copies = 1.0;
		wxGetApp().InputDouble(_("Enter number of copies"), _("number of copies"), number_of_copies);
		ncopies = (int)(number_of_copies + 0.5);
		if(ncopies < 1)return;
	}

	// clear the selection
	std::list<HeeksObj *> selected_items = wxGetApp().m_marked_list->list();
	wxGetApp().m_marked_list->Clear(true);

	// pick "from" position
	if(!wxGetApp().PickPosition(_("Click position to move from"), from))return;

	// pick "to" position
	wxGetApp().CreateTransformGLList(selected_items, false);
	wxGetApp().m_drag_matrix = gp_Trsf();
	if(!copy)
	{
		for(std::list<HeeksObj*>::const_iterator It = selected_items.begin(); It != selected_items.end(); It++){
			HeeksObj* object = *It;
			if(object->m_visible)wxGetApp().m_hidden_for_drag.push_back(object);
			object->m_visible = false;
		}
	}
	double to[3];
	wxGetApp().PickPosition(_("Click position to move to"), to, on_move_translate);
	if(!copy)
	{
		for(std::list<HeeksObj*>::iterator It = wxGetApp().m_hidden_for_drag.begin(); It != wxGetApp().m_hidden_for_drag.end(); It++)
		{
			HeeksObj* object = *It;
			object->m_visible = true;
		}
		wxGetApp().m_hidden_for_drag.clear();
	}
	wxGetApp().DestroyTransformGLList();

	// transform the objects
	if(copy)
	{
		for(int i = 0; i<ncopies; i++)
		{
			gp_Trsf mat;
			mat.SetTranslationPart(make_vector(make_point(from), make_point(to)) * (i + 1));
			double m[16];
			extract(mat, m);
			for(std::list<HeeksObj*>::iterator It = selected_items.begin(); It != selected_items.end(); It++)
			{
				HeeksObj* object = *It;
				HeeksObj* new_object = object->MakeACopy();
				object->Owner()->Add(new_object, NULL);
				new_object->ModifyByMatrix(m);
			}
		}
		wxGetApp().m_marked_list->Clear(true);
	}
	else
	{
		gp_Trsf mat;
		mat.SetTranslationPart(make_vector(make_point(from), make_point(to)));
		double m[16];
		extract(mat, m);
		wxGetApp().Transform(selected_items, m);
	}
}

//static
void TransformTools::Rotate(bool copy, bool allow3DRotation)
{
	//rotation axis - Z axis by default
	gp_Dir axis_Dir = gp_Dir(0,0,1);
	gp_Pnt line_Pos = gp_Pnt(0,0,0);

	// pick items
	if(wxGetApp().m_marked_list->size() == 0){
		wxGetApp().PickObjects(_("Pick objects to rotate"));
	}
	if(wxGetApp().m_marked_list->size() == 0)return;

	// get number of copies
	int ncopies = 1;
	if(copy)
	{
		// check for uncopyable objects
		RemoveUncopyable();
		if(wxGetApp().m_marked_list->size() == 0)return;

		// input "number of copies"
		double number_of_copies = 1.0;
		wxGetApp().InputDouble(_("Enter number of copies"), _("number of copies"), number_of_copies);
		ncopies = (int)(number_of_copies + 0.5);
		if(ncopies < 1)return;
	}

	// clear the selection
	std::list<HeeksObj *> selected_items = wxGetApp().m_marked_list->list();
	wxGetApp().m_marked_list->Clear(true);

	if(allow3DRotation)
	{
		// pick a line to use as rotation axis
		bool line_found = false;
		gp_Lin line;
		int save_filter = wxGetApp().m_marked_list->m_filter;
		wxGetApp().PickObjects(_("Pick line for rotation axis"), MARKING_FILTER_LINE | MARKING_FILTER_ILINE, true);
		wxGetApp().m_marked_list->m_filter = save_filter;
		for(std::list<HeeksObj *>::const_iterator It = wxGetApp().m_marked_list->list().begin(); It != wxGetApp().m_marked_list->list().end(); It++)
		{
			HeeksObj* object = *It;
			if(object->GetType() == LineType)
			{
				line = ((HLine*)object)->GetLine();
				line_found = true;
			}
			else if(object->GetType() == ILineType)
			{
				line = ((HILine*)object)->GetLine();
				line_found = true;
			}
		}
		if(!line_found)return;
		axis_Dir=line.Direction();
		line_Pos= line.Location();
	}
	else
	{
		// pick "centre" position
		if(!wxGetApp().PickPosition(_("Click centre position to rotate about"), centre))return;
		line_Pos.SetXYZ(gp_XYZ(centre[0],centre[1],centre[2]));
	}

	// enter angle
	double angle = 45.0;
	if(!wxGetApp().InputDouble(_("Enter angle to rotate by"), _("angle"), angle))return;

	// transform the objects
	if(copy)
	{
		for(int i = 0; i<ncopies; i++)
		{
			gp_Trsf mat;
			mat.SetRotation(gp_Ax1(line_Pos, axis_Dir), angle * Pi/180 * (i+1));
			double m[16];
			extract(mat, m);
			for(std::list<HeeksObj*>::iterator It = selected_items.begin(); It != selected_items.end(); It++)
			{
				HeeksObj* object = *It;
				HeeksObj* new_object = object->MakeACopy();
				new_object->ModifyByMatrix(m);              // Rotate the duplicate object.
				object->Owner()->Add(new_object, NULL);     // And add it to this object's owner
			}
		}
		wxGetApp().m_marked_list->Clear(true);
	}
	else
	{
		gp_Trsf mat;
		mat.SetRotation(gp_Ax1(line_Pos, axis_Dir), angle * Pi/180);
		double m[16];
		extract(mat, m);
		wxGetApp().Transform(selected_items, m);
	}
}

//static
void TransformTools::Mirror(bool copy)
{
	// pick items
	if(wxGetApp().m_marked_list->size() == 0){
		wxGetApp().PickObjects(_("Pick objects to mirror"));
	}
	if(wxGetApp().m_marked_list->size() == 0)return;

	if(copy)
	{
		// check for uncopyable objects
		RemoveUncopyable();
		if(wxGetApp().m_marked_list->size() == 0)return;

		// input "number of copies"
		double number_of_copies = 1.0;
		wxGetApp().InputDouble(_("Enter number of copies"), _("number of copies"), number_of_copies);
		int ncopies = (int)(number_of_copies + 0.5);
		if(ncopies < 1)return;
	}

	// clear the selection
	std::list<HeeksObj *> selected_items = wxGetApp().m_marked_list->list();
	wxGetApp().m_marked_list->Clear(true);

	// pick a line to mirror about
	bool line_found = false;
	gp_Lin line;
	int save_filter = wxGetApp().m_marked_list->m_filter;
	wxGetApp().PickObjects(_("Pick line to mirror about"), MARKING_FILTER_LINE | MARKING_FILTER_ILINE, true);
	wxGetApp().m_marked_list->m_filter = save_filter;
	for(std::list<HeeksObj *>::const_iterator It = wxGetApp().m_marked_list->list().begin(); It != wxGetApp().m_marked_list->list().end(); It++)
	{
		HeeksObj* object = *It;
		if(object->GetType() == LineType)
		{
			line = ((HLine*)object)->GetLine();
			line_found = true;
		}
		else if(object->GetType() == ILineType)
		{
			line = ((HILine*)object)->GetLine();
			line_found = true;
		}
	}
	if(!line_found)return;

	// transform the objects
	gp_Trsf mat;
	mat.SetMirror(gp_Ax1(line.Location(), line.Direction()));
	double m[16];
	extract(mat, m);

	if(copy)
	{
		for(std::list<HeeksObj*>::iterator It = selected_items.begin(); It != selected_items.end(); It++)
		{
			HeeksObj* object = *It;
			HeeksObj* new_object = object->MakeACopy();
			object->Owner()->Add(new_object, NULL);
			new_object->ModifyByMatrix(m);
		}
		wxGetApp().m_marked_list->Clear(true);
	}
	else
	{
		wxGetApp().Transform(selected_items, m);
	}
}

void TransformTools::Scale(bool copy)
{
	// pick items
	if(wxGetApp().m_marked_list->size() == 0){
		wxGetApp().PickObjects(_("Pick objects to scale"));
	}
	if(wxGetApp().m_marked_list->size() == 0)return;

	// get number of copies
	int ncopies = 1;
	if(copy)
	{
		// check for uncopyable objects
		RemoveUncopyable();
		if(wxGetApp().m_marked_list->size() == 0)return;

		// input "number of copies"
		double number_of_copies = 1.0;
		wxGetApp().InputDouble(_("Enter number of copies"), _("number of copies"), number_of_copies);
		ncopies = (int)(number_of_copies + 0.5);
		if(ncopies < 1)return;
	}

	// clear the selection
	std::list<HeeksObj *> selected_items = wxGetApp().m_marked_list->list();
	wxGetApp().m_marked_list->Clear(true);

	// pick "centre" position
	if(!wxGetApp().PickPosition(_("Click centre position to scale about"), centre))return;

	// enter scale factor
	double scale = 2.0;
	if(!wxGetApp().InputDouble(_("Enter scale factor"), _("scale factor"), scale))return;

	// transform the objects
	if(copy)
	{
		for(int i = 0; i<ncopies; i++)
		{
			gp_Trsf mat;
			mat.SetScale(make_point(centre), scale * (i+1));
			double m[16];
			extract(mat, m);
			for(std::list<HeeksObj*>::iterator It = selected_items.begin(); It != selected_items.end(); It++)
			{
				HeeksObj* object = *It;
				HeeksObj* new_object = object->MakeACopy();
				object->Owner()->Add(new_object, NULL);
				new_object->ModifyByMatrix(m);
			}
		}
		wxGetApp().m_marked_list->Clear(true);
	}
	else
	{
		gp_Trsf mat;
		mat.SetScale(make_point(centre), scale);
		double m[16];
		extract(mat, m);
		wxGetApp().Transform(selected_items, m);
	}
}
<|endoftext|>


<commit_before>// -*- coding: us-ascii-unix -*-
// Copyright 2012 Lukas Kemmer
//
// Licensed under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You
// may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.

#ifndef FAINT_PY_INCLUDE_HH
#define FAINT_PY_INCLUDE_HH
#include "util/dumb-ptr.hh"

#ifdef _WIN32
// pymath.h:s round conflicts with math.h round (last checked with
// Python 3.4, VC2013).
#define HAVE_ROUND

#pragma warning(push)
// Warnings emitted by Python header since 3.4
#pragma warning(disable:4510) // default constructor could not be generated
#pragma warning(disable:4512) // 'class' : assignment operator could not be generated
#pragma warning(disable:4610) // 'class' can never be instantiated - user-defined constructor required
#endif

// On Windows, debug python (python##_d.lib) would be linked if _DEBUG
// is defined temporarily undefine to allow linking release Python
// with a debug build of Faint.
#ifdef _DEBUG
#define FAINT_UNDEFFED_DEBUG
#undef _DEBUG
#endif

#include <Python.h>

#ifdef _WIN32
#pragma warning(pop)
#endif
// Redefine _DEBUG
#ifdef  FAINT_UNDEFFED_DEBUG
#define _DEBUG
#undef FAINT_UNDEFFED_DEBUG
#endif

namespace faint{

// Custom variant of Py_XDECREF, to avoid visual studio warning
// C4127: conditional expression is constant
void py_xdecref(PyObject*);

struct Decreffer{
  void operator()(PyObject* obj){
    py_xdecref(obj);
  }
};

template<typename T>
struct CastDecreffer{
  void operator()(T* obj){
    py_xdecref((PyObject*)obj);
  }
};

dumb_ptr<PyObject> borrowed(PyObject*);

// Pointer to PyObject* which decrements the objects reference count
// when it goes out of scope.
using scoped_ref = std::unique_ptr<PyObject, Decreffer>;

// Pointer to specific types (which must be PyObject*:s)
//
template<typename T>
using typed_scoped_ref = std::unique_ptr<T, CastDecreffer<T>>;

// Increments the ref-count of the argument and returns a new reference
scoped_ref new_ref(PyObject*);

template<typename T>
constexpr bool managed(const T&){
  return
    std::is_same<typename T::deleter_type, Decreffer>::value ||
    std::is_same<typename T::deleter_type,
                 CastDecreffer<typename T::element_type>>::value;
}

const int init_ok = 0;
const int init_fail = -1;

template<typename T>
PyObject* py_rich_compare(const T& lhs, const T& rhs, int op){
  if (lhs < rhs){
    if (op == Py_LT || op == Py_LE || op == Py_NE){
      Py_RETURN_TRUE;
    }
    Py_RETURN_FALSE;
  }
  else if (lhs == rhs){
    if (op == Py_EQ || op == Py_LE || op == Py_GE){
      Py_RETURN_TRUE;
    }
    Py_RETURN_FALSE;
  }
  else{
    assert(lhs > rhs);
    if (op == Py_GT || op == Py_GE || op == Py_NE){
      Py_RETURN_TRUE;
    }
    Py_RETURN_FALSE;
  }
}

} // namespace

#endif
<commit_msg>Remove WIN32-specific HAVE_ROUND-define<commit_after>// -*- coding: us-ascii-unix -*-
// Copyright 2012 Lukas Kemmer
//
// Licensed under the Apache License, Version 2.0 (the "License"); you
// may not use this file except in compliance with the License. You
// may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.

#ifndef FAINT_PY_INCLUDE_HH
#define FAINT_PY_INCLUDE_HH
#include "util/dumb-ptr.hh"

#ifdef _WIN32

#pragma warning(push)
// Warnings emitted by Python header since 3.4
#pragma warning(disable:4510) // default constructor could not be generated
#pragma warning(disable:4512) // 'class' : assignment operator could not be generated
#pragma warning(disable:4610) // 'class' can never be instantiated - user-defined constructor required
#endif

// On Windows, debug python (python##_d.lib) would be linked if _DEBUG
// is defined temporarily undefine to allow linking release Python
// with a debug build of Faint.
#ifdef _DEBUG
#define FAINT_UNDEFFED_DEBUG
#undef _DEBUG
#endif

#include <Python.h>

#ifdef _WIN32
#pragma warning(pop)
#endif
// Redefine _DEBUG
#ifdef  FAINT_UNDEFFED_DEBUG
#define _DEBUG
#undef FAINT_UNDEFFED_DEBUG
#endif

namespace faint{

// Custom variant of Py_XDECREF, to avoid visual studio warning
// C4127: conditional expression is constant
void py_xdecref(PyObject*);

struct Decreffer{
  void operator()(PyObject* obj){
    py_xdecref(obj);
  }
};

template<typename T>
struct CastDecreffer{
  void operator()(T* obj){
    py_xdecref((PyObject*)obj);
  }
};

dumb_ptr<PyObject> borrowed(PyObject*);

// Pointer to PyObject* which decrements the objects reference count
// when it goes out of scope.
using scoped_ref = std::unique_ptr<PyObject, Decreffer>;

// Pointer to specific types (which must be PyObject*:s)
//
template<typename T>
using typed_scoped_ref = std::unique_ptr<T, CastDecreffer<T>>;

// Increments the ref-count of the argument and returns a new reference
scoped_ref new_ref(PyObject*);

template<typename T>
constexpr bool managed(const T&){
  return
    std::is_same<typename T::deleter_type, Decreffer>::value ||
    std::is_same<typename T::deleter_type,
                 CastDecreffer<typename T::element_type>>::value;
}

const int init_ok = 0;
const int init_fail = -1;

template<typename T>
PyObject* py_rich_compare(const T& lhs, const T& rhs, int op){
  if (lhs < rhs){
    if (op == Py_LT || op == Py_LE || op == Py_NE){
      Py_RETURN_TRUE;
    }
    Py_RETURN_FALSE;
  }
  else if (lhs == rhs){
    if (op == Py_EQ || op == Py_LE || op == Py_GE){
      Py_RETURN_TRUE;
    }
    Py_RETURN_FALSE;
  }
  else{
    assert(lhs > rhs);
    if (op == Py_GT || op == Py_GE || op == Py_NE){
      Py_RETURN_TRUE;
    }
    Py_RETURN_FALSE;
  }
}

} // namespace

#endif
<|endoftext|>


<commit_before>#include "pybind11/pybind11.h"
#include "pybind11/operators.h"
#include "pybind11/stl_bind.h"

#include <sstream>
#include <molecule.h>
#include <iowrapper.h>

namespace py = pybind11;
using namespace py::literals;
using namespace Vipster;

template <typename Array, typename holder_type = std::unique_ptr<Array>, typename... Args>
py::class_<Array, holder_type> bind_array(py::module &m, std::string const &name, Args&&... args) {
    using Class_ = pybind11::class_<Array, holder_type>;
    using ValueType = typename Array::value_type;
    using SizeType = typename Array::size_type;

    Class_ cl(m, name.c_str(), std::forward<Args>(args)...);
    cl.def(py::init());
    cl.def("__getitem__",[](const Array &v, SizeType i)->const ValueType&{
        if(i<0 || i>= v.size())
            throw py::index_error();
        return v[i];
    }, py::return_value_policy::reference_internal);
    cl.def("__setitem__",[](Array &v, SizeType i, ValueType f){
        if(i<0 || i>= v.size())
            throw py::index_error();
        v[i] = f;
    });
    cl.def(py::init([](const py::iterable& it){
        Array arr;
        SizeType i=0;
        for(py::handle h:it){
            arr[i] = h.cast<ValueType>();
            i++;
        }
        return arr;
    }));
    cl.def(py::self == py::self);
    py::implicitly_convertible<py::iterable, Array>();
    cl.def("__repr__", [name](const Array &v){
        std::string repr = name + "[";
        for(size_t i=0; i<v.size()-1; ++i){
            repr += py::str(py::cast(v[i]).attr("__repr__")());
            repr += ", ";
        }
        repr += py::str(py::cast(v[v.size()-1]).attr("__repr__")());
        repr += "]";
        return repr;
    });
    return cl;
}

PYBIND11_MODULE(vipster, m) {
    m.doc() = "Vipster\n"
              "=======\n\n"
              "A molecular modeling framework with periodic structures in mind.\n"
              "Use readFile() and writeFile() to handle files.\n"
              "Please inspect Molecule and Step as the main data"
              "containers for more information.";

    /*
     * Step (Atoms, Bonds, Cell + PSE)
     */

    bind_array<Vec>(m, "Vec");
    bind_array<Mat>(m, "Mat");
    bind_array<ColVec>(m, "ColVec");
    py::bind_vector<std::vector<StepProper>>(m,"__StepVector__");
    py::bind_vector<std::vector<Bond>>(m,"__BondVector__");
    py::bind_vector<std::vector<std::string>>(m,"__StringVector__");
    py::bind_map<std::map<std::string,std::string>>(m,"__StrStrMap__");

    py::enum_<AtomFmt>(m, "AtomFmt")
        .value("Bohr", AtomFmt::Bohr)
        .value("Angstrom", AtomFmt::Angstrom)
        .value("Crystal", AtomFmt::Crystal)
        .value("Alat", AtomFmt::Alat)
    ;

    py::enum_<BondLevel>(m, "BondLevel")
        .value("None", BondLevel::None)
        .value("Molecule", BondLevel::Molecule)
        .value("Cell", BondLevel::Cell)
    ;

    py::enum_<BondFrequency>(m, "BondFrequency")
        .value("Never", BondFrequency::Never)
        .value("Once", BondFrequency::Once)
        .value("Always", BondFrequency::Always)
    ;

    py::enum_<CdmFmt>(m, "CellDimFmt")
        .value("Bohr", CdmFmt::Bohr)
        .value("Angstrom", CdmFmt::Angstrom)
    ;

    py::enum_<AtomProperty>(m, "AtomProperty")
        .value("FixX", AtomProperty::FixX)
        .value("FixY", AtomProperty::FixY)
        .value("FixZ", AtomProperty::FixZ)
        .value("Hidden", AtomProperty::Hidden)
    ;

    py::class_<AtomProperties>(m, "AtomProperties")
        .def("__getitem__",[](const AtomProperties &bs, AtomProperty ap){
            return bs[static_cast<uint8_t>(ap)];
        })
        .def("__setitem__",[](AtomProperties &bs, AtomProperty ap, bool val){
            bs[static_cast<uint8_t>(ap)] = val;
        })
    ;

    py::class_<Atom>(m, "Atom")
        .def_property("name", [](const Atom &a)->const std::string&{return a.name;},
                      [](Atom &a, std::string s){a.name = s;})
        .def_property("coord", [](const Atom &a)->const Vec&{return a.coord;},
                      [](Atom &a, Vec c){a.coord = c;})
        .def_property("charge", [](const Atom &a)->const float&{return a.charge;},
                      [](Atom &a, float c){a.charge = c;})
        .def_property("properties", [](const Atom &a)->const AtomProperties&{return a.properties;},
                      [](Atom &a, AtomProperties bs){a.properties = bs;})
        .def(py::self == py::self)
        .def(py::self != py::self)
    ;

    py::class_<Bond>(m, "Bond")
        .def_readwrite("at1", &Bond::at1)
        .def_readwrite("at2", &Bond::at2)
        .def_readwrite("dist", &Bond::dist)
        .def_readwrite("xdiff", &Bond::xdiff)
        .def_readwrite("ydiff", &Bond::ydiff)
        .def_readwrite("zdiff", &Bond::zdiff)
    ;

    py::class_<PseMap, std::shared_ptr<PseMap>>(m, "PseMap")
        .def("__getitem__", &PseMap::operator [], py::return_value_policy::reference_internal)
        .def("__setitem__", [](PseMap &pse, std::string n, PseEntry& e){pse[n] = e;})
    ;

    py::class_<PseEntry>(m, "PseEntry")
        .def_readwrite("PWPP", &PseEntry::PWPP)
        .def_readwrite("CPPP", &PseEntry::CPPP)
        .def_readwrite("CPNL", &PseEntry::CPNL)
        .def_readwrite("Z", &PseEntry::Z)
        .def_readwrite("m", &PseEntry::m)
        .def_readwrite("bondcut", &PseEntry::bondcut)
        .def_readwrite("covr", &PseEntry::covr)
        .def_readwrite("vdwr", &PseEntry::vdwr)
        .def_readwrite("col", &PseEntry::col)
    ;

    py::class_<Step>(m, "Step")
        .def_readonly("pse", &Step::pse)
        .def_property("comment", &Step::getComment, &Step::setComment)
        .def("newAtom", [](Step& s){s.newAtom();})
        .def("newAtom", py::overload_cast<std::string, Vec, float, AtomProperties>(&StepProper::newAtom),
             "name"_a, "coord"_a=Vec{}, "charge"_a=float{}, "properties"_a=AtomProperties{})
        .def("newAtom", py::overload_cast<const Atom&>(&StepProper::newAtom), "at"_a)
        .def("__getitem__", [](Step& s, int i){
                if (i<0){
                    i = i+static_cast<int>(s.getNat());
                }
                if ((i<0) || i>=static_cast<int>(s.getNat())){
                    throw py::index_error();
                }
                return s[static_cast<size_t>(i)];
            })
        .def("__setitem__", [](Step& s, int i, const Atom& at){
                if (i<0){
                    i = i+static_cast<int>(s.getNat());
                }
                if ((i<0) || i>=static_cast<int>(s.getNat())){
                    throw py::index_error();
                }
                s[static_cast<size_t>(i)] = at;
        })
        .def("__len__", &Step::getNat)
        .def_property_readonly("nat", &Step::getNat)
        .def("__iter__", [](const Step& s){return py::make_iterator(s.begin(), s.end());})
        .def("delAtom", &Step::delAtom, "i"_a)
        .def("getTypes", [](const Step& s){
            auto oldT = s.getTypes();
            return std::vector<std::string>(oldT.begin(), oldT.end());
        })
        .def_property_readonly("ntyp", &Step::getNtyp)
    //FMT
        .def("getFmt", &Step::getFmt)
        .def("asFmt", py::overload_cast<AtomFmt>(&Step::asFmt), "fmt"_a,
             py::return_value_policy::reference_internal)
    //CELL
        .def("enableCell", &Step::enableCell, "enable"_a)
        .def("getCellDim", &Step::getCellDim)
        .def("setCellDim", &Step::setCellDim, "cdm"_a, "fmt"_a, "scale"_a=false)
        .def("getCellVec", &Step::getCellVec)
        .def("setCellVec", &Step::setCellVec, "vec"_a, "scale"_a=false)
        .def("getCenter", &Step::getCenter, "fmt"_a, "com"_a=false)
    //BONDS
        .def("getBonds", py::overload_cast<BondLevel, BondFrequency>(&Step::getBonds, py::const_),
             "level"_a=BondLevel::Cell, "update"_a=BondFrequency::Always)
        .def("getBonds", py::overload_cast<float, BondLevel, BondFrequency>(&StepProper::getBonds, py::const_),
             "cutfac"_a, "level"_a=BondLevel::Cell, "update"_a=BondFrequency::Always)
        .def_property_readonly("nbond", &StepProper::getNbond)
    ;

    //TODO: allow construction?
    py::class_<StepProper, Step>(m, "StepProper")
        .def("setFmt", &StepProper::setFmt, "fmt"_a, "scale"_a=false);
    py::class_<StepFormatter, Step>(m, "StepFormatter");

    /*
     * K-Points
     */
    py::bind_vector<std::vector<DiscreteKPoint>>(m, "__KPointVector__");

    py::enum_<KPointFmt>(m, "KPointFmt")
        .value("Gamma",KPointFmt::Gamma)
        .value("MPG",KPointFmt::MPG)
        .value("Discrete",KPointFmt::Discrete)
    ;

    py::class_<KPoints> k(m, "KPoints");
    k.def(py::init())
        .def_readwrite("active", &KPoints::active)
        .def_readwrite("mpg", &KPoints::mpg)
        .def_readwrite("discrete", &KPoints::discrete)
    ;

    py::class_<KPoints::MPG>(k, "MPG")
        .def_readwrite("x",&KPoints::MPG::x)
        .def_readwrite("y",&KPoints::MPG::y)
        .def_readwrite("z",&KPoints::MPG::z)
        .def_readwrite("sx",&KPoints::MPG::sx)
        .def_readwrite("sy",&KPoints::MPG::sy)
        .def_readwrite("sz",&KPoints::MPG::sz)
    ;

    py::class_<KPoints::Discrete> disc(k, "Discrete");
    disc.def_readwrite("properties", &KPoints::Discrete::properties)
        .def_readwrite("kpoints", &KPoints::Discrete::kpoints)
    ;

    py::class_<DiscreteKPoint> dp(m, "DiscreteKPoint");
    dp.def(py::init([](const Vec& p, float w){return DiscreteKPoint{p,w};}))
        .def_readwrite("pos", &DiscreteKPoint::pos)
        .def_readwrite("weight", &DiscreteKPoint::weight)
    ;

    py::enum_<KPoints::Discrete::Properties>(dp, "Properties", py::arithmetic())
        .value("none", KPoints::Discrete::Properties::none)
        .value("crystal", KPoints::Discrete::Properties::crystal)
        .value("band", KPoints::Discrete::Properties::band)
        .value("contour", KPoints::Discrete::Properties::contour)
    ;

    /*
     * Molecule (Steps + KPoints)
     */
    py::class_<Molecule>(m, "Molecule")
        .def(py::init())
        .def_readonly("pse", &Molecule::pse)
        .def("newStep", [](Molecule& m){m.newStep();})
        .def("newStep", py::overload_cast<const StepProper&>(&Molecule::newStep), "step"_a)
        .def("getStep", py::overload_cast<size_t>(&Molecule::getStep), "i"_a, py::return_value_policy::reference_internal)
        .def("getSteps",py::overload_cast<>(&Molecule::getSteps), py::return_value_policy::reference_internal)
        .def_property_readonly("nstep", &Molecule::getNstep)
        .def_property("name", &Molecule::getName, &Molecule::setName)
        .def_property("kpoints", py::overload_cast<>(&Molecule::getKPoints), &Molecule::setKPoints)
    ;

    /*
     * IO
     */
    py::enum_<IOFmt>(m,"IOFmt")
        .value("XYZ", IOFmt::XYZ)
        .value("PWI", IOFmt::PWI)
        .value("PWO", IOFmt::PWO)
        .value("LMP", IOFmt::LMP)
        .value("DMP", IOFmt::DMP)
    ;

    auto io = m.def_submodule("IO");

    py::class_<BaseParam>(io, "BaseParam")
        .def_readwrite("name", &BaseParam::name)
    ;

    py::class_<BaseConfig>(io, "BaseConfig")
        .def_readwrite("name", &BaseConfig::name)
    ;

    py::class_<IO::PWParam, BaseParam>(io, "PWParam")
        .def_readwrite("control", &IO::PWParam::control)
        .def_readwrite("system", &IO::PWParam::system)
        .def_readwrite("electrons", &IO::PWParam::electrons)
        .def_readwrite("ions", &IO::PWParam::ions)
        .def_readwrite("cell", &IO::PWParam::cell)
    ;

    py::enum_<IO::LmpAtomStyle>(io, "LmpAtomStyle")
        .value("Angle", IO::LmpAtomStyle::Angle)
        .value("Atomic", IO::LmpAtomStyle::Atomic)
        .value("Bond", IO::LmpAtomStyle::Bond)
        .value("Charge", IO::LmpAtomStyle::Charge)
        .value("Full", IO::LmpAtomStyle::Full)
        .value("Molecular", IO::LmpAtomStyle::Molecular)
    ;

    py::class_<IO::LmpConfig, BaseConfig>(io, "LmpConfig")
        .def_readwrite("style", &IO::LmpConfig::style)
        .def_readwrite("angles", &IO::LmpConfig::angles)
        .def_readwrite("bonds", &IO::LmpConfig::bonds)
        .def_readwrite("dihedrals", &IO::LmpConfig::dihedrals)
        .def_readwrite("impropers", &IO::LmpConfig::impropers)
    ;

    m.def("readFile",[](std::string fn, IOFmt fmt){
        IO::Data data = readFile(fn,fmt);
        return py::make_tuple<py::return_value_policy::automatic>(data.mol, std::move(data.param));
    },"filename"_a,"format"_a);
    m.def("writeFile", &writeFile, "filename"_a, "format"_a, "molecule"_a, "param"_a=nullptr, "config"_a=nullptr);
}
<commit_msg>add IO::State to python interface<commit_after>#include "pybind11/pybind11.h"
#include "pybind11/operators.h"
#include "pybind11/stl_bind.h"

#include <sstream>
#include <molecule.h>
#include <iowrapper.h>

namespace py = pybind11;
using namespace py::literals;
using namespace Vipster;

template <typename Array, typename holder_type = std::unique_ptr<Array>, typename... Args>
py::class_<Array, holder_type> bind_array(py::module &m, std::string const &name, Args&&... args) {
    using Class_ = pybind11::class_<Array, holder_type>;
    using ValueType = typename Array::value_type;
    using SizeType = typename Array::size_type;

    Class_ cl(m, name.c_str(), std::forward<Args>(args)...);
    cl.def(py::init());
    cl.def("__getitem__",[](const Array &v, SizeType i)->const ValueType&{
        if(i<0 || i>= v.size())
            throw py::index_error();
        return v[i];
    }, py::return_value_policy::reference_internal);
    cl.def("__setitem__",[](Array &v, SizeType i, ValueType f){
        if(i<0 || i>= v.size())
            throw py::index_error();
        v[i] = f;
    });
    cl.def(py::init([](const py::iterable& it){
        Array arr;
        SizeType i=0;
        for(py::handle h:it){
            arr[i] = h.cast<ValueType>();
            i++;
        }
        return arr;
    }));
    cl.def(py::self == py::self);
    py::implicitly_convertible<py::iterable, Array>();
    cl.def("__repr__", [name](const Array &v){
        std::string repr = name + "[";
        for(size_t i=0; i<v.size()-1; ++i){
            repr += py::str(py::cast(v[i]).attr("__repr__")());
            repr += ", ";
        }
        repr += py::str(py::cast(v[v.size()-1]).attr("__repr__")());
        repr += "]";
        return repr;
    });
    return cl;
}

PYBIND11_MODULE(vipster, m) {
    m.doc() = "Vipster\n"
              "=======\n\n"
              "A molecular modeling framework with periodic structures in mind.\n"
              "Use readFile() and writeFile() to handle files.\n"
              "Please inspect Molecule and Step as the main data"
              "containers for more information.";

    /*
     * Step (Atoms, Bonds, Cell + PSE)
     */

    bind_array<Vec>(m, "Vec");
    bind_array<Mat>(m, "Mat");
    bind_array<ColVec>(m, "ColVec");
    py::bind_vector<std::vector<StepProper>>(m,"__StepVector__");
    py::bind_vector<std::vector<Bond>>(m,"__BondVector__");
    py::bind_vector<std::vector<std::string>>(m,"__StringVector__");
    py::bind_map<std::map<std::string,std::string>>(m,"__StrStrMap__");

    py::enum_<AtomFmt>(m, "AtomFmt")
        .value("Bohr", AtomFmt::Bohr)
        .value("Angstrom", AtomFmt::Angstrom)
        .value("Crystal", AtomFmt::Crystal)
        .value("Alat", AtomFmt::Alat)
    ;

    py::enum_<BondLevel>(m, "BondLevel")
        .value("None", BondLevel::None)
        .value("Molecule", BondLevel::Molecule)
        .value("Cell", BondLevel::Cell)
    ;

    py::enum_<BondFrequency>(m, "BondFrequency")
        .value("Never", BondFrequency::Never)
        .value("Once", BondFrequency::Once)
        .value("Always", BondFrequency::Always)
    ;

    py::enum_<CdmFmt>(m, "CellDimFmt")
        .value("Bohr", CdmFmt::Bohr)
        .value("Angstrom", CdmFmt::Angstrom)
    ;

    py::enum_<AtomProperty>(m, "AtomProperty")
        .value("FixX", AtomProperty::FixX)
        .value("FixY", AtomProperty::FixY)
        .value("FixZ", AtomProperty::FixZ)
        .value("Hidden", AtomProperty::Hidden)
    ;

    py::class_<AtomProperties>(m, "AtomProperties")
        .def("__getitem__",[](const AtomProperties &bs, AtomProperty ap){
            return bs[static_cast<uint8_t>(ap)];
        })
        .def("__setitem__",[](AtomProperties &bs, AtomProperty ap, bool val){
            bs[static_cast<uint8_t>(ap)] = val;
        })
    ;

    py::class_<Atom>(m, "Atom")
        .def_property("name", [](const Atom &a)->const std::string&{return a.name;},
                      [](Atom &a, std::string s){a.name = s;})
        .def_property("coord", [](const Atom &a)->const Vec&{return a.coord;},
                      [](Atom &a, Vec c){a.coord = c;})
        .def_property("charge", [](const Atom &a)->const float&{return a.charge;},
                      [](Atom &a, float c){a.charge = c;})
        .def_property("properties", [](const Atom &a)->const AtomProperties&{return a.properties;},
                      [](Atom &a, AtomProperties bs){a.properties = bs;})
        .def(py::self == py::self)
        .def(py::self != py::self)
    ;

    py::class_<Bond>(m, "Bond")
        .def_readwrite("at1", &Bond::at1)
        .def_readwrite("at2", &Bond::at2)
        .def_readwrite("dist", &Bond::dist)
        .def_readwrite("xdiff", &Bond::xdiff)
        .def_readwrite("ydiff", &Bond::ydiff)
        .def_readwrite("zdiff", &Bond::zdiff)
    ;

    py::class_<PseMap, std::shared_ptr<PseMap>>(m, "PseMap")
        .def("__getitem__", &PseMap::operator [], py::return_value_policy::reference_internal)
        .def("__setitem__", [](PseMap &pse, std::string n, PseEntry& e){pse[n] = e;})
    ;

    py::class_<PseEntry>(m, "PseEntry")
        .def_readwrite("PWPP", &PseEntry::PWPP)
        .def_readwrite("CPPP", &PseEntry::CPPP)
        .def_readwrite("CPNL", &PseEntry::CPNL)
        .def_readwrite("Z", &PseEntry::Z)
        .def_readwrite("m", &PseEntry::m)
        .def_readwrite("bondcut", &PseEntry::bondcut)
        .def_readwrite("covr", &PseEntry::covr)
        .def_readwrite("vdwr", &PseEntry::vdwr)
        .def_readwrite("col", &PseEntry::col)
    ;

    py::class_<Step>(m, "Step")
        .def_readonly("pse", &Step::pse)
        .def_property("comment", &Step::getComment, &Step::setComment)
        .def("newAtom", [](Step& s){s.newAtom();})
        .def("newAtom", py::overload_cast<std::string, Vec, float, AtomProperties>(&StepProper::newAtom),
             "name"_a, "coord"_a=Vec{}, "charge"_a=float{}, "properties"_a=AtomProperties{})
        .def("newAtom", py::overload_cast<const Atom&>(&StepProper::newAtom), "at"_a)
        .def("__getitem__", [](Step& s, int i){
                if (i<0){
                    i = i+static_cast<int>(s.getNat());
                }
                if ((i<0) || i>=static_cast<int>(s.getNat())){
                    throw py::index_error();
                }
                return s[static_cast<size_t>(i)];
            })
        .def("__setitem__", [](Step& s, int i, const Atom& at){
                if (i<0){
                    i = i+static_cast<int>(s.getNat());
                }
                if ((i<0) || i>=static_cast<int>(s.getNat())){
                    throw py::index_error();
                }
                s[static_cast<size_t>(i)] = at;
        })
        .def("__len__", &Step::getNat)
        .def_property_readonly("nat", &Step::getNat)
        .def("__iter__", [](const Step& s){return py::make_iterator(s.begin(), s.end());})
        .def("delAtom", &Step::delAtom, "i"_a)
        .def("getTypes", [](const Step& s){
            auto oldT = s.getTypes();
            return std::vector<std::string>(oldT.begin(), oldT.end());
        })
        .def_property_readonly("ntyp", &Step::getNtyp)
    //FMT
        .def("getFmt", &Step::getFmt)
        .def("asFmt", py::overload_cast<AtomFmt>(&Step::asFmt), "fmt"_a,
             py::return_value_policy::reference_internal)
    //CELL
        .def("enableCell", &Step::enableCell, "enable"_a)
        .def("getCellDim", &Step::getCellDim)
        .def("setCellDim", &Step::setCellDim, "cdm"_a, "fmt"_a, "scale"_a=false)
        .def("getCellVec", &Step::getCellVec)
        .def("setCellVec", &Step::setCellVec, "vec"_a, "scale"_a=false)
        .def("getCenter", &Step::getCenter, "fmt"_a, "com"_a=false)
    //BONDS
        .def("getBonds", py::overload_cast<BondLevel, BondFrequency>(&Step::getBonds, py::const_),
             "level"_a=BondLevel::Cell, "update"_a=BondFrequency::Always)
        .def("getBonds", py::overload_cast<float, BondLevel, BondFrequency>(&StepProper::getBonds, py::const_),
             "cutfac"_a, "level"_a=BondLevel::Cell, "update"_a=BondFrequency::Always)
        .def_property_readonly("nbond", &StepProper::getNbond)
    ;

    //TODO: allow construction?
    py::class_<StepProper, Step>(m, "StepProper")
        .def("setFmt", &StepProper::setFmt, "fmt"_a, "scale"_a=false);
    py::class_<StepFormatter, Step>(m, "StepFormatter");

    /*
     * K-Points
     */
    py::bind_vector<std::vector<DiscreteKPoint>>(m, "__KPointVector__");

    py::enum_<KPointFmt>(m, "KPointFmt")
        .value("Gamma",KPointFmt::Gamma)
        .value("MPG",KPointFmt::MPG)
        .value("Discrete",KPointFmt::Discrete)
    ;

    py::class_<KPoints> k(m, "KPoints");
    k.def(py::init())
        .def_readwrite("active", &KPoints::active)
        .def_readwrite("mpg", &KPoints::mpg)
        .def_readwrite("discrete", &KPoints::discrete)
    ;

    py::class_<KPoints::MPG>(k, "MPG")
        .def_readwrite("x",&KPoints::MPG::x)
        .def_readwrite("y",&KPoints::MPG::y)
        .def_readwrite("z",&KPoints::MPG::z)
        .def_readwrite("sx",&KPoints::MPG::sx)
        .def_readwrite("sy",&KPoints::MPG::sy)
        .def_readwrite("sz",&KPoints::MPG::sz)
    ;

    py::class_<KPoints::Discrete> disc(k, "Discrete");
    disc.def_readwrite("properties", &KPoints::Discrete::properties)
        .def_readwrite("kpoints", &KPoints::Discrete::kpoints)
    ;

    py::class_<DiscreteKPoint> dp(m, "DiscreteKPoint");
    dp.def(py::init([](const Vec& p, float w){return DiscreteKPoint{p,w};}))
        .def_readwrite("pos", &DiscreteKPoint::pos)
        .def_readwrite("weight", &DiscreteKPoint::weight)
    ;

    py::enum_<KPoints::Discrete::Properties>(dp, "Properties", py::arithmetic())
        .value("none", KPoints::Discrete::Properties::none)
        .value("crystal", KPoints::Discrete::Properties::crystal)
        .value("band", KPoints::Discrete::Properties::band)
        .value("contour", KPoints::Discrete::Properties::contour)
    ;

    /*
     * Molecule (Steps + KPoints)
     */
    py::class_<Molecule>(m, "Molecule")
        .def(py::init())
        .def_readonly("pse", &Molecule::pse)
        .def("newStep", [](Molecule& m){m.newStep();})
        .def("newStep", py::overload_cast<const StepProper&>(&Molecule::newStep), "step"_a)
        .def("getStep", py::overload_cast<size_t>(&Molecule::getStep), "i"_a, py::return_value_policy::reference_internal)
        .def("getSteps",py::overload_cast<>(&Molecule::getSteps), py::return_value_policy::reference_internal)
        .def_property_readonly("nstep", &Molecule::getNstep)
        .def_property("name", &Molecule::getName, &Molecule::setName)
        .def_property("kpoints", py::overload_cast<>(&Molecule::getKPoints), &Molecule::setKPoints)
    ;

    /*
     * IO
     */
    py::enum_<IOFmt>(m,"IOFmt")
        .value("XYZ", IOFmt::XYZ)
        .value("PWI", IOFmt::PWI)
        .value("PWO", IOFmt::PWO)
        .value("LMP", IOFmt::LMP)
        .value("DMP", IOFmt::DMP)
    ;

    auto io = m.def_submodule("IO");

    py::class_<BaseParam>(io, "BaseParam")
        .def_readwrite("name", &BaseParam::name)
    ;

    py::class_<BaseConfig>(io, "BaseConfig")
        .def_readwrite("name", &BaseConfig::name)
    ;

    py::class_<IO::PWParam, BaseParam>(io, "PWParam")
        .def_readwrite("control", &IO::PWParam::control)
        .def_readwrite("system", &IO::PWParam::system)
        .def_readwrite("electrons", &IO::PWParam::electrons)
        .def_readwrite("ions", &IO::PWParam::ions)
        .def_readwrite("cell", &IO::PWParam::cell)
    ;

    py::enum_<IO::LmpAtomStyle>(io, "LmpAtomStyle")
        .value("Angle", IO::LmpAtomStyle::Angle)
        .value("Atomic", IO::LmpAtomStyle::Atomic)
        .value("Bond", IO::LmpAtomStyle::Bond)
        .value("Charge", IO::LmpAtomStyle::Charge)
        .value("Full", IO::LmpAtomStyle::Full)
        .value("Molecular", IO::LmpAtomStyle::Molecular)
    ;

    py::class_<IO::LmpConfig, BaseConfig>(io, "LmpConfig")
        .def_readwrite("style", &IO::LmpConfig::style)
        .def_readwrite("angles", &IO::LmpConfig::angles)
        .def_readwrite("bonds", &IO::LmpConfig::bonds)
        .def_readwrite("dihedrals", &IO::LmpConfig::dihedrals)
        .def_readwrite("impropers", &IO::LmpConfig::impropers)
    ;

    py::class_<IO::State>(io, "State")
        .def_readwrite("index", &IO::State::index)
        .def_readwrite("atom_fmt", &IO::State::atom_fmt)
        .def_readwrite("cell_fmt", &IO::State::cell_fmt)
    ;

    m.def("readFile",[](std::string fn, IOFmt fmt){
        IO::Data data = readFile(fn,fmt);
        return py::make_tuple<py::return_value_policy::automatic>(data.mol, std::move(data.param));
    },"filename"_a,"format"_a);
    m.def("writeFile", &writeFile, "filename"_a, "format"_a, "molecule"_a,
          "param"_a=nullptr, "config"_a=nullptr, "state"_a=IO::State{});
}
<|endoftext|>