<commit_before>/* -*- mode: c++; c-basic-offset:4 -*-
    uiserver/output.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2007 Klarälvdalens Datakonsult AB

    Kleopatra 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.

    Kleopatra 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 "output.h"

#include "detail_p.h"
#include "kleo-assuan.h"

#include <utils/kdpipeiodevice.h>

#include <KLocale>
#include <KMessageBox>

#include <QTemporaryFile>
#include <QString>

#include <errno.h>

using namespace Kleo;
using namespace Kleo::_detail;
using namespace boost;

namespace {

    class TemporaryFile : public QTemporaryFile {
    public:
        explicit TemporaryFile() : QTemporaryFile() {}
        explicit TemporaryFile( const QString & templateName ) : QTemporaryFile( templateName ) {}
        explicit TemporaryFile( QObject * parent ) : QTemporaryFile( parent ) {}
        explicit TemporaryFile( const QString & templateName, QObject * parent ) : QTemporaryFile( templateName, parent ) {}

        /* reimp */ void close() {
            if ( isOpen() )
                m_oldFileName = fileName();
            QTemporaryFile::close();
        }

        QString oldFileName() const { return m_oldFileName; }

    private:
        QString m_oldFileName;
    };

    template <typename T_IODevice>
    struct inhibit_close : T_IODevice {
        explicit inhibit_close() : T_IODevice() {}
        template <typename T1>
        explicit inhibit_close( T1 & t1 ) : T_IODevice( t1 ) {}

        /* reimp */ void close() {}
        void reallyClose() { T_IODevice::close(); }
    };

    class OutputImplBase : public Output {
    public:
        OutputImplBase()
            : Output(),
              m_label(),
              m_isFinalized( false ),
              m_isFinalizing( false ),
              m_cancelPending( false ),
              m_canceled( false )
        {

        }

        /* reimp */ QString label() const { return m_label; }
        void setLabel( const QString & l ) { m_label = l; }

        /* reimp */ bool isFinalized() const { return m_isFinalized; }
        /* reimp */ void finalize() {
            if ( m_isFinalized || m_isFinalizing )
                return;
            m_isFinalizing = true;
            try { doFinalize(); } catch ( ... ) { m_isFinalizing = false; throw; }
            m_isFinalizing = false;
            m_isFinalized = true;
            if ( m_cancelPending )
                cancel();
        }

        /* reimp */ void cancel() {
            if ( m_isFinalizing ) {
                m_cancelPending = true;
            } else if ( !m_canceled ) {
                m_isFinalizing = true;
                try { doCancel(); } catch ( ... ) {}
                m_isFinalizing = false;
                m_isFinalized = true;
                m_canceled = true;
            }
        }
    private:
        virtual void doFinalize() = 0;
        virtual void doCancel() = 0;
    private:
        QString m_label;
        bool m_isFinalized   : 1;
        bool m_isFinalizing  : 1;
        bool m_cancelPending : 1;
        bool m_canceled      : 1;
    };

    class PipeOutput : public OutputImplBase {
    public:
        explicit PipeOutput( assuan_fd_t fd );

        /* reimp */ shared_ptr<QIODevice> ioDevice() const { return m_io; }
        /* reimp */ void doFinalize() { m_io->reallyClose(); }
        /* reimp */ void doCancel() { doFinalize(); }
    private:
        shared_ptr< inhibit_close<KDPipeIODevice> > m_io;
    };

    class FileOutput : public OutputImplBase {
    public:
        explicit FileOutput( const QString & fileName );

        enum OverwritePolicy {
            Allow = true,
            Deny = false,
            Ask
        };
        void setOverwritePolicy( OverwritePolicy overwrite ) { m_overwrite = overwrite; }

        /* reimp */ QString label() const { return m_fileName; }
        /* reimp */ shared_ptr<QIODevice> ioDevice() const { return m_tmpFile; }
        /* reimp */ void doFinalize();
        /* reimp */ void doCancel() {}
    private:
        const QString m_fileName;
        shared_ptr< TemporaryFile > m_tmpFile;
        OverwritePolicy m_overwrite;
    };

#if 0
    class ClipboardOutput : public Output {
    public:
        explicit ClipboardOutput( QClipboard::Mode mode );
        ~ClipboardOutput();

        /* reimp */ QString label() const;
        /* reimp */ shared_ptr<QIODevice> ioDevice() const;
        /* reimp */ void doFinalize();
        /* reimp */ void doCancel() {}
    };
#endif

}

shared_ptr<Output> Output::createFromPipeDevice( assuan_fd_t fd, const QString & label ) {
    shared_ptr<PipeOutput> po( new PipeOutput( fd ) );
    po->setLabel( label );
    return po;
}

PipeOutput::PipeOutput( assuan_fd_t fd )
    : OutputImplBase(),
      m_io( new inhibit_close<KDPipeIODevice> )
{
    errno = 0;
    if ( !m_io->open( fd, QIODevice::WriteOnly ) )
        throw assuan_exception( errno ? gpg_error_from_errno( errno ) : gpg_error( GPG_ERR_EIO ),
                                i18n( "Couldn't open FD %1 for writing",
                                      assuanFD2int( fd ) ) );
}

shared_ptr<Output> Output::createFromFile( const QString & fileName, bool allowOverwrite ) {
    shared_ptr<FileOutput> fo( new FileOutput( fileName ) );
    if ( allowOverwrite )
        fo->setOverwritePolicy( FileOutput::Allow );
    return fo;
}

FileOutput::FileOutput( const QString & fileName )
    : OutputImplBase(),
      m_fileName( fileName ),
      m_tmpFile( new TemporaryFile( fileName ) ),
      m_overwrite( Ask )
{
    errno = 0;
    if ( !m_tmpFile->open() )
        throw assuan_exception( errno ? gpg_error_from_errno( errno ) : gpg_error( GPG_ERR_EIO ),
                                i18n( "Couldn't create temporary file for output \"%1\"", fileName ) );
}

static bool obtainOverwritePermission( const QString & fileName, QWidget * parent ) {
    return KMessageBox::questionYesNo( parent, i18n("The file %1 already exists.\n"
                                                    "Overwrite?", fileName ),
                                       i18n("Overwrite Existing File?"), KStandardGuiItem::overwrite(), KStandardGuiItem::cancel() ) == KMessageBox::Yes ;
}

void FileOutput::doFinalize() {

    assuan_assert( m_tmpFile );

    const QString tmpFileName = m_tmpFile->oldFileName();

    if ( m_tmpFile->isOpen() )
        m_tmpFile->close();

    if ( QFile::rename( tmpFileName, m_fileName ) ) {
        m_tmpFile->setAutoRemove( false );
        return;
    }

    if ( !obtainOverwritePermission( m_fileName, 0 ) )
        throw assuan_exception( gpg_error( GPG_ERR_CANCELED ),
                                i18n( "Overwriting declined" ) );

    if ( !QFile::remove( m_fileName ) )
        throw assuan_exception( errno ? gpg_error_from_errno( errno ) : gpg_error( GPG_ERR_EIO ),
                                i18n("Couldn't remove file \"%1\" for overwriting.", m_fileName ) );

    if ( QFile::rename( tmpFileName, m_fileName ) ) {
        m_tmpFile->setAutoRemove( false );
        return;
    }

    throw assuan_exception( errno ? gpg_error_from_errno( errno ) : gpg_error( GPG_ERR_EIO ),
                            i18n( "Couldn't rename file \"%1\" to \"%2\"",
                                  tmpFileName, m_fileName ) );
}

#if 0
shared_ptr<Output> Output::createFromClipboard( QClipboard::Mode mode ) {
    notImplemented();
}
#endif

Output::~Output() {}
<commit_msg>oldFileName() is only set on close(), so ask for it only after close() has been assured<commit_after>/* -*- mode: c++; c-basic-offset:4 -*-
    uiserver/output.cpp

    This file is part of Kleopatra, the KDE keymanager
    Copyright (c) 2007 Klarälvdalens Datakonsult AB

    Kleopatra 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.

    Kleopatra 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 "output.h"

#include "detail_p.h"
#include "kleo-assuan.h"

#include <utils/kdpipeiodevice.h>

#include <KLocale>
#include <KMessageBox>

#include <QTemporaryFile>
#include <QString>

#include <errno.h>

using namespace Kleo;
using namespace Kleo::_detail;
using namespace boost;

namespace {

    class TemporaryFile : public QTemporaryFile {
    public:
        explicit TemporaryFile() : QTemporaryFile() {}
        explicit TemporaryFile( const QString & templateName ) : QTemporaryFile( templateName ) {}
        explicit TemporaryFile( QObject * parent ) : QTemporaryFile( parent ) {}
        explicit TemporaryFile( const QString & templateName, QObject * parent ) : QTemporaryFile( templateName, parent ) {}

        /* reimp */ void close() {
            if ( isOpen() )
                m_oldFileName = fileName();
            QTemporaryFile::close();
        }

        QString oldFileName() const { return m_oldFileName; }

    private:
        QString m_oldFileName;
    };

    template <typename T_IODevice>
    struct inhibit_close : T_IODevice {
        explicit inhibit_close() : T_IODevice() {}
        template <typename T1>
        explicit inhibit_close( T1 & t1 ) : T_IODevice( t1 ) {}

        /* reimp */ void close() {}
        void reallyClose() { T_IODevice::close(); }
    };

    class OutputImplBase : public Output {
    public:
        OutputImplBase()
            : Output(),
              m_label(),
              m_isFinalized( false ),
              m_isFinalizing( false ),
              m_cancelPending( false ),
              m_canceled( false )
        {

        }

        /* reimp */ QString label() const { return m_label; }
        void setLabel( const QString & l ) { m_label = l; }

        /* reimp */ bool isFinalized() const { return m_isFinalized; }
        /* reimp */ void finalize() {
            if ( m_isFinalized || m_isFinalizing )
                return;
            m_isFinalizing = true;
            try { doFinalize(); } catch ( ... ) { m_isFinalizing = false; throw; }
            m_isFinalizing = false;
            m_isFinalized = true;
            if ( m_cancelPending )
                cancel();
        }

        /* reimp */ void cancel() {
            if ( m_isFinalizing ) {
                m_cancelPending = true;
            } else if ( !m_canceled ) {
                m_isFinalizing = true;
                try { doCancel(); } catch ( ... ) {}
                m_isFinalizing = false;
                m_isFinalized = true;
                m_canceled = true;
            }
        }
    private:
        virtual void doFinalize() = 0;
        virtual void doCancel() = 0;
    private:
        QString m_label;
        bool m_isFinalized   : 1;
        bool m_isFinalizing  : 1;
        bool m_cancelPending : 1;
        bool m_canceled      : 1;
    };

    class PipeOutput : public OutputImplBase {
    public:
        explicit PipeOutput( assuan_fd_t fd );

        /* reimp */ shared_ptr<QIODevice> ioDevice() const { return m_io; }
        /* reimp */ void doFinalize() { m_io->reallyClose(); }
        /* reimp */ void doCancel() { doFinalize(); }
    private:
        shared_ptr< inhibit_close<KDPipeIODevice> > m_io;
    };

    class FileOutput : public OutputImplBase {
    public:
        explicit FileOutput( const QString & fileName );

        enum OverwritePolicy {
            Allow = true,
            Deny = false,
            Ask
        };
        void setOverwritePolicy( OverwritePolicy overwrite ) { m_overwrite = overwrite; }

        /* reimp */ QString label() const { return m_fileName; }
        /* reimp */ shared_ptr<QIODevice> ioDevice() const { return m_tmpFile; }
        /* reimp */ void doFinalize();
        /* reimp */ void doCancel() {}
    private:
        const QString m_fileName;
        shared_ptr< TemporaryFile > m_tmpFile;
        OverwritePolicy m_overwrite;
    };

#if 0
    class ClipboardOutput : public Output {
    public:
        explicit ClipboardOutput( QClipboard::Mode mode );
        ~ClipboardOutput();

        /* reimp */ QString label() const;
        /* reimp */ shared_ptr<QIODevice> ioDevice() const;
        /* reimp */ void doFinalize();
        /* reimp */ void doCancel() {}
    };
#endif

}

shared_ptr<Output> Output::createFromPipeDevice( assuan_fd_t fd, const QString & label ) {
    shared_ptr<PipeOutput> po( new PipeOutput( fd ) );
    po->setLabel( label );
    return po;
}

