<commit_before>/*
 * Skaffari - a mail account administration web interface based on Cutelyst
 * Copyright (C) 2018 Matthias Fehring <kontakt@buschmann23.de>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "skvalidatordomainexists.h"
#include "../common/global.h"
#include <Cutelyst/Plugins/Utils/Sql>
#include <Cutelyst/Context>
#include <QSqlQuery>
#include <QSqlError>

SkValidatorDomainExists::SkValidatorDomainExists(const QString &field, const Cutelyst::ValidatorMessages &messages) :
    ValidatorRule(field, messages, QString())
{
}

SkValidatorDomainExists::~SkValidatorDomainExists()
{
}

Cutelyst::ValidatorReturnType SkValidatorDomainExists::validate(Cutelyst::Context *c, const Cutelyst::ParamsMultiMap &params) const
{
    Cutelyst::ValidatorReturnType result;

    const QString v = value(params);

    if (!v.isEmpty()) {
        bool ok = false;
        const dbid_t id = v.toUInt(&ok);
        if (ok) {
            if (id > 0) {
                QSqlQuery q = CPreparedSqlQueryThread(QStringLiteral("SELECT domain_name FROM domain WHERE id = :id"));
                q.bindValue(QStringLiteral(":id"), id);

                if (q.exec()) {
                    if (!q.next() || q.value(0).toString().isEmpty()) {
                        result.errorMessage = validationError(c, id);
                    } else {
                        result.value.setValue<dbid_t>(id);
                    }
                } else {
                    result.errorMessage = c->translate("SkValidatorDomainExists", "Failed to check for existing domain: %1").arg(q.lastError().text());
                }
            } else {
                result.value.setValue<dbid_t>(id);
            }
        } else {
            result.errorMessage = parsingError(c);
        }
    }

    return result;
}

QString SkValidatorDomainExists::genericValidationError(Cutelyst::Context *c, const QVariant &errorData) const
{
    QString error;
    dbid_t id = errorData.value<dbid_t>();
    const QString _label = label(c);
    if (_label.isEmpty()) {
        error = c->translate("SkValidatorDomainExists", "The domain with ID %1 does not exist.").arg(id);
    } else {
        error = c->translate("SkValidatorDomainExists", "The domain with ID %1 selected for the “%2” field does not exist.").arg(QString::number(id), _label);
    }
    return error;
}

QString SkValidatorDomainExists::genericParsingError(Cutelyst::Context *c, const QVariant &errorData) const
{
    QString error;
    Q_UNUSED(errorData)
    const QString _label = label(c);
    if (_label.isEmpty()) {
        error = c->translate("SkValidatorDomainExists", "Failed to convert the input data into a database ID.");
    } else {
        error = c->translate("SkValidatorDomainExists", "Failed to convert the input data of the “%1” field into a database ID.").arg(_label);
    }
    return error;
}
<commit_msg>SkValidatorDomainExists: check in context of current user<commit_after>/*
 * Skaffari - a mail account administration web interface based on Cutelyst
 * Copyright (C) 2018 Matthias Fehring <kontakt@buschmann23.de>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "skvalidatordomainexists.h"
#include "../common/global.h"
#include <Cutelyst/Plugins/Utils/Sql>
#include <Cutelyst/Context>
#include <Cutelyst/Plugins/Authentication/authentication.h>
#include <Cutelyst/Plugins/Authentication/authenticationuser.h>
#include <QSqlQuery>
#include <QSqlError>

SkValidatorDomainExists::SkValidatorDomainExists(const QString &field, const Cutelyst::ValidatorMessages &messages) :
    ValidatorRule(field, messages, QString())
{
}

SkValidatorDomainExists::~SkValidatorDomainExists()
{
}

Cutelyst::ValidatorReturnType SkValidatorDomainExists::validate(Cutelyst::Context *c, const Cutelyst::ParamsMultiMap &params) const
{
    Cutelyst::ValidatorReturnType result;

    const QString v = value(params);

    if (!v.isEmpty()) {
        bool ok = false;
        const dbid_t id = v.toUInt(&ok);
        if (ok) {
            if (id > 0) {
                QSqlQuery q;
                if (c->stash(QStringLiteral("userType")).value<qint16>() == 0) {
                    q = CPreparedSqlQueryThread(QStringLiteral("SELECT domain_name FROM domain WHERE id = :id"));
                } else {
                    const dbid_t userId = c->stash(QStringLiteral("userId")).value<dbid_t>();
                    q = CPreparedSqlQueryThread(QStringLiteral("SELECT dom.domain_name FROM domain dom LEFT JOIN domainadmin da ON dom.id = da.domain_id WHERE da.admin_id = :admin_id AND dom.id = :id"));
                    q.bindValue(QStringLiteral(":admin_id"), userId);
                }
                q.bindValue(QStringLiteral(":id"), id);

                if (q.exec()) {
                    if (!q.next() || q.value(0).toString().isEmpty()) {
                        result.errorMessage = validationError(c, id);
                    } else {
                        result.value.setValue<dbid_t>(id);
                    }
                } else {
                    result.errorMessage = c->translate("SkValidatorDomainExists", "Failed to check for existing domain: %1").arg(q.lastError().text());
                }
            } else {
                result.value.setValue<dbid_t>(id);
            }
        } else {
            result.errorMessage = parsingError(c);
        }
    }

    return result;
}

QString SkValidatorDomainExists::genericValidationError(Cutelyst::Context *c, const QVariant &errorData) const
{
    QString error;
    dbid_t id = errorData.value<dbid_t>();
    const QString _label = label(c);
    const qint16 userType = c->stash(QStringLiteral("userType")).value<qint16>();
    if (_label.isEmpty()) {
        if (userType == 0) {
            error = c->translate("SkValidatorDomainExists", "The domain with ID %1 does not exist.").arg(id);
        } else {
            error = c->translate("SkValidatorDomainExists", "The domain with ID %1 either does not exist or you do not have access rights for it.").arg(id);
        }
    } else {
        if (userType == 0) {
            error = c->translate("SkValidatorDomainExists", "The domain with ID %1 selected for the “%2” field does not exist.").arg(QString::number(id), _label);
        } else {
            error = c->translate("SkValidatorDomainExists", "The domain with ID %1 selected for the “%2“ field either does not exist or you do not have access rights for it.").arg(QString::number(id), _label);
        }
    }
    return error;
}

QString SkValidatorDomainExists::genericParsingError(Cutelyst::Context *c, const QVariant &errorData) const
{
    QString error;
    Q_UNUSED(errorData)
    const QString _label = label(c);
    if (_label.isEmpty()) {
        error = c->translate("SkValidatorDomainExists", "Failed to convert the input data into a database ID.");
    } else {
        error = c->translate("SkValidatorDomainExists", "Failed to convert the input data of the “%1” field into a database ID.").arg(_label);
    }
    return error;
}
<|endoftext|>


<commit_before>/*
    KNode, the KDE newsreader
    Copyright (c) 1999-2005 the KNode authors.
    See file AUTHORS for details

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

#include <stdlib.h>

#include <QDir>
#include <QFile>
#include <QLabel>
#include <QProgressBar>
#include <QVBoxLayout>
#include <QApplication>
#include <QFrame>
#include <QTextStream>
#include <QCloseEvent>

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

#include "knfolder.h"
#include "knglobals.h"
#include "kncleanup.h"
#include "knconfig.h"
#include "knfoldermanager.h"
#include "kngroupmanager.h"
#include "knarticlemanager.h"
#include "knnntpaccount.h"

KNCleanUp::KNCleanUp() :  d_lg(0)
{
}

KNCleanUp::~KNCleanUp()
{
  delete d_lg;
}

void KNCleanUp::start()
{
  if ( mColList.isEmpty() )
    return;

  d_lg = new ProgressDialog( mColList.count() );
  d_lg->show();

  for ( QList<KNArticleCollection*>::Iterator it = mColList.begin(); it != mColList.end(); ++it ) {
    if ( (*it)->type() == KNCollection::CTgroup ) {
      d_lg->showMessage( i18n("Deleting expired articles in %1", (*it)->name() ) );
      qApp->processEvents();
      expireGroup( static_cast<KNGroup*>( (*it) ) );
      d_lg->doProgress();
    }
    else if ( (*it)->type() == KNCollection::CTfolder ) {
      d_lg->showMessage( i18n("Compacting folder %1", (*it)->name() ) );
      qApp->processEvents();
      compactFolder( static_cast<KNFolder*>( (*it) ) );
      d_lg->doProgress();
    }
  }

  delete d_lg;
  d_lg=0;
}

void KNCleanUp::reset()
{
  mColList.clear();
  if(d_lg) {
    delete d_lg;
    d_lg=0;
  }
}

void KNCleanUp::expireGroup( KNGroup *g, bool showResult )
{
  int expDays=0, idRef=0, foundId=-1, delCnt=0, leftCnt=0, newCnt=0, firstArtNr=g->firstNr(), firstNew=-1;
  bool unavailable=false;
  KNRemoteArticle *art, *ref;

  KNode::Cleanup *conf = g->activeCleanupConfig();

  g->setNotUnloadable(true);

  if (!g->isLoaded() && !knGlobals.groupManager()->loadHeaders(g)) {
    g->setNotUnloadable(false);
    return;
  }

  //find all expired
  for(int i=0; i<g->length(); i++) {
    art=g->at(i);
    if(art->isRead())
      expDays = conf->maxAgeForRead();
    else
      expDays = conf->maxAgeForUnread();

    unavailable = false;
    if ((art->articleNumber() != -1) && conf->removeUnavailable())
      unavailable = (art->articleNumber() < firstArtNr);

    art->setExpired( (art->date()->ageInDays() >= expDays) || unavailable );
  }

  //save threads
  if (conf->preserveThreads()) {
    for(int i=0; i<g->length(); i++) {
      art=g->at(i);
      if(!art->isExpired()) {
        idRef=art->idRef();
        while(idRef!=0) {
          ref=g->byId(idRef);
          ref->setExpired(false);
          idRef=ref->idRef();
        }
      }
    }
  }

  //restore threading
  for(int i=0; i<g->length(); i++) {
    art=g->at(i);
    if(!art->isExpired()) {
      idRef=art->idRef();
      foundId=0;
      while(foundId==0 && idRef!=0) {
        ref=g->byId(idRef);
        if(!ref->isExpired()) foundId=ref->id();
        idRef=ref->idRef();
      }
      art->setIdRef(foundId);
    }
  }

  //delete expired
  for(int i=0; i<g->length(); i++) {
    art=g->at(i);
    if(art->isExpired()) {
      if(art->isRead())
        g->decReadCount();
      delCnt++;
      if (art->hasContent())
        knGlobals.articleManager()->unloadArticle(art, true);
    }
    else if(art->isNew() && !art->isRead()) {
      if(firstNew==-1)
        firstNew=i;
      newCnt++;
    }
  }

  g->setNotUnloadable(false);

  if(delCnt>0) {
    g->saveStaticData(g->length(), true);
    g->saveDynamicData(g->length(), true);
    g->decCount(delCnt);
    g->setNewCount(newCnt);
    g->setFirstNewIndex(firstNew);
    g->saveInfo();
    knGlobals.groupManager()->unloadHeaders(g, true);
  }
  else
    g->syncDynamicData();

  conf->setLastExpireDate();
  g->saveInfo();
  leftCnt=g->count();

  kDebug(5003) <<"KNCleanUp::expireGroup() :" << g->groupname() <<":"
    << delCnt << "deleted ," << leftCnt << "left";

  if(showResult)
    KMessageBox::information(knGlobals.topWidget,
      i18n("%1
expired: %2
left: %3", g->groupname(), delCnt, leftCnt));
}

void KNCleanUp::compactFolder(KNFolder *f)
{
  KNLocalArticle *art;

  if (!f)
    return;

  QDir dir(f->path());

  if(!dir.exists())
    return;

  f->setNotUnloadable(true);

  if (!f->isLoaded() && !knGlobals.folderManager()->loadHeaders(f)) {
    f->setNotUnloadable(false);
    return;
  }

  f->closeFiles();
  QFileInfo info(f->m_boxFile);
  QString oldName=info.fileName();
  QString newName=oldName+".new";
  QFile newMBoxFile( info.absolutePath() + '/' + newName );

  if( (f->m_boxFile.open(QIODevice::ReadOnly)) && (newMBoxFile.open(QIODevice::WriteOnly)) ) {
    QTextStream ts(&newMBoxFile);
    ts.setCodec( "ISO 8859-1" );
    for(int idx=0; idx<f->length(); idx++) {
      art=f->at(idx);
      if ( f->m_boxFile.seek( art->startOffset() ) ) {
        ts << "From aaa@aaa Mon Jan 01 00:00:00 1997\n";
        ts.flush();
        art->setStartOffset( newMBoxFile.pos() );
        while ( f->m_boxFile.pos() < (uint)art->endOffset() )
          ts << f->m_boxFile.readLine();
        ts.flush();
        art->setEndOffset( newMBoxFile.pos() );
        newMBoxFile.putChar('\n');
      }
    }

    f->syncIndex(true);
    newMBoxFile.close();
    f->closeFiles();

    dir.remove(oldName);
    dir.rename(newName, oldName);
  }

  f->setNotUnloadable(false);
}

//===============================================================================================

KNCleanUp::ProgressDialog::ProgressDialog( int steps, QWidget *parent ) :
  KDialog( parent )
{
  const int w=400,
            h=160;

  setCaption(i18n("Cleaning Up"));
  setButtons( KDialog::None );

  setFixedSize(w,h);
  QFrame *top = new QFrame( this );
  top->setGeometry(0,0, w,h);

  QVBoxLayout *topL=new QVBoxLayout(top);
  topL->setSpacing(10);

  QLabel *l=new QLabel(i18n("Cleaning up. Please wait..."),top);
  topL->addWidget(l);

  KSeparator *sep=new KSeparator(top);
  topL->addWidget(sep);

  m_sg=new QLabel(top);
  topL->addWidget(m_sg);

  mProgressBar = new QProgressBar( top );
  topL->addWidget( mProgressBar );
  mProgressBar->setRange( 0, steps );
  mProgressBar->setValue( 0 );

  if(knGlobals.topWidget->isVisible()) {
    int x, y;
    x=(knGlobals.topWidget->width()-w)/2;
    y=(knGlobals.topWidget->height()-h)/2;
    if(x<0 || y<0) {
      x=0;
      y=0;
    }
    x+=knGlobals.topWidget->x();
    y+=knGlobals.topWidget->y();
    move(x,y);
  }
}

KNCleanUp::ProgressDialog::~ProgressDialog()
{
}

void KNCleanUp::ProgressDialog::showMessage(const QString &s)
{
  m_sg->setText(s);
}

void KNCleanUp::ProgressDialog::doProgress()
{
  mProgressBar->setValue( mProgressBar->value() + 1 );
}

void KNCleanUp::ProgressDialog::closeEvent(QCloseEvent *)
{
  // do nothing => prevent that the user closes the window
}
<commit_msg>Additional safety check, suggested by André Wöbbeking.<commit_after>/*
    KNode, the KDE newsreader
    Copyright (c) 1999-2005 the KNode authors.
    See file AUTHORS for details

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

#include <stdlib.h>

#include <QDir>
#include <QFile>
#include <QLabel>
#include <QProgressBar>
#include <QVBoxLayout>
#include <QApplication>
#include <QFrame>
#include <QTextStream>
#include <QCloseEvent>

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

#include "knfolder.h"
#include "knglobals.h"
#include "kncleanup.h"
#include "knconfig.h"
#include "knfoldermanager.h"
#include "kngroupmanager.h"
#include "knarticlemanager.h"
#include "knnntpaccount.h"

KNCleanUp::KNCleanUp() :  d_lg(0)
{
}

KNCleanUp::~KNCleanUp()
{
  delete d_lg;
}

void KNCleanUp::start()
{
  if ( mColList.isEmpty() )
    return;

  d_lg = new ProgressDialog( mColList.count() );
  d_lg->show();

  for ( QList<KNArticleCollection*>::Iterator it = mColList.begin(); it != mColList.end(); ++it ) {
    if ( (*it)->type() == KNCollection::CTgroup ) {
      d_lg->showMessage( i18n("Deleting expired articles in %1", (*it)->name() ) );
      qApp->processEvents();
      expireGroup( static_cast<KNGroup*>( (*it) ) );
      d_lg->doProgress();
    }
    else if ( (*it)->type() == KNCollection::CTfolder ) {
      d_lg->showMessage( i18n("Compacting folder %1", (*it)->name() ) );
      qApp->processEvents();
      compactFolder( static_cast<KNFolder*>( (*it) ) );
      d_lg->doProgress();
    }
  }

  delete d_lg;
  d_lg=0;
}

void KNCleanUp::reset()
{
  mColList.clear();
  if(d_lg) {
    delete d_lg;
    d_lg=0;
  }
}

void KNCleanUp::expireGroup( KNGroup *g, bool showResult )
{
  int expDays=0, idRef=0, foundId=-1, delCnt=0, leftCnt=0, newCnt=0, firstArtNr=g->firstNr(), firstNew=-1;
  bool unavailable=false;
  KNRemoteArticle *art, *ref;

  KNode::Cleanup *conf = g->activeCleanupConfig();

  g->setNotUnloadable(true);

  if (!g->isLoaded() && !knGlobals.groupManager()->loadHeaders(g)) {
    g->setNotUnloadable(false);
    return;
  }

  //find all expired
  for(int i=0; i<g->length(); i++) {
    art=g->at(i);
    if(art->isRead())
      expDays = conf->maxAgeForRead();
    else
      expDays = conf->maxAgeForUnread();

    unavailable = false;
    if ((art->articleNumber() != -1) && conf->removeUnavailable())
      unavailable = (art->articleNumber() < firstArtNr);

    art->setExpired( (art->date()->ageInDays() >= expDays) || unavailable );
  }

  //save threads
  if (conf->preserveThreads()) {
    for(int i=0; i<g->length(); i++) {
      art=g->at(i);
      if(!art->isExpired()) {
        idRef=art->idRef();
        while(idRef!=0) {
          ref=g->byId(idRef);
          ref->setExpired(false);
          idRef=ref->idRef();
        }
      }
    }
  }

  //restore threading
  for(int i=0; i<g->length(); i++) {
    art=g->at(i);
    if(!art->isExpired()) {
      idRef=art->idRef();
      foundId=0;
      while(foundId==0 && idRef!=0) {
        ref=g->byId(idRef);
        if(!ref->isExpired()) foundId=ref->id();
        idRef=ref->idRef();
      }
      art->setIdRef(foundId);
    }
  }

  //delete expired
  for(int i=0; i<g->length(); i++) {
    art=g->at(i);
    if(art->isExpired()) {
      if(art->isRead())
        g->decReadCount();
      delCnt++;
      if (art->hasContent())
        knGlobals.articleManager()->unloadArticle(art, true);
    }
    else if(art->isNew() && !art->isRead()) {
      if(firstNew==-1)
        firstNew=i;
      newCnt++;
    }
  }

  g->setNotUnloadable(false);

  if(delCnt>0) {
    g->saveStaticData(g->length(), true);
    g->saveDynamicData(g->length(), true);
    g->decCount(delCnt);
    g->setNewCount(newCnt);
    g->setFirstNewIndex(firstNew);
    g->saveInfo();
    knGlobals.groupManager()->unloadHeaders(g, true);
  }
  else
    g->syncDynamicData();

  conf->setLastExpireDate();
  g->saveInfo();
  leftCnt=g->count();

  kDebug(5003) <<"KNCleanUp::expireGroup() :" << g->groupname() <<":"
    << delCnt << "deleted ," << leftCnt << "left";

  if(showResult)
    KMessageBox::information(knGlobals.topWidget,
      i18n("%1
expired: %2
left: %3", g->groupname(), delCnt, leftCnt));
}

void KNCleanUp::compactFolder(KNFolder *f)
{
  KNLocalArticle *art;

  if (!f)
    return;

  QDir dir(f->path());

  if(!dir.exists())
    return;

  f->setNotUnloadable(true);

  if (!f->isLoaded() && !knGlobals.folderManager()->loadHeaders(f)) {
    f->setNotUnloadable(false);
    return;
  }

  f->closeFiles();
  QFileInfo info(f->m_boxFile);
  QString oldName=info.fileName();
  QString newName=oldName+".new";
  QFile newMBoxFile( info.absolutePath() + '/' + newName );

  if( (f->m_boxFile.open(QIODevice::ReadOnly)) && (newMBoxFile.open(QIODevice::WriteOnly)) ) {
    QTextStream ts(&newMBoxFile);
    ts.setCodec( "ISO 8859-1" );
    for(int idx=0; idx<f->length(); idx++) {
      art=f->at(idx);
      if ( f->m_boxFile.seek( art->startOffset() ) ) {
        ts << "From aaa@aaa Mon Jan 01 00:00:00 1997\n";
        ts.flush();
        art->setStartOffset( newMBoxFile.pos() );
        while ( f->m_boxFile.pos() < (uint)art->endOffset() && !f->m_boxFile.atEnd() )
          ts << f->m_boxFile.readLine();
        ts.flush();
        art->setEndOffset( newMBoxFile.pos() );
        newMBoxFile.putChar('\n');
      }
    }

    f->syncIndex(true);
    newMBoxFile.close();
    f->closeFiles();

    dir.remove(oldName);
    dir.rename(newName, oldName);
  }

  f->setNotUnloadable(false);
}

//===============================================================================================

KNCleanUp::ProgressDialog::ProgressDialog( int steps, QWidget *parent ) :
  KDialog( parent )
{
  const int w=400,
            h=160;

  setCaption(i18n("Cleaning Up"));
  setButtons( KDialog::None );

  setFixedSize(w,h);
  QFrame *top = new QFrame( this );
  top->setGeometry(0,0, w,h);

  QVBoxLayout *topL=new QVBoxLayout(top);
  topL->setSpacing(10);

  QLabel *l=new QLabel(i18n("Cleaning up. Please wait..."),top);
  topL->addWidget(l);

  KSeparator *sep=new KSeparator(top);
  topL->addWidget(sep);

  m_sg=new QLabel(top);
  topL->addWidget(m_sg);

  mProgressBar = new QProgressBar( top );
  topL->addWidget( mProgressBar );
  mProgressBar->setRange( 0, steps );
  mProgressBar->setValue( 0 );

  if(knGlobals.topWidget->isVisible()) {
    int x, y;
    x=(knGlobals.topWidget->width()-w)/2;
    y=(knGlobals.topWidget->height()-h)/2;
    if(x<0 || y<0) {
      x=0;
      y=0;
    }
    x+=knGlobals.topWidget->x();
    y+=knGlobals.topWidget->y();
    move(x,y);
  }
}

KNCleanUp::ProgressDialog::~ProgressDialog()
{
}

void KNCleanUp::ProgressDialog::showMessage(const QString &s)
{
  m_sg->setText(s);
}

void KNCleanUp::ProgressDialog::doProgress()
{
  mProgressBar->setValue( mProgressBar->value() + 1 );
}

void KNCleanUp::ProgressDialog::closeEvent(QCloseEvent *)
{
  // do nothing => prevent that the user closes the window
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: refltype.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 05:12:21 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _REGISTRY_REFLTYPE_HXX_
#define _REGISTRY_REFLTYPE_HXX_

#include "registry/types.h"

#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif

/** specifies the type source of a binary type blob.

    Currently only RT_UNO_IDL type is used.
 */
