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

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

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

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include "kmailchanges.h"
#include "kolabconfig.h"

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

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

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

    }

    void apply()
    {
      QString defaultDomain = KolabConfig::self()->server();
      QString email;
      QString user = KolabConfig::self()->user();
      int pos = user.find( "@" );
      // with kolab the userid _is_ the full email
      if ( pos > 0 ) {
        // The user typed in a full email address. Assume it's correct
        email = user;
        const QString h = user.mid( pos+1 );
        if ( !h.isEmpty() )
          // The user did type in a domain on the email address. Use that
          defaultDomain = h;
      }
      else
        // Construct the email address. And use it for the username also
        user = email = user+"@"+KolabConfig::self()->server();

      KConfig c( "kmailrc" );
      c.setGroup( "General" );
      c.writeEntry( "Default domain", defaultDomain );
      uint accCnt = c.readNumEntry( "accounts", 0 );
      c.writeEntry( "accounts", accCnt+1 );
      uint transCnt = c.readNumEntry( "transports", 0 );
      c.writeEntry( "transports", transCnt+1 );

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

      c.writeEntry( "login", user );

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

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

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

      c.setGroup( QString("Transport %1").arg(transCnt+1) );
      c.writeEntry( "name", "Kolab Server" );
      c.writeEntry( "host", KolabConfig::self()->server() );
      c.writeEntry( "type", "smtp" );
      c.writeEntry( "port", "465" );
      c.writeEntry( "encryption", "SSL" );
      c.writeEntry( "auth", true );
      c.writeEntry( "authtype", "PLAIN" );
      c.writeEntry( "user", email );
      c.writeEntry( "pass", encryptStr(KolabConfig::self()->password()) );
      c.writeEntry( "storepass", "true" );

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

      KPIM::IdentityManager identityManager;
      if ( !identityManager.allEmails().contains( email ) ) {
        // Not sure how to name the identity. First one is "Default", next one "Kolab", but then...
        KPIM::Identity& identity = identityManager.newFromScratch( i18n( "Kolab" ) );
        identity.setFullName( KolabConfig::self()->realName() );
        identity.setEmailAddr( email );
        identityManager.commit();
      }

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

};

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

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

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

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

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

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

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

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

  changes.append( new CreateDisconnectedImapAccount );
}
<commit_msg>Fix kolabwizard creating multiple identities with the same name (https://intevation.de/roundup/kolab/issue767). First identity is still called "Kolab" (since most people only have one kolab account), after that they're called after the hostname, and "hostname 2", "hostname 3" in case of duplicates.<commit_after>/*
    This file is part of kdepim.

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

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

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.
*/

#include "kmailchanges.h"
#include "kolabconfig.h"

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

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

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

    }

    void apply()
    {
      QString defaultDomain = KolabConfig::self()->server();
      QString email;
      QString user = KolabConfig::self()->user();
      int pos = user.find( "@" );
      // with kolab the userid _is_ the full email
      if ( pos > 0 ) {
        // The user typed in a full email address. Assume it's correct
        email = user;
        const QString h = user.mid( pos+1 );
        if ( !h.isEmpty() )
          // The user did type in a domain on the email address. Use that
          defaultDomain = h;
      }
      else
        // Construct the email address. And use it for the username also
        user = email = user+"@"+KolabConfig::self()->server();

      KConfig c( "kmailrc" );
      c.setGroup( "General" );
      c.writeEntry( "Default domain", defaultDomain );
      uint accCnt = c.readNumEntry( "accounts", 0 );
      c.writeEntry( "accounts", accCnt+1 );
      uint transCnt = c.readNumEntry( "transports", 0 );
      c.writeEntry( "transports", transCnt+1 );

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

      c.writeEntry( "login", user );

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

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

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

      c.setGroup( QString("Transport %1").arg(transCnt+1) );
      c.writeEntry( "name", "Kolab Server" );
      c.writeEntry( "host", KolabConfig::self()->server() );
      c.writeEntry( "type", "smtp" );
      c.writeEntry( "port", "465" );
      c.writeEntry( "encryption", "SSL" );
      c.writeEntry( "auth", true );
      c.writeEntry( "authtype", "PLAIN" );
      c.writeEntry( "user", email );
      c.writeEntry( "pass", encryptStr(KolabConfig::self()->password()) );
      c.writeEntry( "storepass", "true" );

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

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

        KPIM::Identity& identity = identityManager.newFromScratch( accountName );
        identity.setFullName( KolabConfig::self()->realName() );
        identity.setEmailAddr( email );
        identityManager.commit();
      }

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

};

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

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

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

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

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

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

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

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

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


<commit_before>/* detectMotionObject.cpp */
//-----------------------------------------------------------------------
// include files
//-----------------------------------------------------------------------
#include <vector>
#include <opencv2/opencv.hpp>
#include "detectMotionObject.h"
#include "optFlow2RGB.h"

//-----------------------------------------------------------------------
// using namespace
//-----------------------------------------------------------------------
using namespace std;

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

//***********************************************************************
// Function : detectMotionObject |
//***********************************************************************
void detectMotionObject( cv::Mat& curr, cv::Mat& gray, std::vector<cv::Rect>& detected_obj ){
    // 平滑化
    blur( gray, gray, cv::Size(3,3) );
    // cv::imshow("gray", gray);

    // 二値化
    cv::Mat bin;
    cv::threshold((gray.type() == CV_32FC1) ? cv::Mat1b(gray*255): gray, bin, 10, 255.0, CV_THRESH_BINARY);
    // cv::imshow("bin", bin);

    //輪郭の座標リスト
    std::vector<std::vector<cv::Point>> contours;

    //輪郭取得
    cv::findContours(bin, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);

    cv::Mat curr_disp = curr.clone();
    for (auto contour: contours){
        // 輪郭を直線近似する
        std::vector< cv::Point > approx;
        cv::approxPolyDP(cv::Mat(contour), approx, 0.01 * cv::arcLength(contour, true), true);
        // 近似の面積が一定以上なら取得
        double area = cv::contourArea(approx);

        if (area > 1000.0){
            // 検出された輪郭線を緑で描画
            // cv::polylines(curr_disp, *contour, true, cv::Scalar(0, 255, 0), 2);

            // 外接矩形を描画
            detected_obj.push_back( cv::boundingRect(cv::Mat(approx).reshape(2)) );
            // cv::rectangle(curr_disp, detected_obj.back().tl(), detected_obj.back().br(), cv::Scalar(255, 0, 0), 2, CV_AA);
        }
    }

    //全体を表示する場合
    // cv::imshow("coun", curr_disp);
}
<commit_msg>近接する矩形をマージする処理の追加<commit_after>/* detectMotionObject.cpp */
//-----------------------------------------------------------------------
// include files
//-----------------------------------------------------------------------
#include <vector>
#include <opencv2/opencv.hpp>
#include "detectMotionObject.h"
#include "optFlow2RGB.h"

//-----------------------------------------------------------------------
// using namespace
//-----------------------------------------------------------------------
using namespace std;

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

//***********************************************************************
// Function : detectMotionObject |
//***********************************************************************
void detectMotionObject( cv::Mat& curr, cv::Mat& gray, std::vector<cv::Rect>& detected_obj ){
    // 平滑化
    blur( gray, gray, cv::Size(3,3) );
    // cv::imshow("gray", gray);

    // 二値化
    cv::Mat bin;
    cv::threshold((gray.type() == CV_32FC1) ? cv::Mat1b(gray*255): gray, bin, 10, 255.0, CV_THRESH_BINARY);
    // cv::imshow("bin", bin);

    //輪郭の座標リスト
    std::vector<std::vector<cv::Point>> contours;

    //輪郭取得
    cv::findContours(bin, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);

    cv::Mat curr_disp = curr.clone();
    std::vector<cv::Rect> detected_obj_tmp;
    for (auto contour: contours){
        // 輪郭を直線近似する
        std::vector< cv::Point > approx;
        cv::approxPolyDP(cv::Mat(contour), approx, 0.01 * cv::arcLength(contour, true), true);
        // 近似の面積が一定以上なら取得
        double area = cv::contourArea(approx);

        if (area > 1000.0){
            // 検出された輪郭線を緑で描画
            // cv::polylines(curr_disp, *contour, true, cv::Scalar(0, 255, 0), 2);

            // 外接矩形を描画
            detected_obj_tmp.push_back( cv::boundingRect(cv::Mat(approx).reshape(2)) );
            // cv::rectangle(curr_disp, detected_obj.back().tl(), detected_obj.back().br(), cv::Scalar(255, 0, 0), 2, CV_AA);
        }
    }

    // 近接する矩形同士をマージ
//    cout << detected_obj_tmp.size() << ", ";
    if( detected_obj_tmp.size() > 1 ){
        for(auto& i: detected_obj_tmp){
            if(i.area() == 0){
                continue;
            }
            cv::Point2i i_centerP = (i.tl() + i.br())/2;
            int i_S = i.area();
            for(auto& j: detected_obj_tmp){
                if(i == j || j.area() == 0){
                    continue;
                }
                cv::Point2i j_centerP = (j.tl() + j.br())/2;
                int j_S = j.area();
                cv::Rect rect_tmp(i_centerP, j_centerP);
                int contain = 0;
                if(i_S > j_S){
                    contain += (i.contains(rect_tmp.tl()))?1:0;
                    contain += (i.contains(rect_tmp.tl() + cv::Point2i(rect_tmp.width,0)))?1:0;
                    contain += (i.contains(rect_tmp.tl() + cv::Point2i(0,rect_tmp.height)))?1:0;
                    contain += (i.contains(rect_tmp.br()))?1:0;
                } else {
                    contain += (j.contains(rect_tmp.tl()))?1:0;
                    contain += (j.contains(rect_tmp.tl() + cv::Point2i(rect_tmp.width,0)))?1:0;
                    contain += (j.contains(rect_tmp.tl() + cv::Point2i(0,rect_tmp.height)))?1:0;
                    contain += (j.contains(rect_tmp.br()))?1:0;
                }

                if(contain > 3){
                    i |= j;
                } else if( contain == 2){
                    if( rect_tmp.width > rect_tmp.height ){
                        if( 10 < rect_tmp.width - (i.width + j.width)/2 ){
                            i |= j;
                            j = cv::Rect();
                        }
                    } else {
                        if( 10 < rect_tmp.height - (i.height + j.height)/2 ){
                            i |= j;
                            j = cv::Rect();
                        }
                    }
                }
            }
        }
    }
    for(auto i: detected_obj_tmp){
        if(i.area() > 0){
            detected_obj.push_back(i);
        }
    }

//    cout << detected_obj.size() << "| ";
    //全体を表示する場合
    // cv::imshow("coun", curr_disp);
}
<|endoftext|>