PipeOutput::PipeOutput( assuan_fd_t fd )
    : OutputImplBase(),
      m_io( new inhibit_close<KDPipeIODevice> )
{
    errno = 0;
    if ( !m_io->open( fd, QIODevice::WriteOnly ) )
        throw assuan_exception( errno ? gpg_error_from_errno( errno ) : gpg_error( GPG_ERR_EIO ),
                                i18n( "Couldn't open FD %1 for writing",
                                      assuanFD2int( fd ) ) );
}

shared_ptr<Output> Output::createFromFile( const QString & fileName, bool allowOverwrite ) {
    shared_ptr<FileOutput> fo( new FileOutput( fileName ) );
    if ( allowOverwrite )
        fo->setOverwritePolicy( FileOutput::Allow );
    return fo;
}

FileOutput::FileOutput( const QString & fileName )
    : OutputImplBase(),
      m_fileName( fileName ),
      m_tmpFile( new TemporaryFile( fileName ) ),
      m_overwrite( Ask )
{
    errno = 0;
    if ( !m_tmpFile->open() )
        throw assuan_exception( errno ? gpg_error_from_errno( errno ) : gpg_error( GPG_ERR_EIO ),
                                i18n( "Couldn't create temporary file for output \"%1\"", fileName ) );
}

static bool obtainOverwritePermission( const QString & fileName, QWidget * parent ) {
    return KMessageBox::questionYesNo( parent, i18n("The file %1 already exists.\n"
                                                    "Overwrite?", fileName ),
                                       i18n("Overwrite Existing File?"), KStandardGuiItem::overwrite(), KStandardGuiItem::cancel() ) == KMessageBox::Yes ;
}

void FileOutput::doFinalize() {

    assuan_assert( m_tmpFile );

    if ( m_tmpFile->isOpen() )
        m_tmpFile->close();

    const QString tmpFileName = m_tmpFile->oldFileName();

    if ( QFile::rename( tmpFileName, m_fileName ) ) {
        m_tmpFile->setAutoRemove( false );
        return;
    }

    if ( !obtainOverwritePermission( m_fileName, 0 ) )
        throw assuan_exception( gpg_error( GPG_ERR_CANCELED ),
                                i18n( "Overwriting declined" ) );

    if ( !QFile::remove( m_fileName ) )
        throw assuan_exception( errno ? gpg_error_from_errno( errno ) : gpg_error( GPG_ERR_EIO ),
                                i18n("Couldn't remove file \"%1\" for overwriting.", m_fileName ) );

    if ( QFile::rename( tmpFileName, m_fileName ) ) {
        m_tmpFile->setAutoRemove( false );
        return;
    }

    throw assuan_exception( errno ? gpg_error_from_errno( errno ) : gpg_error( GPG_ERR_EIO ),
                            i18n( "Couldn't rename file \"%1\" to \"%2\"",
                                  tmpFileName, m_fileName ) );
}

#if 0
shared_ptr<Output> Output::createFromClipboard( QClipboard::Mode mode ) {
    notImplemented();
}
#endif

Output::~Output() {}
<|endoftext|>


<commit_before>// kmsearchpatternedit.cpp
// Author: Marc Mutz <Marc@Mutz.com>
// This code is under GPL

#include "kmsearchpatternedit.h"

#include <klocale.h>
#include <kdebug.h>

#include <qradiobutton.h>
#include <qlineedit.h>
#include <qcombobox.h>
#include <qbuttongroup.h>
#include <qstringlist.h>

#include <assert.h>
#include <kparts/componentfactory.h>
#include <kregexpeditorinterface.h>
#include <qpushbutton.h>
#include <qdialog.h>

static QStringList sFilterFieldList, sFilterFuncList;

//=============================================================================
//
// class KMSearchRuleWidget
//
//=============================================================================

KMSearchRuleWidget::KMSearchRuleWidget(QWidget *parent, KMSearchRule *aRule, const char *name, bool headersOnly)
  : QHBox(parent,name), mRegExpEditDialog(0)
{
  initLists( headersOnly ); // sFilter{Func,Field}List are local to KMSearchRuleWidget
  initWidget();

  if ( aRule )
    setRule(aRule);
  else
    reset();
}

void KMSearchRuleWidget::initWidget()
{
  setSpacing(4);

  mRuleField = new QComboBox( true, this, "mRuleField" );
  mRuleFunc = new QComboBox( false, this, "mRuleFunc" );
  mRuleValue = new QLineEdit( this, "mRuleValue" );

  if( !KTrader::self()->query("KRegExpEditor/KRegExpEditor").isEmpty() ) {
    mRuleEditBut = new QPushButton( i18n("Edit"), this, "mRuleEditBut" );
    connect( mRuleEditBut, SIGNAL( clicked() ), this, SLOT( editRegExp()));
    connect( mRuleFunc, SIGNAL( activated(int) ), this, SLOT( functionChanged(int) ) );
    functionChanged( mRuleFunc->currentItem() );
  }

  mRuleFunc->insertStringList(sFilterFuncList);
  mRuleFunc->adjustSize();

  mRuleField->insertStringList(sFilterFieldList);
  // don't show sliders when popping up this menu
  mRuleField->setSizeLimit( mRuleField->count() );
  mRuleField->adjustSize();

  connect( mRuleField, SIGNAL(textChanged(const QString &)),
	   this, SIGNAL(fieldChanged(const QString &)) );
  connect( mRuleValue, SIGNAL(textChanged(const QString &)),
	   this, SIGNAL(contentsChanged(const QString &)) );
}

void KMSearchRuleWidget::editRegExp()
{
  if ( mRegExpEditDialog == 0 )
    mRegExpEditDialog = KParts::ComponentFactory::createInstanceFromQuery<QDialog>( "KRegExpEditor/KRegExpEditor", QString::null, this );

  KRegExpEditorInterface *iface = static_cast<KRegExpEditorInterface *>( mRegExpEditDialog->qt_cast( "KRegExpEditorInterface" ) );
  if( iface ) {
    iface->setRegExp( mRuleValue->text() );
    if( mRegExpEditDialog->exec() == QDialog::Accepted )
      mRuleValue->setText( iface->regExp() );
  }
}

void KMSearchRuleWidget::functionChanged( int which )
{
  mRuleEditBut->setEnabled( which == 4 || which == 5 );
}

void KMSearchRuleWidget::setRule(KMSearchRule *aRule)
{
  assert ( aRule );

  blockSignals(TRUE);
  //--------------set the field
  int i = indexOfRuleField( aRule->field() );

  if ( i<0 ) { // not found -> user defined field
    mRuleField->changeItem( QString(aRule->field()), 0 );
    i=0;
  } else // found in the list of predefined fields
    mRuleField->changeItem( "", 0 );

  mRuleField->setCurrentItem( i );

  //--------------set function and contents
  mRuleFunc->setCurrentItem( (int)aRule->function() );
  mRuleValue->setText( aRule->contents() );

  if (mRegExpEditDialog)
    functionChanged( (int)aRule->function() );

  blockSignals(FALSE);
}

KMSearchRule* KMSearchRuleWidget::rule() const
{
  KMSearchRule *r = new KMSearchRule;

  r->init( ruleFieldToEnglish( mRuleField->currentText() ).latin1(),
	   (KMSearchRule::Function)mRuleFunc->currentItem(),
	   mRuleValue->text() );

  return r;
}

void KMSearchRuleWidget::reset()
{
  blockSignals(TRUE);

  mRuleField->changeItem( "", 0 );
  mRuleField->setCurrentItem( 0 );

  mRuleFunc->setCurrentItem( 0 );

  mRuleValue->clear();

  blockSignals(FALSE);
}

QString KMSearchRuleWidget::ruleFieldToEnglish(const QString & i18nVal) const
{
  if (i18nVal == i18n("<recipients>")) return QString::fromLatin1("<recipients>");
  if (i18nVal == i18n("<body>")) return QString::fromLatin1("<body>");
  if (i18nVal == i18n("<message>")) return QString::fromLatin1("<message>");
  if (i18nVal == i18n("<any header>")) return QString::fromLatin1("<any header>");
  if (i18nVal == i18n("<size>")) return QString::fromLatin1("<size>");
  if (i18nVal == i18n("<age in days>")) return QString::fromLatin1("<age in days>");
  return i18nVal;
}

int KMSearchRuleWidget::indexOfRuleField(const QString aName) const
{
  int i;

  if ( aName.isEmpty() ) return -1;

  QString i18n_aName = i18n( aName.latin1() );

  for (i=sFilterFieldList.count()-1; i>=0; i--) {
    if (*(sFilterFieldList.at(i))==i18n_aName) break;
  }
  return i;
}

void KMSearchRuleWidget::initLists(bool headersOnly) const
{
  //---------- initialize list of filter operators
  if ( sFilterFuncList.isEmpty() )
  {
    // also see KMSearchRule::matches() and KMSearchRule::Function
    // if you change the following strings!
    sFilterFuncList.append(i18n("contains"));
    sFilterFuncList.append(i18n("doesn't contain"));
    sFilterFuncList.append(i18n("equals"));
    sFilterFuncList.append(i18n("doesn't equal"));
    sFilterFuncList.append(i18n("matches regular expr."));
    sFilterFuncList.append(i18n("doesn't match reg. expr."));
    sFilterFuncList.append(i18n("is greater than"));
    sFilterFuncList.append(i18n("is less than or equal to"));
    sFilterFuncList.append(i18n("is less than"));
    sFilterFuncList.append(i18n("is greater than or equal to"));
  }

  //---------- initialize list of filter operators
  if ( sFilterFieldList.isEmpty() )
  {
    sFilterFieldList.append("");
    // also see KMSearchRule::matches() and ruleFieldToEnglish() if
    // you change the following i18n-ized strings!
    if( !headersOnly )  sFilterFieldList.append(i18n("<message>"));
    if( !headersOnly )  sFilterFieldList.append(i18n("<body>"));
    sFilterFieldList.append(i18n("<any header>"));
    sFilterFieldList.append(i18n("<recipients>"));
    sFilterFieldList.append(i18n("<size>"));
    sFilterFieldList.append(i18n("<age in days>"));
    // these others only represent message headers and you can add to
    // them as you like
    sFilterFieldList.append("Subject");
    sFilterFieldList.append("From");
    sFilterFieldList.append("To");
    sFilterFieldList.append("Cc");
    sFilterFieldList.append("Reply-To");
    sFilterFieldList.append("List-Id");
    sFilterFieldList.append("Organization");
    sFilterFieldList.append("Resent-From");
    sFilterFieldList.append("X-Loop");
    sFilterFieldList.append("X-Mailing-List");
  }
}

//=============================================================================
//
// class KMFilterActionWidgetLister (the filter action editor)
//
//=============================================================================

KMSearchRuleWidgetLister::KMSearchRuleWidgetLister( QWidget *parent, const char* name, bool headersOnly )
  : KWidgetLister( 2, FILTER_MAX_RULES, parent, name )
{
  mRuleList = 0;
  mHeadersOnly = headersOnly;
}

KMSearchRuleWidgetLister::~KMSearchRuleWidgetLister()
{
}

void KMSearchRuleWidgetLister::setRuleList( QPtrList<KMSearchRule> *aList )
{
  assert ( aList );

  if ( mRuleList )
    regenerateRuleListFromWidgets();

  mRuleList = aList;

  if ( mWidgetList.first() ) // move this below next 'if'?
    mWidgetList.first()->blockSignals(TRUE);

  if ( aList->count() == 0 ) {
    slotClear();
    mWidgetList.first()->blockSignals(FALSE);
    return;
  }

  int superfluousItems = (int)mRuleList->count() - mMaxWidgets ;
  if ( superfluousItems > 0 ) {
    kdDebug(5006) << "KMSearchRuleWidgetLister: Clipping rule list to "
		  << mMaxWidgets << " items!" << endl;

    for ( ; superfluousItems ; superfluousItems-- )
      mRuleList->removeLast();
  }

  // set the right number of widgets
  setNumberOfShownWidgetsTo( QMAX((int)mRuleList->count(),mMinWidgets) );

  // load the actions into the widgets
  QPtrListIterator<KMSearchRule> rIt( *mRuleList );
  QPtrListIterator<QWidget> wIt( mWidgetList );
  for ( rIt.toFirst(), wIt.toFirst() ;
	rIt.current() && wIt.current() ; ++rIt, ++wIt ) {
    ((KMSearchRuleWidget*)(*wIt))->setRule( (*rIt) );
  }
  for ( ; wIt.current() ; ++wIt )
    ((KMSearchRuleWidget*)(*wIt))->reset();

  assert( mWidgetList.first() );
  mWidgetList.first()->blockSignals(FALSE);
}