enum RTTypeSource
{
    RT_UNO_IDL,
    RT_CORBA_IDL,
    RT_JAVA
};

/** specifies a helper class for const values.

    This class is used for easy handling of constants or enum values
    as fields in binary type blob.
 */
class RTConstValue
{
public:
    /// stores the type of the constant value.
    RTValueType         m_type;
    /// stores the value of the constant.
    RTConstValueUnion m_value;

    /// Default constructor.
    RTConstValue()
        : m_type(RT_TYPE_NONE)
    {
        m_value.aDouble = 0.0;
    }

    /// Destructor
    ~RTConstValue() {}
};

/** deprecated.

    An earlier version of UNO used an unique identifier for interfaces. In the
    current version of UNO this uik was eliminated and this type is not longer used.
 */
struct RTUik
{
    sal_uInt32 m_Data1;
    sal_uInt16 m_Data2;
    sal_uInt16 m_Data3;
    sal_uInt32 m_Data4;
    sal_uInt32 m_Data5;
};

/// specifies the calling onvention for type reader/wrter api
#define TYPEREG_CALLTYPE    SAL_CALL

#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.9.66); FILE MERGED 2008/04/01 15:23:06 thb 1.9.66.2: #i85898# Stripping all external header guards 2008/03/31 07:25:17 rt 1.9.66.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: refltype.hxx,v $
 * $Revision: 1.10 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _REGISTRY_REFLTYPE_HXX_