<commit_before>/****************************************************************************
 *   Copyright (C) 2011  Instituto Nokia de Tecnologia (INdT)               *
 *                                                                          *
 *   This file may be used under the terms of the GNU Lesser                *
 *   General Public License version 2.1 as published by the Free Software   *
 *   Foundation and appearing in the file LICENSE.LGPL included in the      *
 *   packaging of this file.  Please review the following information to    *
 *   ensure the GNU Lesser General Public License version 2.1 requirements  *
 *   will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.   *
 *                                                                          *
 *   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 Lesser General Public License for more details.                    *
 ****************************************************************************/

#include "BookmarkModel.h"

#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlRecord>

BookmarkModel::BookmarkModel(QSqlDatabase database, QObject *parent)
    : QSqlTableModel(parent,  database)
{
    connect(this, SIGNAL(rowsInserted(const QModelIndex&, int, int)), SIGNAL(countChanged()));
    connect(this, SIGNAL(rowsRemoved(const QModelIndex&, int, int)), SIGNAL(countChanged()));
    setEditStrategy(OnManualSubmit);
}

void BookmarkModel::generateRoleNames()
{
    for (int i = 0; i < this->columnCount(); i++)
        m_roles[Qt::UserRole + i] = this->headerData(i, Qt::Horizontal).toByteArray();

    setRoleNames(m_roles);
}

QString BookmarkModel::tableCreateQuery() const
{
    const QLatin1String bookmarkQuery("CREATE TABLE IF NOT EXISTS bookmarks (id INTEGER PRIMARY KEY AUTOINCREMENT,"
                                  "name VARCHAR, url VARCHAR, dateAdded DATE);");

    return bookmarkQuery;

}

void BookmarkModel::setFilter(const QString& filter)
{
    QSqlTableModel::setFilter(filter);
}

bool BookmarkModel::select()
{
    return QSqlTableModel::select();
}

void BookmarkModel::insert(const QString& name, const QString& url)
{
    if (contains(url))
        return;
    QSqlRecord record = this->record();
    record.setValue(QLatin1String("name"), name);
    record.setValue(QLatin1String("url"), url);

    insertRecord(-1, record);
    submitAll();
}

void BookmarkModel::remove(const QString& url)
{
    if (!contains(url))
        return;

    QSqlQuery sqlQuery(database());
    sqlQuery.prepare(QLatin1String("SELECT id FROM bookmarks WHERE url = ?"));
    sqlQuery.addBindValue(url);
    sqlQuery.exec();
    sqlQuery.first();
    int indexToDelete = -1;
    for (int row = 0; row < rowCount(); ++row) {
        if (createIndex(row, 0).data(Qt::DisplayRole).toInt() == sqlQuery.value(0).toInt()) {
            indexToDelete = row;
            break;
        }
    }

    if (indexToDelete >= 0) {
        beginRemoveRows(createIndex(indexToDelete, 0), indexToDelete, indexToDelete);
        removeRow(indexToDelete);
        submitAll();
        endRemoveRows();
    }
}

void BookmarkModel::togglePin(const QString& url)
{
    if (contains(url))
        remove(url);
    else
        insert(url, url);
}

void BookmarkModel::update(int index, const QString& name, const QString& url)
{
    setData(createIndex(index, 1), name);
    setData(createIndex(index, 2), url);
}

bool BookmarkModel::contains(const QString& url)
{
    QSqlQuery sqlQuery(database());
    sqlQuery.prepare(QLatin1String("SELECT id FROM bookmarks WHERE url = ?"));
    sqlQuery.addBindValue(url);
    sqlQuery.exec();
    return sqlQuery.first();
}

QVariant BookmarkModel::data(const QModelIndex& index, int role) const
{
    QVariant value;
    if (role < Qt::UserRole)
        value = QSqlQueryModel::data(index, role);
    else {
        const int columnId = role - Qt::UserRole;
        const QModelIndex modelIndex = createIndex(index.row(), columnId);
        value = QSqlTableModel::data(modelIndex, Qt::DisplayRole);
    }
    return value;
}
<commit_msg>BookmarkModel insertion method must advertise it's actions.<commit_after>/****************************************************************************
 *   Copyright (C) 2011  Instituto Nokia de Tecnologia (INdT)               *
 *                                                                          *
 *   This file may be used under the terms of the GNU Lesser                *
 *   General Public License version 2.1 as published by the Free Software   *
 *   Foundation and appearing in the file LICENSE.LGPL included in the      *
 *   packaging of this file.  Please review the following information to    *
 *   ensure the GNU Lesser General Public License version 2.1 requirements  *
 *   will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.   *
 *                                                                          *
 *   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 Lesser General Public License for more details.                    *
 ****************************************************************************/

#include "BookmarkModel.h"

#include <QtSql/QSqlError>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlRecord>

BookmarkModel::BookmarkModel(QSqlDatabase database, QObject *parent)
    : QSqlTableModel(parent,  database)
{
    connect(this, SIGNAL(rowsInserted(const QModelIndex&, int, int)), SIGNAL(countChanged()));
    connect(this, SIGNAL(rowsRemoved(const QModelIndex&, int, int)), SIGNAL(countChanged()));
    setEditStrategy(OnManualSubmit);
}

void BookmarkModel::generateRoleNames()
{
    for (int i = 0; i < this->columnCount(); i++)
        m_roles[Qt::UserRole + i] = this->headerData(i, Qt::Horizontal).toByteArray();

    setRoleNames(m_roles);
}

QString BookmarkModel::tableCreateQuery() const
{
    const QLatin1String bookmarkQuery("CREATE TABLE IF NOT EXISTS bookmarks (id INTEGER PRIMARY KEY AUTOINCREMENT,"
                                  "name VARCHAR, url VARCHAR, dateAdded DATE);");

    return bookmarkQuery;

}

void BookmarkModel::setFilter(const QString& filter)
{
    QSqlTableModel::setFilter(filter);
}

bool BookmarkModel::select()
{
    return QSqlTableModel::select();
}

void BookmarkModel::insert(const QString& name, const QString& url)
{
    if (contains(url))
        return;
    QSqlRecord record = this->record();
    record.setValue(QLatin1String("name"), name);
    record.setValue(QLatin1String("url"), url);

    QModelIndex index = QModelIndex();
    beginInsertRows(index, rowCount(index), rowCount(index));
    insertRecord(-1, record);
    endInsertRows();
    submitAll();
}

void BookmarkModel::remove(const QString& url)
{
    if (!contains(url))
        return;

    QSqlQuery sqlQuery(database());
    sqlQuery.prepare(QLatin1String("SELECT id FROM bookmarks WHERE url = ?"));
    sqlQuery.addBindValue(url);
    sqlQuery.exec();
    sqlQuery.first();
    int indexToDelete = -1;
    for (int row = 0; row < rowCount(); ++row) {
        if (createIndex(row, 0).data(Qt::DisplayRole).toInt() == sqlQuery.value(0).toInt()) {
            indexToDelete = row;
            break;
        }
    }

    if (indexToDelete >= 0) {
        beginRemoveRows(createIndex(indexToDelete, 0), indexToDelete, indexToDelete);
        removeRow(indexToDelete);
        submitAll();
        endRemoveRows();
    }
}

void BookmarkModel::togglePin(const QString& url)
{
    if (contains(url))
        remove(url);
    else
        insert(url, url);
}

void BookmarkModel::update(int index, const QString& name, const QString& url)
{
    setData(createIndex(index, 1), name);
    setData(createIndex(index, 2), url);
}

bool BookmarkModel::contains(const QString& url)
{
    QSqlQuery sqlQuery(database());
    sqlQuery.prepare(QLatin1String("SELECT id FROM bookmarks WHERE url = ?"));
    sqlQuery.addBindValue(url);
    sqlQuery.exec();
    return sqlQuery.first();
}

QVariant BookmarkModel::data(const QModelIndex& index, int role) const
{
    QVariant value;
    if (role < Qt::UserRole)
        value = QSqlQueryModel::data(index, role);
    else {
        const int columnId = role - Qt::UserRole;
        const QModelIndex modelIndex = createIndex(index.row(), columnId);
        value = QSqlTableModel::data(modelIndex, Qt::DisplayRole);
    }
    return value;
}
<|endoftext|>


<commit_before>
#include "allocore/ui/al_PresetMapper.hpp"

using namespace al;

void PresetMapper::readEntries(std::string path)
{
	Dir presetDir(path);
	while (presetDir.read()) {
		FileInfo entry = presetDir.entry();
		if (entry.type() == FileInfo::DIR) {
			readEntries(entry.name());
		} else if (entry.type() == FileInfo::REG) {
			if (entry.name().size() > 4 && entry.name().substr(entry.name().size() - 4) == ".txt") {
				std::cout << "Found map: " << entry.name();
			}
		}
	}
}

PresetMapper::~PresetMapper() { }

PresetMapper &PresetMapper::registerPresetHandler(PresetHandler &handler) {
	mPresetHandler = &handler;
	if (mFindAutomatically) {
		findPresetMaps();
	}
	return *this;
}

bool PresetMapper::archive(std::string mapName, bool overwrite)
{
	bool ok = true;
	std::string fullPath = mPresetHandler->buildMapPath(mapName) + "_archive";
	if (overwrite) {
		if(File::isDirectory(fullPath)) {
			if (!Dir::removeRecursively(fullPath)) {
				std::cout << "Error removing directory: " << fullPath << " aborting preset map archiving." << std::endl;
				return false;
			}
		} else {
			if (File::remove(fullPath) != 0) {
				std::cout << "Error removing file: " << fullPath << " aborting preset map archiving." << std::endl;
				return false;
			}
		}
		if (!Dir::make(fullPath)) {
			std::cout << "Error creating preset map archive directory " << fullPath << std::endl;
			return false;
		}
	} else {
		int counter = 0;
		while (File::isDirectory(fullPath)) {
			std::string newName = mapName + "_" + std::to_string(counter++);
			fullPath = mPresetHandler->buildMapPath(newName) + "_archive";
			if (counter == 0) { // We've wrapped and run out of names...
				std::cout << "Out of names for preset map archive." << std::endl;
				return false;
			}
		}
		if (!Dir::make(fullPath)) {
			std::cout << "Error creating preset map archive directory " << fullPath << std::endl;
			return false;
		}
	}
	std::map<int, std::string> presetMap = mPresetHandler->readPresetMap(mapName);
	for(auto const &preset : presetMap) {
		std::string presetFilename = mPresetHandler->getCurrentPath() + preset.second + ".preset";
		if (!File::copy(presetFilename, fullPath)) {
			std::cout << "Error copying preset " << presetFilename << " when archiving preset map." << std::endl;
			ok = false;
		}
	}
	if (!File::copy(mPresetHandler->buildMapPath(mapName), fullPath + "default.presetMap")) {
		std::cout << "Error copying map: " << mapName << " when archiving preset map." << std::endl;
		ok = false;
	}

	return ok;
}