void KMSearchRuleWidgetLister::reset()
{
  if ( mRuleList )
    regenerateRuleListFromWidgets();

  mRuleList = 0;
  slotClear();
}

QWidget* KMSearchRuleWidgetLister::createWidget( QWidget *parent )
{
  return new KMSearchRuleWidget(parent, 0, 0, mHeadersOnly);
}

void KMSearchRuleWidgetLister::clearWidget( QWidget *aWidget )
{
  if ( aWidget )
    ((KMSearchRuleWidget*)aWidget)->reset();
}

void KMSearchRuleWidgetLister::regenerateRuleListFromWidgets()
{
  if ( !mRuleList ) return;

  mRuleList->clear();

  QPtrListIterator<QWidget> it( mWidgetList );
  for ( it.toFirst() ; it.current() ; ++it ) {
    KMSearchRule *r = ((KMSearchRuleWidget*)(*it))->rule();
    if ( r )
      mRuleList->append( r );
  }
}

//=============================================================================
//
// class KMSearchPatternEdit
//
//=============================================================================

KMSearchPatternEdit::KMSearchPatternEdit(QWidget *parent, const char *name, bool headersOnly )
  : QGroupBox( 1/*columns*/, Horizontal, parent, name )
{
  setTitle( i18n("Search Criteria") );
  initLayout( headersOnly );
}

KMSearchPatternEdit::KMSearchPatternEdit(const QString & title, QWidget *parent, const char *name, bool headersOnly )
  : QGroupBox( 1/*column*/, Horizontal, title, parent, name )
{
  initLayout( headersOnly );
}

KMSearchPatternEdit::~KMSearchPatternEdit()
{
}

void KMSearchPatternEdit::initLayout(bool headersOnly)
{
  //------------the radio buttons
  mAllRBtn = new QRadioButton( i18n("Match a&ll of the following"), this, "mAllRBtn" );
  mAnyRBtn = new QRadioButton( i18n("Match an&y of the following"), this, "mAnyRBtn" );

  mAllRBtn->setChecked(TRUE);
  mAnyRBtn->setChecked(FALSE);

  QButtonGroup *bg = new QButtonGroup( this );
  bg->hide();
  bg->insert( mAllRBtn, (int)KMSearchPattern::OpAnd );
  bg->insert( mAnyRBtn, (int)KMSearchPattern::OpOr );

  //------------the list of KMSearchRuleWidget's
  mRuleLister = new KMSearchRuleWidgetLister( this, "swl", headersOnly );
  mRuleLister->slotClear();

  //------------connect a few signals
  connect( bg, SIGNAL(clicked(int)),
	   this, SLOT(slotRadioClicked(int)) );

  KMSearchRuleWidget *srw = (KMSearchRuleWidget*)mRuleLister->mWidgetList.first();
  if ( srw ) {
    connect( srw, SIGNAL(fieldChanged(const QString &)),
	     this, SLOT(slotAutoNameHack()) );
    connect( srw, SIGNAL(contentsChanged(const QString &)),
	     this, SLOT(slotAutoNameHack()) );
  } else
    kdDebug(5006) << "KMSearchPatternEdit: no first KMSearchRuleWidget, though slotClear() has been called!" << endl;
}

void KMSearchPatternEdit::setSearchPattern( KMSearchPattern *aPattern )
{
  assert( aPattern );

  mRuleLister->setRuleList( aPattern );

  mPattern = aPattern;

  blockSignals(TRUE);
  if ( mPattern->op() == KMSearchPattern::OpOr )
    mAnyRBtn->setChecked(TRUE);
  else
    mAllRBtn->setChecked(TRUE);
  blockSignals(FALSE);

  setEnabled( TRUE );
}

void KMSearchPatternEdit::reset()
{
  mRuleLister->reset();

  blockSignals(TRUE);
  mAllRBtn->setChecked( TRUE );
  blockSignals(FALSE);

  setEnabled( FALSE );
}

void KMSearchPatternEdit::slotRadioClicked(int aIdx)
{
  if ( mPattern )
    mPattern->setOp( (KMSearchPattern::Operator)aIdx );
}

void KMSearchPatternEdit::slotAutoNameHack()
{
  mRuleLister->regenerateRuleListFromWidgets();
  emit maybeNameChanged();
}

#include "kmsearchpatternedit.moc"
<commit_msg>unbreak the "edit button doesn't enable/disable properly" behaviour. again.<commit_after>// kmsearchpatternedit.cpp
// Author: Marc Mutz <Marc@Mutz.com>
// This code is under GPL

#include "kmsearchpatternedit.h"

#include <klocale.h>
#include <kdebug.h>

#include <qradiobutton.h>
#include <qlineedit.h>
#include <qcombobox.h>
#include <qbuttongroup.h>
#include <qstringlist.h>

#include <assert.h>
#include <kparts/componentfactory.h>
#include <kregexpeditorinterface.h>
#include <qpushbutton.h>
#include <qdialog.h>

static QStringList sFilterFieldList, sFilterFuncList;

//=============================================================================
//
// class KMSearchRuleWidget
//
//=============================================================================

KMSearchRuleWidget::KMSearchRuleWidget(QWidget *parent, KMSearchRule *aRule, const char *name, bool headersOnly)
  : QHBox(parent,name),
    mRuleEditBut(0),
    mRegExpEditDialog(0)
{
  initLists( headersOnly ); // sFilter{Func,Field}List are local to KMSearchRuleWidget
  initWidget();

  if ( aRule )
    setRule(aRule);
  else
    reset();
}

void KMSearchRuleWidget::initWidget()
{
  setSpacing(4);

  mRuleField = new QComboBox( true, this, "mRuleField" );
  mRuleFunc = new QComboBox( false, this, "mRuleFunc" );
  mRuleValue = new QLineEdit( this, "mRuleValue" );

  if( !KTrader::self()->query("KRegExpEditor/KRegExpEditor").isEmpty() ) {
    mRuleEditBut = new QPushButton( i18n("Edit"), this, "mRuleEditBut" );
    connect( mRuleEditBut, SIGNAL( clicked() ), this, SLOT( editRegExp()));
    connect( mRuleFunc, SIGNAL( activated(int) ), this, SLOT( functionChanged(int) ) );
    functionChanged( mRuleFunc->currentItem() );
  }

  mRuleFunc->insertStringList(sFilterFuncList);
  mRuleFunc->adjustSize();

  mRuleField->insertStringList(sFilterFieldList);
  // don't show sliders when popping up this menu
  mRuleField->setSizeLimit( mRuleField->count() );
  mRuleField->adjustSize();

  connect( mRuleField, SIGNAL(textChanged(const QString &)),
	   this, SIGNAL(fieldChanged(const QString &)) );
  connect( mRuleValue, SIGNAL(textChanged(const QString &)),
	   this, SIGNAL(contentsChanged(const QString &)) );
}

void KMSearchRuleWidget::editRegExp()
{
  if ( mRegExpEditDialog == 0 )
    mRegExpEditDialog = KParts::ComponentFactory::createInstanceFromQuery<QDialog>( "KRegExpEditor/KRegExpEditor", QString::null, this );

  KRegExpEditorInterface *iface = static_cast<KRegExpEditorInterface *>( mRegExpEditDialog->qt_cast( "KRegExpEditorInterface" ) );
  if( iface ) {
    iface->setRegExp( mRuleValue->text() );
    if( mRegExpEditDialog->exec() == QDialog::Accepted )
      mRuleValue->setText( iface->regExp() );
  }
}

void KMSearchRuleWidget::functionChanged( int which )
{
  mRuleEditBut->setEnabled( which == 4 || which == 5 );
}

void KMSearchRuleWidget::setRule(KMSearchRule *aRule)
{
  assert ( aRule );

  blockSignals(TRUE);
  //--------------set the field
  int i = indexOfRuleField( aRule->field() );

  if ( i<0 ) { // not found -> user defined field
    mRuleField->changeItem( QString(aRule->field()), 0 );
    i=0;
  } else // found in the list of predefined fields
    mRuleField->changeItem( "", 0 );

  mRuleField->setCurrentItem( i );

  //--------------set function and contents
  mRuleFunc->setCurrentItem( (int)aRule->function() );
  mRuleValue->setText( aRule->contents() );

  if (mRuleEditBut)
    functionChanged( (int)aRule->function() );

  blockSignals(FALSE);
}

KMSearchRule* KMSearchRuleWidget::rule() const
{
  KMSearchRule *r = new KMSearchRule;

  r->init( ruleFieldToEnglish( mRuleField->currentText() ).latin1(),
	   (KMSearchRule::Function)mRuleFunc->currentItem(),
	   mRuleValue->text() );

  return r;
}

void KMSearchRuleWidget::reset()
{
  blockSignals(TRUE);

  mRuleField->changeItem( "", 0 );
  mRuleField->setCurrentItem( 0 );

  mRuleFunc->setCurrentItem( 0 );

  mRuleValue->clear();

  blockSignals(FALSE);
}

QString KMSearchRuleWidget::ruleFieldToEnglish(const QString & i18nVal) const
{
  if (i18nVal == i18n("<recipients>")) return QString::fromLatin1("<recipients>");
  if (i18nVal == i18n("<body>")) return QString::fromLatin1("<body>");
  if (i18nVal == i18n("<message>")) return QString::fromLatin1("<message>");
  if (i18nVal == i18n("<any header>")) return QString::fromLatin1("<any header>");
  if (i18nVal == i18n("<size>")) return QString::fromLatin1("<size>");
  if (i18nVal == i18n("<age in days>")) return QString::fromLatin1("<age in days>");
  return i18nVal;
}

int KMSearchRuleWidget::indexOfRuleField(const QString aName) const
{
  int i;

  if ( aName.isEmpty() ) return -1;

  QString i18n_aName = i18n( aName.latin1() );

  for (i=sFilterFieldList.count()-1; i>=0; i--) {
    if (*(sFilterFieldList.at(i))==i18n_aName) break;
  }
  return i;
}

void KMSearchRuleWidget::initLists(bool headersOnly) const
{
  //---------- initialize list of filter operators
  if ( sFilterFuncList.isEmpty() )
  {
    // also see KMSearchRule::matches() and KMSearchRule::Function
    // if you change the following strings!
    sFilterFuncList.append(i18n("contains"));
    sFilterFuncList.append(i18n("doesn't contain"));
    sFilterFuncList.append(i18n("equals"));
    sFilterFuncList.append(i18n("doesn't equal"));
    sFilterFuncList.append(i18n("matches regular expr."));
    sFilterFuncList.append(i18n("doesn't match reg. expr."));
    sFilterFuncList.append(i18n("is greater than"));
    sFilterFuncList.append(i18n("is less than or equal to"));
    sFilterFuncList.append(i18n("is less than"));
    sFilterFuncList.append(i18n("is greater than or equal to"));
  }

  //---------- initialize list of filter operators
  if ( sFilterFieldList.isEmpty() )
  {
    sFilterFieldList.append("");
    // also see KMSearchRule::matches() and ruleFieldToEnglish() if
    // you change the following i18n-ized strings!
    if( !headersOnly )  sFilterFieldList.append(i18n("<message>"));
    if( !headersOnly )  sFilterFieldList.append(i18n("<body>"));
    sFilterFieldList.append(i18n("<any header>"));
    sFilterFieldList.append(i18n("<recipients>"));
    sFilterFieldList.append(i18n("<size>"));
    sFilterFieldList.append(i18n("<age in days>"));
    // these others only represent message headers and you can add to
    // them as you like
    sFilterFieldList.append("Subject");
    sFilterFieldList.append("From");
    sFilterFieldList.append("To");
    sFilterFieldList.append("Cc");
    sFilterFieldList.append("Reply-To");
    sFilterFieldList.append("List-Id");
    sFilterFieldList.append("Organization");
    sFilterFieldList.append("Resent-From");
    sFilterFieldList.append("X-Loop");
    sFilterFieldList.append("X-Mailing-List");
  }
}

//=============================================================================
//
// class KMFilterActionWidgetLister (the filter action editor)
//
//=============================================================================

KMSearchRuleWidgetLister::KMSearchRuleWidgetLister( QWidget *parent, const char* name, bool headersOnly )
  : KWidgetLister( 2, FILTER_MAX_RULES, parent, name )
{
  mRuleList = 0;
  mHeadersOnly = headersOnly;
}