#define _REGISTRY_REFLTYPE_HXX_

#include "registry/types.h"
#include <sal/types.h>

/** specifies the type source of a binary type blob.

    Currently only RT_UNO_IDL type is used.
 */
enum RTTypeSource
{
    RT_UNO_IDL,
    RT_CORBA_IDL,
    RT_JAVA
};

/** specifies a helper class for const values.

    This class is used for easy handling of constants or enum values
    as fields in binary type blob.
 */
class RTConstValue
{
public:
    /// stores the type of the constant value.
    RTValueType         m_type;
    /// stores the value of the constant.
    RTConstValueUnion m_value;

    /// Default constructor.
    RTConstValue()
        : m_type(RT_TYPE_NONE)
    {
        m_value.aDouble = 0.0;
    }

    /// Destructor
    ~RTConstValue() {}
};

/** deprecated.

    An earlier version of UNO used an unique identifier for interfaces. In the
    current version of UNO this uik was eliminated and this type is not longer used.
 */
struct RTUik
{
    sal_uInt32 m_Data1;
    sal_uInt16 m_Data2;
    sal_uInt16 m_Data3;
    sal_uInt32 m_Data4;
    sal_uInt32 m_Data5;
};

/// specifies the calling onvention for type reader/wrter api
#define TYPEREG_CALLTYPE    SAL_CALL

#endif
<|endoftext|>


<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <memory>

#include "tensorflow/compiler/xla/client/computation_builder.h"
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/compiler/xla/legacy_flags/cpu_compiler_flags.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/primitive_util.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/tests/client_library_test_base.h"
#include "tensorflow/compiler/xla/tests/test_macros.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/types.h"

namespace xla {
namespace {

class PrngTest : public ClientLibraryTestBase {
 protected:
  template <typename T>
  void UniformTest(T a, T b, tensorflow::gtl::ArraySlice<int64> dims);
  void BernoulliTest(float p, tensorflow::gtl::ArraySlice<int64> dims);

  // Computes the χ² statistic of a sample of the discrete uniform distribution
  // of the given range size. `expected_count` is the number of times each
  // possible value is expected to be generated. Thus, the sample size is
  // `range_size * expected_count`.
  double UniformChiSquared(int32 range_size, int32 expected_count);
};

template <typename T>
void PrngTest::UniformTest(T a, T b, tensorflow::gtl::ArraySlice<int64> dims) {
  ComputationBuilder builder(client_, TestName());
  builder.RngUniform(
      builder.ConstantR0<T>(a), builder.ConstantR0<T>(b),
      ShapeUtil::MakeShape(primitive_util::NativeToPrimitiveType<T>(), dims));

  auto actual = ExecuteAndTransferOrDie(&builder, /*arguments=*/{});
  EXPECT_TRUE(ContainersEqual(dims, actual->shape().dimensions()));
  LiteralUtil::EachCell<T>(*actual,
                           [=](tensorflow::gtl::ArraySlice<int64>, T value) {
                             EXPECT_LE(a, value);
                             EXPECT_LT(value, b);
                           });
}

void PrngTest::BernoulliTest(float p, tensorflow::gtl::ArraySlice<int64> dims) {
  ComputationBuilder builder(client_, TestName());
  auto shape = ShapeUtil::MakeShape(U32, dims);
  builder.RngBernoulli(builder.ConstantR0<float>(p), shape);

  TF_ASSIGN_OR_ASSERT_OK(auto computation, builder.Build());
  ExecutionOptions execution_options;
  execution_options.set_seed(42);
  TF_ASSIGN_OR_ASSERT_OK(
      auto actual,
      client_->ExecuteAndTransfer(computation, /*arguments=*/{},
                                  &execution_options));
  EXPECT_TRUE(ContainersEqual(dims, actual->shape().dimensions()));
  int32 sum = 0;
  LiteralUtil::EachCell<uint32>(
      *actual, [&sum](tensorflow::gtl::ArraySlice<int64>, uint32 value) {
        EXPECT_TRUE(value == 0 || value == 1);
        sum += value;
      });
  int32 total = ShapeUtil::ElementsIn(shape);
  float p_tilde = sum / static_cast<float>(total);

  // Test within expected range using normal approximation. The test uses a
  // fixed seed and has a fixed output per p and backend. Using the normal
  // approximation as this test is invoked for different `p` and the different
  // backends could use different random number generators and produce different
  // values. Choose 95% confidence level, so that z_{1-\alpha/2} = 1.96.
  float normal_approximation_term = 1.96 * sqrt(p * (1 - p) / total);
  EXPECT_GE(p_tilde, p - normal_approximation_term);
  EXPECT_LE(p_tilde, p + normal_approximation_term);
}

// Uniform random number generation tests
XLA_TEST_F(PrngTest, ScalarU01) { UniformTest<float>(0, 1, {}); }
XLA_TEST_F(PrngTest, ZeroValuesU01) { UniformTest<float>(0, 1, {0}); }
XLA_TEST_F(PrngTest, TenValuesU01) { UniformTest<float>(0, 1, {10}); }
XLA_TEST_F(PrngTest, TenValuesU37) { UniformTest<float>(3, 7, {10}); }
XLA_TEST_F(PrngTest, ZeroValuesR2) { UniformTest<float>(0, 1, {0, 20}); }
XLA_TEST_F(PrngTest, LargeU01) { UniformTest<float>(0, 1, {0x100, 0x100}); }
XLA_TEST_F(PrngTest, TwelveValuesU524) { UniformTest<int32>(5, 24, {12}); }

namespace {
template <typename T>
T Square(T x) {
  return x * x;
}
}  // namespace

double PrngTest::UniformChiSquared(int32 range_size, int32 expected_count) {
  int32 sample_size = range_size * expected_count;

  ComputationBuilder builder(client_, TestName());
  builder.RngUniform(builder.ConstantR0<int32>(0),
                     builder.ConstantR0<int32>(range_size),
                     ShapeUtil::MakeShape(S32, {sample_size}));

  auto actual = ExecuteAndTransferOrDie(&builder, /*arguments=*/{});
  std::vector<int32> counts(range_size, 0);
  LiteralUtil::EachCell<int32>(
      *actual, [&counts](tensorflow::gtl::ArraySlice<int64>, int32 value) {
        ++counts[value];
      });
  int64 sum = 0;
  for (int32 i = 0; i < range_size; ++i) {
    sum += Square(counts[i] - expected_count);
  }
  return static_cast<double>(sum) / expected_count;
}

// We only test distribution of uniform discrete PRNG as other types are based
// on it.
// These range sizes are arbitrary but include prime numbers, powers of 2, and
// other composite numbers.
// The level of significance in all these cases is 1/20.
// TODO(b/35723038): Use parametrized tests where possible.
XLA_TEST_F(PrngTest, Uniformity7) {
  EXPECT_LT(UniformChiSquared(7, 256), 12.5916);
}
XLA_TEST_F(PrngTest, Uniformity61) {
  EXPECT_LT(UniformChiSquared(61, 256), 79.0819);
}
XLA_TEST_F(PrngTest, Uniformity64) {
  EXPECT_LT(UniformChiSquared(64, 256), 82.5287);
}
XLA_TEST_F(PrngTest, Uniformity108) {
  EXPECT_LT(UniformChiSquared(108, 256), 132.144);
}
XLA_TEST_F(PrngTest, Uniformity256) {
  EXPECT_LT(UniformChiSquared(256, 256), 293.248);
}

XLA_TEST_F(PrngTest, MapUsingRng) {
  // Build a x -> (x + U[0,1)) computation.
  auto build_sum_rng = [this](ComputationBuilder& builder) {
    auto b = builder.CreateSubBuilder("sum_with_rng");
    auto x = b->Parameter(0, ShapeUtil::MakeShape(F32, {}), "input");
    b->Add(x,
           b->RngUniform(b->ConstantR0<float>(0), b->ConstantR0<float>(1),
                         ShapeUtil::MakeShape(F32, {})));
    return b->BuildAndNoteError();
  };

  ComputationBuilder builder(client_, TestName());
  std::unique_ptr<Literal> param0_literal =
      LiteralUtil::CreateR1<float>({2.2f, 5.3f, 4.4f, 5.5f});
  TF_ASSIGN_OR_ASSERT_OK(std::unique_ptr<GlobalData> param0_data,
                         client_->TransferToServer(*param0_literal));

  auto param0 = builder.Parameter(0, param0_literal->shape(), "param0");
  auto fn = build_sum_rng(builder);
  builder.Map({param0}, fn);

  TF_ASSIGN_OR_ASSERT_OK(auto computation, builder.Build());

  ExecutionOptions execution_options;
  execution_options.set_seed(125);
  TF_ASSIGN_OR_ASSERT_OK(
      auto actual,
      client_->ExecuteAndTransfer(computation,
                                  /*arguments=*/{param0_data.get()},
                                  &execution_options));

  EXPECT_EQ(actual->f32s_size(), param0_literal->f32s_size());
  for (int i = 0; i < param0_literal->f32s_size(); ++i) {
    EXPECT_GE(actual->f32s(i), param0_literal->f32s(i));
    EXPECT_LT(actual->f32s(i), param0_literal->f32s(i) + 1.0f);
  }
}

// This tests demonstrates the global seeding behaviour.
// * If a seed is passed in via Execute (ExecuteAndTransfer) then the output is
//   fixed (i.e., there is a single output for a given seed);
// * If no seed is passed in then the output of every call can be different;
XLA_TEST_F(PrngTest, PassInGlobalRngSeed) {
  // Build a U[0,1) computation.
  auto build_computation = [this]() {
    ComputationBuilder builder(client_, TestName());
    builder.RngUniform(builder.ConstantR0<float>(0),
                       builder.ConstantR0<float>(1),
                       ShapeUtil::MakeShape(F32, {10}));
    return builder.Build();
  };

  ExecutionOptions execution_options1;
  execution_options1.set_seed(42);

  ExecutionOptions execution_options2;
  execution_options2.set_seed(65);

  std::unique_ptr<Literal> result1;
  {
    TF_ASSIGN_OR_ASSERT_OK(auto computation, build_computation());
    TF_ASSIGN_OR_ASSERT_OK(
        result1,
        client_->ExecuteAndTransfer(computation, /*arguments=*/{},
                                    &execution_options1));
  }
  std::unique_ptr<Literal> result2;
  std::unique_ptr<Literal> result3;
  {
    TF_ASSIGN_OR_ASSERT_OK(auto computation, build_computation());
    TF_ASSIGN_OR_ASSERT_OK(
        result2,
        client_->ExecuteAndTransfer(computation, /*arguments=*/{},
                                    &execution_options1));
    TF_ASSIGN_OR_ASSERT_OK(
        result3,
        client_->ExecuteAndTransfer(computation, /*arguments=*/{},
                                    &execution_options1));
  }

  std::unique_ptr<Literal> result4;
  std::unique_ptr<Literal> result5;
  std::unique_ptr<Literal> result6;
  {
    TF_ASSIGN_OR_ASSERT_OK(auto computation, build_computation());
    TF_ASSIGN_OR_ASSERT_OK(
        result4,
        client_->ExecuteAndTransfer(computation, /*arguments=*/{},
                                    &execution_options2));
    TF_ASSIGN_OR_ASSERT_OK(
        result5, client_->ExecuteAndTransfer(computation, /*arguments=*/{}));
    TF_ASSIGN_OR_ASSERT_OK(
        result6, client_->ExecuteAndTransfer(computation, /*arguments=*/{}));
  }

  LiteralTestUtil::ExpectEqual(*result1, *result2);
  LiteralTestUtil::ExpectEqual(*result1, *result3);
  LiteralTestUtil::ExpectNotEqual(*result1, *result4);
  LiteralTestUtil::ExpectNotEqual(*result4, *result5);
  LiteralTestUtil::ExpectNotEqual(*result5, *result6);
}

// Bernoulli random number generation tests
XLA_TEST_F(PrngTest, HundredValuesB10p5) { BernoulliTest(0.5, {100}); }
XLA_TEST_F(PrngTest, HundredValuesB10p1) { BernoulliTest(0.1, {100}); }

XLA_TEST_F(PrngTest, TenValuesN01) {
  ComputationBuilder builder(client_, TestName());
  builder.RngNormal(builder.ConstantR0<float>(0), builder.ConstantR0<float>(1),
                    ShapeUtil::MakeShape(F32, {10}));

  ExecuteAndTransferOrDie(&builder, /*arguments=*/{});
  // TODO(b/25995601): Test that resultant values are reasonable
}

}  // namespace
}  // namespace xla