bool PresetMapper::load(std::string archiveName)
{
	if (! (archiveName.size() > 18 && archiveName.substr(archiveName.size() - 18) == ".presetMap_archive") ) {
		archiveName +=".presetMap_archive";
	}
	std::string mapPath = mPresetHandler->getRootPath() + archiveName;
	if (File::isDirectory(mapPath)) {
		mPresetHandler->setSubDirectory(archiveName);
		mPresetHandler->setCurrentPresetMap("default");
	} else {
		std::cout << "Error loading archive: " << archiveName << std::endl;
		return false;
	}
	return true;
}

std::vector<std::string> PresetMapper::listAvailableMaps(bool showArchives)
{
	std::vector<std::string> mapList;
	Dir mapperDir(mPresetHandler->getCurrentPath());

	// TODO it makes more sense to sort entries alphabetically
	while(mapperDir.read()) {
		const FileInfo &info = mapperDir.entry();
		if (info.type() == FileInfo::DIR && showArchives) {
			std::string name = info.name();
			if ( (name.size() > 18 && name.substr(name.size() - 18) == ".presetMap_archive")) {
				mapList.push_back(name);
			}
		} else if (info.type() == FileInfo::REG && !showArchives) {
			std::string name = info.name();
			if ( (name.size() > 4 && name.substr(name.size() - 4) == ".txt")
			     || (name.size() > 10 && name.substr(name.size() - 10) == ".presetMap")) {
				mapList.push_back(name);
			}
		}
	}
	return mapList;
}

bool PresetMapper::consumeMessage(osc::Message &m, std::string rootOSCPath)
{
	if(m.addressPattern() == rootOSCPath + "/map" && m.typeTags() == "s"){
		std::string val;
		m >> val;
		std::cout << "OSC: Recall preset map: " << val << std::endl;
		this->load(val);
		return true;
	}
	return false;
}

bool PresetMapper::restore(std::string mapName, bool overwrite, bool autoCreate)
{
	bool ok = true;
	if (mapName.size() > 18 && mapName.substr(mapName.size() - 18) == ".presetMap_archive") { // restore from archive
		std::cout << "Restoring archive " << mapName << std::endl;
		Dir mapDirectory(mPresetHandler->getCurrentPath() + mapName);
		std::string mapNewName = mapName.substr(0, mapName.size() - sizeof("_archive") + 1);
		while (mapDirectory.read()) {
			const FileInfo &entry = mapDirectory.entry();
			if (entry.type() == FileInfo::REG) {
				if (entry.name().substr(entry.name().size() - 7) == ".preset") {
					if (overwrite && File::exists(mPresetHandler->getCurrentPath() + "/" + entry.name())) {
						File::remove(mPresetHandler->getCurrentPath() + entry.name());
					}
					if (!File::copy(mPresetHandler->getCurrentPath() + mapName + "/" + entry.name(),
					                mPresetHandler->getCurrentPath() + entry.name())) {
						std::cout << "Error restoring preset " << entry.name() << " for " << mapName << std::endl;
						ok = false;
					}
				} else if (entry.name() == "default.presetMap") {

					if (overwrite && File::exists(mPresetHandler->getCurrentPath() + "/" + mapNewName)) {
						File::remove(mPresetHandler->getCurrentPath() + "/" + entry.name());
					}

					if (!File::copy(mPresetHandler->getCurrentPath() + "/" + mapName + "/default.presetMap",
					                mPresetHandler->getCurrentPath() + "/" + mapNewName)) {
						std::cout << "Error restoring preset map " << mapNewName << " for " << mapName << std::endl;
						ok = false;
					}
				} else {
					std::cout << "PresetMapper::restore() invalid file: " << entry.name() << std::endl;
				}
			}
		}
		mPresetHandler->setCurrentPresetMap(mapNewName, autoCreate);
	} else { // set preset map directly
		mPresetHandler->setCurrentPresetMap(mapName, autoCreate);
	}
	return ok;
}

void PresetMapper::findPresetMaps() {
	std::string presetsPath = mPresetHandler->getCurrentPath();

	Dir presetDir(presetsPath);
	while (presetDir.read()) {
		FileInfo entry = presetDir.entry();
		if (entry.name().size() > 4 && entry.name().substr(entry.name().size() - 4) == ".txt") {
			std::cout << "Found map: " << entry.name() << std::endl;
		}
	}
}
<commit_msg>Fixed issue setting preset map archive sub dir<commit_after>
#include "allocore/ui/al_PresetMapper.hpp"

using namespace al;

void PresetMapper::readEntries(std::string path)
{
	Dir presetDir(path);
	while (presetDir.read()) {
		FileInfo entry = presetDir.entry();
		if (entry.type() == FileInfo::DIR) {
			readEntries(entry.name());
		} else if (entry.type() == FileInfo::REG) {
			if (entry.name().size() > 4 && entry.name().substr(entry.name().size() - 4) == ".txt") {
				std::cout << "Found map: " << entry.name();
			}
		}
	}
}

PresetMapper::~PresetMapper() { }

PresetMapper &PresetMapper::registerPresetHandler(PresetHandler &handler) {
	mPresetHandler = &handler;
	if (mFindAutomatically) {
		findPresetMaps();
	}
	return *this;
}

bool PresetMapper::archive(std::string mapName, bool overwrite)
{
	bool ok = true;
	std::string fullPath = mPresetHandler->buildMapPath(mapName) + "_archive";
	if (overwrite) {
		if(File::isDirectory(fullPath)) {
			if (!Dir::removeRecursively(fullPath)) {
				std::cout << "Error removing directory: " << fullPath << " aborting preset map archiving." << std::endl;
				return false;
			}
		} else {
			if (File::remove(fullPath) != 0) {
				std::cout << "Error removing file: " << fullPath << " aborting preset map archiving." << std::endl;
				return false;
			}
		}
		if (!Dir::make(fullPath)) {
			std::cout << "Error creating preset map archive directory " << fullPath << std::endl;
			return false;
		}
	} else {
		int counter = 0;
		while (File::isDirectory(fullPath)) {
			std::string newName = mapName + "_" + std::to_string(counter++);
			fullPath = mPresetHandler->buildMapPath(newName) + "_archive";
			if (counter == 0) { // We've wrapped and run out of names...
				std::cout << "Out of names for preset map archive." << std::endl;
				return false;
			}
		}
		if (!Dir::make(fullPath)) {
			std::cout << "Error creating preset map archive directory " << fullPath << std::endl;
			return false;
		}
	}
	std::map<int, std::string> presetMap = mPresetHandler->readPresetMap(mapName);
	for(auto const &preset : presetMap) {
		std::string presetFilename = mPresetHandler->getCurrentPath() + preset.second + ".preset";
		if (!File::copy(presetFilename, fullPath)) {
			std::cout << "Error copying preset " << presetFilename << " when archiving preset map." << std::endl;
			ok = false;
		}
	}
	if (!File::copy(mPresetHandler->buildMapPath(mapName), fullPath + "default.presetMap")) {
		std::cout << "Error copying map: " << mapName << " when archiving preset map." << std::endl;
		ok = false;
	}

	return ok;
}

bool PresetMapper::load(std::string archiveName)
{
	if (! (archiveName.size() > 18 && archiveName.substr(archiveName.size() - 18) == ".presetMap_archive") ) {
		archiveName +=".presetMap_archive";
	}
	std::string mapPath = mPresetHandler->getRootPath() + archiveName;
	if (File::isDirectory(archiveName)) {
		mPresetHandler->setSubDirectory(archiveName);
		mPresetHandler->setCurrentPresetMap("default");
	} else {
		std::cout << "Error loading archive: " << archiveName << std::endl;
		return false;
	}
	return true;
}

std::vector<std::string> PresetMapper::listAvailableMaps(bool showArchives)
{
	std::vector<std::string> mapList;
	Dir mapperDir(mPresetHandler->getCurrentPath());

	// TODO it makes more sense to sort entries alphabetically
	while(mapperDir.read()) {
		const FileInfo &info = mapperDir.entry();
		if (info.type() == FileInfo::DIR && showArchives) {
			std::string name = info.name();
			if ( (name.size() > 18 && name.substr(name.size() - 18) == ".presetMap_archive")) {
				mapList.push_back(name);
			}
		} else if (info.type() == FileInfo::REG && !showArchives) {
			std::string name = info.name();
			if ( (name.size() > 4 && name.substr(name.size() - 4) == ".txt")
			     || (name.size() > 10 && name.substr(name.size() - 10) == ".presetMap")) {
				mapList.push_back(name);
			}
		}
	}
	return mapList;
}

bool PresetMapper::consumeMessage(osc::Message &m, std::string rootOSCPath)
{
	if(m.addressPattern() == rootOSCPath + "/map" && m.typeTags() == "s"){
		std::string val;
		m >> val;
		std::cout << "OSC: Recall preset map: " << val << std::endl;
		this->load(val);
		return true;
	}
	return false;
}

bool PresetMapper::restore(std::string mapName, bool overwrite, bool autoCreate)
{
	bool ok = true;
	if (mapName.size() > 18 && mapName.substr(mapName.size() - 18) == ".presetMap_archive") { // restore from archive
		std::cout << "Restoring archive " << mapName << std::endl;
		Dir mapDirectory(mPresetHandler->getCurrentPath() + mapName);
		std::string mapNewName = mapName.substr(0, mapName.size() - sizeof("_archive") + 1);
		while (mapDirectory.read()) {
			const FileInfo &entry = mapDirectory.entry();
			if (entry.type() == FileInfo::REG) {
				if (entry.name().substr(entry.name().size() - 7) == ".preset") {
					if (overwrite && File::exists(mPresetHandler->getCurrentPath() + "/" + entry.name())) {
						File::remove(mPresetHandler->getCurrentPath() + entry.name());
					}
					if (!File::copy(mPresetHandler->getCurrentPath() + mapName + "/" + entry.name(),
					                mPresetHandler->getCurrentPath() + entry.name())) {
						std::cout << "Error restoring preset " << entry.name() << " for " << mapName << std::endl;
						ok = false;
					}
				} else if (entry.name() == "default.presetMap") {

					if (overwrite && File::exists(mPresetHandler->getCurrentPath() + "/" + mapNewName)) {
						File::remove(mPresetHandler->getCurrentPath() + "/" + entry.name());
					}

					if (!File::copy(mPresetHandler->getCurrentPath() + "/" + mapName + "/default.presetMap",
					                mPresetHandler->getCurrentPath() + "/" + mapNewName)) {
						std::cout << "Error restoring preset map " << mapNewName << " for " << mapName << std::endl;
						ok = false;
					}
				} else {
					std::cout << "PresetMapper::restore() invalid file: " << entry.name() << std::endl;
				}
			}
		}
		mPresetHandler->setCurrentPresetMap(mapNewName, autoCreate);
	} else { // set preset map directly
		mPresetHandler->setCurrentPresetMap(mapName, autoCreate);
	}
	return ok;
}