KMSearchRuleWidgetLister::~KMSearchRuleWidgetLister()
{
}

void KMSearchRuleWidgetLister::setRuleList( QPtrList<KMSearchRule> *aList )
{
  assert ( aList );

  if ( mRuleList )
    regenerateRuleListFromWidgets();

  mRuleList = aList;

  if ( mWidgetList.first() ) // move this below next 'if'?
    mWidgetList.first()->blockSignals(TRUE);

  if ( aList->count() == 0 ) {
    slotClear();
    mWidgetList.first()->blockSignals(FALSE);
    return;
  }

  int superfluousItems = (int)mRuleList->count() - mMaxWidgets ;
  if ( superfluousItems > 0 ) {
    kdDebug(5006) << "KMSearchRuleWidgetLister: Clipping rule list to "
		  << mMaxWidgets << " items!" << endl;

    for ( ; superfluousItems ; superfluousItems-- )
      mRuleList->removeLast();
  }

  // set the right number of widgets
  setNumberOfShownWidgetsTo( QMAX((int)mRuleList->count(),mMinWidgets) );

  // load the actions into the widgets
  QPtrListIterator<KMSearchRule> rIt( *mRuleList );
  QPtrListIterator<QWidget> wIt( mWidgetList );
  for ( rIt.toFirst(), wIt.toFirst() ;
	rIt.current() && wIt.current() ; ++rIt, ++wIt ) {
    ((KMSearchRuleWidget*)(*wIt))->setRule( (*rIt) );
  }
  for ( ; wIt.current() ; ++wIt )
    ((KMSearchRuleWidget*)(*wIt))->reset();

  assert( mWidgetList.first() );
  mWidgetList.first()->blockSignals(FALSE);
}

void KMSearchRuleWidgetLister::reset()
{
  if ( mRuleList )
    regenerateRuleListFromWidgets();

  mRuleList = 0;
  slotClear();
}

QWidget* KMSearchRuleWidgetLister::createWidget( QWidget *parent )
{
  return new KMSearchRuleWidget(parent, 0, 0, mHeadersOnly);
}

void KMSearchRuleWidgetLister::clearWidget( QWidget *aWidget )
{
  if ( aWidget )
    ((KMSearchRuleWidget*)aWidget)->reset();
}

void KMSearchRuleWidgetLister::regenerateRuleListFromWidgets()
{
  if ( !mRuleList ) return;

  mRuleList->clear();

  QPtrListIterator<QWidget> it( mWidgetList );
  for ( it.toFirst() ; it.current() ; ++it ) {
    KMSearchRule *r = ((KMSearchRuleWidget*)(*it))->rule();
    if ( r )
      mRuleList->append( r );
  }
}

//=============================================================================
//
// class KMSearchPatternEdit
//
//=============================================================================

KMSearchPatternEdit::KMSearchPatternEdit(QWidget *parent, const char *name, bool headersOnly )
  : QGroupBox( 1/*columns*/, Horizontal, parent, name )
{
  setTitle( i18n("Search Criteria") );
  initLayout( headersOnly );
}

KMSearchPatternEdit::KMSearchPatternEdit(const QString & title, QWidget *parent, const char *name, bool headersOnly )
  : QGroupBox( 1/*column*/, Horizontal, title, parent, name )
{
  initLayout( headersOnly );
}

KMSearchPatternEdit::~KMSearchPatternEdit()
{
}

void KMSearchPatternEdit::initLayout(bool headersOnly)
{
  //------------the radio buttons
  mAllRBtn = new QRadioButton( i18n("Match a&ll of the following"), this, "mAllRBtn" );
  mAnyRBtn = new QRadioButton( i18n("Match an&y of the following"), this, "mAnyRBtn" );

  mAllRBtn->setChecked(TRUE);
  mAnyRBtn->setChecked(FALSE);

  QButtonGroup *bg = new QButtonGroup( this );
  bg->hide();
  bg->insert( mAllRBtn, (int)KMSearchPattern::OpAnd );
  bg->insert( mAnyRBtn, (int)KMSearchPattern::OpOr );

  //------------the list of KMSearchRuleWidget's
  mRuleLister = new KMSearchRuleWidgetLister( this, "swl", headersOnly );
  mRuleLister->slotClear();

  //------------connect a few signals
  connect( bg, SIGNAL(clicked(int)),
	   this, SLOT(slotRadioClicked(int)) );

  KMSearchRuleWidget *srw = (KMSearchRuleWidget*)mRuleLister->mWidgetList.first();
  if ( srw ) {
    connect( srw, SIGNAL(fieldChanged(const QString &)),
	     this, SLOT(slotAutoNameHack()) );
    connect( srw, SIGNAL(contentsChanged(const QString &)),
	     this, SLOT(slotAutoNameHack()) );
  } else
    kdDebug(5006) << "KMSearchPatternEdit: no first KMSearchRuleWidget, though slotClear() has been called!" << endl;
}

void KMSearchPatternEdit::setSearchPattern( KMSearchPattern *aPattern )
{
  assert( aPattern );

  mRuleLister->setRuleList( aPattern );

  mPattern = aPattern;

  blockSignals(TRUE);
  if ( mPattern->op() == KMSearchPattern::OpOr )
    mAnyRBtn->setChecked(TRUE);
  else
    mAllRBtn->setChecked(TRUE);
  blockSignals(FALSE);

  setEnabled( TRUE );
}

void KMSearchPatternEdit::reset()
{
  mRuleLister->reset();

  blockSignals(TRUE);
  mAllRBtn->setChecked( TRUE );
  blockSignals(FALSE);

  setEnabled( FALSE );
}

void KMSearchPatternEdit::slotRadioClicked(int aIdx)
{
  if ( mPattern )
    mPattern->setOp( (KMSearchPattern::Operator)aIdx );
}

void KMSearchPatternEdit::slotAutoNameHack()
{
  mRuleLister->regenerateRuleListFromWidgets();
  emit maybeNameChanged();
}

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


<commit_before>#define BOOST_TEST_MODULE json test
#include <boost/test/unit_test.hpp>
#include "json.hh"

using namespace ten;

const char json_text[] =
"{ \"store\": {"
"    \"book\": ["
"      { \"category\": \"reference\","
"        \"author\": \"Nigel Rees\","
"        \"title\": \"Sayings of the Century\","
"        \"price\": 8.95"
"      },"
"      { \"category\": \"fiction\","
"        \"author\": \"Evelyn Waugh\","
"        \"title\": \"Sword of Honour\","
"        \"price\": 12.99"
"      },"
"      { \"category\": \"fiction\","
"        \"author\": \"Herman Melville\","
"        \"title\": \"Moby Dick\","
"        \"isbn\": \"0-553-21311-3\","
"        \"price\": 8.99"
"      },"
"      { \"category\": \"fiction\","
"        \"author\": \"J. R. R. Tolkien\","
"        \"title\": \"The Lord of the Rings\","
"        \"isbn\": \"0-395-19395-8\","
"        \"price\": 22.99"
"      }"
"    ],"
"    \"bicycle\": {"
"      \"color\": \"red\","
"      \"price\": 19.95"
"    }"
"  }"
"}";

BOOST_AUTO_TEST_CASE(json_test_path1) {
    json o(json::load(json_text));
    BOOST_REQUIRE(o.get());

    static const char a1[] = "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]";
    json r1(o.path("/store/book/author"));
    BOOST_CHECK_EQUAL(json::load(a1), r1);

    json r2(o.path("//author"));
    BOOST_CHECK_EQUAL(json::load(a1), r2);

    // jansson hashtable uses size_t for hash
    // we think this is causing the buckets to change on 32bit vs. 64bit
#if (__SIZEOF_SIZE_T__ == 4)
    static const char a3[] = "[{\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}, {\"color\": \"red\", \"price\": 19.95}]";
#elif (__SIZEOF_SIZE_T__ == 8)
    static const char a3[] = "[{\"color\": \"red\", \"price\": 19.95}, {\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]";
#endif
    json r3(o.path("/store/*"));
    json t3(json::load(a3));
    BOOST_CHECK_EQUAL(t3, r3);

#if (__SIZEOF_SIZE_T__ == 4)
    static const char a4[] = "[8.95, 12.99, 8.99, 22.99, 19.95]";
#elif (__SIZEOF_SIZE_T__ == 8)
    static const char a4[] = "[19.95, 8.95, 12.99, 8.99, 22.99]";
#endif
    json r4(o.path("/store//price"));
    BOOST_CHECK_EQUAL(json::load(a4), r4);

    static const char a5[] = "{\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}";
    json r5(o.path("//book[3]"));
    BOOST_CHECK_EQUAL(json::load(a5), r5);

    static const char a6[] = "\"J. R. R. Tolkien\"";
    json r6(o.path("/store/book[3]/author"));
    BOOST_CHECK_EQUAL(json::load(a6), r6);
    BOOST_CHECK(json::load(a6) == r6);

    static const char a7[] = "[{\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]";
    json r7(o.path("/store/book[category=\"fiction\"]"));
    BOOST_CHECK_EQUAL(json::load(a7), r7);
}

BOOST_AUTO_TEST_CASE(json_test_path2) {
    json o(json::load("[{\"type\": 0}, {\"type\": 1}]"));
    BOOST_CHECK_EQUAL(json::load("[{\"type\":1}]"), o.path("/[type=1]"));
}

BOOST_AUTO_TEST_CASE(json_test_filter_key_exists) {
    json o(json::load(json_text));
    BOOST_REQUIRE(o.get());

    static const char a[] = "["
"      { \"category\": \"fiction\","
"        \"author\": \"Herman Melville\","
"        \"title\": \"Moby Dick\","
"        \"isbn\": \"0-553-21311-3\","
"        \"price\": 8.99"
"      },"
"      { \"category\": \"fiction\","
"        \"author\": \"J. R. R. Tolkien\","
"        \"title\": \"The Lord of the Rings\","
"        \"isbn\": \"0-395-19395-8\","
"        \"price\": 22.99"
"      }]";
    json r(o.path("//book[isbn]"));
    BOOST_CHECK_EQUAL(json::load(a), r);

    json r1(o.path("//book[doesnotexist]"));
    BOOST_REQUIRE(r1.is_array());
    BOOST_CHECK_EQUAL(0, r1.asize());
}

BOOST_AUTO_TEST_CASE(json_test_path3) {
    json o(json::load(json_text));
    BOOST_REQUIRE(o.get());

    BOOST_CHECK_EQUAL(o, o.path("/"));
    BOOST_CHECK_EQUAL("Sayings of the Century",
        o.path("/store/book[category=\"reference\"]/title"));

    static const char text[] = "["
    "{\"type\":\"a\", \"value\":0},"
    "{\"type\":\"b\", \"value\":1},"
    "{\"type\":\"c\", \"value\":2},"
    "{\"type\":\"c\", \"value\":3}"
    "]";

    BOOST_CHECK_EQUAL(json(1), json::load(text).path("/[type=\"b\"]/value"));
}
<commit_msg>new tests<commit_after>#define BOOST_TEST_MODULE json test
#include <boost/test/unit_test.hpp>
#include "json.hh"

using namespace ten;

const char json_text[] =
"{ \"store\": {"
"    \"book\": ["
"      { \"category\": \"reference\","
"        \"author\": \"Nigel Rees\","
"        \"title\": \"Sayings of the Century\","
"        \"price\": 8.95"
"      },"
"      { \"category\": \"fiction\","
"        \"author\": \"Evelyn Waugh\","
"        \"title\": \"Sword of Honour\","
"        \"price\": 12.99"
"      },"
"      { \"category\": \"fiction\","
"        \"author\": \"Herman Melville\","
"        \"title\": \"Moby Dick\","
"        \"isbn\": \"0-553-21311-3\","
"        \"price\": 8.99"
"      },"
"      { \"category\": \"fiction\","
"        \"author\": \"J. R. R. Tolkien\","
"        \"title\": \"The Lord of the Rings\","
"        \"isbn\": \"0-395-19395-8\","
"        \"price\": 22.99"
"      }"
"    ],"
"    \"bicycle\": {"
"      \"color\": \"red\","
"      \"price\": 19.95"
"    }"
"  }"
"}";