int main(int argc, char** argv) {
  std::vector<tensorflow::Flag> flag_list;
  xla::legacy_flags::AppendCpuCompilerFlags(&flag_list);
  xla::string usage = tensorflow::Flags::Usage(argv[0], flag_list);
  const bool parse_result = tensorflow::Flags::Parse(&argc, argv, flag_list);
  if (!parse_result) {
    LOG(ERROR) << "\n" << usage;
    return 2;
  }
  testing::InitGoogleTest(&argc, argv);
  if (argc > 1) {
    LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage;
    return 2;
  }
  return RUN_ALL_TESTS();
}
<commit_msg>[XLA] Fix undefined behavior on int32 overflow in prng_test<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <memory>

#include "tensorflow/compiler/xla/client/computation_builder.h"
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/compiler/xla/legacy_flags/cpu_compiler_flags.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/primitive_util.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/tests/client_library_test_base.h"
#include "tensorflow/compiler/xla/tests/test_macros.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/platform/protobuf.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/types.h"

namespace xla {
namespace {

class PrngTest : public ClientLibraryTestBase {
 protected:
  template <typename T>
  void UniformTest(T a, T b, tensorflow::gtl::ArraySlice<int64> dims);
  void BernoulliTest(float p, tensorflow::gtl::ArraySlice<int64> dims);

  // Computes the χ² statistic of a sample of the discrete uniform distribution
  // of the given range size. `expected_count` is the number of times each
  // possible value is expected to be generated. Thus, the sample size is
  // `range_size * expected_count`.
  double UniformChiSquared(int32 range_size, int32 expected_count);
};

template <typename T>
void PrngTest::UniformTest(T a, T b, tensorflow::gtl::ArraySlice<int64> dims) {
  ComputationBuilder builder(client_, TestName());
  builder.RngUniform(
      builder.ConstantR0<T>(a), builder.ConstantR0<T>(b),
      ShapeUtil::MakeShape(primitive_util::NativeToPrimitiveType<T>(), dims));

  auto actual = ExecuteAndTransferOrDie(&builder, /*arguments=*/{});
  EXPECT_TRUE(ContainersEqual(dims, actual->shape().dimensions()));
  LiteralUtil::EachCell<T>(*actual,
                           [=](tensorflow::gtl::ArraySlice<int64>, T value) {
                             EXPECT_LE(a, value);
                             EXPECT_LT(value, b);
                           });
}

void PrngTest::BernoulliTest(float p, tensorflow::gtl::ArraySlice<int64> dims) {
  ComputationBuilder builder(client_, TestName());
  auto shape = ShapeUtil::MakeShape(U32, dims);
  builder.RngBernoulli(builder.ConstantR0<float>(p), shape);

  TF_ASSIGN_OR_ASSERT_OK(auto computation, builder.Build());
  ExecutionOptions execution_options;
  execution_options.set_seed(42);
  TF_ASSIGN_OR_ASSERT_OK(
      auto actual,
      client_->ExecuteAndTransfer(computation, /*arguments=*/{},
                                  &execution_options));
  EXPECT_TRUE(ContainersEqual(dims, actual->shape().dimensions()));
  int32 sum = 0;
  LiteralUtil::EachCell<uint32>(
      *actual, [&sum](tensorflow::gtl::ArraySlice<int64>, uint32 value) {
        EXPECT_TRUE(value == 0 || value == 1);
        sum += value;
      });
  int32 total = ShapeUtil::ElementsIn(shape);
  float p_tilde = sum / static_cast<float>(total);

  // Test within expected range using normal approximation. The test uses a
  // fixed seed and has a fixed output per p and backend. Using the normal
  // approximation as this test is invoked for different `p` and the different
  // backends could use different random number generators and produce different
  // values. Choose 95% confidence level, so that z_{1-\alpha/2} = 1.96.
  float normal_approximation_term = 1.96 * sqrt(p * (1 - p) / total);
  EXPECT_GE(p_tilde, p - normal_approximation_term);
  EXPECT_LE(p_tilde, p + normal_approximation_term);
}

// Uniform random number generation tests
XLA_TEST_F(PrngTest, ScalarU01) { UniformTest<float>(0, 1, {}); }
XLA_TEST_F(PrngTest, ZeroValuesU01) { UniformTest<float>(0, 1, {0}); }
XLA_TEST_F(PrngTest, TenValuesU01) { UniformTest<float>(0, 1, {10}); }
XLA_TEST_F(PrngTest, TenValuesU37) { UniformTest<float>(3, 7, {10}); }
XLA_TEST_F(PrngTest, ZeroValuesR2) { UniformTest<float>(0, 1, {0, 20}); }
XLA_TEST_F(PrngTest, LargeU01) { UniformTest<float>(0, 1, {0x100, 0x100}); }
XLA_TEST_F(PrngTest, TwelveValuesU524) { UniformTest<int32>(5, 24, {12}); }

namespace {
template <typename T>
T Square(T x) {
  return x * x;
}
}  // namespace

double PrngTest::UniformChiSquared(int32 range_size, int32 expected_count) {
  int32 sample_size = range_size * expected_count;

  ComputationBuilder builder(client_, TestName());
  builder.RngUniform(builder.ConstantR0<int32>(0),
                     builder.ConstantR0<int32>(range_size),
                     ShapeUtil::MakeShape(S32, {sample_size}));

  auto actual = ExecuteAndTransferOrDie(&builder, /*arguments=*/{});
  std::vector<int32> counts(range_size, 0);
  LiteralUtil::EachCell<int32>(
      *actual, [&counts](tensorflow::gtl::ArraySlice<int64>, int32 value) {
        ++counts[value];
      });
  int64 sum = 0;
  for (int32 i = 0; i < range_size; ++i) {
    sum += Square(static_cast<int64>(counts[i] - expected_count));
  }
  return static_cast<double>(sum) / expected_count;
}

// We only test distribution of uniform discrete PRNG as other types are based
// on it.
// These range sizes are arbitrary but include prime numbers, powers of 2, and
// other composite numbers.
// The level of significance in all these cases is 1/20.
// TODO(b/35723038): Use parametrized tests where possible.
XLA_TEST_F(PrngTest, Uniformity7) {
  EXPECT_LT(UniformChiSquared(7, 256), 12.5916);
}
XLA_TEST_F(PrngTest, Uniformity61) {
  EXPECT_LT(UniformChiSquared(61, 256), 79.0819);
}
XLA_TEST_F(PrngTest, Uniformity64) {
  EXPECT_LT(UniformChiSquared(64, 256), 82.5287);
}
XLA_TEST_F(PrngTest, Uniformity108) {
  EXPECT_LT(UniformChiSquared(108, 256), 132.144);
}
XLA_TEST_F(PrngTest, Uniformity256) {
  EXPECT_LT(UniformChiSquared(256, 256), 293.248);
}

XLA_TEST_F(PrngTest, MapUsingRng) {
  // Build a x -> (x + U[0,1)) computation.
  auto build_sum_rng = [this](ComputationBuilder& builder) {
    auto b = builder.CreateSubBuilder("sum_with_rng");
    auto x = b->Parameter(0, ShapeUtil::MakeShape(F32, {}), "input");
    b->Add(x,
           b->RngUniform(b->ConstantR0<float>(0), b->ConstantR0<float>(1),
                         ShapeUtil::MakeShape(F32, {})));
    return b->BuildAndNoteError();
  };

  ComputationBuilder builder(client_, TestName());
  std::unique_ptr<Literal> param0_literal =
      LiteralUtil::CreateR1<float>({2.2f, 5.3f, 4.4f, 5.5f});
  TF_ASSIGN_OR_ASSERT_OK(std::unique_ptr<GlobalData> param0_data,
                         client_->TransferToServer(*param0_literal));

  auto param0 = builder.Parameter(0, param0_literal->shape(), "param0");
  auto fn = build_sum_rng(builder);
  builder.Map({param0}, fn);

  TF_ASSIGN_OR_ASSERT_OK(auto computation, builder.Build());

  ExecutionOptions execution_options;
  execution_options.set_seed(125);
  TF_ASSIGN_OR_ASSERT_OK(
      auto actual,
      client_->ExecuteAndTransfer(computation,
                                  /*arguments=*/{param0_data.get()},
                                  &execution_options));

  EXPECT_EQ(actual->f32s_size(), param0_literal->f32s_size());
  for (int i = 0; i < param0_literal->f32s_size(); ++i) {
    EXPECT_GE(actual->f32s(i), param0_literal->f32s(i));
    EXPECT_LT(actual->f32s(i), param0_literal->f32s(i) + 1.0f);
  }
}

// This tests demonstrates the global seeding behaviour.
// * If a seed is passed in via Execute (ExecuteAndTransfer) then the output is
//   fixed (i.e., there is a single output for a given seed);
// * If no seed is passed in then the output of every call can be different;
XLA_TEST_F(PrngTest, PassInGlobalRngSeed) {
  // Build a U[0,1) computation.
  auto build_computation = [this]() {
    ComputationBuilder builder(client_, TestName());
    builder.RngUniform(builder.ConstantR0<float>(0),
                       builder.ConstantR0<float>(1),
                       ShapeUtil::MakeShape(F32, {10}));
    return builder.Build();
  };

  ExecutionOptions execution_options1;
  execution_options1.set_seed(42);

  ExecutionOptions execution_options2;
  execution_options2.set_seed(65);

  std::unique_ptr<Literal> result1;
  {
    TF_ASSIGN_OR_ASSERT_OK(auto computation, build_computation());
    TF_ASSIGN_OR_ASSERT_OK(
        result1,
        client_->ExecuteAndTransfer(computation, /*arguments=*/{},
                                    &execution_options1));
  }
  std::unique_ptr<Literal> result2;
  std::unique_ptr<Literal> result3;
  {
    TF_ASSIGN_OR_ASSERT_OK(auto computation, build_computation());
    TF_ASSIGN_OR_ASSERT_OK(
        result2,
        client_->ExecuteAndTransfer(computation, /*arguments=*/{},
                                    &execution_options1));
    TF_ASSIGN_OR_ASSERT_OK(
        result3,
        client_->ExecuteAndTransfer(computation, /*arguments=*/{},
                                    &execution_options1));
  }

  std::unique_ptr<Literal> result4;
  std::unique_ptr<Literal> result5;
  std::unique_ptr<Literal> result6;
  {
    TF_ASSIGN_OR_ASSERT_OK(auto computation, build_computation());
    TF_ASSIGN_OR_ASSERT_OK(
        result4,
        client_->ExecuteAndTransfer(computation, /*arguments=*/{},
                                    &execution_options2));
    TF_ASSIGN_OR_ASSERT_OK(
        result5, client_->ExecuteAndTransfer(computation, /*arguments=*/{}));
    TF_ASSIGN_OR_ASSERT_OK(
        result6, client_->ExecuteAndTransfer(computation, /*arguments=*/{}));
  }

  LiteralTestUtil::ExpectEqual(*result1, *result2);
  LiteralTestUtil::ExpectEqual(*result1, *result3);
  LiteralTestUtil::ExpectNotEqual(*result1, *result4);
  LiteralTestUtil::ExpectNotEqual(*result4, *result5);
  LiteralTestUtil::ExpectNotEqual(*result5, *result6);
}

// Bernoulli random number generation tests
XLA_TEST_F(PrngTest, HundredValuesB10p5) { BernoulliTest(0.5, {100}); }
XLA_TEST_F(PrngTest, HundredValuesB10p1) { BernoulliTest(0.1, {100}); }

XLA_TEST_F(PrngTest, TenValuesN01) {
  ComputationBuilder builder(client_, TestName());
  builder.RngNormal(builder.ConstantR0<float>(0), builder.ConstantR0<float>(1),
                    ShapeUtil::MakeShape(F32, {10}));

  ExecuteAndTransferOrDie(&builder, /*arguments=*/{});
  // TODO(b/25995601): Test that resultant values are reasonable
}

}  // namespace
}  // namespace xla