void PresetMapper::findPresetMaps() {
	std::string presetsPath = mPresetHandler->getCurrentPath();

	Dir presetDir(presetsPath);
	while (presetDir.read()) {
		FileInfo entry = presetDir.entry();
		if (entry.name().size() > 4 && entry.name().substr(entry.name().size() - 4) == ".txt") {
			std::cout << "Found map: " << entry.name() << std::endl;
		}
	}
}
<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "OpenSimProtocolModule.h"
#include "RexProtocolMsgIDs.h"

#include "Poco/Net/NetException.h"

namespace OpenSimProtocol
{
	OpenSimProtocolModule::OpenSimProtocolModule() :
    ModuleInterfaceImpl(Foundation::Module::MT_OpenSimProtocol),
    connected_(false)
    {
    }

    // virtual
    OpenSimProtocolModule::~OpenSimProtocolModule()
    {
    }

    // virtual
    void OpenSimProtocolModule::Load()
    {
        LogInfo("System " + Name() + " loaded.");
    }

    // virtual
    void OpenSimProtocolModule::Unload()
    {
        LogInfo("System " + Name() + " unloaded.");
    }

    // virtual
    void OpenSimProtocolModule::Initialize()
    {
        ///\todo Read the template filename from a config file.
		const char *filename = "./data/message_template.msg";

		networkManager_ = boost::shared_ptr<NetMessageManager>(new NetMessageManager(filename));
		assert(networkManager_);

		networkManager_->RegisterNetworkListener(this);

        // Register event categories.
        eventManager_ = framework_->GetEventManager();
        networkStateEventCategory_ = eventManager_->RegisterEventCategory("NetworkState");
        networkEventInCategory_ = eventManager_->RegisterEventCategory("OpenSimNetworkIn");
        networkEventOutCategory_ = eventManager_->RegisterEventCategory("OpenSimNetworkOut");

        LogInfo("System " + Name() + " initialized.");
    }

    // virtual
    void OpenSimProtocolModule::Uninitialize()
    {
		if(connected_)
		    DisconnectFromRexServer();

        networkManager_->UnregisterNetworkListener(this);

		LogInfo("System " + Name() + " uninitialized.");
    }

    // virtual
    void OpenSimProtocolModule::Update(Core::f64 frametime)
    {
        {
            PROFILE(OpenSimProtocolModule_Update);
            if (loginWorker_.IsReady() && loginWorker_.GetState() == Connection::STATE_XMLRPC_REPLY_RECEIVED)
            {
                // XML-RPC reply received; get the login parameters and signal that we're ready to
                // establish an UDP connection.
                clientParameters_ = loginWorker_.GetClientParameters();
                loginWorker_.SetConnectionState(Connection::STATE_INIT_UDP);
            }

            if (connected_)
            {
                try
                {
                    networkManager_->ProcessMessages();
                }
                catch(Poco::Net::NetException &e)
                {
                    LogError(e.what());
                    LogInfo("Network error occured. Closing server connection.");
                    DisconnectFromRexServer();
                }
            }
        }
        RESETPROFILER;
    }

    //virtual
    void OpenSimProtocolModule::OnNetworkMessageReceived(NetMsgID msgID, NetInMessage *msg)
    {
        // Send a Network event. The message ID functions as the event ID.
        NetworkEventInboundData data(msgID, msg);
        eventManager_->SendEvent(networkEventInCategory_, msgID, &data);
    }

    //virtual
    void OpenSimProtocolModule::OnNetworkMessageSent(const NetOutMessage *msg)
    {
        // Send a NetworkOutStats event.
        NetworkEventOutboundData data(msg->GetMessageID(), msg);
        eventManager_->SendEvent(networkEventOutCategory_, msg->GetMessageID(), &data);
    }

    void OpenSimProtocolModule::LoginToServer(
        const std::string& first_name,
		const std::string& last_name,
		const std::string& password,
		const std::string& address,
		int port,
		ConnectionThreadState *thread_state)
	{
		std::string callMethod = "login_to_simulator";
		loginWorker_.SetupXMLRPCLogin(first_name, last_name, password, address, boost::lexical_cast<std::string>(port), callMethod, thread_state);

		// Start the thread.
		boost::thread(boost::ref(loginWorker_));
	}

	void OpenSimProtocolModule::LoginToCBServer(
		const std::string& first_name,
		const std::string& last_name,
		const std::string& address,
		int port,
		ConnectionThreadState *thread_state)
	{
		std::string callMethod = "login_to_simulator";
		loginWorker_.SetupXMLRPCLogin(first_name, last_name, "auth_done", address, boost::lexical_cast<std::string>(port), callMethod, thread_state, "openid", "openid", "openid", true);

		// Start the thread.
		boost::thread(boost::ref(loginWorker_));
	}

    bool OpenSimProtocolModule::LoginUsingRexAuthentication(
        const std::string& first_name,
		const std::string& last_name,
		const std::string& password,
		const std::string& address,
		int port,
		const std::string& auth_server_address,
		const std::string& auth_login,
		ConnectionThreadState *thread_state)
	{
		bool authentication = true;
		std::string callMethod = "ClientAuthentication";
		int pos = auth_server_address.find(":");
		std::string auth_port = "";
		std::string auth_address = "";

		if (pos != std::string::npos)
		{
			auth_port = auth_server_address.substr(pos+1);
			auth_address = auth_server_address.substr(0,pos);
		}
		else
		{
			OpenSimProtocolModule::LogInfo("No port defined for the authentication server, using default port (10001).");
			auth_port = "10001";
			auth_address = auth_server_address;
		}

        loginWorker_.SetupXMLRPCLogin(first_name, last_name, password, address, boost::lexical_cast<std::string>(port), callMethod,
            thread_state, auth_login, auth_address, auth_port, authentication);

        // Start the thread.
		boost::thread(boost::ref(loginWorker_));

		return true;
	}

    bool OpenSimProtocolModule::CreateUDPConnection(const char *address, int port)
	{
        loginWorker_.SetConnectionState(Connection::STATE_INIT_UDP);

	    bool udp_success = networkManager_->ConnectTo(address, port);
        if (!udp_success)
            return false;

        loginWorker_.SetConnectionState(Connection::STATE_CONNECTED);

        // Send event indicating a succesfull connection.
        eventManager_->SendEvent(networkStateEventCategory_, Events::EVENT_SERVER_CONNECTED, NULL);
        connected_ = true;

        return true;
	}

	void OpenSimProtocolModule::DisconnectFromRexServer()
	{
	    if(!connected_)
	        return;

	    networkManager_->Disconnect();
	    loginWorker_.SetConnectionState(Connection::STATE_DISCONNECTED);
	    connected_ = false;

	    eventManager_->SendEvent(networkStateEventCategory_, Events::EVENT_SERVER_DISCONNECTED, NULL);
	}

	void OpenSimProtocolModule::DumpNetworkMessage(NetMsgID id, NetInMessage *msg)
	{
	    networkManager_->DumpNetworkMessage(id, msg);
	}

	NetOutMessage *OpenSimProtocolModule::StartMessageBuilding(NetMsgID msgId)
	{
	    return networkManager_->StartNewMessage(msgId);
	}

	void OpenSimProtocolModule::FinishMessageBuilding(NetOutMessage *msg)
	{
	    networkManager_->FinishMessage(msg);
	}
}

extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler);
void SetProfiler(Foundation::Profiler *profiler)
{
    Foundation::ProfilerSection::SetProfiler(profiler);
}

using namespace OpenSimProtocol;

POCO_BEGIN_MANIFEST(Foundation::ModuleInterface)
   POCO_EXPORT_CLASS(OpenSimProtocolModule)
POCO_END_MANIFEST
<commit_msg>[Fix] searches port number from end to begin not begin to end. <commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"
#include "OpenSimProtocolModule.h"
#include "RexProtocolMsgIDs.h"

#include "Poco/Net/NetException.h"

namespace OpenSimProtocol
{
	OpenSimProtocolModule::OpenSimProtocolModule() :
    ModuleInterfaceImpl(Foundation::Module::MT_OpenSimProtocol),
    connected_(false)
    {
    }

    // virtual
    OpenSimProtocolModule::~OpenSimProtocolModule()
    {
    }

    // virtual
    void OpenSimProtocolModule::Load()
    {
        LogInfo("System " + Name() + " loaded.");
    }

    // virtual
    void OpenSimProtocolModule::Unload()
    {
        LogInfo("System " + Name() + " unloaded.");
    }

    // virtual
    void OpenSimProtocolModule::Initialize()
    {
        ///\todo Read the template filename from a config file.
		const char *filename = "./data/message_template.msg";

		networkManager_ = boost::shared_ptr<NetMessageManager>(new NetMessageManager(filename));
		assert(networkManager_);

		networkManager_->RegisterNetworkListener(this);

        // Register event categories.
        eventManager_ = framework_->GetEventManager();
        networkStateEventCategory_ = eventManager_->RegisterEventCategory("NetworkState");
        networkEventInCategory_ = eventManager_->RegisterEventCategory("OpenSimNetworkIn");
        networkEventOutCategory_ = eventManager_->RegisterEventCategory("OpenSimNetworkOut");

        LogInfo("System " + Name() + " initialized.");
    }

    // virtual
    void OpenSimProtocolModule::Uninitialize()
    {
		if(connected_)
		    DisconnectFromRexServer();

        networkManager_->UnregisterNetworkListener(this);

		LogInfo("System " + Name() + " uninitialized.");
    }

    // virtual
    void OpenSimProtocolModule::Update(Core::f64 frametime)
    {
        {
            PROFILE(OpenSimProtocolModule_Update);
            if (loginWorker_.IsReady() && loginWorker_.GetState() == Connection::STATE_XMLRPC_REPLY_RECEIVED)
            {
                // XML-RPC reply received; get the login parameters and signal that we're ready to
                // establish an UDP connection.
                clientParameters_ = loginWorker_.GetClientParameters();
                loginWorker_.SetConnectionState(Connection::STATE_INIT_UDP);
            }

            if (connected_)
            {
                try
                {
                    networkManager_->ProcessMessages();
                }
                catch(Poco::Net::NetException &e)
                {
                    LogError(e.what());
                    LogInfo("Network error occured. Closing server connection.");
                    DisconnectFromRexServer();
                }
            }
        }
        RESETPROFILER;
    }

    //virtual
    void OpenSimProtocolModule::OnNetworkMessageReceived(NetMsgID msgID, NetInMessage *msg)
    {
        // Send a Network event. The message ID functions as the event ID.
        NetworkEventInboundData data(msgID, msg);
        eventManager_->SendEvent(networkEventInCategory_, msgID, &data);
    }