BOOST_AUTO_TEST_CASE(json_test_path1) {
    json o(json::load(json_text));
    BOOST_REQUIRE(o.get());

    static const char a1[] = "[\"Nigel Rees\", \"Evelyn Waugh\", \"Herman Melville\", \"J. R. R. Tolkien\"]";
    json r1(o.path("/store/book/author"));
    BOOST_CHECK_EQUAL(json::load(a1), r1);

    json r2(o.path("//author"));
    BOOST_CHECK_EQUAL(json::load(a1), r2);

    // jansson hashtable uses size_t for hash
    // we think this is causing the buckets to change on 32bit vs. 64bit
#if (__SIZEOF_SIZE_T__ == 4)
    static const char a3[] = "[{\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}, {\"color\": \"red\", \"price\": 19.95}]";
#elif (__SIZEOF_SIZE_T__ == 8)
    static const char a3[] = "[{\"color\": \"red\", \"price\": 19.95}, {\"category\": \"reference\", \"author\": \"Nigel Rees\", \"title\": \"Sayings of the Century\", \"price\": 8.95}, {\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]";
#endif
    json r3(o.path("/store/*"));
    json t3(json::load(a3));
    BOOST_CHECK_EQUAL(t3, r3);

#if (__SIZEOF_SIZE_T__ == 4)
    static const char a4[] = "[8.95, 12.99, 8.99, 22.99, 19.95]";
#elif (__SIZEOF_SIZE_T__ == 8)
    static const char a4[] = "[19.95, 8.95, 12.99, 8.99, 22.99]";
#endif
    json r4(o.path("/store//price"));
    BOOST_CHECK_EQUAL(json::load(a4), r4);

    static const char a5[] = "{\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}";
    json r5(o.path("//book[3]"));
    BOOST_CHECK_EQUAL(json::load(a5), r5);

    static const char a6[] = "\"J. R. R. Tolkien\"";
    json r6(o.path("/store/book[3]/author"));
    BOOST_CHECK_EQUAL(json::load(a6), r6);
    BOOST_CHECK(json::load(a6) == r6);

    static const char a7[] = "[{\"category\": \"fiction\", \"author\": \"Evelyn Waugh\", \"title\": \"Sword of Honour\", \"price\": 12.99}, {\"category\": \"fiction\", \"author\": \"Herman Melville\", \"title\": \"Moby Dick\", \"isbn\": \"0-553-21311-3\", \"price\": 8.99}, {\"category\": \"fiction\", \"author\": \"J. R. R. Tolkien\", \"title\": \"The Lord of the Rings\", \"isbn\": \"0-395-19395-8\", \"price\": 22.99}]";
    json r7(o.path("/store/book[category=\"fiction\"]"));
    BOOST_CHECK_EQUAL(json::load(a7), r7);
}

BOOST_AUTO_TEST_CASE(json_test_path2) {
    json o(json::load("[{\"type\": 0}, {\"type\": 1}]"));
    BOOST_CHECK_EQUAL(json::load("[{\"type\":1}]"), o.path("/[type=1]"));
}

BOOST_AUTO_TEST_CASE(json_test_filter_key_exists) {
    json o(json::load(json_text));
    BOOST_REQUIRE(o.get());

    static const char a[] = "["
"      { \"category\": \"fiction\","
"        \"author\": \"Herman Melville\","
"        \"title\": \"Moby Dick\","
"        \"isbn\": \"0-553-21311-3\","
"        \"price\": 8.99"
"      },"
"      { \"category\": \"fiction\","
"        \"author\": \"J. R. R. Tolkien\","
"        \"title\": \"The Lord of the Rings\","
"        \"isbn\": \"0-395-19395-8\","
"        \"price\": 22.99"
"      }]";
    json r(o.path("//book[isbn]"));
    BOOST_CHECK_EQUAL(json::load(a), r);

    json r1(o.path("//book[doesnotexist]"));
    BOOST_REQUIRE(r1.is_array());
    BOOST_CHECK_EQUAL(0, r1.asize());
}

BOOST_AUTO_TEST_CASE(json_test_truth) {
    json o(json::object());
    BOOST_CHECK(o.oget("nothing").is_true() == false);
    BOOST_CHECK(o.oget("nothing").is_false() == false);
    BOOST_CHECK(o.oget("nothing").is_null() == false);
    BOOST_CHECK(!o.oget("nothing"));
}

BOOST_AUTO_TEST_CASE(json_test_path3) {
    json o(json::load(json_text));
    BOOST_REQUIRE(o.get());

    BOOST_CHECK_EQUAL(o, o.path("/"));
    BOOST_CHECK_EQUAL("Sayings of the Century",
        o.path("/store/book[category=\"reference\"]/title"));

    static const char text[] = "["
    "{\"type\":\"a\", \"value\":0},"
    "{\"type\":\"b\", \"value\":1},"
    "{\"type\":\"c\", \"value\":2},"
    "{\"type\":\"c\", \"value\":3}"
    "]";

    BOOST_CHECK_EQUAL(json(1), json::load(text).path("/[type=\"b\"]/value"));
}
<|endoftext|>


<commit_before>#pragma once

#include "constants.hpp"
#include "device_grabber.hpp"
#include "event_dispatcher_manager.hpp"
#include "local_datagram_server.hpp"
#include "process_monitor.hpp"
#include "session.hpp"
#include "types.hpp"
#include <vector>

class grabber_server final {
public:
  grabber_server(const grabber_server&) = delete;

  grabber_server(event_dispatcher_manager& event_dispatcher_manager,
                 device_grabber& device_grabber) : event_dispatcher_manager_(event_dispatcher_manager),
                                                   device_grabber_(device_grabber),
                                                   exit_loop_(false) {
    const size_t buffer_length = 1024 * 1024;
    buffer_.resize(buffer_length);

    const char* path = constants::get_grabber_socket_file_path();
    unlink(path);
    server_ = std::make_unique<local_datagram_server>(path);

    if (auto uid = session::get_current_console_user_id()) {
      chown(path, *uid, 0);
    }
    chmod(path, 0600);

    exit_loop_ = false;
    thread_ = std::thread([this] { this->worker(); });
  }

  ~grabber_server(void) {
    unlink(constants::get_grabber_socket_file_path());

    exit_loop_ = true;
    if (thread_.joinable()) {
      thread_.join();
    }

    server_ = nullptr;
    console_user_server_process_monitor_ = nullptr;
    device_grabber_.ungrab_devices();
  }

private:
  void worker(void) {
    if (!server_) {
      return;
    }

    while (!exit_loop_) {
      boost::system::error_code ec;
      std::size_t n = server_->receive(boost::asio::buffer(buffer_), boost::posix_time::seconds(1), ec);

      if (!ec && n > 0) {
        switch (krbn::operation_type(buffer_[0])) {
        case krbn::operation_type::connect:
          if (n != sizeof(krbn::operation_type_connect_struct)) {
            logger::get_logger().error("invalid size for krbn::operation_type::connect");
          } else {
            auto p = reinterpret_cast<krbn::operation_type_connect_struct*>(&(buffer_[0]));

            switch (p->connect_from) {
            case krbn::connect_from::event_dispatcher:
              logger::get_logger().info("karabiner_event_dispatcher is connected (pid:{0})", p->pid);
              event_dispatcher_manager_.create_event_dispatcher_client();
              break;

            case krbn::connect_from::console_user_server:
              logger::get_logger().info("karabiner_grabber is connected (pid:{0})", p->pid);

              device_grabber_.post_connect_ack();
              device_grabber_.grab_devices();

              // monitor the last process
              console_user_server_process_monitor_ = nullptr;
              console_user_server_process_monitor_ = std::make_unique<process_monitor>(logger::get_logger(),
                                                                                p->pid,
                                                                                std::bind(&grabber_server::console_user_server_exit_callback, this));

              break;
            }
          }
          break;

        case krbn::operation_type::system_preferences_values_updated:
          if (n < sizeof(krbn::operation_type_system_preferences_values_updated_struct)) {
            logger::get_logger().error("invalid size for krbn::operation_type::system_preferences_values_updated ({0})", n);
          } else {
            logger::get_logger().info("system_preferences_values_updated");
          }
          break;

        case krbn::operation_type::set_caps_lock_led_state:
          if (n < sizeof(krbn::operation_type_set_caps_lock_led_state_struct)) {
            logger::get_logger().error("invalid size for krbn::operation_type::set_caps_lock_led_state ({0})", n);
          } else {
            auto p = reinterpret_cast<krbn::operation_type_set_caps_lock_led_state_struct*>(&(buffer_[0]));
            // bind variables
            auto led_state = p->led_state;
            dispatch_async(dispatch_get_main_queue(), ^{
              device_grabber_.set_caps_lock_led_state(led_state);
            });
          }
          break;

        case krbn::operation_type::clear_simple_modifications:
          device_grabber_.clear_simple_modifications();
          break;

        case krbn::operation_type::add_simple_modification:
          if (n < sizeof(krbn::operation_type_add_simple_modification_struct)) {
            logger::get_logger().error("invalid size for krbn::operation_type::add_simple_modification ({0})", n);
          } else {
            auto p = reinterpret_cast<krbn::operation_type_add_simple_modification_struct*>(&(buffer_[0]));
            device_grabber_.add_simple_modification(p->from_key_code, p->to_key_code);
          }
          break;

        default:
          break;
        }
      }
    }
  }

  void console_user_server_exit_callback(void) {
    device_grabber_.ungrab_devices();
  }

  event_dispatcher_manager& event_dispatcher_manager_;
  device_grabber& device_grabber_;

  std::vector<uint8_t> buffer_;
  std::unique_ptr<local_datagram_server> server_;
  std::thread thread_;
  std::atomic<bool> exit_loop_;

  std::unique_ptr<process_monitor> console_user_server_process_monitor_;
};
<commit_msg>fix log message<commit_after>#pragma once

#include "constants.hpp"
#include "device_grabber.hpp"
#include "event_dispatcher_manager.hpp"
#include "local_datagram_server.hpp"
#include "process_monitor.hpp"
#include "session.hpp"
#include "types.hpp"
#include <vector>

class grabber_server final {
public:
  grabber_server(const grabber_server&) = delete;

  grabber_server(event_dispatcher_manager& event_dispatcher_manager,
                 device_grabber& device_grabber) : event_dispatcher_manager_(event_dispatcher_manager),
                                                   device_grabber_(device_grabber),
                                                   exit_loop_(false) {
    const size_t buffer_length = 1024 * 1024;
    buffer_.resize(buffer_length);

    const char* path = constants::get_grabber_socket_file_path();
    unlink(path);
    server_ = std::make_unique<local_datagram_server>(path);

    if (auto uid = session::get_current_console_user_id()) {
      chown(path, *uid, 0);
    }
    chmod(path, 0600);

    exit_loop_ = false;
    thread_ = std::thread([this] { this->worker(); });
  }

  ~grabber_server(void) {
    unlink(constants::get_grabber_socket_file_path());

    exit_loop_ = true;
    if (thread_.joinable()) {
      thread_.join();
    }

    server_ = nullptr;
    console_user_server_process_monitor_ = nullptr;
    device_grabber_.ungrab_devices();
  }

private:
  void worker(void) {
    if (!server_) {
      return;
    }

    while (!exit_loop_) {
      boost::system::error_code ec;
      std::size_t n = server_->receive(boost::asio::buffer(buffer_), boost::posix_time::seconds(1), ec);

      if (!ec && n > 0) {
        switch (krbn::operation_type(buffer_[0])) {
        case krbn::operation_type::connect:
          if (n != sizeof(krbn::operation_type_connect_struct)) {
            logger::get_logger().error("invalid size for krbn::operation_type::connect");
          } else {
            auto p = reinterpret_cast<krbn::operation_type_connect_struct*>(&(buffer_[0]));

            switch (p->connect_from) {
            case krbn::connect_from::event_dispatcher:
              logger::get_logger().info("karabiner_event_dispatcher is connected (pid:{0})", p->pid);
              event_dispatcher_manager_.create_event_dispatcher_client();
              break;

            case krbn::connect_from::console_user_server:
              logger::get_logger().info("karabiner_console_user_server is connected (pid:{0})", p->pid);

              device_grabber_.post_connect_ack();
              device_grabber_.grab_devices();

              // monitor the last process
              console_user_server_process_monitor_ = nullptr;
              console_user_server_process_monitor_ = std::make_unique<process_monitor>(logger::get_logger(),
                                                                                p->pid,
                                                                                std::bind(&grabber_server::console_user_server_exit_callback, this));

              break;
            }
          }
          break;

        case krbn::operation_type::system_preferences_values_updated:
          if (n < sizeof(krbn::operation_type_system_preferences_values_updated_struct)) {
            logger::get_logger().error("invalid size for krbn::operation_type::system_preferences_values_updated ({0})", n);
          } else {
            logger::get_logger().info("system_preferences_values_updated");
          }
          break;

        case krbn::operation_type::set_caps_lock_led_state:
          if (n < sizeof(krbn::operation_type_set_caps_lock_led_state_struct)) {
            logger::get_logger().error("invalid size for krbn::operation_type::set_caps_lock_led_state ({0})", n);
          } else {
            auto p = reinterpret_cast<krbn::operation_type_set_caps_lock_led_state_struct*>(&(buffer_[0]));
            // bind variables
            auto led_state = p->led_state;
            dispatch_async(dispatch_get_main_queue(), ^{
              device_grabber_.set_caps_lock_led_state(led_state);
            });
          }
          break;

        case krbn::operation_type::clear_simple_modifications:
          device_grabber_.clear_simple_modifications();
          break;

        case krbn::operation_type::add_simple_modification:
          if (n < sizeof(krbn::operation_type_add_simple_modification_struct)) {
            logger::get_logger().error("invalid size for krbn::operation_type::add_simple_modification ({0})", n);
          } else {
            auto p = reinterpret_cast<krbn::operation_type_add_simple_modification_struct*>(&(buffer_[0]));
            device_grabber_.add_simple_modification(p->from_key_code, p->to_key_code);
          }
          break;

        default:
          break;
        }
      }
    }
  }