int main(int argc, char** argv) {
  std::vector<tensorflow::Flag> flag_list;
  xla::legacy_flags::AppendCpuCompilerFlags(&flag_list);
  xla::string usage = tensorflow::Flags::Usage(argv[0], flag_list);
  const bool parse_result = tensorflow::Flags::Parse(&argc, argv, flag_list);
  if (!parse_result) {
    LOG(ERROR) << "\n" << usage;
    return 2;
  }
  testing::InitGoogleTest(&argc, argv);
  if (argc > 1) {
    LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage;
    return 2;
  }
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>#ifndef __GLOBALS_HPP_INCLUDED
#define __GLOBALS_HPP_INCLUDED

#include "code/ylikuutio/callback_system/key_and_callback_struct.hpp"
#include "any_value.hpp"

// GCC (at least g++ 4.7.2) and Visual Studio 2015 do support
// setting default values of a struct using C++11 syntax.
// Clang 3.7.0 and Visual Studio 2013 do not support
// setting default values of a struct using C++11 syntax.
// Visual Studio 2013 fails to compile, whereas Clang-compiled
// executable with code with setting default values of a struct
// causes Segmentation fault upon execution of the program.
// Compilers that don't support setting default values of a struct
// are handled by setting the default values in a macro.
// http://stackoverflow.com/questions/16782103/initializing-default-values-in-a-struct/16783513#16783513
#ifdef __clang__
#elif defined(__GNUC__)
#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#elif defined(_WIN32)
#if (_MSC_VER >= 1900)
#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#endif
#endif

// GLEW must be included here, because `globals.hpp` may be compiled
// first, and if `GL/glew.h` is not included before `glfw3.h` (?),
// then g++ prints the following error:
// `error: #error gl.h included before glew.h`
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif

// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <stdint.h> // uint32_t etc.
#include <string>   // std::string
#include <unordered_map> // std::unordered_map
#include <vector>   // std::vector

#ifndef PI
#define PI 3.14159265359f
#endif

namespace config
{
    class SettingMaster;
    class Setting;
}

namespace callback_system
{
    class CallbackEngine;
    class CallbackObject;
    class CallbackParameter;
}

namespace graph
{
    class Graph;
}

typedef datatypes::AnyValue* (*ConsoleCommandCallback) (
        console::Console*,
        ontology::Universe*,
        std::vector<std::string>& command_parameters);

typedef struct ConsoleStruct
{
    ConsoleStruct()
        : universe_pointer(nullptr), font2D_pointer(nullptr)
    {
        // constructor.
    }
    std::vector<KeyAndCallbackStruct>** current_keypress_callback_engine_vector_pointer_pointer;
    std::vector<KeyAndCallbackStruct>** current_keyrelease_callback_engine_vector_pointer_pointer;
    std::unordered_map<std::string, ConsoleCommandCallback>* command_callback_map_pointer;
    ontology::Universe* universe_pointer;
    ontology::Font2D* font2D_pointer;
} ConsoleStruct;

typedef datatypes::AnyValue* (*ActivateCallback) (ontology::Universe* universe, config::SettingMaster* setting_master);

typedef struct SettingStruct
{
    SettingStruct(datatypes::AnyValue& initial_value)
        : initial_value(initial_value), should_ylikuutio_call_activate_callback_now(true), setting_master_pointer(nullptr), activate_callback(nullptr)
    {
        // constructor.
    }
    std::string name;
    datatypes::AnyValue& initial_value;
    config::SettingMaster* setting_master_pointer;
    ActivateCallback activate_callback;
    bool should_ylikuutio_call_activate_callback_now;
} SettingStruct;

typedef struct
{
    uint32_t screen_width;
    uint32_t screen_height;
    uint32_t x;
    uint32_t y;
    uint32_t text_size;
    uint32_t font_size;
    std::string text;
    const char* text_char;
    const char* char_font_texture_file_format;
    const char* horizontal_alignment;
    const char* vertical_alignment;
} PrintingStruct;

typedef struct
{
    double rho;
    double theta;
    double phi;
} SphericalCoordinatesStruct;

typedef struct SphericalWorldStruct
{
    SphericalWorldStruct()
        :SRTM_latitude_step_in_degrees(1.0f/1200.0f), SRTM_longitude_step_in_degrees(1.0f/1200.0f)
    {
        // constructor.
    }
    double southern_latitude;
    double northern_latitude;
    double western_longitude;
    double eastern_longitude;
    double SRTM_latitude_step_in_degrees;
    double SRTM_longitude_step_in_degrees;
} SphericalWorldStruct;

typedef struct TriangulateQuadsStruct
{
    TriangulateQuadsStruct()
        : should_ylikuutio_use_real_texture_coordinates(true), x_step(1), z_step(1)
    {
        // constructor.
    }
    uint32_t image_width;
    uint32_t image_height;
    uint32_t x_step;
    uint32_t z_step;
    std::string triangulation_type;
    bool should_ylikuutio_use_real_texture_coordinates;
    double sphere_radius;
    SphericalWorldStruct spherical_world_struct;
} TriangulateQuadsStruct;

typedef struct TriangulatePolygonsStruct
{
    TriangulatePolygonsStruct()
        : should_ylikuutio_use_real_texture_coordinates(true)
    {
        // constructor.
    }
    std::vector<std::vector<glm::vec2>>* input_vertices;
    bool should_ylikuutio_use_real_texture_coordinates;
} TriangulatePolygonsStruct;

typedef struct
{
    uint32_t image_width;
    uint32_t image_height;
    bool should_ylikuutio_use_real_texture_coordinates;
} BilinearInterpolationStruct;

typedef struct
{
    uint32_t image_width;
    uint32_t image_height;
    double sphere_radius;
    bool is_bilinear_interpolation_in_use;
    SphericalWorldStruct spherical_world_struct;
} TransformationStruct;

typedef datatypes::AnyValue* (*InputParametersToAnyValueCallback) (
        callback_system::CallbackEngine*,
        callback_system::CallbackObject*,
        std::vector<callback_system::CallbackParameter*>&);

namespace console
{
    class Console;
}
typedef datatypes::AnyValue* (*InputParametersToAnyValueCallbackWithConsole) (
        callback_system::CallbackEngine*,
        callback_system::CallbackObject*,
        std::vector<callback_system::CallbackParameter*>&,
        console::Console*);

typedef datatypes::AnyValue* (*GetContentCallback) (
        callback_system::CallbackEngine*,
        callback_system::CallbackObject*,
        std::vector<callback_system::CallbackParameter*>&,
        uint32_t x_start,
        uint32_t y_start,
        uint32_t z_start,
        uint32_t x_size,
        uint32_t y_size,
        uint32_t z_size);

#endif
<commit_msg>Added missing forward declarations: `Universe` and `Font2D`.<commit_after>#ifndef __GLOBALS_HPP_INCLUDED
#define __GLOBALS_HPP_INCLUDED

#include "code/ylikuutio/callback_system/key_and_callback_struct.hpp"
#include "any_value.hpp"

// GCC (at least g++ 4.7.2) and Visual Studio 2015 do support
// setting default values of a struct using C++11 syntax.
// Clang 3.7.0 and Visual Studio 2013 do not support
// setting default values of a struct using C++11 syntax.
// Visual Studio 2013 fails to compile, whereas Clang-compiled
// executable with code with setting default values of a struct
// causes Segmentation fault upon execution of the program.
// Compilers that don't support setting default values of a struct
// are handled by setting the default values in a macro.
// http://stackoverflow.com/questions/16782103/initializing-default-values-in-a-struct/16783513#16783513
#ifdef __clang__
#elif defined(__GNUC__)
#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#elif defined(_WIN32)
#if (_MSC_VER >= 1900)
#define __STRUCT_DEFAULT_VALUES_ARE_ACCEPTED
#endif
#endif

// GLEW must be included here, because `globals.hpp` may be compiled
// first, and if `GL/glew.h` is not included before `glfw3.h` (?),
// then g++ prints the following error:
// `error: #error gl.h included before glew.h`
#ifndef __GL_GLEW_H_INCLUDED
#define __GL_GLEW_H_INCLUDED
#include <GL/glew.h> // GLfloat, GLuint etc.
#endif

// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif

// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif

// Include standard headers
#include <stdint.h> // uint32_t etc.
#include <string>   // std::string
#include <unordered_map> // std::unordered_map
#include <vector>   // std::vector

#ifndef PI
#define PI 3.14159265359f
#endif

namespace config
{
    class SettingMaster;
    class Setting;
}

namespace callback_system
{
    class CallbackEngine;
    class CallbackObject;
    class CallbackParameter;
}

namespace graph
{
    class Graph;
}

namespace ontology
{
    class Universe;
    class Font2D;
}

typedef datatypes::AnyValue* (*ConsoleCommandCallback) (
        console::Console*,
        ontology::Universe*,
        std::vector<std::string>& command_parameters);

typedef struct ConsoleStruct
{
    ConsoleStruct()
        : universe_pointer(nullptr), font2D_pointer(nullptr)
    {
        // constructor.
    }
    std::vector<KeyAndCallbackStruct>** current_keypress_callback_engine_vector_pointer_pointer;
    std::vector<KeyAndCallbackStruct>** current_keyrelease_callback_engine_vector_pointer_pointer;
    std::unordered_map<std::string, ConsoleCommandCallback>* command_callback_map_pointer;
    ontology::Universe* universe_pointer;
    ontology::Font2D* font2D_pointer;
} ConsoleStruct;

typedef datatypes::AnyValue* (*ActivateCallback) (ontology::Universe* universe, config::SettingMaster* setting_master);

typedef struct SettingStruct
{
    SettingStruct(datatypes::AnyValue& initial_value)
        : initial_value(initial_value), should_ylikuutio_call_activate_callback_now(true), setting_master_pointer(nullptr), activate_callback(nullptr)
    {
        // constructor.
    }
    std::string name;
    datatypes::AnyValue& initial_value;
    config::SettingMaster* setting_master_pointer;
    ActivateCallback activate_callback;
    bool should_ylikuutio_call_activate_callback_now;
} SettingStruct;

typedef struct
{
    uint32_t screen_width;
    uint32_t screen_height;
    uint32_t x;
    uint32_t y;
    uint32_t text_size;
    uint32_t font_size;
    std::string text;
    const char* text_char;
    const char* char_font_texture_file_format;
    const char* horizontal_alignment;
    const char* vertical_alignment;
} PrintingStruct;

typedef struct
{
    double rho;
    double theta;
    double phi;
} SphericalCoordinatesStruct;

typedef struct SphericalWorldStruct
{
    SphericalWorldStruct()
        :SRTM_latitude_step_in_degrees(1.0f/1200.0f), SRTM_longitude_step_in_degrees(1.0f/1200.0f)
    {
        // constructor.
    }
    double southern_latitude;
    double northern_latitude;
    double western_longitude;
    double eastern_longitude;
    double SRTM_latitude_step_in_degrees;
    double SRTM_longitude_step_in_degrees;
} SphericalWorldStruct;

typedef struct TriangulateQuadsStruct
{
    TriangulateQuadsStruct()
        : should_ylikuutio_use_real_texture_coordinates(true), x_step(1), z_step(1)
    {
        // constructor.
    }
    uint32_t image_width;
    uint32_t image_height;
    uint32_t x_step;
    uint32_t z_step;
    std::string triangulation_type;
    bool should_ylikuutio_use_real_texture_coordinates;
    double sphere_radius;
    SphericalWorldStruct spherical_world_struct;
} TriangulateQuadsStruct;

typedef struct TriangulatePolygonsStruct
{
    TriangulatePolygonsStruct()
        : should_ylikuutio_use_real_texture_coordinates(true)
    {
        // constructor.
    }
    std::vector<std::vector<glm::vec2>>* input_vertices;
    bool should_ylikuutio_use_real_texture_coordinates;
} TriangulatePolygonsStruct;

typedef struct
{
    uint32_t image_width;
    uint32_t image_height;
    bool should_ylikuutio_use_real_texture_coordinates;
} BilinearInterpolationStruct;

typedef struct
{
    uint32_t image_width;
    uint32_t image_height;
    double sphere_radius;
    bool is_bilinear_interpolation_in_use;
    SphericalWorldStruct spherical_world_struct;
} TransformationStruct;

typedef datatypes::AnyValue* (*InputParametersToAnyValueCallback) (
        callback_system::CallbackEngine*,
        callback_system::CallbackObject*,
        std::vector<callback_system::CallbackParameter*>&);

namespace console
{
    class Console;
}
typedef datatypes::AnyValue* (*InputParametersToAnyValueCallbackWithConsole) (
        callback_system::CallbackEngine*,
        callback_system::CallbackObject*,
        std::vector<callback_system::CallbackParameter*>&,
        console::Console*);

typedef datatypes::AnyValue* (*GetContentCallback) (
        callback_system::CallbackEngine*,
        callback_system::CallbackObject*,
        std::vector<callback_system::CallbackParameter*>&,
        uint32_t x_start,
        uint32_t y_start,
        uint32_t z_start,
        uint32_t x_size,
        uint32_t y_size,
        uint32_t z_size);

#endif
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/views/importer_view.h"

#include "app/l10n_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "views/controls/button/checkbox.h"
#include "views/controls/label.h"
#include "views/grid_layout.h"
#include "views/standard_layout.h"
#include "views/widget/widget.h"
#include "views/window/window.h"

using views::ColumnSet;
using views::GridLayout;

namespace browser {

// Declared in browser_dialogs.h so caller's don't have to depend on our header.
void ShowImporterView(views::Widget* parent,
                      Profile* profile) {
  views::Window::CreateChromeWindow(parent->GetNativeView(), gfx::Rect(),
                                    new ImporterView(profile))->Show();
}

}  // namespace browser

ImporterView::ImporterView(Profile* profile)
    : import_from_label_(NULL),
      profile_combobox_(NULL),
      import_items_label_(NULL),
      history_checkbox_(NULL),
      favorites_checkbox_(NULL),
      passwords_checkbox_(NULL),
      search_engines_checkbox_(NULL),
      profile_(profile),
      importer_host_(new ImporterHost()) {
  DCHECK(profile);
  SetupControl();
}

ImporterView::~ImporterView() {
}

void ImporterView::SetupControl() {
  // Adds all controls.
  import_from_label_ =
      new views::Label(l10n_util::GetString(IDS_IMPORT_FROM_LABEL));

  profile_combobox_ = new views::Combobox(this);
  profile_combobox_->set_listener(this);

  import_items_label_ =
      new views::Label(l10n_util::GetString(IDS_IMPORT_ITEMS_LABEL));

  history_checkbox_ =
      InitCheckbox(l10n_util::GetString(IDS_IMPORT_HISTORY_CHKBOX), true);
  favorites_checkbox_ =
      InitCheckbox(l10n_util::GetString(IDS_IMPORT_FAVORITES_CHKBOX), true);
  passwords_checkbox_ =
      InitCheckbox(l10n_util::GetString(IDS_IMPORT_PASSWORDS_CHKBOX), true);
  search_engines_checkbox_ =
      InitCheckbox(l10n_util::GetString(IDS_IMPORT_SEARCH_ENGINES_CHKBOX),
                   true);

  // Arranges controls by using GridLayout.
  const int column_set_id = 0;
  GridLayout* layout = CreatePanelGridLayout(this);
  SetLayoutManager(layout);
  ColumnSet* column_set = layout->AddColumnSet(column_set_id);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
  column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0,
                        GridLayout::FIXED, 200, 0);

  layout->StartRow(0, column_set_id);
  layout->AddView(import_from_label_);
  layout->AddView(profile_combobox_);

  layout->AddPaddingRow(0, kUnrelatedControlVerticalSpacing);
  layout->StartRow(0, column_set_id);
  layout->AddView(import_items_label_, 3, 1);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
  layout->StartRow(0, column_set_id);
  layout->AddView(favorites_checkbox_, 3, 1);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
  layout->StartRow(0, column_set_id);
  layout->AddView(search_engines_checkbox_, 3, 1);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
  layout->StartRow(0, column_set_id);
  layout->AddView(passwords_checkbox_, 3, 1);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
  layout->StartRow(0, column_set_id);
  layout->AddView(history_checkbox_, 3, 1);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
}