    //virtual
    void OpenSimProtocolModule::OnNetworkMessageSent(const NetOutMessage *msg)
    {
        // Send a NetworkOutStats event.
        NetworkEventOutboundData data(msg->GetMessageID(), msg);
        eventManager_->SendEvent(networkEventOutCategory_, msg->GetMessageID(), &data);
    }

    void OpenSimProtocolModule::LoginToServer(
        const std::string& first_name,
		const std::string& last_name,
		const std::string& password,
		const std::string& address,
		int port,
		ConnectionThreadState *thread_state)
	{
		std::string callMethod = "login_to_simulator";
		loginWorker_.SetupXMLRPCLogin(first_name, last_name, password, address, boost::lexical_cast<std::string>(port), callMethod, thread_state);

		// Start the thread.
		boost::thread(boost::ref(loginWorker_));
	}

	void OpenSimProtocolModule::LoginToCBServer(
		const std::string& first_name,
		const std::string& last_name,
		const std::string& address,
		int port,
		ConnectionThreadState *thread_state)
	{
		std::string callMethod = "login_to_simulator";
		loginWorker_.SetupXMLRPCLogin(first_name, last_name, "auth_done", address, boost::lexical_cast<std::string>(port), callMethod, thread_state, "openid", "openid", "openid", true);

		// Start the thread.
		boost::thread(boost::ref(loginWorker_));
	}

    bool OpenSimProtocolModule::LoginUsingRexAuthentication(
        const std::string& first_name,
		const std::string& last_name,
		const std::string& password,
		const std::string& address,
		int port,
		const std::string& auth_server_address,
		const std::string& auth_login,
		ConnectionThreadState *thread_state)
	{
		bool authentication = true;
		std::string callMethod = "ClientAuthentication";
		int pos = auth_server_address.rfind(":");
		std::string auth_port = "";
		std::string auth_address = "";

		if (pos != std::string::npos)
		{
			auth_port = auth_server_address.substr(pos+1);
			auth_address = auth_server_address.substr(0,pos);
		}
		else
		{
			OpenSimProtocolModule::LogInfo("No port defined for the authentication server, using default port (10001).");
			auth_port = "10001";
			auth_address = auth_server_address;
		}

        loginWorker_.SetupXMLRPCLogin(first_name, last_name, password, address, boost::lexical_cast<std::string>(port), callMethod,
            thread_state, auth_login, auth_address, auth_port, authentication);

        // Start the thread.
		boost::thread(boost::ref(loginWorker_));

		return true;
	}

    bool OpenSimProtocolModule::CreateUDPConnection(const char *address, int port)
	{
        loginWorker_.SetConnectionState(Connection::STATE_INIT_UDP);

	    bool udp_success = networkManager_->ConnectTo(address, port);
        if (!udp_success)
            return false;

        loginWorker_.SetConnectionState(Connection::STATE_CONNECTED);

        // Send event indicating a succesfull connection.
        eventManager_->SendEvent(networkStateEventCategory_, Events::EVENT_SERVER_CONNECTED, NULL);
        connected_ = true;

        return true;
	}

	void OpenSimProtocolModule::DisconnectFromRexServer()
	{
	    if(!connected_)
	        return;

	    networkManager_->Disconnect();
	    loginWorker_.SetConnectionState(Connection::STATE_DISCONNECTED);
	    connected_ = false;

	    eventManager_->SendEvent(networkStateEventCategory_, Events::EVENT_SERVER_DISCONNECTED, NULL);
	}

	void OpenSimProtocolModule::DumpNetworkMessage(NetMsgID id, NetInMessage *msg)
	{
	    networkManager_->DumpNetworkMessage(id, msg);
	}

	NetOutMessage *OpenSimProtocolModule::StartMessageBuilding(NetMsgID msgId)
	{
	    return networkManager_->StartNewMessage(msgId);
	}

	void OpenSimProtocolModule::FinishMessageBuilding(NetOutMessage *msg)
	{
	    networkManager_->FinishMessage(msg);
	}
}

extern "C" void POCO_LIBRARY_API SetProfiler(Foundation::Profiler *profiler);
void SetProfiler(Foundation::Profiler *profiler)
{
    Foundation::ProfilerSection::SetProfiler(profiler);
}

using namespace OpenSimProtocol;

POCO_BEGIN_MANIFEST(Foundation::ModuleInterface)
   POCO_EXPORT_CLASS(OpenSimProtocolModule)
POCO_END_MANIFEST
<|endoftext|>


<commit_before>/*************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
*                                                                        *
* Author: The ALICE Off-line Project.                                    *
* Contributors are mentioned in the code where appropriate.              *
*                                                                        *
* Permission to use, copy, modify and distribute this software and its   *
* documentation strictly for non-commercial purposes is hereby granted   *
* without fee, provided that the above copyright notice appears in all   *
* copies and that both the copyright notice and this permission notice   *
* appear in the supporting documentation. The authors make no claims     *
* about the suitability of this software for any purpose. It is          *
* provided "as is" without express or implied warranty.                  *
**************************************************************************/

// -----------------------------------------------
// particle level cuts for azimuthal isotropic
// expansion in highly central collisions analysis
// author: Cristian Andrei
//         acristian@niham.nipne.ro
// ------------------------------------------------

#include <TF1.h>
#include <TFile.h>

#include "AliAnalysisCentralCutESD.h"
#include "AliESDtrack.h"

class TObject;
class TParticle;

//____________________________________________________________________
ClassImp(AliAnalysisCentralCutESD)

//____________________________________________________________________
AliAnalysisCentralCutESD::AliAnalysisCentralCutESD(const Char_t* name, const Char_t* title)
    :AliAnalysisCuts(name,title)
    ,fReqPID(kFALSE)
    ,fReqCharge(kFALSE)
    ,fPartType(kPiPlus)
    ,fPIDtype("Custom")
    ,fPriorsFunc(kFALSE)
    ,fPartPriors()
    ,fElectronFunction(0)
    ,fMuonFunction(0)
    ,fPionFunction(0)
    ,fKaonFunction(0)
    ,fProtonFunction(0)
{
// Constructor
// Initialize the priors
    fPartPriors[0] = 0.01;
    fPartPriors[1] = 0.01;
    fPartPriors[2] = 0.85;
    fPartPriors[3] = 0.1;
    fPartPriors[4] = 0.05;

    if(fPriorsFunc){
	TFile *f = TFile::Open("$ALICE_ROOT/PWG2/data/PriorProbabilities.root ");
	if(!f){
	    printf("Can't open PWG2 prior probabilities file!\n Exiting ...\n");
	    return;
	}
	fElectronFunction = (TF1 *)f->Get("fitElectrons");
	fMuonFunction = (TF1 *)f->Get("fitMuons");
	fPionFunction = (TF1 *)f->Get("fitPions");
	fKaonFunction = (TF1 *)f->Get("fitKaons");
	fProtonFunction = (TF1 *)f->Get("fitProtons");
    }

}

AliAnalysisCentralCutESD::~AliAnalysisCentralCutESD() {
// Destructor
// Delete the created priors

	if(fElectronFunction) delete fElectronFunction;
	if(fMuonFunction) delete fMuonFunction;
	if(fPionFunction) delete fPionFunction;
	if(fKaonFunction) delete fKaonFunction;
	if(fProtonFunction) delete fProtonFunction;

}

Bool_t AliAnalysisCentralCutESD::IsSelected(TObject *obj){
// Checks if a particle passes the cuts

    AliESDtrack *track = dynamic_cast<AliESDtrack *>(obj);

    if(!track){
		printf("AliAnalysisCentralCutESD:IsSelected ->Can't get track!\n");
		return kFALSE;
    }

    if(fReqCharge){
		if(!IsCharged(track)) return kFALSE;
    }

    if(fReqPID){
		if(!IsA(track, fPartType)) return kFALSE;
    }

    return kTRUE;
}

Double_t AliAnalysisCentralCutESD::GetPriors(Int_t i, Double_t p) {
//Return the a priori probs

Double_t priors=0;
    if(fPriorsFunc) {
	if(i == 0) priors = fElectronFunction->Eval(p);
	if(i == 1) priors = fMuonFunction->Eval(p);
	if(i == 2) priors = fPionFunction->Eval(p);
	if(i == 3) priors = fKaonFunction->Eval(p);
	if(i == 4) priors = fProtonFunction->Eval(p);
    }
    else {
	priors = fPartPriors[i];
    }

  return priors;
}

Bool_t AliAnalysisCentralCutESD::IsA(AliESDtrack *track, PDG_t reqPartType){
// Determines the type of the particle
    Int_t charge;

    if(reqPartType < 0){
      charge = -1;
    }
    else{
      charge = 1;
    }

    Double_t probability[5] = {0.0,0.0,0.0,0.0,0.0};
    Double_t w[5] = {0.0,0.0,0.0,0.0,0.0};

    Long64_t partType = 0;

    Double_t p = track->P();

    track->GetESDpid(probability);

    Double_t s = 0.0;

    for(Int_t i = 0; i < AliPID::kSPECIES; i++){
		s += probability[i]*GetPriors(i,p);
    }

    if(!s < 0.000001) {
		for(Int_t i = 0; i < AliPID::kSPECIES; i++){
	    	w[i] = probability[i]*GetPriors(i,p)/s;
		}
    }

    if(fPIDtype.Contains("Bayesian")) {
		partType = TMath::LocMax(AliPID::kSPECIES,w);
		if(partType<0.) return kFALSE;
    }

    else if(fPIDtype.Contains("Custom")){
		for(Int_t i=0;i<AliPID::kSPECIES;i++)   {
			if(w[i]>0.9){
				partType = i;
			}
		}
    }

    else{
		printf("Unknown PID method!\n");
		return kFALSE;
    }
    if(partType<0.) return kFALSE;
    if((AliPID::ParticleCode(partType)) != reqPartType){
		return kFALSE;
    }

	if(track->Charge() != charge) return kFALSE;

    return kTRUE;

}

Bool_t AliAnalysisCentralCutESD::IsCharged(AliESDtrack* const track) const{

    if(track->Charge() == 0) return kFALSE;

    return kTRUE;

}
<commit_msg>Fixing Coverity 11174 (B.Hippolyte)<commit_after>/*************************************************************************
* Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
*                                                                        *
* Author: The ALICE Off-line Project.                                    *
* Contributors are mentioned in the code where appropriate.              *
*                                                                        *
* Permission to use, copy, modify and distribute this software and its   *
* documentation strictly for non-commercial purposes is hereby granted   *
* without fee, provided that the above copyright notice appears in all   *
* copies and that both the copyright notice and this permission notice   *
* appear in the supporting documentation. The authors make no claims     *
* about the suitability of this software for any purpose. It is          *
* provided "as is" without express or implied warranty.                  *
**************************************************************************/