  void console_user_server_exit_callback(void) {
    device_grabber_.ungrab_devices();
  }

  event_dispatcher_manager& event_dispatcher_manager_;
  device_grabber& device_grabber_;

  std::vector<uint8_t> buffer_;
  std::unique_ptr<local_datagram_server> server_;
  std::thread thread_;
  std::atomic<bool> exit_loop_;

  std::unique_ptr<process_monitor> console_user_server_process_monitor_;
};
<|endoftext|>


<commit_before>#include "test/util.hpp"
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <cstring>
#include <bitset>
#include <algorithm>
#include <tudocomp/coders/HuffmanCoder.hpp>

void test_huffmantable_storing(const std::string& text) {
	using namespace tdc::huff;
	if(text.length() <=  1) return;
	extended_huffmantable table = gen_huffmantable(text);
	std::stringstream ss;
	{
		tdc::io::Output out(ss);
		tdc::io::BitOStream bit_os(out);
		huffmantable_encode(bit_os, table);
	}

		tdc::io::Input in(ss);
		tdc::io::BitIStream bit_in(in);
		huffmantable tab2 = huffmantable_decode(bit_in);

	ASSERT_EQ(table.longest, tab2.longest);
	ASSERT_EQ(table.alphabet_size, tab2.alphabet_size);
	for(size_t i = 0; i < table.longest; ++i) {
		ASSERT_EQ(table.numl[i], tab2.numl[i]);
	}
	for(size_t i = 0; i < table.alphabet_size; ++i) {
		ASSERT_EQ(table.ordered_map_from_effective[i], tab2.ordered_map_from_effective[i]);
	}
	const uint8_t*const ordered_codelengths2 = gen_ordered_codelength(table.alphabet_size, table.numl, table.longest);
	for(size_t i = 0; i < table.alphabet_size; ++i) {
		ASSERT_EQ(ordered_codelengths2[i], table.ordered_codelengths[i]);
	}
	delete [] ordered_codelengths2;
}

void test_huffmantable_coding(const std::string& text) {
	using namespace tdc::huff;
	if(text.length() <=  1) return;
	extended_huffmantable table = gen_huffmantable(text);
	//encode
	std::stringstream input(text);
	std::stringstream output;

	{//write
		tdc::io::Output out(output);
		tdc::io::BitOStream bit_os(out);
		huffman_encode(input, bit_os, text.length(), table.ordered_map_from_effective, table.ordered_codelengths, table.alphabet_size, table.codewords);
	}

	{//read
		tdc::io::Input in(output);
		tdc::io::BitIStream bit_in(in);

	//decode
	input.clear();
	input.str(std::string{});
	huffman_decode(
			bit_in,
			input,
			table.ordered_map_from_effective,
			table.ordered_codelengths,
			table.alphabet_size,
			table.numl,
			table.longest);
	}
	ASSERT_EQ(input.str(), text);
    ASSERT_EQ(input.str().size(), text.size());
}

void test_huff(const std::string& text) {
	using namespace tdc::huff;
	if(text.length() <=  1) return;
	test_huffmantable_coding(text);
	test_huffmantable_storing(text);

	std::stringstream soutput;
	std::stringstream sback;
	{
		tdc::io::Input in(text);
		tdc::io::Output out(soutput);
		encode(in, out);
	}
	{

		std::string s = soutput.str();
		tdc::io::Input in(s);
		tdc::io::Output out(sback);
		decode(in, out);
	}
	auto sbacks = sback.str();
	ASSERT_EQ(text, sbacks);
    ASSERT_EQ(text.size(), sbacks.size());
}

TEST(huffman, stringgenerators) {
	std::function<void(std::string&)> func(test_huff);
	test::on_string_generators(func,20);
}

// #include "tudocomp/util/Generators.hpp"
// TEST(Sandbox, example) {
//
// 	{
// 		std::string s = thue_morse_word(10);
// 		// tdc::io::Input input(s);
// 		// auto iview = input.as_view();
// 		// auto iview2 = input.as_view();
// 		// DCHECK_EQ(iview.size(), iview2.size());
// 		test(s);
// 	}
// 	// for(size_t i = 8; i < n; ++i) {
// 	// 	std::cout << "String " << i << std::endl;
// 	// 	std::string s = thue_morse_word(i);
// 	// 	test(s);
// 	// }
// 	size_t n = 100;
// 	for(size_t i = 2; i < n; ++i) {
// 	 	for(size_t j = 0; j < i; ++j) {
// 	 		std::string s = random_uniform(2*i,Ranges::numbers,j);
// 			DLOG(INFO) << "i = " << i << " j = " << j;
// 				test(s);
// 		}
// 	}
// 	n=20;
// 	for(size_t i = 2; i < n; ++i) {
// 	 	for(size_t j = 0; j < 2+50/(i+1); ++j) {
// 	 		std::string s = random_uniform(1<<i,Ranges::numbers,j);
// 			DLOG(INFO) << "i = " << i << " j = " << j;
// 				test(s);
// 		}
// 	}
//
// }

TEST(huff, nullbyte) {
    test_huff("hel\0lo"_v);
    test_huff("hello\0"_v);
    test_huff("hello\0\0\0"_v);
}

TEST(Coder, binary_output) {
    //auto v = "abcabacba"_v;
    //test::TestOutput o(false);
    //auto coder = tdc::create_algo<HuffmanCoder::Encoder>("", o, ViewLiterals(v));
}
<commit_msg>Added more detailed huffman tests<commit_after>#include "test/util.hpp"
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <cstring>
#include <bitset>
#include <algorithm>
#include <tudocomp/coders/HuffmanCoder.hpp>

void test_huffmantable_storing(const std::string& text) {
	using namespace tdc::huff;
	if(text.length() <=  1) return;
	extended_huffmantable table = gen_huffmantable(text);
	std::stringstream ss;
	{
		tdc::io::Output out(ss);
		tdc::io::BitOStream bit_os(out);
		huffmantable_encode(bit_os, table);
	}

		tdc::io::Input in(ss);
		tdc::io::BitIStream bit_in(in);
		huffmantable tab2 = huffmantable_decode(bit_in);

	ASSERT_EQ(table.longest, tab2.longest);
	ASSERT_EQ(table.alphabet_size, tab2.alphabet_size);
	for(size_t i = 0; i < table.longest; ++i) {
		ASSERT_EQ(table.numl[i], tab2.numl[i]);
	}
	for(size_t i = 0; i < table.alphabet_size; ++i) {
		ASSERT_EQ(table.ordered_map_from_effective[i], tab2.ordered_map_from_effective[i]);
	}
	const uint8_t*const ordered_codelengths2 = gen_ordered_codelength(table.alphabet_size, table.numl, table.longest);
	for(size_t i = 0; i < table.alphabet_size; ++i) {
		ASSERT_EQ(ordered_codelengths2[i], table.ordered_codelengths[i]);
	}
	delete [] ordered_codelengths2;
}

void test_huffmantable_coding(const std::string& text) {
	using namespace tdc::huff;
	if(text.length() <=  1) return;
	extended_huffmantable table = gen_huffmantable(text);
	//encode
	std::stringstream input(text);
	std::stringstream output;

	{//write
		tdc::io::Output out(output);
		tdc::io::BitOStream bit_os(out);
		huffman_encode(input, bit_os, text.length(), table.ordered_map_from_effective, table.ordered_codelengths, table.alphabet_size, table.codewords);
	}

	{//read
		tdc::io::Input in(output);
		tdc::io::BitIStream bit_in(in);

	//decode
	input.clear();
	input.str(std::string{});
	huffman_decode(
			bit_in,
			input,
			table.ordered_map_from_effective,
			table.ordered_codelengths,
			table.alphabet_size,
			table.numl,
			table.longest);
	}
	ASSERT_EQ(input.str(), text);
    ASSERT_EQ(input.str().size(), text.size());
}

void test_huff(const std::string& text) {
	using namespace tdc::huff;
	if(text.length() <=  1) return;
	test_huffmantable_coding(text);
	test_huffmantable_storing(text);

	std::stringstream soutput;
	std::stringstream sback;
	{
		tdc::io::Input in(text);
		tdc::io::Output out(soutput);
		encode(in, out);
	}
	{

		std::string s = soutput.str();
		tdc::io::Input in(s);
		tdc::io::Output out(sback);
		decode(in, out);
	}
	auto sbacks = sback.str();
	ASSERT_EQ(text, sbacks);
    ASSERT_EQ(text.size(), sbacks.size());
}

TEST(huffman, stringgenerators) {
	std::function<void(std::string&)> func(test_huff);
	test::on_string_generators(func,20);
}

// #include "tudocomp/util/Generators.hpp"
// TEST(Sandbox, example) {
//
// 	{
// 		std::string s = thue_morse_word(10);
// 		// tdc::io::Input input(s);
// 		// auto iview = input.as_view();
// 		// auto iview2 = input.as_view();
// 		// DCHECK_EQ(iview.size(), iview2.size());
// 		test(s);
// 	}
// 	// for(size_t i = 8; i < n; ++i) {
// 	// 	std::cout << "String " << i << std::endl;
// 	// 	std::string s = thue_morse_word(i);
// 	// 	test(s);
// 	// }
// 	size_t n = 100;
// 	for(size_t i = 2; i < n; ++i) {
// 	 	for(size_t j = 0; j < i; ++j) {
// 	 		std::string s = random_uniform(2*i,Ranges::numbers,j);
// 			DLOG(INFO) << "i = " << i << " j = " << j;
// 				test(s);
// 		}
// 	}
// 	n=20;
// 	for(size_t i = 2; i < n; ++i) {
// 	 	for(size_t j = 0; j < 2+50/(i+1); ++j) {
// 	 		std::string s = random_uniform(1<<i,Ranges::numbers,j);
// 			DLOG(INFO) << "i = " << i << " j = " << j;
// 				test(s);
// 		}
// 	}
//
// }

TEST(huff, nullbyte) {
    test_huff("hel\0lo"_v);
    test_huff("hello\0"_v);
    test_huff("hello\0\0\0"_v);
}

void test_binary_out(string_ref in, std::vector<uint64_t> packed_ints_out) {
    auto v = in;
    test::TestOutput o(false);
    {
        auto env = tdc::builder<HuffmanCoder>().env();
        typename HuffmanCoder::Encoder coder(std::move(env), o, ViewLiterals(v));

        for (auto c : v) {
            //coder.encode(c, literal_r);
        }
    }
    auto res = o.result();
    test::assert_eq_binary(res, packed_ints_out);
}