gfx::Size ImporterView::GetPreferredSize() {
  return gfx::Size(views::Window::GetLocalizedContentsSize(
      IDS_IMPORT_DIALOG_WIDTH_CHARS,
      IDS_IMPORT_DIALOG_HEIGHT_LINES));
}

void ImporterView::Layout() {
  GetLayoutManager()->Layout(this);
}

std::wstring ImporterView::GetDialogButtonLabel(
    MessageBoxFlags::DialogButton button) const {
  if (button == MessageBoxFlags::DIALOGBUTTON_OK) {
    return l10n_util::GetString(IDS_IMPORT_COMMIT);
  } else {
    return std::wstring();
  }
}

bool ImporterView::IsModal() const {
  return true;
}

std::wstring ImporterView::GetWindowTitle() const {
  return l10n_util::GetString(IDS_IMPORT_SETTINGS_TITLE);
}

bool ImporterView::Accept() {
  if (!IsDialogButtonEnabled(MessageBoxFlags::DIALOGBUTTON_OK)) {
    return false;
  }

  uint16 items = GetCheckedItems();

  Browser* browser = BrowserList::GetLastActive();
  int selected_index = profile_combobox_->selected_item();
  HWND parent_hwnd =
      reinterpret_cast<HWND>(browser->window()->GetNativeHandle());
  StartImportingWithUI(parent_hwnd, items, importer_host_.get(),
                       importer_host_->GetSourceProfileInfoAt(selected_index),
                       profile_, this, false);
  // We return false here to prevent the window from being closed. We will be
  // notified back by our implementation of ImportObserver when the import is
  // complete so that we can close ourselves.
  return false;
}

views::View* ImporterView::GetContentsView() {
  return this;
}

int ImporterView::GetItemCount(views::Combobox* source) {
  DCHECK(source == profile_combobox_);
  DCHECK(importer_host_.get());
  int item_count = importer_host_->GetAvailableProfileCount();
  if (checkbox_items_.size() < static_cast<size_t>(item_count))
    checkbox_items_.resize(item_count, ALL);
  return item_count;
}

std::wstring ImporterView::GetItemAt(views::Combobox* source, int index) {
  DCHECK(source == profile_combobox_);
  DCHECK(importer_host_.get());
  return importer_host_->GetSourceProfileNameAt(index);
}

void ImporterView::ItemChanged(views::Combobox* combobox,
                               int prev_index, int new_index) {
  DCHECK(combobox);
  DCHECK(checkbox_items_.size() >=
      static_cast<size_t>(importer_host_->GetAvailableProfileCount()));

  if (prev_index == new_index)
    return;

  // Save the current state
  uint16 prev_items = GetCheckedItems();
  checkbox_items_[prev_index] = prev_items;

  // Enable/Disable the checkboxes for this Item
  uint16 new_enabled_items = importer_host_->GetSourceProfileInfoAt(
      new_index).services_supported;
  SetCheckedItemsState(new_enabled_items);

  // Set the checked items for this Item
  uint16 new_items = checkbox_items_[new_index];
  SetCheckedItems(new_items);
}

void ImporterView::ImportCanceled() {
  ImportComplete();
}

void ImporterView::ImportComplete() {
  // Now close this window since the import completed or was canceled.
  window()->Close();
}

views::Checkbox* ImporterView::InitCheckbox(const std::wstring& text,
                                            bool checked) {
  views::Checkbox* checkbox = new views::Checkbox(text);
  checkbox->SetChecked(checked);
  return checkbox;
}

uint16 ImporterView::GetCheckedItems() {
  uint16 items = NONE;
  if (history_checkbox_->IsEnabled() && history_checkbox_->checked())
    items |= HISTORY;
  if (favorites_checkbox_->IsEnabled() && favorites_checkbox_->checked())
    items |= FAVORITES;
  if (passwords_checkbox_->IsEnabled() && passwords_checkbox_->checked())
    items |= PASSWORDS;
  if (search_engines_checkbox_->IsEnabled() &&
      search_engines_checkbox_->checked())
    items |= SEARCH_ENGINES;
  return items;
}

void ImporterView::SetCheckedItemsState(uint16 items) {
  if (items & HISTORY) {
    history_checkbox_->SetEnabled(true);
  } else {
    history_checkbox_->SetEnabled(false);
    history_checkbox_->SetChecked(false);
  }
  if (items & FAVORITES) {
    favorites_checkbox_->SetEnabled(true);
  } else {
    favorites_checkbox_->SetEnabled(false);
    favorites_checkbox_->SetChecked(false);
  }
  if (items & PASSWORDS) {
    passwords_checkbox_->SetEnabled(true);
  } else {
    passwords_checkbox_->SetEnabled(false);
    passwords_checkbox_->SetChecked(false);
  }
  if (items & SEARCH_ENGINES) {
    search_engines_checkbox_->SetEnabled(true);
  } else {
    search_engines_checkbox_->SetEnabled(false);
    search_engines_checkbox_->SetChecked(false);
  }
}

void ImporterView::SetCheckedItems(uint16 items) {
  if (history_checkbox_->IsEnabled())
    history_checkbox_->SetChecked(!!(items & HISTORY));

  if (favorites_checkbox_->IsEnabled())
    favorites_checkbox_->SetChecked(!!(items & FAVORITES));

  if (passwords_checkbox_->IsEnabled())
    passwords_checkbox_->SetChecked(!!(items & PASSWORDS));

  if (search_engines_checkbox_->IsEnabled())
    search_engines_checkbox_->SetChecked(!!(items & SEARCH_ENGINES));
}
<commit_msg>Fix HWND for Importer Dialog<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/views/importer_view.h"

#include "app/l10n_util.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "views/controls/button/checkbox.h"
#include "views/controls/label.h"
#include "views/grid_layout.h"
#include "views/standard_layout.h"
#include "views/widget/widget.h"
#include "views/window/window.h"

using views::ColumnSet;
using views::GridLayout;