// -----------------------------------------------
// particle level cuts for azimuthal isotropic
// expansion in highly central collisions analysis
// author: Cristian Andrei
//         acristian@niham.nipne.ro
// ------------------------------------------------

#include <TF1.h>
#include <TFile.h>

#include "AliAnalysisCentralCutESD.h"
#include "AliESDtrack.h"

class TObject;
class TParticle;

//____________________________________________________________________
ClassImp(AliAnalysisCentralCutESD)

//____________________________________________________________________
AliAnalysisCentralCutESD::AliAnalysisCentralCutESD(const Char_t* name, const Char_t* title)
    :AliAnalysisCuts(name,title)
    ,fReqPID(kFALSE)
    ,fReqCharge(kFALSE)
    ,fPartType(kPiPlus)
    ,fPIDtype("Custom")
    ,fPriorsFunc(kFALSE)
    ,fPartPriors()
    ,fElectronFunction(0)
    ,fMuonFunction(0)
    ,fPionFunction(0)
    ,fKaonFunction(0)
    ,fProtonFunction(0)
{
// Constructor
// Initialize the priors
    fPartPriors[0] = 0.01;
    fPartPriors[1] = 0.01;
    fPartPriors[2] = 0.85;
    fPartPriors[3] = 0.1;
    fPartPriors[4] = 0.05;

    if(fPriorsFunc){
	TFile *f = TFile::Open("$ALICE_ROOT/PWG2/data/PriorProbabilities.root ");
	if(!f){
	    printf("Can't open PWG2 prior probabilities file!\n Exiting ...\n");
	    return;
	}
	fElectronFunction = (TF1 *)f->Get("fitElectrons");
	fMuonFunction = (TF1 *)f->Get("fitMuons");
	fPionFunction = (TF1 *)f->Get("fitPions");
	fKaonFunction = (TF1 *)f->Get("fitKaons");
	fProtonFunction = (TF1 *)f->Get("fitProtons");
    }

}

AliAnalysisCentralCutESD::~AliAnalysisCentralCutESD() {
// Destructor
// Delete the created priors

	if(fElectronFunction) delete fElectronFunction;
	if(fMuonFunction) delete fMuonFunction;
	if(fPionFunction) delete fPionFunction;
	if(fKaonFunction) delete fKaonFunction;
	if(fProtonFunction) delete fProtonFunction;

}

Bool_t AliAnalysisCentralCutESD::IsSelected(TObject *obj){
// Checks if a particle passes the cuts

    AliESDtrack *track = dynamic_cast<AliESDtrack *>(obj);

    if(!track){
		printf("AliAnalysisCentralCutESD:IsSelected ->Can't get track!\n");
		return kFALSE;
    }

    if(fReqCharge){
		if(!IsCharged(track)) return kFALSE;
    }

    if(fReqPID){
		if(!IsA(track, fPartType)) return kFALSE;
    }

    return kTRUE;
}

Double_t AliAnalysisCentralCutESD::GetPriors(Int_t i, Double_t p) {
//Return the a priori probs

Double_t priors=0;
    if(fPriorsFunc) {
	if(i == 0) priors = fElectronFunction->Eval(p);
	if(i == 1) priors = fMuonFunction->Eval(p);
	if(i == 2) priors = fPionFunction->Eval(p);
	if(i == 3) priors = fKaonFunction->Eval(p);
	if(i == 4) priors = fProtonFunction->Eval(p);
    }
    else {
	priors = fPartPriors[i];
    }

  return priors;
}

Bool_t AliAnalysisCentralCutESD::IsA(AliESDtrack *track, PDG_t reqPartType){
// Determines the type of the particle
    Int_t charge;

    if(reqPartType < 0){
      charge = -1;
    }
    else{
      charge = 1;
    }

    Double_t probability[5] = {0.0,0.0,0.0,0.0,0.0};
    Double_t w[5] = {0.0,0.0,0.0,0.0,0.0};

    Long64_t partType = 0;

    Double_t p = track->P();

    track->GetESDpid(probability);

    Double_t s = 0.0;

    for(Int_t i = 0; i < AliPID::kSPECIES; i++){
		s += probability[i]*GetPriors(i,p);
    }

    if(!s < 0.000001) {
		for(Int_t i = 0; i < AliPID::kSPECIES; i++){
	    	w[i] = probability[i]*GetPriors(i,p)/s;
		}
    }

    if(fPIDtype.Contains("Bayesian")) {
		partType = TMath::LocMax(AliPID::kSPECIES,w);
		if(partType<0.) return kFALSE;
    }

    else if(fPIDtype.Contains("Custom")){
		for(Int_t i=0;i<AliPID::kSPECIES;i++)   {
			if(w[i]>0.9){
				partType = i;
			}
		}
    }

    else{
		printf("Unknown PID method!\n");
		return kFALSE;
    }

    if(partType<0.) return kFALSE;

    else if((AliPID::ParticleCode(partType)) != reqPartType) return kFALSE;

    if(track->Charge() != charge) return kFALSE;

    return kTRUE;

}

Bool_t AliAnalysisCentralCutESD::IsCharged(AliESDtrack* const track) const{

    if(track->Charge() == 0) return kFALSE;

    return kTRUE;

}
<|endoftext|>


<commit_before>#include "application.h"
#include "object.h"

#include <atomic>

static std::atomic_int  s_return_value (0);
static std::atomic_bool s_run (true);

std::condition_variable     Application::m_step_exec;
lockable<std::queue<vfunc>> Application::m_signal_queue;

Application::Application (void) { }
Application::~Application(void) { }

int Application::exec(void)
{
  while(s_run)
  {
    std::unique_lock<std::mutex> lk(m_signal_queue); // multithread protection
    m_step_exec.wait(lk, [] { return !m_signal_queue.empty(); } ); // wait for notify_one() call and non-empty queue

    while(m_signal_queue.size())
    {
      m_signal_queue.back()();
      m_signal_queue.pop();
    }
  }
  return s_return_value;
}

void Application::quit(int return_value)
{
  s_return_value = return_value;
  s_run = false;
}
<commit_msg>corrected queue position to execute<commit_after>#include "application.h"
#include "object.h"

#include <atomic>

static std::atomic_int  s_return_value (0);
static std::atomic_bool s_run (true);

std::condition_variable     Application::m_step_exec;
lockable<std::queue<vfunc>> Application::m_signal_queue;

Application::Application (void) { }
Application::~Application(void) { }

int Application::exec(void)
{
  while(s_run)
  {
    std::unique_lock<std::mutex> lk(m_signal_queue); // multithread protection
    m_step_exec.wait(lk, [] { return !m_signal_queue.empty(); } ); // wait for notify_one() call and non-empty queue

    while(m_signal_queue.size())
    {
      m_signal_queue.front()();
      m_signal_queue.pop();
    }
  }
  return s_return_value;
}