TEST(Coder, binary_output) {
    test_binary_out("abcabacba"_v, {
        // leading 1 bit to signify start of header
        0b1,       1,

        // compressed int, table.longest == 2
        0b0,       1,
        0b0000010, 7, // == 2

        // compressed int, numl[0]
        0b0,       1,
        0b0000001, 7, // == 1

        // compressed int, numl[1]
        0b0,       1,
        0b0000010, 7, // == 2

        // compressed int, alphabet_size
        0b0,       1,
        0b0000011, 7, // == 3

        // characters
        0b01100001, 8, // == 97 == 'a'
        0b01100010, 8, // == 98 == 'b'
        0b01100011, 8, // == 99 == 'c'

        // BitOStream termination
        0b0000001, 7, // 1 valid bit at the end
    });
}

TEST(Coder, binary_output_null) {
    test_binary_out("ab\0""aba\0""ba"_v, {
        // leading 1 bit to signify start of header
        0b1,       1,

        // compressed int, table.longest == 2
        0b0,       1,
        0b0000010, 7, // == 2

        // compressed int, numl[0]
        0b0,       1,
        0b0000001, 7, // == 1

        // compressed int, numl[1]
        0b0,       1,
        0b0000010, 7, // == 2

        // compressed int, alphabet_size
        0b0,       1,
        0b0000011, 7, // == 3

        // characters
        0b01100001, 8, // == 97 == 'a'
        0b01100010, 8, // == 98 == 'b'
        0b00000000, 8, // == 0 == '\0'

        // BitOStream termination
        0b0000001, 7, // 1 valid bit at the end
    });
}
<|endoftext|>


<commit_before>///
/// @file  pi_deleglise_rivat1.cpp
/// @brief Implementation of the Lagarias-Miller-Odlyzko prime counting
///        algorithm with the improvements of Deleglise and Rivat.
///        This implementation is based on src/lmo/pi_lmo5.cpp and the
///        paper: Tomás Oliveira e Silva, Computing pi(x): the
///        combinatorial method, Revista do DETUA, vol. 4, no. 6, March
///        2006, pp. 759-768.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primecount-internal.hpp>
#include <primesieve.hpp>
#include <BitSieve.hpp>
#include <pmath.hpp>
#include <PhiTiny.hpp>
#include <tos_counters.hpp>

#include <stdint.h>
#include <algorithm>
#include <vector>

using namespace std;
using namespace primecount;

namespace {

/// Cross-off the multiples of prime in the sieve array.
/// For each element that is unmarked the first time update
/// the special counters tree data structure.
///
template <typename T1, typename T2>
void cross_off(int64_t prime, int64_t low, int64_t high, int64_t& next_multiple, T1& sieve, T2& counters)
{
  int64_t segment_size = sieve.size();
  int64_t k = next_multiple;

  for (; k < high; k += prime * 2)
  {
    if (sieve[k - low])
    {
      sieve.unset(k - low);
      cnt_update(counters, k - low, segment_size);
    }
  }
  next_multiple = k;
}

/// Calculate the contribution of the special leaves.
/// @see ../docs/computing-special-leaves.md
/// @pre y > 0 && c > 1
///
int64_t S2(int64_t x,
           int64_t y,
           int64_t z,
           int64_t pi_y,
           int64_t c,
           vector<int32_t>& primes,
           vector<int32_t>& lpf,
           vector<int32_t>& mu)
{
  int64_t limit = z + 1;
  int64_t segment_size = next_power_of_2(isqrt(limit));
  int64_t pi_sqrty = pi_bsearch(primes, isqrt(y));
  int64_t S2_result = 0;

  BitSieve sieve(segment_size);
  vector<int32_t> counters(segment_size);
  vector<int32_t> pi = make_pi(y);
  vector<int64_t> next(primes.begin(), primes.end());
  vector<int64_t> phi(primes.size(), 0);

  // Segmented sieve of Eratosthenes
  for (int64_t low = 1; low < limit; low += segment_size)
  {
    // Current segment = interval [low, high[
    int64_t high = min(low + segment_size, limit);
    int64_t b = 2;

    sieve.memset(low);

    // phi(y, b) nodes with b <= c do not contribute to S2, so we
    // simply sieve out the multiples of the first c primes
    for (; b <= c; b++)
    {
      int64_t k = next[b];
      for (int64_t prime = primes[b]; k < high; k += prime * 2)
        sieve.unset(k - low);
      next[b] = k;
    }

    // Initialize special tree data structure from sieve
    cnt_finit(sieve, counters, segment_size);

    // For c + 1 <= b <= pi_sqrty
    // Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m]
    // which satisfy: low <= (x / n) < high
    for (; b <= pi_sqrty; b++)
    {
      int64_t prime = primes[b];
      int64_t min_m = max(x / (prime * high), y / prime);
      int64_t max_m = min(x / (prime * low), y);

      if (prime >= max_m)
        goto next_segment;

      for (int64_t m = max_m; m > min_m; m--)
      {
        if (mu[m] != 0 && prime < lpf[m])
        {
          int64_t n = prime * m;
          int64_t count = cnt_query(counters, (x / n) - low);
          int64_t phi_xn = phi[b] + count;
          S2_result -= mu[m] * phi_xn;
        }
      }

      phi[b] += cnt_query(counters, (high - 1) - low);
      cross_off(prime, low, high, next[b], sieve, counters);
    }

    // For pi_sqrty <= b < pi_y
    // Find all special leaves: n = primes[b] * primes[l]
    // which satisfy: low <= (x / n) < high
    for (; b < pi_y; b++)
    {
      int64_t prime = primes[b];
      int64_t l = pi[min(x / (prime * low), y)];

      if (prime >= primes[l])
        goto next_segment;

      int64_t min_hard_leaf = max(x / (prime * high), y / prime);
      min_hard_leaf = in_between(prime, min_hard_leaf, y);
      int64_t min_trivial_leaf = min(x / (prime * prime), y);
      int64_t min_easy_leaf = min(z / prime, y);

      min_trivial_leaf = max(min_hard_leaf, min_trivial_leaf);
      min_easy_leaf = max(min_hard_leaf, min_easy_leaf);

      // Find all trivial leaves which satisfy:
      // phi(x / (primes[b] * primes[l]), b - 1) = 1
      if (primes[l] > min_trivial_leaf)
      {
        int64_t l_min = pi[min_trivial_leaf];
        S2_result += l - l_min;
        l = l_min;
      }

      // Find all easy leaves: n = primes[b] * primes[l]
      // x / n <= y such that phi(x / n, b - 1) = pi[x / n] - b + 2
      for (; l > min_easy_leaf; l--)
      {
        int64_t n = prime * primes[l];
        int64_t xn = x / n;
        assert(xn < isquare(primes[b]));
        S2_result += pi[xn] - b + 2;
      }

      // Find all hard leaves which satisfy:
      // low <= (x / n) < high
      for (; primes[l] > min_hard_leaf; l--)
      {
        int64_t n = prime * primes[l];
        int64_t xn = x / n;
        int64_t count = cnt_query(counters, xn - low);
        int64_t phi_xn = phi[b] + count;
        S2_result += phi_xn;
      }

      phi[b] += cnt_query(counters, (high - 1) - low);
      cross_off(prime, low, high, next[b], sieve, counters);
    }

    next_segment:;
  }

  return S2_result;
}

} // namespace

namespace primecount {

/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * log x) space.
///
int64_t pi_deleglise_rivat1(int64_t x)
{
  if (x < 2)
    return 0;

  // alpha is a tuning factor
  double d = (double) x;
  double alpha = in_between(1, log(d) - 3 * log(log(d)), iroot<6>(x));
  int64_t y = (int64_t) (alpha * iroot<3>(x));
  int64_t z = x / y;

  vector<int32_t> mu = make_moebius(y);
  vector<int32_t> lpf = make_least_prime_factor(y);
  vector<int32_t> primes;
  primes.push_back(0);
  primesieve::generate_primes(y, &primes);

  int64_t pi_y = primes.size() - 1;
  int64_t c = min<int64_t>(PhiTiny::MAX_A, pi_y);
  int64_t s1 = S1(x, y, c, primes, lpf , mu);
  int64_t s2 = S2(x, y, z, pi_y, c, primes, lpf , mu);
  int64_t p2 = P2(x, y, 1);
  int64_t phi = s1 + s2;
  int64_t sum = phi + pi_y - 1 - p2;

  return sum;
}

} // namespace primecount
<commit_msg>Use primecount::generate_primes()<commit_after>///
/// @file  pi_deleglise_rivat1.cpp
/// @brief Implementation of the Lagarias-Miller-Odlyzko prime counting
///        algorithm with the improvements of Deleglise and Rivat.
///        This implementation is based on src/lmo/pi_lmo5.cpp and the
///        paper: Tomás Oliveira e Silva, Computing pi(x): the
///        combinatorial method, Revista do DETUA, vol. 4, no. 6, March
///        2006, pp. 759-768.
///
/// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <primecount-internal.hpp>
#include <BitSieve.hpp>
#include <pmath.hpp>
#include <PhiTiny.hpp>
#include <tos_counters.hpp>

#include <stdint.h>
#include <algorithm>
#include <vector>

using namespace std;
using namespace primecount;

namespace {

/// Cross-off the multiples of prime in the sieve array.
/// For each element that is unmarked the first time update
/// the special counters tree data structure.
///
template <typename T1, typename T2>
void cross_off(int64_t prime, int64_t low, int64_t high, int64_t& next_multiple, T1& sieve, T2& counters)
{
  int64_t segment_size = sieve.size();
  int64_t k = next_multiple;

  for (; k < high; k += prime * 2)
  {
    if (sieve[k - low])
    {
      sieve.unset(k - low);
      cnt_update(counters, k - low, segment_size);
    }
  }
  next_multiple = k;
}

/// Calculate the contribution of the special leaves.
/// @see ../docs/computing-special-leaves.md
/// @pre y > 0 && c > 1
///
int64_t S2(int64_t x,
           int64_t y,
           int64_t z,
           int64_t pi_y,
           int64_t c,
           vector<int32_t>& primes,
           vector<int32_t>& lpf,
           vector<int32_t>& mu)
{
  int64_t limit = z + 1;
  int64_t segment_size = next_power_of_2(isqrt(limit));
  int64_t pi_sqrty = pi_bsearch(primes, isqrt(y));
  int64_t S2_result = 0;

  BitSieve sieve(segment_size);
  vector<int32_t> counters(segment_size);
  vector<int32_t> pi = make_pi(y);
  vector<int64_t> next(primes.begin(), primes.end());
  vector<int64_t> phi(primes.size(), 0);

  // Segmented sieve of Eratosthenes
  for (int64_t low = 1; low < limit; low += segment_size)
  {
    // Current segment = interval [low, high[
    int64_t high = min(low + segment_size, limit);
    int64_t b = 2;

    sieve.memset(low);

    // phi(y, b) nodes with b <= c do not contribute to S2, so we
    // simply sieve out the multiples of the first c primes
    for (; b <= c; b++)
    {
      int64_t k = next[b];
      for (int64_t prime = primes[b]; k < high; k += prime * 2)
        sieve.unset(k - low);
      next[b] = k;
    }

    // Initialize special tree data structure from sieve
    cnt_finit(sieve, counters, segment_size);

    // For c + 1 <= b <= pi_sqrty
    // Find all special leaves: n = primes[b] * m, with mu[m] != 0 and primes[b] < lpf[m]
    // which satisfy: low <= (x / n) < high
    for (; b <= pi_sqrty; b++)
    {
      int64_t prime = primes[b];
      int64_t min_m = max(x / (prime * high), y / prime);
      int64_t max_m = min(x / (prime * low), y);

      if (prime >= max_m)
        goto next_segment;

      for (int64_t m = max_m; m > min_m; m--)
      {
        if (mu[m] != 0 && prime < lpf[m])
        {
          int64_t n = prime * m;
          int64_t count = cnt_query(counters, (x / n) - low);
          int64_t phi_xn = phi[b] + count;
          S2_result -= mu[m] * phi_xn;
        }
      }

      phi[b] += cnt_query(counters, (high - 1) - low);
      cross_off(prime, low, high, next[b], sieve, counters);
    }

    // For pi_sqrty <= b < pi_y
    // Find all special leaves: n = primes[b] * primes[l]
    // which satisfy: low <= (x / n) < high
    for (; b < pi_y; b++)
    {
      int64_t prime = primes[b];
      int64_t l = pi[min(x / (prime * low), y)];

      if (prime >= primes[l])
        goto next_segment;

      int64_t min_hard_leaf = max(x / (prime * high), y / prime);
      min_hard_leaf = in_between(prime, min_hard_leaf, y);
      int64_t min_trivial_leaf = min(x / (prime * prime), y);
      int64_t min_easy_leaf = min(z / prime, y);

      min_trivial_leaf = max(min_hard_leaf, min_trivial_leaf);
      min_easy_leaf = max(min_hard_leaf, min_easy_leaf);

      // Find all trivial leaves which satisfy:
      // phi(x / (primes[b] * primes[l]), b - 1) = 1
      if (primes[l] > min_trivial_leaf)
      {
        int64_t l_min = pi[min_trivial_leaf];
        S2_result += l - l_min;
        l = l_min;
      }

      // Find all easy leaves: n = primes[b] * primes[l]
      // x / n <= y such that phi(x / n, b - 1) = pi[x / n] - b + 2
      for (; l > min_easy_leaf; l--)
      {
        int64_t n = prime * primes[l];
        int64_t xn = x / n;
        assert(xn < isquare(primes[b]));
        S2_result += pi[xn] - b + 2;
      }

      // Find all hard leaves which satisfy:
      // low <= (x / n) < high
      for (; primes[l] > min_hard_leaf; l--)
      {
        int64_t n = prime * primes[l];
        int64_t xn = x / n;
        int64_t count = cnt_query(counters, xn - low);
        int64_t phi_xn = phi[b] + count;
        S2_result += phi_xn;
      }

      phi[b] += cnt_query(counters, (high - 1) - low);
      cross_off(prime, low, high, next[b], sieve, counters);
    }

    next_segment:;
  }

  return S2_result;
}

} // namespace