namespace browser {

// Declared in browser_dialogs.h so caller's don't have to depend on our header.
void ShowImporterView(views::Widget* parent,
                      Profile* profile) {
  views::Window::CreateChromeWindow(parent->GetNativeView(), gfx::Rect(),
                                    new ImporterView(profile))->Show();
}

}  // namespace browser

ImporterView::ImporterView(Profile* profile)
    : import_from_label_(NULL),
      profile_combobox_(NULL),
      import_items_label_(NULL),
      history_checkbox_(NULL),
      favorites_checkbox_(NULL),
      passwords_checkbox_(NULL),
      search_engines_checkbox_(NULL),
      profile_(profile),
      importer_host_(new ImporterHost()) {
  DCHECK(profile);
  SetupControl();
}

ImporterView::~ImporterView() {
}

void ImporterView::SetupControl() {
  // Adds all controls.
  import_from_label_ =
      new views::Label(l10n_util::GetString(IDS_IMPORT_FROM_LABEL));

  profile_combobox_ = new views::Combobox(this);
  profile_combobox_->set_listener(this);

  import_items_label_ =
      new views::Label(l10n_util::GetString(IDS_IMPORT_ITEMS_LABEL));

  history_checkbox_ =
      InitCheckbox(l10n_util::GetString(IDS_IMPORT_HISTORY_CHKBOX), true);
  favorites_checkbox_ =
      InitCheckbox(l10n_util::GetString(IDS_IMPORT_FAVORITES_CHKBOX), true);
  passwords_checkbox_ =
      InitCheckbox(l10n_util::GetString(IDS_IMPORT_PASSWORDS_CHKBOX), true);
  search_engines_checkbox_ =
      InitCheckbox(l10n_util::GetString(IDS_IMPORT_SEARCH_ENGINES_CHKBOX),
                   true);

  // Arranges controls by using GridLayout.
  const int column_set_id = 0;
  GridLayout* layout = CreatePanelGridLayout(this);
  SetLayoutManager(layout);
  ColumnSet* column_set = layout->AddColumnSet(column_set_id);
  column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
  column_set->AddColumn(GridLayout::FILL, GridLayout::CENTER, 0,
                        GridLayout::FIXED, 200, 0);

  layout->StartRow(0, column_set_id);
  layout->AddView(import_from_label_);
  layout->AddView(profile_combobox_);

  layout->AddPaddingRow(0, kUnrelatedControlVerticalSpacing);
  layout->StartRow(0, column_set_id);
  layout->AddView(import_items_label_, 3, 1);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
  layout->StartRow(0, column_set_id);
  layout->AddView(favorites_checkbox_, 3, 1);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
  layout->StartRow(0, column_set_id);
  layout->AddView(search_engines_checkbox_, 3, 1);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
  layout->StartRow(0, column_set_id);
  layout->AddView(passwords_checkbox_, 3, 1);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
  layout->StartRow(0, column_set_id);
  layout->AddView(history_checkbox_, 3, 1);
  layout->AddPaddingRow(0, kRelatedControlVerticalSpacing);
}

gfx::Size ImporterView::GetPreferredSize() {
  return gfx::Size(views::Window::GetLocalizedContentsSize(
      IDS_IMPORT_DIALOG_WIDTH_CHARS,
      IDS_IMPORT_DIALOG_HEIGHT_LINES));
}

void ImporterView::Layout() {
  GetLayoutManager()->Layout(this);
}

std::wstring ImporterView::GetDialogButtonLabel(
    MessageBoxFlags::DialogButton button) const {
  if (button == MessageBoxFlags::DIALOGBUTTON_OK) {
    return l10n_util::GetString(IDS_IMPORT_COMMIT);
  } else {
    return std::wstring();
  }
}

bool ImporterView::IsModal() const {
  return true;
}

std::wstring ImporterView::GetWindowTitle() const {
  return l10n_util::GetString(IDS_IMPORT_SETTINGS_TITLE);
}

bool ImporterView::Accept() {
  if (!IsDialogButtonEnabled(MessageBoxFlags::DIALOGBUTTON_OK)) {
    return false;
  }

  uint16 items = GetCheckedItems();

  int selected_index = profile_combobox_->selected_item();
  StartImportingWithUI(GetWidget()->GetNativeView(), items,
                       importer_host_.get(),
                       importer_host_->GetSourceProfileInfoAt(selected_index),
                       profile_, this, false);
  // We return false here to prevent the window from being closed. We will be
  // notified back by our implementation of ImportObserver when the import is
  // complete so that we can close ourselves.
  return false;
}

views::View* ImporterView::GetContentsView() {
  return this;
}

int ImporterView::GetItemCount(views::Combobox* source) {
  DCHECK(source == profile_combobox_);
  DCHECK(importer_host_.get());
  int item_count = importer_host_->GetAvailableProfileCount();
  if (checkbox_items_.size() < static_cast<size_t>(item_count))
    checkbox_items_.resize(item_count, ALL);
  return item_count;
}

std::wstring ImporterView::GetItemAt(views::Combobox* source, int index) {
  DCHECK(source == profile_combobox_);
  DCHECK(importer_host_.get());
  return importer_host_->GetSourceProfileNameAt(index);
}

void ImporterView::ItemChanged(views::Combobox* combobox,
                               int prev_index, int new_index) {
  DCHECK(combobox);
  DCHECK(checkbox_items_.size() >=
      static_cast<size_t>(importer_host_->GetAvailableProfileCount()));

  if (prev_index == new_index)
    return;

  // Save the current state
  uint16 prev_items = GetCheckedItems();
  checkbox_items_[prev_index] = prev_items;

  // Enable/Disable the checkboxes for this Item
  uint16 new_enabled_items = importer_host_->GetSourceProfileInfoAt(
      new_index).services_supported;
  SetCheckedItemsState(new_enabled_items);

  // Set the checked items for this Item
  uint16 new_items = checkbox_items_[new_index];
  SetCheckedItems(new_items);
}

void ImporterView::ImportCanceled() {
  ImportComplete();
}

void ImporterView::ImportComplete() {
  // Now close this window since the import completed or was canceled.
  window()->Close();
}

views::Checkbox* ImporterView::InitCheckbox(const std::wstring& text,
                                            bool checked) {
  views::Checkbox* checkbox = new views::Checkbox(text);
  checkbox->SetChecked(checked);
  return checkbox;
}

uint16 ImporterView::GetCheckedItems() {
  uint16 items = NONE;
  if (history_checkbox_->IsEnabled() && history_checkbox_->checked())
    items |= HISTORY;
  if (favorites_checkbox_->IsEnabled() && favorites_checkbox_->checked())
    items |= FAVORITES;
  if (passwords_checkbox_->IsEnabled() && passwords_checkbox_->checked())
    items |= PASSWORDS;
  if (search_engines_checkbox_->IsEnabled() &&
      search_engines_checkbox_->checked())
    items |= SEARCH_ENGINES;
  return items;
}

void ImporterView::SetCheckedItemsState(uint16 items) {
  if (items & HISTORY) {
    history_checkbox_->SetEnabled(true);
  } else {
    history_checkbox_->SetEnabled(false);
    history_checkbox_->SetChecked(false);
  }
  if (items & FAVORITES) {
    favorites_checkbox_->SetEnabled(true);
  } else {
    favorites_checkbox_->SetEnabled(false);
    favorites_checkbox_->SetChecked(false);
  }
  if (items & PASSWORDS) {
    passwords_checkbox_->SetEnabled(true);
  } else {
    passwords_checkbox_->SetEnabled(false);
    passwords_checkbox_->SetChecked(false);
  }
  if (items & SEARCH_ENGINES) {
    search_engines_checkbox_->SetEnabled(true);
  } else {
    search_engines_checkbox_->SetEnabled(false);
    search_engines_checkbox_->SetChecked(false);
  }
}

void ImporterView::SetCheckedItems(uint16 items) {
  if (history_checkbox_->IsEnabled())
    history_checkbox_->SetChecked(!!(items & HISTORY));

  if (favorites_checkbox_->IsEnabled())
    favorites_checkbox_->SetChecked(!!(items & FAVORITES));

  if (passwords_checkbox_->IsEnabled())
    passwords_checkbox_->SetChecked(!!(items & PASSWORDS));

  if (search_engines_checkbox_->IsEnabled())
    search_engines_checkbox_->SetChecked(!!(items & SEARCH_ENGINES));
}
<|endoftext|>


<commit_before>// FIXME: https://code.google.com/p/address-sanitizer/issues/detail?id=316
// XFAIL: android
//
// Different size: detect a bug if detect_odr_violation>=1
// RUN: %clangxx_asan -DBUILD_SO=1 -fPIC -shared %s -o %t-ODR-SO.so
// RUN: %clangxx_asan %s %t-ODR-SO.so -Wl,-R. -o %t-ODR-EXE
// RUN: ASAN_OPTIONS=detect_odr_violation=1 not %run %t-ODR-EXE 2>&1 | FileCheck %s
// RUN: ASAN_OPTIONS=detect_odr_violation=2 not %run %t-ODR-EXE 2>&1 | FileCheck %s
// RUN: ASAN_OPTIONS=detect_odr_violation=0     %run %t-ODR-EXE 2>&1 | FileCheck %s --check-prefix=DISABLED
// RUN:                                     not %run %t-ODR-EXE 2>&1 | FileCheck %s
//
// Same size: report a bug only if detect_odr_violation>=2.
// RUN: %clangxx_asan -DBUILD_SO=1 -fPIC -shared %s -o %t-ODR-SO.so -DSZ=100
// RUN: ASAN_OPTIONS=detect_odr_violation=1     %run %t-ODR-EXE 2>&1 | FileCheck %s --check-prefix=DISABLED
// RUN: ASAN_OPTIONS=detect_odr_violation=2 not %run %t-ODR-EXE 2>&1 | FileCheck %s
// RUN:                                     not %run %t-ODR-EXE 2>&1 | FileCheck %s

// GNU driver doesn't handle .so files properly.
// REQUIRES: Clang

#ifndef SZ
# define SZ 4
#endif

#if BUILD_SO
namespace foo { char G[SZ]; }
#else
#include <stdio.h>
namespace foo { char G[100]; }
// CHECK: ERROR: AddressSanitizer: odr-violation
// CHECK: size=100 'foo::G' {{.*}}odr-violation.cc:[[@LINE-2]]:22
// CHECK: size={{4|100}} 'foo::G'
int main(int argc, char **argv) {
  printf("PASS: %p\n", &foo::G);
}
#endif

// CHECK: These globals were registered at these points:
// CHECK: ODR-EXE
// CHECK: ODR-SO
// CHECK: SUMMARY: AddressSanitizer: odr-violation: global 'foo::G' at {{.*}}odr-violation.cc
// DISABLED: PASS
<commit_msg>[asan] fix odr-violation.cc test to always use slow unwinding (hopefully fixes the ARM bot)<commit_after>// FIXME: https://code.google.com/p/address-sanitizer/issues/detail?id=316
// XFAIL: android
//
// We use fast_unwind_on_malloc=0 to have full unwinding even w/o frame
// pointers. This setting is not on by default because it's too expensive.
//
// Different size: detect a bug if detect_odr_violation>=1
// RUN: %clangxx_asan -DBUILD_SO=1 -fPIC -shared %s -o %t-ODR-SO.so
// RUN: %clangxx_asan %s %t-ODR-SO.so -Wl,-R. -o %t-ODR-EXE
// RUN: ASAN_OPTIONS=fast_unwind_on_malloc=0:detect_odr_violation=1 not %run %t-ODR-EXE 2>&1 | FileCheck %s
// RUN: ASAN_OPTIONS=fast_unwind_on_malloc=0:detect_odr_violation=2 not %run %t-ODR-EXE 2>&1 | FileCheck %s
// RUN: ASAN_OPTIONS=fast_unwind_on_malloc=0:detect_odr_violation=0     %run %t-ODR-EXE 2>&1 | FileCheck %s --check-prefix=DISABLED
// RUN:                                     not %run %t-ODR-EXE 2>&1 | FileCheck %s
//
// Same size: report a bug only if detect_odr_violation>=2.
// RUN: %clangxx_asan -DBUILD_SO=1 -fPIC -shared %s -o %t-ODR-SO.so -DSZ=100
// RUN: ASAN_OPTIONS=fast_unwind_on_malloc=0:detect_odr_violation=1     %run %t-ODR-EXE 2>&1 | FileCheck %s --check-prefix=DISABLED
// RUN: ASAN_OPTIONS=fast_unwind_on_malloc=0:detect_odr_violation=2 not %run %t-ODR-EXE 2>&1 | FileCheck %s
// RUN:                                     not %run %t-ODR-EXE 2>&1 | FileCheck %s