void Application::quit(int return_value)
{
  s_return_value = return_value;
  s_run = false;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * 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 "SkQuadClipper.h"
#include "SkGeometry.h"

static bool chopMonoQuadAtY(SkPoint pts[3], SkScalar y, SkScalar* t) {
    /* Solve F(t) = y where F(t) := [0](1-t)^2 + 2[1]t(1-t) + [2]t^2
     *  We solve for t, using quadratic equation, hence we have to rearrange
     * our cooefficents to look like At^2 + Bt + C
     */
    SkScalar A = pts[0].fY - pts[1].fY - pts[1].fY + pts[2].fY;
    SkScalar B = 2*(pts[1].fY - pts[0].fY);
    SkScalar C = pts[0].fY - y;

    SkScalar roots[2];  // we only expect one, but make room for 2 for safety
    int count = SkFindUnitQuadRoots(A, B, C, roots);
    if (count) {
        *t = roots[0];
        return true;
    }
    return false;
}

SkQuadClipper::SkQuadClipper() {}

void SkQuadClipper::setClip(const SkIRect& clip) {
    // conver to scalars, since that's where we'll see the points
    fClip.set(clip);
}

/*  If we somehow returned the fact that we had to flip the pts in Y, we could
    communicate that to setQuadratic, and then avoid having to flip it back
    here (only to have setQuadratic do the flip again)
 */
bool SkQuadClipper::clipQuad(const SkPoint srcPts[3], SkPoint dst[3]) {
    bool reverse;

    // we need the data to be monotonically descending in Y
    if (srcPts[0].fY > srcPts[2].fY) {
        dst[0] = srcPts[2];
        dst[1] = srcPts[1];
        dst[2] = srcPts[0];
        reverse = true;
    } else {
        memcpy(dst, srcPts, 3 * sizeof(SkPoint));
        reverse = false;
    }

    // are we completely above or below
    const SkScalar ctop = fClip.fTop;
    const SkScalar cbot = fClip.fBottom;
    if (dst[2].fY <= ctop || dst[0].fY >= cbot) {
        return false;
    }

    SkScalar t;
    SkPoint tmp[5]; // for SkChopQuadAt

    // are we partially above
    if (dst[0].fY < ctop && chopMonoQuadAtY(dst, ctop, &t)) {
        SkChopQuadAt(dst, tmp, t);
        dst[0] = tmp[2];
        dst[1] = tmp[3];
    }

    // are we partially below
    if (dst[2].fY > cbot && chopMonoQuadAtY(dst, cbot, &t)) {
        SkChopQuadAt(dst, tmp, t);
        dst[1] = tmp[1];
        dst[2] = tmp[2];
    }

    if (reverse) {
        SkTSwap<SkPoint>(dst[0], dst[2]);
    }
    return true;
}

<commit_msg>pull clipper fix from skia/trunk rev.404<commit_after>/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * 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 "SkQuadClipper.h"
#include "SkGeometry.h"

static bool chopMonoQuadAtY(SkPoint pts[3], SkScalar y, SkScalar* t) {
    /* Solve F(t) = y where F(t) := [0](1-t)^2 + 2[1]t(1-t) + [2]t^2
     *  We solve for t, using quadratic equation, hence we have to rearrange
     * our cooefficents to look like At^2 + Bt + C
     */
    SkScalar A = pts[0].fY - pts[1].fY - pts[1].fY + pts[2].fY;
    SkScalar B = 2*(pts[1].fY - pts[0].fY);
    SkScalar C = pts[0].fY - y;

    SkScalar roots[2];  // we only expect one, but make room for 2 for safety
    int count = SkFindUnitQuadRoots(A, B, C, roots);
    if (count) {
        *t = roots[0];
        return true;
    }
    return false;
}

SkQuadClipper::SkQuadClipper() {}

void SkQuadClipper::setClip(const SkIRect& clip) {
    // conver to scalars, since that's where we'll see the points
    fClip.set(clip);
}

/*  If we somehow returned the fact that we had to flip the pts in Y, we could
    communicate that to setQuadratic, and then avoid having to flip it back
    here (only to have setQuadratic do the flip again)
 */
bool SkQuadClipper::clipQuad(const SkPoint srcPts[3], SkPoint dst[3]) {
    bool reverse;

    // we need the data to be monotonically increasing in Y
    if (srcPts[0].fY > srcPts[2].fY) {
        dst[0] = srcPts[2];
        dst[1] = srcPts[1];
        dst[2] = srcPts[0];
        reverse = true;
    } else {
        memcpy(dst, srcPts, 3 * sizeof(SkPoint));
        reverse = false;
    }

    // are we completely above or below
    const SkScalar ctop = fClip.fTop;
    const SkScalar cbot = fClip.fBottom;
    if (dst[2].fY <= ctop || dst[0].fY >= cbot) {
        return false;
    }

    SkScalar t;
    SkPoint tmp[5]; // for SkChopQuadAt

    // are we partially above
    if (dst[0].fY < ctop) {
        if (chopMonoQuadAtY(dst, ctop, &t)) {
            // take the 2nd chopped quad
            SkChopQuadAt(dst, tmp, t);
            dst[0] = tmp[2];
            dst[1] = tmp[3];
        } else {
            // if chopMonoQuadAtY failed, then we may have hit inexact numerics
            // so we just clamp against the top
            for (int i = 0; i < 3; i++) {
                if (dst[i].fY < ctop) {
                    dst[i].fY = ctop;
                }
            }
        }
    }

    // are we partially below
    if (dst[2].fY > cbot) {
        if (chopMonoQuadAtY(dst, cbot, &t)) {
            SkChopQuadAt(dst, tmp, t);
            dst[1] = tmp[1];
            dst[2] = tmp[2];
        } else {
            // if chopMonoQuadAtY failed, then we may have hit inexact numerics
            // so we just clamp against the bottom
            for (int i = 0; i < 3; i++) {
                if (dst[i].fY > cbot) {
                    dst[i].fY = cbot;
                }
            }
        }
    }

    if (reverse) {
        SkTSwap<SkPoint>(dst[0], dst[2]);
    }
    return true;
}

<|endoftext|>


<commit_before>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in
*       the documentation and/or other materials provided
*       with the distribution.
*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
*       names of its contributors may be used to endorse or promote
*       products derived from this software without specific prior
*       written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/

#include <iostream>

#include <boost/scoped_ptr.hpp>

#include <pdal/Stage.hpp>
#include <pdal/StageIterator.hpp>
#include <pdal/FileUtils.hpp>
#include <pdal/PointBuffer.hpp>
#include <pdal/filters/Stats.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/property_tree/json_parser.hpp>

#include "AppSupport.hpp"
#include "Application.hpp"

using namespace pdal;

class PcInfo : public Application
{
public:
    PcInfo(int argc, char* argv[]);
    int execute(); // overrride

private:
    void addSwitches(); // overrride
    void validateSwitches(); // overrride

    void dumpOnePoint(const Stage&) const;
    void dumpStats(pdal::filters::Stats& filter) const;
    void dumpSchema(const Stage&) const;
    void dumpStage(const Stage&) const;

    std::string m_inputFile;
    std::string m_outputFile;
    bool m_showStats;
    bool m_showSchema;
    bool m_showStage;
	pdal::Options m_options;
    boost::uint64_t m_pointNumber;
    std::ostream* m_outputStream;
	boost::uint32_t m_seed;
};

PcInfo::PcInfo(int argc, char* argv[])
    : Application(argc, argv, "pcinfo")
    , m_inputFile("")
    , m_outputFile("")
    , m_showStats(false)
    , m_showSchema(false)
    , m_showStage(false)
    , m_pointNumber((std::numeric_limits<boost::uint64_t>::max)())
    , m_outputStream(0)
{
    return;
}

void PcInfo::validateSwitches()
{
    if (m_inputFile == "")
    {
        throw app_usage_error("input file name required");
    }

    return;
}

void PcInfo::addSwitches()
{
    namespace po = boost::program_options;

    po::options_description* file_options = new po::options_description("file options");

    file_options->add_options()
        ("input,i", po::value<std::string>(&m_inputFile)->default_value(""), "input file name")
        ("output,o", po::value<std::string>(&m_outputFile)->default_value(""), "output file name")
        ;

    addSwitchSet(file_options);

    po::options_description* processing_options = new po::options_description("processing options");

    processing_options->add_options()
        ("point,p", po::value<boost::uint64_t>(&m_pointNumber)->implicit_value(0), "point to dump")
        ("stats,a", po::value<bool>(&m_showStats)->zero_tokens()->implicit_value(true), "dump stats on all points (reads entire dataset)")
        ("schema,s", po::value<bool>(&m_showSchema)->zero_tokens()->implicit_value(true), "dump the schema")
        ("stage,r", po::value<bool>(&m_showStage)->zero_tokens()->implicit_value(true), "dump the stage info")
        ("seed", po::value<boost::uint32_t>(&m_seed)->default_value(0), "Seed value for random sample")
        ;

    addSwitchSet(processing_options);

    addPositionalSwitch("input", 1);

    return;
}

void PcInfo::dumpOnePoint(const Stage& stage) const
{
    const Schema& schema = stage.getSchema();

    PointBuffer data(schema, 1);

    boost::scoped_ptr<StageSequentialIterator> iter(stage.createSequentialIterator(data));
    iter->skip(m_pointNumber);

    const boost::uint32_t numRead = iter->read(data);
    if (numRead != 1)
    {
        throw app_runtime_error("problem reading point number " + m_pointNumber);
    }

    boost::property_tree::ptree tree = data.toPTree();

    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    ostr << "Point " << m_pointNumber << ":\n";
    write_json(ostr, tree.get_child("0"));
    ostr << "\n";

    return;
}

void PcInfo::dumpStats(pdal::filters::Stats& filter) const
{

    const Schema& schema = filter.getSchema();

    PointBuffer data(schema);

    boost::scoped_ptr<StageSequentialIterator> iter(filter.createSequentialIterator(data));

    boost::uint64_t totRead = 0;
    while (!iter->atEnd())
    {

        const boost::uint32_t numRead = iter->read(data);
        totRead += numRead;
    }

    boost::property_tree::ptree tree = static_cast<pdal::filters::iterators::sequential::Stats*>(iter.get())->toPTree();

    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    write_json(ostr, tree);

    return;
}

void PcInfo::dumpSchema(const Stage& stage) const
{
    const Schema& schema = stage.getSchema();

    boost::property_tree::ptree tree = schema.toPTree();

    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    boost::property_tree::write_json(ostr, tree);

    return;
}

void PcInfo::dumpStage(const Stage& stage) const
{
    boost::property_tree::ptree tree = stage.toPTree();

    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    boost::property_tree::write_json(ostr, tree);

    return;
}

int PcInfo::execute()
{
    if (m_outputFile != "")
    {
        m_outputStream = FileUtils::createFile(m_outputFile);
        if (!m_outputStream)
        {
            throw app_runtime_error("cannot open output file: " + m_outputFile);
        }
    }

    Options readerOptions;
    {
        readerOptions.add<std::string>("filename", m_inputFile);
        readerOptions.add<bool>("debug", isDebug());
        readerOptions.add<boost::uint32_t>("verbose", getVerboseLevel());
    }

    Stage* reader = AppSupport::makeReader(readerOptions);

	if (m_seed != 0)
	{
		Option seed_option("seed", m_seed, "seed value");
		m_options.add(seed_option);
	}
	pdal::Options options = m_options + readerOptions;

    pdal::filters::Stats* filter = new pdal::filters::Stats(*reader, options);

    filter->initialize();

    if (m_pointNumber != (std::numeric_limits<boost::uint64_t>::max)())
    {
        dumpOnePoint(*filter);
    }

    if (m_showStats)
    {
        dumpStats(*filter);
    }

    if (m_showSchema)
    {
        dumpSchema(*reader);
    }

    if (m_showStage)
    {
        dumpStage(*reader);
    }

    delete filter;
    delete reader;

    if (m_outputStream)
    {
        FileUtils::closeFile(m_outputStream);
    }

    return 0;
}

int main(int argc, char* argv[])
{
    PcInfo app(argc, argv);
    return app.run();
}

<commit_msg>add sample size option<commit_after>/******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek (mpg@flaxen.com)
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
*     * Redistributions of source code must retain the above copyright
*       notice, this list of conditions and the following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright
*       notice, this list of conditions and the following disclaimer in
*       the documentation and/or other materials provided
*       with the distribution.
*     * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
*       names of its contributors may be used to endorse or promote
*       products derived from this software without specific prior
*       written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/

#include <iostream>

#include <boost/scoped_ptr.hpp>

#include <pdal/Stage.hpp>
#include <pdal/StageIterator.hpp>
#include <pdal/FileUtils.hpp>
#include <pdal/PointBuffer.hpp>
#include <pdal/filters/Stats.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/property_tree/json_parser.hpp>

#include "AppSupport.hpp"
#include "Application.hpp"

using namespace pdal;

class PcInfo : public Application
{
public:
    PcInfo(int argc, char* argv[]);
    int execute(); // overrride

private:
    void addSwitches(); // overrride
    void validateSwitches(); // overrride

    void dumpOnePoint(const Stage&) const;
    void dumpStats(pdal::filters::Stats& filter) const;
    void dumpSchema(const Stage&) const;
    void dumpStage(const Stage&) const;

    std::string m_inputFile;
    std::string m_outputFile;
    bool m_showStats;
    bool m_showSchema;
    bool m_showStage;
	pdal::Options m_options;
    boost::uint64_t m_pointNumber;
    std::ostream* m_outputStream;
	boost::uint32_t m_seed;
    boost::uint32_t m_sample_size;

};

PcInfo::PcInfo(int argc, char* argv[])
    : Application(argc, argv, "pcinfo")
    , m_inputFile("")
    , m_outputFile("")
    , m_showStats(false)
    , m_showSchema(false)
    , m_showStage(false)
    , m_pointNumber((std::numeric_limits<boost::uint64_t>::max)())
    , m_outputStream(0)
{
    return;
}

void PcInfo::validateSwitches()
{
    if (m_inputFile == "")
    {
        throw app_usage_error("input file name required");
    }

    return;
}

void PcInfo::addSwitches()
{
    namespace po = boost::program_options;

    po::options_description* file_options = new po::options_description("file options");

    file_options->add_options()
        ("input,i", po::value<std::string>(&m_inputFile)->default_value(""), "input file name")
        ("output,o", po::value<std::string>(&m_outputFile)->default_value(""), "output file name")
        ;

    addSwitchSet(file_options);

    po::options_description* processing_options = new po::options_description("processing options");

    processing_options->add_options()
        ("point,p", po::value<boost::uint64_t>(&m_pointNumber)->implicit_value(0), "point to dump")
        ("stats,a", po::value<bool>(&m_showStats)->zero_tokens()->implicit_value(true), "dump stats on all points (reads entire dataset)")
        ("schema,s", po::value<bool>(&m_showSchema)->zero_tokens()->implicit_value(true), "dump the schema")
        ("stage,r", po::value<bool>(&m_showStage)->zero_tokens()->implicit_value(true), "dump the stage info")
        ("seed", po::value<boost::uint32_t>(&m_seed)->default_value(0), "Seed value for random sample")
        ("sample_size", po::value<boost::uint32_t>(&m_sample_size)->default_value(1000), "Sample size for random sample")
        ;

    addSwitchSet(processing_options);

    addPositionalSwitch("input", 1);

    return;
}

void PcInfo::dumpOnePoint(const Stage& stage) const
{
    const Schema& schema = stage.getSchema();

    PointBuffer data(schema, 1);

    boost::scoped_ptr<StageSequentialIterator> iter(stage.createSequentialIterator(data));
    iter->skip(m_pointNumber);

    const boost::uint32_t numRead = iter->read(data);
    if (numRead != 1)
    {
        throw app_runtime_error("problem reading point number " + m_pointNumber);
    }

    boost::property_tree::ptree tree = data.toPTree();

    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    ostr << "Point " << m_pointNumber << ":\n";
    write_json(ostr, tree.get_child("0"));
    ostr << "\n";

    return;
}

void PcInfo::dumpStats(pdal::filters::Stats& filter) const
{

    const Schema& schema = filter.getSchema();

    PointBuffer data(schema);

    boost::scoped_ptr<StageSequentialIterator> iter(filter.createSequentialIterator(data));

    boost::uint64_t totRead = 0;
    while (!iter->atEnd())
    {

        const boost::uint32_t numRead = iter->read(data);
        totRead += numRead;
    }

    boost::property_tree::ptree tree = static_cast<pdal::filters::iterators::sequential::Stats*>(iter.get())->toPTree();

    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    write_json(ostr, tree);

    return;
}

void PcInfo::dumpSchema(const Stage& stage) const
{
    const Schema& schema = stage.getSchema();

    boost::property_tree::ptree tree = schema.toPTree();

    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    boost::property_tree::write_json(ostr, tree);

    return;
}

void PcInfo::dumpStage(const Stage& stage) const
{
    boost::property_tree::ptree tree = stage.toPTree();

    std::ostream& ostr = m_outputStream ? *m_outputStream : std::cout;

    boost::property_tree::write_json(ostr, tree);

    return;
}

int PcInfo::execute()
{
    if (m_outputFile != "")
    {
        m_outputStream = FileUtils::createFile(m_outputFile);
        if (!m_outputStream)
        {
            throw app_runtime_error("cannot open output file: " + m_outputFile);
        }
    }

    Options readerOptions;
    {
        readerOptions.add<std::string>("filename", m_inputFile);
        readerOptions.add<bool>("debug", isDebug());
        readerOptions.add<boost::uint32_t>("verbose", getVerboseLevel());
    }

    Stage* reader = AppSupport::makeReader(readerOptions);

	if (m_seed != 0)
	{
		Option seed_option("seed", m_seed, "seed value");
		m_options.add(seed_option);
	}

    Option sample_size("sample_size", m_sample_size, "sample size for random sample");
    m_options.add(sample_size);

	pdal::Options options = m_options + readerOptions;

    pdal::filters::Stats* filter = new pdal::filters::Stats(*reader, options);

    filter->initialize();

    if (m_pointNumber != (std::numeric_limits<boost::uint64_t>::max)())
    {
        dumpOnePoint(*filter);
    }

    if (m_showStats)
    {
        dumpStats(*filter);
    }

    if (m_showSchema)
    {
        dumpSchema(*reader);
    }

    if (m_showStage)
    {
        dumpStage(*reader);
    }

    delete filter;
    delete reader;

    if (m_outputStream)
    {
        FileUtils::closeFile(m_outputStream);
    }

    return 0;
}

int main(int argc, char* argv[])
{
    PcInfo app(argc, argv);
    return app.run();
}

<|endoftext|>


<commit_before>// Copyright (c) 2011 The Native Client 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 "native_client/src/shared/platform/nacl_check.h"
#include "native_client/tests/ppapi_test_lib/get_browser_interface.h"
#include "native_client/tests/ppapi_test_lib/test_interface.h"

#include "ppapi/c/pp_size.h"
#include "ppapi/c/ppb_image_data.h"
#include "ppapi/c/ppb_instance.h"
#include "ppapi/c/ppb_graphics_2d.h"

namespace {

// Tests PPB_Instance::IsFullFrame().
void TestIsFullFrame() {
  // TODO(elijahtaylor): Need a test when IsFullFrame is true, should be
  // covered by http://code.google.com/p/nativeclient/issues/detail?id=1932
  PP_Bool full_frame = PPBInstance()->IsFullFrame(pp_instance());
  EXPECT_ASYNC(full_frame == PP_FALSE);

  full_frame = PPBInstance()->IsFullFrame(kInvalidInstance);
  EXPECT_ASYNC(full_frame == PP_FALSE);

  TEST_PASSED_ASYNC;
}

void TestBindGraphics() {
  PP_Size size = PP_MakeSize(100, 100);

  PP_Resource graphics1 = PPBGraphics2D()->Create(
      pp_instance(), &size, PP_TRUE);
  PP_Resource graphics2 = PPBGraphics2D()->Create(
      pp_instance(), &size, PP_TRUE);

  EXPECT_ASYNC(graphics1 != kInvalidResource);
  EXPECT_ASYNC(graphics2 != kInvalidResource);

  PP_Bool ret = PPBInstance()->BindGraphics(pp_instance(), graphics1);
  EXPECT_ASYNC(ret == PP_TRUE);

  // We should be allowed to replace one device with another.
  ret = PPBInstance()->BindGraphics(pp_instance(), graphics2);
  EXPECT_ASYNC(ret == PP_TRUE);

  // This should fail because instance is not valid.
  ret = PPBInstance()->BindGraphics(kInvalidInstance, graphics1);
  EXPECT_ASYNC(ret == PP_FALSE);

  // This should fail because instance is not valid and graphics2 is bound.
  ret = PPBInstance()->BindGraphics(kInvalidInstance, graphics2);
  EXPECT_ASYNC(ret == PP_FALSE);

  // This is not a failure, binding resource 0 simply unbinds all devices.
  ret = PPBInstance()->BindGraphics(pp_instance(), kInvalidResource);
  EXPECT_ASYNC(ret == PP_TRUE);

  PP_Resource image_data = PPBImageData()->Create(
      pp_instance(), PP_IMAGEDATAFORMAT_RGBA_PREMUL, &size, PP_FALSE);
  EXPECT_ASYNC(image_data != kInvalidResource);

  // TODO(elijahtaylor): Enable this test once fixed in chrome.
  // http://code.google.com/p/nativeclient/issues/detail?id=1999

  // This should fail because the resource is the wrong type.
  // ret = PPBInstance()->BindGraphics(pp_instance(), image_data);
  // EXPECT_ASYNC(ret == PP_FALSE);

  TEST_PASSED_ASYNC;
}

}  // namespace

void SetupTests() {
  RegisterTest("TestIsFullFrame", TestIsFullFrame);
  RegisterTest("TestBindGraphics", TestBindGraphics);
}

void SetupPluginInterfaces() {
  // none
}
<commit_msg>Remove _ASYNC suffix from new ppb_instance test.<commit_after>// Copyright (c) 2011 The Native Client 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 "native_client/src/shared/platform/nacl_check.h"
#include "native_client/tests/ppapi_test_lib/get_browser_interface.h"
#include "native_client/tests/ppapi_test_lib/test_interface.h"

#include "ppapi/c/pp_size.h"
#include "ppapi/c/ppb_image_data.h"
#include "ppapi/c/ppb_instance.h"
#include "ppapi/c/ppb_graphics_2d.h"

namespace {

// Tests PPB_Instance::IsFullFrame().
void TestIsFullFrame() {
  // TODO(elijahtaylor): Need a test when IsFullFrame is true, should be
  // covered by http://code.google.com/p/nativeclient/issues/detail?id=1932
  PP_Bool full_frame = PPBInstance()->IsFullFrame(pp_instance());
  EXPECT(full_frame == PP_FALSE);

  full_frame = PPBInstance()->IsFullFrame(kInvalidInstance);
  EXPECT(full_frame == PP_FALSE);

  TEST_PASSED;
}

void TestBindGraphics() {
  PP_Size size = PP_MakeSize(100, 100);

  PP_Resource graphics1 = PPBGraphics2D()->Create(
      pp_instance(), &size, PP_TRUE);
  PP_Resource graphics2 = PPBGraphics2D()->Create(
      pp_instance(), &size, PP_TRUE);

  EXPECT(graphics1 != kInvalidResource);
  EXPECT(graphics2 != kInvalidResource);

  PP_Bool ret = PPBInstance()->BindGraphics(pp_instance(), graphics1);
  EXPECT(ret == PP_TRUE);

  // We should be allowed to replace one device with another.
  ret = PPBInstance()->BindGraphics(pp_instance(), graphics2);
  EXPECT(ret == PP_TRUE);

  // This should fail because instance is not valid.
  ret = PPBInstance()->BindGraphics(kInvalidInstance, graphics1);
  EXPECT(ret == PP_FALSE);

  // This should fail because instance is not valid and graphics2 is bound.
  ret = PPBInstance()->BindGraphics(kInvalidInstance, graphics2);
  EXPECT(ret == PP_FALSE);

  // This is not a failure, binding resource 0 simply unbinds all devices.
  ret = PPBInstance()->BindGraphics(pp_instance(), kInvalidResource);
  EXPECT(ret == PP_TRUE);

  PP_Resource image_data = PPBImageData()->Create(
      pp_instance(), PP_IMAGEDATAFORMAT_RGBA_PREMUL, &size, PP_FALSE);
  EXPECT(image_data != kInvalidResource);

  // TODO(elijahtaylor): Enable this test once fixed in chrome.
  // http://code.google.com/p/nativeclient/issues/detail?id=1999

  // This should fail because the resource is the wrong type.
  // ret = PPBInstance()->BindGraphics(pp_instance(), image_data);
  // EXPECT(ret == PP_FALSE);

  TEST_PASSED;
}

}  // namespace

void SetupTests() {
  RegisterTest("TestIsFullFrame", TestIsFullFrame);
  RegisterTest("TestBindGraphics", TestBindGraphics);
}

void SetupPluginInterfaces() {
  // none
}
<|endoftext|>