namespace primecount {

/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * log x) space.
///
int64_t pi_deleglise_rivat1(int64_t x)
{
  if (x < 2)
    return 0;

  // alpha is a tuning factor
  double d = (double) x;
  double alpha = in_between(1, log(d) - 3 * log(log(d)), iroot<6>(x));
  int64_t y = (int64_t) (alpha * iroot<3>(x));
  int64_t z = x / y;

  vector<int32_t> mu = make_moebius(y);
  vector<int32_t> lpf = make_least_prime_factor(y);
  vector<int32_t> primes = generate_primes(y);

  int64_t pi_y = primes.size() - 1;
  int64_t c = min<int64_t>(PhiTiny::MAX_A, pi_y);
  int64_t s1 = S1(x, y, c, primes, lpf , mu);
  int64_t s2 = S2(x, y, z, pi_y, c, primes, lpf , mu);
  int64_t p2 = P2(x, y, 1);
  int64_t phi = s1 + s2;
  int64_t sum = phi + pi_y - 1 - p2;

  return sum;
}

} // namespace primecount
<|endoftext|>


<commit_before>//
//#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <ctime>
#include <algorithm>
#include <cmath>
#include "GPIOClass.h"

using namespace std;

void Pulse(GPIOClass* pin, double cycles);
void Wait(double seconds);
clock_t timer;
double time_to_complete;
double resolution = 100;

#define PI 4*atan(1)

int main (int argc, char *argv[]) {
	string type = argv[1];
	transform(type.begin(), type.end(), type.begin(), :: tolower);
	// lets assume that the way to run this is
	// pwm.exe [rising/falling/sine/constant]
	if (argc != 2) {
		cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl;
		return -1;
	}

	while (time_to_complete <= 0) {
		cout << "Input How Long To Run (in seconds)" << endl;
		cin >> time_to_complete;
	}

	GPIOClass* out1 = new GPIOClass("4");
	GPIOClass* in2 = new GPIOClass("17");

	out1->export_gpio();
	in2->export_gpio();

	out1->setdir_gpio("out");
	in2->setdir_gpio("in");

	cout << "Pins are setup." << endl;
	// avoiding flickering will be at 100hz
	// aka turn on and off 100 times a sec
	// a cycle of 0 is off
	// a cycle of 100 is on

	if (type == "rising") {
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		double t = time_to_complete;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			if(t > 0){
				t -= 1;
			}
			//cout << t << endl;
			Pulse(out1, sin((PI/2) * (1/t)));
			Wait(sin((PI/2) * (1/t)));
		}
	}
	if (type == "falling") {

	}
	if (type == "sine") {

	}
	if (type == "constant") {
		out1->setval_gpio("1"); // turn the pin on
		Wait(time_to_complete); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		out1->setval_gpio("0"); // turn the pin off
	}
	if (type == "blink") { // aka. TESTR
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			Pulse(out1, 1 * resolution);
			Wait(0.5);
		}
	}
	cout << "Done." << endl;
}

//1 cycle is 1/100th of a second
//100 cycles is 1 sec
void Pulse(GPIOClass* pin, double cycles) {
	bool running = true;
	while (running) {
		pin->setval_gpio("1"); // turn the pin on
		Wait(cycles / resolution); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		pin->setval_gpio("0"); // turn the pin off
		running = false; // this is unnessesary but could be useful if modified a bit.
	}
}

void Wait ( double seconds )
{
	clock_t endwait;
	endwait = clock () + seconds * CLOCKS_PER_SEC ;
	while (clock() < endwait) {}
}
<commit_msg>Update pwm.cpp<commit_after>//
//#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <ctime>
#include <algorithm>
#include <cmath>
#include "GPIOClass.h"

using namespace std;

void Pulse(GPIOClass* pin, double cycles);
void Wait(double seconds);
clock_t timer;
double time_to_complete;
double resolution = 100;

#define PI 4*atan(1)

int main (int argc, char *argv[]) {
	string type = argv[1];
	transform(type.begin(), type.end(), type.begin(), :: tolower);
	// lets assume that the way to run this is
	// pwm.exe [rising/falling/sine/constant]
	if (argc != 2) {
		cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl;
		return -1;
	}

	while (time_to_complete <= 0) {
		cout << "Input How Long To Run (in seconds)" << endl;
		cin >> time_to_complete;
	}

	GPIOClass* out1 = new GPIOClass("4");
	GPIOClass* in2 = new GPIOClass("17");

	out1->export_gpio();
	in2->export_gpio();

	out1->setdir_gpio("out");
	in2->setdir_gpio("in");

	cout << "Pins are setup." << endl;
	// avoiding flickering will be at 100hz
	// aka turn on and off 100 times a sec
	// a cycle of 0 is off
	// a cycle of 100 is on

	if (type == "rising") {
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		double t = time_to_complete;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			if(t > 0){
				t -= 1;
			}
			cout << t << endl;
			Pulse(out1, sin((PI/2) * (1/t)));
			Wait(sin((PI/2) * (1/t)));
		}
	}
	if (type == "falling") {

	}
	if (type == "sine") {

	}
	if (type == "constant") {
		out1->setval_gpio("1"); // turn the pin on
		Wait(time_to_complete); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		out1->setval_gpio("0"); // turn the pin off
	}
	if (type == "blink") { // aka. TESTR
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			Pulse(out1, 1 * resolution);
			Wait(0.5);
		}
	}
	cout << "Done." << endl;
}

//1 cycle is 1/100th of a second
//100 cycles is 1 sec
void Pulse(GPIOClass* pin, double cycles) {
	bool running = true;
	while (running) {
		pin->setval_gpio("1"); // turn the pin on
		Wait(cycles / resolution); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		pin->setval_gpio("0"); // turn the pin off
		running = false; // this is unnessesary but could be useful if modified a bit.
	}
}

void Wait ( double seconds )
{
	clock_t endwait;
	endwait = clock () + seconds * CLOCKS_PER_SEC ;
	while (clock() < endwait) {}
}
<|endoftext|>


<commit_before>//
//#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <ctime>
#include <algorithm>
#include <cmath>
#include "GPIOClass.h"

using namespace std;

void Pulse(GPIOClass* pin, double cycles);
void Wait(double seconds);
clock_t timer;
double time_to_complete;
double resolution = 100;

#define PI 4*atan(1)

int main (int argc, char *argv[]) {
	string type = argv[1];
	transform(type.begin(), type.end(), type.begin(), :: tolower);
	// lets assume that the way to run this is
	// pwm.exe [rising/falling/sine/constant]
	if (argc != 2) {
		cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl;
		return -1;
	}

	while (time_to_complete <= 0) {
		cout << "Input How Long To Run (in seconds)" << endl;
		cin >> time_to_complete;
	}

	GPIOClass* out1 = new GPIOClass("4");
	GPIOClass* in2 = new GPIOClass("17");

	out1->export_gpio();
	in2->export_gpio();

	out1->setdir_gpio("out");
	in2->setdir_gpio("in");

	cout << "Pins are setup." << endl;
	// avoiding flickering will be at 100hz
	// aka turn on and off 100 times a sec
	// a cycle of 0 is off
	// a cycle of 100 is on

	if (type == "rising") {
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			Pulse(out1, sin((PI/2) * ((time_to_complete * resolution) / resolution )));
			Wait(sin((PI/2) * ((time_to_complete * resolution) / resolution )));
		}
	}
	if (type == "falling") {

	}
	if (type == "sine") {

	}
	if (type == "constant") {

	}
	if (type == "blink") { // aka. TESTR
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			Pulse(out1, 1 * resolution);
			Wait(0.5);
		}
	}
	cout << "Done." << endl;
}

//1 cycle is 1/100th of a second
//100 cycles is 1 sec
void Pulse(GPIOClass* pin, double cycles) {
	bool running = true;
	while (running) {
		pin->setval_gpio("1"); // turn the pin on
		Wait(cycles * 1/resolution); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		pin->setval_gpio("0"); // turn the pin off
		running = false; // this is unnessesary but could be useful if modified a bit.
	}
}

void Wait ( double seconds )
{
	clock_t endwait;
	endwait = clock () + seconds * CLOCKS_PER_SEC ;
	while (clock() < endwait) {}
}
<commit_msg>Update pwm.cpp<commit_after>//
//#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <ctime>
#include <algorithm>
#include <cmath>
#include "GPIOClass.h"

using namespace std;

void Pulse(GPIOClass* pin, double cycles);
void Wait(double seconds);
clock_t timer;
double time_to_complete;
double resolution = 100;

#define PI 4*atan(1)

int main (int argc, char *argv[]) {
	string type = argv[1];
	transform(type.begin(), type.end(), type.begin(), :: tolower);
	// lets assume that the way to run this is
	// pwm.exe [rising/falling/sine/constant]
	if (argc != 2) {
		cout << "Usage: pwm [rising/falling/sine/constant/blink]" << endl;
		return -1;
	}

	while (time_to_complete <= 0) {
		cout << "Input How Long To Run (in seconds)" << endl;
		cin >> time_to_complete;
	}

	GPIOClass* out1 = new GPIOClass("4");
	GPIOClass* in2 = new GPIOClass("17");

	out1->export_gpio();
	in2->export_gpio();

	out1->setdir_gpio("out");
	in2->setdir_gpio("in");

	cout << "Pins are setup." << endl;
	// avoiding flickering will be at 100hz
	// aka turn on and off 100 times a sec
	// a cycle of 0 is off
	// a cycle of 100 is on

	if (type == "rising") {
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			Pulse(out1, sin((PI/2) * 1/time_to_complete));
			Wait(sin((PI/2) * 1/time_to_complete));
		}
	}
	if (type == "falling") {

	}
	if (type == "sine") {

	}
	if (type == "constant") {

	}
	if (type == "blink") { // aka. TESTR
		clock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;
		while (clock() < finish) {
			// pulse for however long we need to to achieve brightness.
			Pulse(out1, 1 * resolution);
			Wait(0.5);
		}
	}
	cout << "Done." << endl;
}

//1 cycle is 1/100th of a second
//100 cycles is 1 sec
void Pulse(GPIOClass* pin, double cycles) {
	bool running = true;
	while (running) {
		pin->setval_gpio("1"); // turn the pin on
		Wait(cycles * 1/resolution); // sleep for number of cycles / 1/100 sec
		//cout << "Waiting during pulse" << endl;
		pin->setval_gpio("0"); // turn the pin off
		running = false; // this is unnessesary but could be useful if modified a bit.
	}
}

void Wait ( double seconds )
{
	clock_t endwait;
	endwait = clock () + seconds * CLOCKS_PER_SEC ;
	while (clock() < endwait) {}
}
<|endoftext|>


<commit_before>#ifndef BOID_TYPE_HPP
#define BOID_TYPE_HPP

enum BoidType { RABBIT, WOLF };

#endif
<commit_msg>Add a random Animal type<commit_after>#ifndef BOID_TYPE_HPP
#define BOID_TYPE_HPP

enum BoidType { RABBIT, WOLF, RANDOM };

#endif
<|endoftext|>