// GNU driver doesn't handle .so files properly.
// REQUIRES: Clang

#ifndef SZ
# define SZ 4
#endif

#if BUILD_SO
namespace foo { char G[SZ]; }
#else
#include <stdio.h>
namespace foo { char G[100]; }
// CHECK: ERROR: AddressSanitizer: odr-violation
// CHECK: size=100 'foo::G' {{.*}}odr-violation.cc:[[@LINE-2]]:22
// CHECK: size={{4|100}} 'foo::G'
int main(int argc, char **argv) {
  printf("PASS: %p\n", &foo::G);
}
#endif

// CHECK: These globals were registered at these points:
// CHECK: ODR-EXE
// CHECK: ODR-SO
// CHECK: SUMMARY: AddressSanitizer: odr-violation: global 'foo::G' at {{.*}}odr-violation.cc
// DISABLED: PASS
<|endoftext|>


<commit_before>// kmmsglist.cpp

#include "kmmsglist.h"
#include "kmmsgdict.h"
#include "kmkernel.h"
#include <assert.h>
#include <stdlib.h>

//-----------------------------------------------------------------------------
KMMsgList::KMMsgList(int initSize): KMMsgListInherited(initSize)
{
  mHigh  = size();
  mCount = 0;
  clear(FALSE);
}

//-----------------------------------------------------------------------------
KMMsgList::~KMMsgList()
{
  clear(TRUE);
}

//-----------------------------------------------------------------------------
void KMMsgList::clear(bool doDelete, bool syncDict)
{
  KMMsgBasePtr msg = 0;
  long i;

  KMMsgDict *dict = 0;
  if (syncDict)
    dict = kernel->msgDict();

  for (i=mHigh-1; i>=0; i--)
  {
    msg = at(i);
    if (msg) {
      if (dict)
        dict->remove(msg);
      KMMsgListInherited::at(i) = NULL;
      if (doDelete) delete msg;
    }
  }
  mHigh  = 0;
  mCount = 0;
}

//-----------------------------------------------------------------------------
bool KMMsgList::resize(int aSize)
{
  int i, oldSize = size();
  KMMsgBasePtr msg;

  assert(aSize>=0);

  // delete messages that will get lost, if any
  if (aSize < mHigh)
  {
    for (i=aSize; i<mHigh; i++)
    {
      msg = at(i);
      if (msg)
      {
	delete msg;
	mCount--;
      }
      mHigh = aSize;
    }
  }

  // do the resizing
  if (!KMMsgListInherited::resize(aSize)) return FALSE;

  // initialize new elements
  for (i=oldSize; i<aSize; i++)
    KMMsgListInherited::at(i) = NULL;

  return TRUE;
}

//-----------------------------------------------------------------------------
bool KMMsgList::reset(int aSize)
{
  if (!resize(aSize)) return FALSE;
  clear();
  return TRUE;
}

//-----------------------------------------------------------------------------
void KMMsgList::set(int idx, KMMsgBasePtr aMsg)
{
  int doubleSize;

  assert(idx>=0);

  if (idx >= size())
  {
    doubleSize = size() << 1;
    resize(idx>doubleSize ? idx+16 : doubleSize);
  }

  if (!at(idx) && aMsg) mCount++;
  else if (at(idx) && !aMsg) mCount--;

  delete at(idx);

  KMMsgListInherited::at(idx) = aMsg;

  if (!aMsg || idx >= mHigh) rethinkHigh();
}

//-----------------------------------------------------------------------------
void KMMsgList::insert(int idx, KMMsgBasePtr aMsg, bool syncDict)
{
  int i, doubleSize;

  assert(idx>=0);
  KMMsgDict *dict = 0;
  if (syncDict)
    dict = kernel->msgDict();

  if (idx >= size())
  {
    doubleSize = size() << 1;
    resize(idx>doubleSize ? idx+16 : doubleSize);
  }

  if (aMsg) mCount++;

  for (i=mHigh; i>idx; i--) {
    if (dict)
      dict->remove(at(i - 1));
    KMMsgListInherited::at(i) = KMMsgListInherited::at(i-1);
    if (dict)
      dict->insert(at(i), i);
  }

  KMMsgListInherited::at(idx) = aMsg;
  if (dict)
    dict->insert(at(idx), idx);

  mHigh++;
}

//-----------------------------------------------------------------------------
int KMMsgList::append(KMMsgBasePtr aMsg, bool syncDict)
{
  int idx = mHigh;
  insert(idx, aMsg, syncDict); // mHigh gets modified in here
  return idx;
}

//-----------------------------------------------------------------------------
void KMMsgList::remove(int idx)
{
  int i;

  assert(idx>=0 && idx<size());
  KMMsgDict *dict = kernel->msgDict();

  if (KMMsgListInherited::at(idx)) {
    mCount--;
    if (dict)
      dict->remove(at(idx));
  }

  unsigned long msn = 0;
  mHigh--;
  for (i=idx; i<mHigh; i++) {
    if (dict)
      msn = dict->remove(at(i + 1));
    KMMsgListInherited::at(i) = KMMsgListInherited::at(i+1);
    if (dict)
      dict->insert(msn, at(i), i);
  }

  KMMsgListInherited::at(mHigh) = NULL;

  rethinkHigh();
}

//-----------------------------------------------------------------------------
KMMsgBasePtr KMMsgList::take(int idx)
{
  KMMsgBasePtr msg=at(idx);
  remove(idx);
  return msg;
}

//-----------------------------------------------------------------------------
void KMMsgList::rethinkHigh(void)
{
  int sz = (int)size();

  if (mHigh < sz && at(mHigh))
  {
    // forward search
    while (mHigh < sz && at(mHigh))
      mHigh++;
  }
  else
  {
    // backward search
    while (mHigh>0 && !at(mHigh-1))
      mHigh--;
  }
}

//-----------------------------------------------------------------------------
void KMMsgList::fillMsgDict(KMMsgDict *dict)
{
  for (int idx = 0; idx < mHigh; idx++)
    if (at(idx))
      dict->insert(0, at(idx), idx);
}
<commit_msg>Make removing many message from huge folders much faster. It's however still slow.<commit_after>// kmmsglist.cpp

#include "kmmsglist.h"
#include "kmmsgdict.h"
#include "kmkernel.h"
#include <assert.h>
#include <stdlib.h>

//-----------------------------------------------------------------------------
KMMsgList::KMMsgList(int initSize): KMMsgListInherited(initSize)
{
  mHigh  = size();
  mCount = 0;
  clear(FALSE);
}

//-----------------------------------------------------------------------------
KMMsgList::~KMMsgList()
{
  clear(TRUE);
}

//-----------------------------------------------------------------------------
void KMMsgList::clear(bool doDelete, bool syncDict)
{
  KMMsgBasePtr msg = 0;
  long i;

  KMMsgDict *dict = 0;
  if (syncDict)
    dict = kernel->msgDict();

  for (i=mHigh-1; i>=0; i--)
  {
    msg = at(i);
    if (msg) {
      if (dict)
        dict->remove(msg);
      KMMsgListInherited::at(i) = NULL;
      if (doDelete) delete msg;
    }
  }
  mHigh  = 0;
  mCount = 0;
}

//-----------------------------------------------------------------------------
bool KMMsgList::resize(int aSize)
{
  int i, oldSize = size();
  KMMsgBasePtr msg;

  assert(aSize>=0);

  // delete messages that will get lost, if any
  if (aSize < mHigh)
  {
    for (i=aSize; i<mHigh; i++)
    {
      msg = at(i);
      if (msg)
      {
	delete msg;
	mCount--;
      }
      mHigh = aSize;
    }
  }

  // do the resizing
  if (!KMMsgListInherited::resize(aSize)) return FALSE;

  // initialize new elements
  for (i=oldSize; i<aSize; i++)
    KMMsgListInherited::at(i) = NULL;

  return TRUE;
}

//-----------------------------------------------------------------------------
bool KMMsgList::reset(int aSize)
{
  if (!resize(aSize)) return FALSE;
  clear();
  return TRUE;
}

//-----------------------------------------------------------------------------
void KMMsgList::set(int idx, KMMsgBasePtr aMsg)
{
  int doubleSize;

  assert(idx>=0);

  if (idx >= size())
  {
    doubleSize = size() << 1;
    resize(idx>doubleSize ? idx+16 : doubleSize);
  }

  if (!at(idx) && aMsg) mCount++;
  else if (at(idx) && !aMsg) mCount--;

  delete at(idx);

  KMMsgListInherited::at(idx) = aMsg;

  if (!aMsg || idx >= mHigh) rethinkHigh();
}

//-----------------------------------------------------------------------------
void KMMsgList::insert(int idx, KMMsgBasePtr aMsg, bool syncDict)
{
  int i, doubleSize;

  assert(idx>=0);
  KMMsgDict *dict = 0;
  if (syncDict)
    dict = kernel->msgDict();

  if (idx >= size())
  {
    doubleSize = size() << 1;
    resize(idx>doubleSize ? idx+16 : doubleSize);
  }

  if (aMsg) mCount++;

  for (i=mHigh; i>idx; i--) {
    if (dict)
      dict->remove(at(i - 1));
    KMMsgListInherited::at(i) = KMMsgListInherited::at(i-1);
    if (dict)
      dict->insert(at(i), i);
  }

  KMMsgListInherited::at(idx) = aMsg;
  if (dict)
    dict->insert(at(idx), idx);

  mHigh++;
}

//-----------------------------------------------------------------------------
int KMMsgList::append(KMMsgBasePtr aMsg, bool syncDict)
{
  int idx = mHigh;
  insert(idx, aMsg, syncDict); // mHigh gets modified in here
  return idx;
}

//-----------------------------------------------------------------------------
void KMMsgList::remove(int idx)
{
  int i;

  assert(idx>=0 && idx<size());
  KMMsgDict *dict = kernel->msgDict();

  if (KMMsgListInherited::at(idx)) {
    mCount--;
    if (dict)
      dict->remove(at(idx));
  }

  unsigned long msn = 0;
  mHigh--;
  for (i=idx; i<mHigh; i++) {
    if (dict)
    {
      msn = dict->getMsgSerNum(at(i + 1)->parent(), i + 1);
      dict->remove(msn);
    }
    KMMsgListInherited::at(i) = KMMsgListInherited::at(i+1);
    if (dict)
      dict->insert(msn, at(i), i);
  }

  KMMsgListInherited::at(mHigh) = NULL;

  rethinkHigh();
}

//-----------------------------------------------------------------------------
KMMsgBasePtr KMMsgList::take(int idx)
{
  KMMsgBasePtr msg=at(idx);
  remove(idx);
  return msg;
}

//-----------------------------------------------------------------------------
void KMMsgList::rethinkHigh(void)
{
  int sz = (int)size();

  if (mHigh < sz && at(mHigh))
  {
    // forward search
    while (mHigh < sz && at(mHigh))
      mHigh++;
  }
  else
  {
    // backward search
    while (mHigh>0 && !at(mHigh-1))
      mHigh--;
  }
}

//-----------------------------------------------------------------------------
void KMMsgList::fillMsgDict(KMMsgDict *dict)
{
  for (int idx = 0; idx < mHigh; idx++)
    if (at(idx))
      dict->insert(0, at(idx), idx);
}
<|endoftext|>