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

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

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

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

#include "listmodel.h"

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

using namespace KXForms;

ListModel::ListModel( QObject *parent ) : QAbstractListModel( parent )
{
}

ListModel::~ListModel()
{
  qDeleteAll( mItems );
}

int ListModel::rowCount( const QModelIndex &parent ) const
{
  Q_UNUSED( parent );
  return mItems.size();
}

int ListModel::columnCount( const QModelIndex &parent ) const
{
  Q_UNUSED( parent );
  if( mVisibleElements.size() > 0 )
    return mVisibleElements.size();
  else
    return 1;
}

QVariant ListModel::data( const QModelIndex & index, int role ) const
{
  if( index.row() > mItems.count() )
    return QVariant();

  Item *item = mItems.at( index.row() );
  if( mVisibleElements.size() == 0 ) {
    if ( role == Qt::DisplayRole ) {
      if ( index.column() == 0 ) return item->label;
      else if ( index.column() == 1 ) return item->ref.toString();
    }
    return QVariant();
  } else {
    if ( role == Qt::DisplayRole ) {
      Reference key = mVisibleElements[index.column()].ref;
      QDomElement e = key.applyElement( item->element );
      if( !e.isNull() )
        return e.text();
      else return QVariant();
    }
    return QVariant();
  }
}

QVariant ListModel::headerData ( int section, Qt::Orientation orientation,
  int role ) const
{
  if ( orientation == Qt::Horizontal ) {
    if( mVisibleElements.size() == 0 ) {
    if ( role == Qt::DisplayRole ) {
      if ( section == 0 ) {
        if ( mLabel.isEmpty() ) return i18n("Label");
        else return mLabel;
      } else if ( section == 1 ) {
        return i18n("Reference");
      }
    }
    } else {
      if ( role == Qt::DisplayRole ) {
          return mVisibleElements[section].label;
      }
    }
  }
  return QVariant();
}

void ListModel::addItem( const QString &label, const Reference &ref, QDomElement element )
{
  beginInsertRows( QModelIndex(), mItems.size(), mItems.size() );

  Item *item = new Item;
  item->label = label;
  item->ref = ref;
  item->element = element;
  mItems.append( item );

  endInsertRows();
}

int ListModel::itemCount( const QString &itemClass )
{
  int count = 0;

  foreach( Item *item, mItems ) {
    if ( item->ref.lastSegment().name() == itemClass ) count++;
  }

  return count;
}

bool ListModel::removeRows( int row, int count, const QModelIndex &parent )
{
  beginRemoveRows( parent, row, row + count - 1 );

  for( int i = 0; i < count; ++i ) {
    Item *item = mItems.at( row );
    mItems.removeAt( row );
    delete item;
  }

  endRemoveRows();

  return true;
}

void ListModel::recalculateSegmentCounts()
{
  int startRow = 0;
  int endRow = 0;

  QMap<QString, int> counts;

  foreach( Item *item, mItems ) {
    int count = 1;
    Reference::Segment segment = item->ref.segments().last();
    QMap<QString, int>::ConstIterator it = counts.find( segment.name() );
    if ( it != counts.end() ) count = it.value();

    if ( count != segment.count() ) {
      item->ref.lastSegment().setCount( count );
    } else {
      startRow++;
    }

    endRow++;

    counts.insert( segment.name(), ++count );
  }

  emit dataChanged( createIndex( startRow, 1 ), createIndex( endRow, 1 ) );
}

ListModel::Item *ListModel::item( const QModelIndex &index )
{
  return mItems.at( index.row() );
}

void ListModel::setLabel( const QString &label )
{
  mLabel = label;
}

QString ListModel::label() const
{
  return mLabel;
}

void ListModel::clear()
{
  if( rowCount() > 0 )
    removeRows( 0, rowCount() );
}

QModelIndex ListModel::moveItem( int from, int to )
{
  mItems.move( from, to );
  emit dataChanged( createIndex( from, 1 ), createIndex( to, 1 ) );
  return createIndex( to, 1 );
}
<commit_msg>crash--<commit_after>/*
    This file is part of KDE.

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

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

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

#include "listmodel.h"

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

using namespace KXForms;

ListModel::ListModel( QObject *parent ) : QAbstractListModel( parent )
{
}

ListModel::~ListModel()
{
  qDeleteAll( mItems );
}

int ListModel::rowCount( const QModelIndex &parent ) const
{
  Q_UNUSED( parent );
  return mItems.size();
}

int ListModel::columnCount( const QModelIndex &parent ) const
{
  Q_UNUSED( parent );
  if( mVisibleElements.size() > 0 )
    return mVisibleElements.size();
  else
    return 1;
}

QVariant ListModel::data( const QModelIndex & index, int role ) const
{
  if( !index.isValid() || index.row() > mItems.count() )
    return QVariant();

  Item *item = mItems.at( index.row() );
  if( mVisibleElements.size() == 0 ) {
    if ( role == Qt::DisplayRole ) {
      if ( index.column() == 0 ) return item->label;
      else if ( index.column() == 1 ) return item->ref.toString();
    }
    return QVariant();
  } else {
    if ( role == Qt::DisplayRole ) {
      Reference key = mVisibleElements[index.column()].ref;
      QDomElement e = key.applyElement( item->element );
      if( !e.isNull() )
        return e.text();
      else return QVariant();
    }
    return QVariant();
  }
}

QVariant ListModel::headerData ( int section, Qt::Orientation orientation,
  int role ) const
{
  if ( orientation == Qt::Horizontal ) {
    if( mVisibleElements.size() == 0 ) {
    if ( role == Qt::DisplayRole ) {
      if ( section == 0 ) {
        if ( mLabel.isEmpty() ) return i18n("Label");
        else return mLabel;
      } else if ( section == 1 ) {
        return i18n("Reference");
      }
    }
    } else {
      if ( role == Qt::DisplayRole ) {
          return mVisibleElements[section].label;
      }
    }
  }
  return QVariant();
}

void ListModel::addItem( const QString &label, const Reference &ref, QDomElement element )
{
  beginInsertRows( QModelIndex(), mItems.size(), mItems.size() );

  Item *item = new Item;
  item->label = label;
  item->ref = ref;
  item->element = element;
  mItems.append( item );

  endInsertRows();
}

int ListModel::itemCount( const QString &itemClass )
{
  int count = 0;

  foreach( Item *item, mItems ) {
    if ( item->ref.lastSegment().name() == itemClass ) count++;
  }

  return count;
}

bool ListModel::removeRows( int row, int count, const QModelIndex &parent )
{
  beginRemoveRows( parent, row, row + count - 1 );

  for( int i = 0; i < count; ++i ) {
    Item *item = mItems.at( row );
    mItems.removeAt( row );
    delete item;
  }

  endRemoveRows();

  return true;
}

void ListModel::recalculateSegmentCounts()
{
  int startRow = 0;
  int endRow = 0;

  QMap<QString, int> counts;

  foreach( Item *item, mItems ) {
    int count = 1;
    Reference::Segment segment = item->ref.segments().last();
    QMap<QString, int>::ConstIterator it = counts.find( segment.name() );
    if ( it != counts.end() ) count = it.value();

    if ( count != segment.count() ) {
      item->ref.lastSegment().setCount( count );
    } else {
      startRow++;
    }

    endRow++;

    counts.insert( segment.name(), ++count );
  }

  emit dataChanged( createIndex( startRow, 1 ), createIndex( endRow, 1 ) );
}

ListModel::Item *ListModel::item( const QModelIndex &index )
{
  return mItems.at( index.row() );
}

void ListModel::setLabel( const QString &label )
{
  mLabel = label;
}

QString ListModel::label() const
{
  return mLabel;
}

void ListModel::clear()
{
  if( rowCount() > 0 )
    removeRows( 0, rowCount() );
}

QModelIndex ListModel::moveItem( int from, int to )
{
  mItems.move( from, to );
  emit dataChanged( createIndex( from, 1 ), createIndex( to, 1 ) );
  return createIndex( to, 1 );
}
<|endoftext|>


<commit_before>/* --
 * Copyright (C) 2013, George Makrydakis <irrequietus@gmail.com>
 *
 * This file is part of odreex.
 *
 * odreex is free software: you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * odreex is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * odreex. If not, see http://www.gnu.org/licenses/.
 *
 */

#include <odreex/ample/test.hh>
#include <odreex/ppmpf/ppfk.hh>
#include <odreex/ppmpf/test.hh>

PPMPF_TEST( ppmpf_tup_empty
          , "PPMPF_TUP_EMPTY with an empty tuple"
          , PPMPF_TUP_EMPTY(())
          , 1 )

PPMPF_TEST( ppmpf_tup_empty1
          , "PPMPF_TUP_EMPTY with a single argument"
          , PPMPF_TUP_EMPTY((a single argument))
          , 0 )

PPMPF_TEST( ppmpf_tup_empty2
          , "PPMPF_TUP_EMPTY with a single comma"
          , PPMPF_TUP_EMPTY((,))
          , 0 )

PPMPF_TEST( ppmpf_tup_empty3
          , "PPMPF_TUP_EMPTY with a macro as argument"
          , PPMPF_TUP_EMPTY((PPMPF_TEST))
          , 0 )

PPMPF_TEST( ppmpf_tup_empty4
          , "PPMPF_TUP_EMPTY with a balanced parenthesis"
          , PPMPF_TUP_EMPTY((()))
          , 0 )

PPMPF_TEST( ppmpf_tup_reverse
          , "PPMPF_TUP_REVERSE with 128 arguments"
          , PPMPF_TUP_REVERSE((0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
                              ,0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
                              ,0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
                              ,0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
                              ,0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
                              ,0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
                              ,0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
                              ,0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f))
          , (f,e,d,c,b,a,9,8,7,6,5,4,3,2,1,0,f,e,d,c,b,a,9,8,7,6,5,4,3,2,1,0,\
f,e,d,c,b,a,9,8,7,6,5,4,3,2,1,0,f,e,d,c,b,a,9,8,7,6,5,4,3,2,1,0,\
f,e,d,c,b,a,9,8,7,6,5,4,3,2,1,0,f,e,d,c,b,a,9,8,7,6,5,4,3,2,1,0,\
f,e,d,c,b,a,9,8,7,6,5,4,3,2,1,0,f,e,d,c,b,a,9,8,7,6,5,4,3,2,1,0))

PPMPF_TEST_BLOCK( ppmpf
                , check_tuple
                , ( ppmpf_tup_empty
                  , ppmpf_tup_empty1
                  , ppmpf_tup_empty2
                  , ppmpf_tup_empty3
                  , ppmpf_tup_empty4
                  , ppmpf_tup_reverse )
                , true )

int main() {
    PPMPF_TEST_RUN( check_tuple
                  , "testing ppmpf tuples" );
    return {};
}
<commit_msg>Added tests for ppmpf tuple joins.<commit_after>/* --
 * Copyright (C) 2013, George Makrydakis <irrequietus@gmail.com>
 *
 * This file is part of odreex.
 *
 * odreex is free software: you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * odreex is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * odreex. If not, see http://www.gnu.org/licenses/.
 *
 */

#include <odreex/ample/test.hh>
#include <odreex/ppmpf/ppfk.hh>
#include <odreex/ppmpf/test.hh>

PPMPF_TEST( ppmpf_tup_empty
          , "PPMPF_TUP_EMPTY with an empty tuple"
          , PPMPF_TUP_EMPTY(())
          , 1 )

PPMPF_TEST( ppmpf_tup_empty1
          , "PPMPF_TUP_EMPTY with a single argument"
          , PPMPF_TUP_EMPTY((a single argument))
          , 0 )

PPMPF_TEST( ppmpf_tup_empty2
          , "PPMPF_TUP_EMPTY with a single comma"
          , PPMPF_TUP_EMPTY((,))
          , 0 )

PPMPF_TEST( ppmpf_tup_empty3
          , "PPMPF_TUP_EMPTY with a macro as argument"
          , PPMPF_TUP_EMPTY((PPMPF_TEST))
          , 0 )

PPMPF_TEST( ppmpf_tup_empty4
          , "PPMPF_TUP_EMPTY with a balanced parenthesis"
          , PPMPF_TUP_EMPTY((()))
          , 0 )

PPMPF_TEST( ppmpf_tup_join
          , "PPMPF_TUP_JOIN of 2 tuples with 2 items each"
          , PPMPF_TUP_JOIN((a,a),(a,a))
          , (a,a,a,a) )

PPMPF_TEST( ppmpf_tup_join1
          , "PPMPF_TUP_JOIN of 2 tuples with 4 items each"
          , PPMPF_TUP_JOIN((a,a,a,a),(b,b,b,b))
          , (a,a,a,a,b,b,b,b) )

PPMPF_TEST( ppmpf_tup_join2
          , "PPMPF_TUP_JOIN 4 tuples using PPMPF_TUP_FOLDL_OF"
          , PPMPF_TUP_FOLDL_OF( ((PPMPF_TUP_JOIN,_1),_2)
                              , ((a,a),(b,b),(c,c),(d,d)) )
          , ((a,a,b,b,c,c,d,d)) )

PPMPF_TEST( ppmpf_tup_reverse
          , "PPMPF_TUP_REVERSE with 128 arguments"
          , PPMPF_TUP_REVERSE((0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
                              ,0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
                              ,0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
                              ,0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
                              ,0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
                              ,0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
                              ,0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
                              ,0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f))
          , (f,e,d,c,b,a,9,8,7,6,5,4,3,2,1,0,f,e,d,c,b,a,9,8,7,6,5,4,3,2,1,0,\
f,e,d,c,b,a,9,8,7,6,5,4,3,2,1,0,f,e,d,c,b,a,9,8,7,6,5,4,3,2,1,0,\
f,e,d,c,b,a,9,8,7,6,5,4,3,2,1,0,f,e,d,c,b,a,9,8,7,6,5,4,3,2,1,0,\
f,e,d,c,b,a,9,8,7,6,5,4,3,2,1,0,f,e,d,c,b,a,9,8,7,6,5,4,3,2,1,0))

PPMPF_TEST_BLOCK( ppmpf
                , check_tuple
                , ( ppmpf_tup_empty
                  , ppmpf_tup_empty1
                  , ppmpf_tup_empty2
                  , ppmpf_tup_empty3
                  , ppmpf_tup_empty4
                  , ppmpf_tup_join
                  , ppmpf_tup_join1
                  , ppmpf_tup_join2
                  , ppmpf_tup_reverse )
                , true )

int main() {
    PPMPF_TEST_RUN( check_tuple
                  , "testing ppmpf tuples" );
    return {};
}
<|endoftext|>


<commit_before>#include <QFile>
#include <QDebug>

#include <schema/parser.h>

#include <common/nsmanager.h>
#include <common/messagehandler.h>
#include <common/parsercontext.h>

int main( int argc, char **argv )
{
  if ( argc != 2 ) {
    qDebug( "Missing argument: filename of schema" );
    return 1;
  }

  QString filename = argv[ 1 ];

  QFile file( filename );

  if ( !file.open( QIODevice::ReadOnly ) ) {
    qDebug( "Can't open file %s", qPrintable( file.fileName() ) );
    return 1;
  }

  NSManager namespaceManager;
  MessageHandler messageHandler;
  ParserContext context;
  context.setNamespaceManager( &namespaceManager );
  context.setMessageHandler( &messageHandler );

  XSD::Parser parser;
  if ( !parser.parseFile( &context, file ) ) {
    qDebug() << "Error parsing file " << filename;
    return 1;
  }

  XSD::Types types = parser.types();

  const XSD::SimpleType::List simpleTypes = types.simpleTypes();
  for ( int i = 0; i < simpleTypes.count(); ++i ) {
    qDebug( "SimpleType: %s %s", qPrintable( simpleTypes[ i ].name() ), qPrintable( simpleTypes[ i ].baseTypeName().qname() ) );
  }

  const XSD::ComplexType::List complexTypes = types.complexTypes();
  for ( int i = 0; i < complexTypes.count(); ++i ) {
    qDebug( "ComplexType: %s %s", qPrintable( complexTypes[ i ].name() ), qPrintable( complexTypes[ i ].baseTypeName().qname() ) );
    const XSD::Element::List elements = complexTypes[ i ].elements();
    for ( int j = 0; j < elements.count(); ++j ) {
      qDebug( "\tElement: %s %s", qPrintable( elements[ j ].name() ), qPrintable( elements[ j ].type().qname() ) );
    }
    const XSD::Attribute::List attributes = complexTypes[ i ].attributes();
    for ( int j = 0; j < attributes.count(); ++j ) {
      qDebug( "\tAttribute: %s %s", qPrintable( attributes[ j ].name() ), qPrintable( attributes[ j ].type().qname() ) );
    }
  }

  const XSD::Element::List elements = types.elements();
  for ( int i = 0; i < elements.count(); ++i ) {
    qDebug( "Element: %s %s", qPrintable( elements[ i ].name() ), qPrintable( elements[ i ].type().qname() ) );
  }

  const XSD::Attribute::List attributes = types.attributes();
  for ( int i = 0; i < attributes.count(); ++i ) {
    qDebug( "Attribute: %s %s", qPrintable( attributes[ i ].name() ), qPrintable( attributes[ i ].type().qname() ) );
  }

  const XSD::AttributeGroup::List attributeGroups = types.attributeGroups();
  for ( int i = 0; i < attributeGroups.count(); ++i ) {
    qDebug( "AttributeGroup: %s", qPrintable( attributeGroups[ i ].name() ) );
  }

  return 0;
}
<commit_msg>Print more information about attributes.<commit_after>#include <QFile>
#include <QDebug>

#include <schema/parser.h>

#include <common/nsmanager.h>
#include <common/messagehandler.h>
#include <common/parsercontext.h>

int main( int argc, char **argv )
{
  if ( argc != 2 ) {
    qDebug( "Missing argument: filename of schema" );
    return 1;
  }

  QString filename = argv[ 1 ];

  QFile file( filename );

  if ( !file.open( QIODevice::ReadOnly ) ) {
    qDebug( "Can't open file %s", qPrintable( file.fileName() ) );
    return 1;
  }

  NSManager namespaceManager;
  MessageHandler messageHandler;
  ParserContext context;
  context.setNamespaceManager( &namespaceManager );
  context.setMessageHandler( &messageHandler );

  XSD::Parser parser;
  if ( !parser.parseFile( &context, file ) ) {
    qDebug() << "Error parsing file " << filename;
    return 1;
  }

  XSD::Types types = parser.types();

  const XSD::SimpleType::List simpleTypes = types.simpleTypes();
  for ( int i = 0; i < simpleTypes.count(); ++i ) {
    XSD::SimpleType t = simpleTypes[ i ];
    qDebug() << "SimpleType: " << t.name() << t.baseTypeName().qname()
      << t.subType();
    qDebug() << "FacetType: " << t.facetType();
    if ( t.facetType() == XSD::SimpleType::ENUM ) {
      qDebug() << "  ENUMS " << t.facetEnums();
    }
  }

  const XSD::ComplexType::List complexTypes = types.complexTypes();
  for ( int i = 0; i < complexTypes.count(); ++i ) {
    qDebug( "ComplexType: %s %s", qPrintable( complexTypes[ i ].name() ), qPrintable( complexTypes[ i ].baseTypeName().qname() ) );
    const XSD::Element::List elements = complexTypes[ i ].elements();
    for ( int j = 0; j < elements.count(); ++j ) {
      qDebug( "\tElement: %s %s", qPrintable( elements[ j ].name() ), qPrintable( elements[ j ].type().qname() ) );
    }
    const XSD::Attribute::List attributes = complexTypes[ i ].attributes();
    for ( int j = 0; j < attributes.count(); ++j ) {
      qDebug( "\tAttribute: %s %s", qPrintable( attributes[ j ].name() ), qPrintable( attributes[ j ].type().qname() ) );
    }
  }

  const XSD::Element::List elements = types.elements();
  for ( int i = 0; i < elements.count(); ++i ) {
    qDebug( "Element: %s %s", qPrintable( elements[ i ].name() ), qPrintable( elements[ i ].type().qname() ) );
  }

  const XSD::Attribute::List attributes = types.attributes();
  for ( int i = 0; i < attributes.count(); ++i ) {
    qDebug( "Attribute: %s %s", qPrintable( attributes[ i ].name() ), qPrintable( attributes[ i ].type().qname() ) );
  }

  const XSD::AttributeGroup::List attributeGroups = types.attributeGroups();
  for ( int i = 0; i < attributeGroups.count(); ++i ) {
    qDebug( "AttributeGroup: %s", qPrintable( attributeGroups[ i ].name() ) );
  }

  return 0;
}
<|endoftext|>


<commit_before>/* Copyright (c) 2007-2012, Eddie Kohler
 * Copyright (c) 2007, Regents of the University of California
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, subject to the conditions
 * listed in the Tamer LICENSE file. These conditions include: you must
 * preserve this copyright notice, and you cannot mention the copyright
 * holders in advertising related to the Software without their permission.
 * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
 * notice is a summary of the Tamer LICENSE file; the license in that file is
 * legally binding.
 */
#include "config.h"
#include <tamer/tamer.hh>
#include "dinternal.hh"
#if HAVE_LIBEVENT
#include <event.h>
#endif

namespace tamer {
#if HAVE_LIBEVENT
namespace {

extern "C" {
void libevent_fdtrigger(int fd, short, void *arg);
}

class driver_libevent : public driver {
  public:
    driver_libevent();
    ~driver_libevent();

    virtual void at_fd(int fd, int action, event<int> e);
    virtual void at_time(const timeval &expiry, event<> e);
    virtual void kill_fd(int fd);

    void cull();
    virtual void loop(loop_flags flags);

    struct eevent {
	::event libevent;
	tamerpriv::simple_event *se;
	int *slot;
	eevent *next;
	eevent **pprev;
	driver_libevent *driver;
    };

    struct event_group {
	event_group *next;
	eevent e[1];
    };

    eevent *_etimer;

    struct fdp {
	::event base;

	inline fdp(driver_libevent *d, int fd) {
	    ::event_set(&base, fd, 0, libevent_fdtrigger, d);
	}
	inline ~fdp() {
	    ::event_del(&base);
	}
	inline void move(driver_libevent *d, int fd, fdp &other) {
	    int x = ::event_pending(&other.base, EV_READ | EV_WRITE, 0)
		& (EV_READ | EV_WRITE);
	    ::event_del(&other.base);
	    ::event_set(&base, fd, x | EV_PERSIST, libevent_fdtrigger, d);
	    if (x)
		::event_add(&base, 0);
	}
    };

    driver_fdset<fdp> fds_;
    int fdactive_;
    ::event signal_base_;

    event_group *_egroup;
    eevent *_efree;
    size_t _ecap;
    eevent *_esignal;

    void expand_events();
    static void fd_disinterest(void *driver, int fd);
    void update_fds();
};

extern "C" {
void libevent_fdtrigger(int fd, short what, void *arg) {
    driver_libevent *d = static_cast<driver_libevent *>(arg);
    driver_fd<driver_libevent::fdp> &x = d->fds_[fd];
    if (what & EV_READ)
	x.e[0].trigger(0);
    if (what & EV_WRITE)
	x.e[1].trigger(0);
    d->fds_.push_change(fd);
}

void libevent_trigger(int, short, void *arg) {
    driver_libevent::eevent *e = static_cast<driver_libevent::eevent *>(arg);
    if (*e->se && e->slot)
	*e->slot = 0;
    e->se->simple_trigger(true);
    *e->pprev = e->next;
    if (e->next)
	e->next->pprev = e->pprev;
    e->next = e->driver->_efree;
    e->driver->_efree = e;
}

void libevent_sigtrigger(int, short, void *arg)
{
    driver_libevent::eevent *e = static_cast<driver_libevent::eevent *>(arg);
    e->driver->dispatch_signals();
}
} // extern "C"

driver_libevent::driver_libevent()
    : _etimer(0), fdactive_(0), _egroup(0), _efree(0), _ecap(0)
{
    ::event_init();
    ::event_priority_init(3);
#if HAVE_EVENT_GET_STRUCT_EVENT_SIZE
    assert(sizeof(::event) >= event_get_struct_event_size());
#endif
    set_now();
    at_signal(0, event<>());	// create signal_fd pipe
    ::event_set(&signal_base_, sig_pipe[0], EV_READ | EV_PERSIST,
		libevent_sigtrigger, this);
    ::event_priority_set(&signal_base_, 0);
    ::event_add(&signal_base_, 0);
}

driver_libevent::~driver_libevent() {
    // discard all active events
    while (_etimer) {
	_etimer->se->simple_trigger(false);
	::event_del(&_etimer->libevent);
	_etimer = _etimer->next;
    }
    ::event_del(&signal_base_);

    // free event groups
    while (_egroup) {
	event_group *next = _egroup->next;
	delete[] reinterpret_cast<unsigned char *>(_egroup);
	_egroup = next;
    }
}

void driver_libevent::expand_events() {
    size_t ncap = (_ecap ? _ecap * 2 : 16);

    event_group *ngroup = reinterpret_cast<event_group *>(new unsigned char[sizeof(event_group) + sizeof(eevent) * (ncap - 1)]);
    ngroup->next = _egroup;
    _egroup = ngroup;
    for (size_t i = 0; i < ncap; i++) {
	ngroup->e[i].driver = this;
	ngroup->e[i].next = _efree;
	_efree = &ngroup->e[i];
    }
}

void driver_libevent::fd_disinterest(void *arg, int fd) {
    driver_libevent *d = static_cast<driver_libevent *>(arg);
    d->fds_.push_change(fd);
}

void driver_libevent::at_fd(int fd, int action, event<int> e) {
    assert(fd >= 0);
    if (e && (action == 0 || action == 1)) {
	fds_.expand(this, fd);
	driver_fd<fdp> &x = fds_[fd];
	if (x.e[action])
	    e = tamer::distribute(TAMER_MOVE(x.e[action]), TAMER_MOVE(e));
	x.e[action] = e;
	tamerpriv::simple_event::at_trigger(e.__get_simple(),
					    fd_disinterest, this, fd);
	fds_.push_change(fd);
    }
}

void driver_libevent::kill_fd(int fd) {
    if (fd >= 0 && fd < fds_.nfds_) {
	driver_fd<fdp> &x = fds_[fd];
	for (int action = 0; action < 2; ++action)
	    x.e[action].trigger(-ECANCELED);
	fds_.push_change(fd);
    }
}

void driver_libevent::update_fds() {
    int fd;
    while ((fd = fds_.pop_change()) >= 0) {
	driver_fd<fdp> &x = fds_[fd];
	int want_what = (x.e[0] ? EV_READ : 0) | (x.e[1] ? EV_WRITE : 0);
	int have_what = ::event_pending(&x.base, EV_READ | EV_WRITE, 0)
	    & (EV_READ | EV_WRITE);
	if (want_what != have_what) {
	    fdactive_ += (want_what != 0) - (have_what != 0);
	    if (have_what != 0)
		::event_del(&x.base);
	    if (want_what != 0) {
		::event_set(&x.base, fd, want_what | EV_PERSIST,
			    libevent_fdtrigger, this);
		::event_add(&x.base, 0);
	    }
	}
    }
}

void driver_libevent::at_time(const timeval &expiry, event<> e)
{
    if (!_efree)
	expand_events();
    if (e) {
	eevent *ee = _efree;
	_efree = ee->next;

	evtimer_set(&ee->libevent, libevent_trigger, ee);
	timeval timeout = expiry;
	timersub(&timeout, &now, &timeout);
	evtimer_add(&ee->libevent, &timeout);

	ee->se = e.__take_simple();
	ee->slot = 0;
	ee->next = _etimer;
	ee->pprev = &_etimer;
	if (_etimer)
	    _etimer->pprev = &ee->next;
	_etimer = ee;
    }
}

void driver_libevent::cull() {
    while (_etimer && !*_etimer->se) {
	eevent *e = _etimer;
	::event_del(&e->libevent);
	tamerpriv::simple_event::unuse_clean(_etimer->se);
	if ((_etimer = e->next))
	    _etimer->pprev = &_etimer;
	e->next = _efree;
	_efree = e;
    }
}

void driver_libevent::loop(loop_flags flags)
{
 again:
    // fix file descriptors
    if (fds_.has_change())
	update_fds();

    int event_flags = EVLOOP_ONCE;
    if (sig_any_active
	|| tamerpriv::abstract_rendezvous::has_unblocked())
	event_flags |= EVLOOP_NONBLOCK;
    else {
	cull();
	if (!_etimer && fdactive_ == 0 && sig_nforeground == 0)
	    // no events scheduled
	    return;
    }

    ::event_loop(event_flags);

    set_now();
    while (tamerpriv::abstract_rendezvous *r = tamerpriv::abstract_rendezvous::pop_unblocked())
	r->run();
    if (flags == loop_forever)
	goto again;
}

} // namespace
#endif

driver *driver::make_libevent()
{
#if HAVE_LIBEVENT
    return new driver_libevent;
#else
    return 0;
#endif
}

} // namespace tamer
<commit_msg>Remove unused code.<commit_after>/* Copyright (c) 2007-2012, Eddie Kohler
 * Copyright (c) 2007, Regents of the University of California
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, subject to the conditions
 * listed in the Tamer LICENSE file. These conditions include: you must
 * preserve this copyright notice, and you cannot mention the copyright
 * holders in advertising related to the Software without their permission.
 * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
 * notice is a summary of the Tamer LICENSE file; the license in that file is
 * legally binding.
 */
#include "config.h"
#include <tamer/tamer.hh>
#include "dinternal.hh"
#if HAVE_LIBEVENT
#include <event.h>
#endif

namespace tamer {
#if HAVE_LIBEVENT
namespace {

extern "C" {
void libevent_fdtrigger(int fd, short, void *arg);
}

class driver_libevent : public driver {
  public:
    driver_libevent();
    ~driver_libevent();

    virtual void at_fd(int fd, int action, event<int> e);
    virtual void at_time(const timeval &expiry, event<> e);
    virtual void kill_fd(int fd);

    void cull();
    virtual void loop(loop_flags flags);

    struct eevent {
	::event libevent;
	tamerpriv::simple_event *se;
	eevent *next;
	eevent **pprev;
	driver_libevent *driver;
    };

    struct event_group {
	event_group *next;
	eevent e[1];
    };

    eevent *_etimer;

    struct fdp {
	::event base;

	inline fdp(driver_libevent *d, int fd) {
	    ::event_set(&base, fd, 0, libevent_fdtrigger, d);
	}
	inline ~fdp() {
	    ::event_del(&base);
	}
	inline void move(driver_libevent *d, int fd, fdp &other) {
	    int x = ::event_pending(&other.base, EV_READ | EV_WRITE, 0)
		& (EV_READ | EV_WRITE);
	    ::event_del(&other.base);
	    ::event_set(&base, fd, x | EV_PERSIST, libevent_fdtrigger, d);
	    if (x)
		::event_add(&base, 0);
	}
    };

    driver_fdset<fdp> fds_;
    int fdactive_;
    ::event signal_base_;

    event_group *_egroup;
    eevent *_efree;
    size_t _ecap;
    eevent *_esignal;

    void expand_events();
    static void fd_disinterest(void *driver, int fd);
    void update_fds();
};

extern "C" {
void libevent_fdtrigger(int fd, short what, void *arg) {
    driver_libevent *d = static_cast<driver_libevent *>(arg);
    driver_fd<driver_libevent::fdp> &x = d->fds_[fd];
    if (what & EV_READ)
	x.e[0].trigger(0);
    if (what & EV_WRITE)
	x.e[1].trigger(0);
    d->fds_.push_change(fd);
}

void libevent_trigger(int, short, void *arg) {
    driver_libevent::eevent *e = static_cast<driver_libevent::eevent *>(arg);
    e->se->simple_trigger(true);
    *e->pprev = e->next;
    if (e->next)
	e->next->pprev = e->pprev;
    e->next = e->driver->_efree;
    e->driver->_efree = e;
}

void libevent_sigtrigger(int, short, void *arg)
{
    driver_libevent::eevent *e = static_cast<driver_libevent::eevent *>(arg);
    e->driver->dispatch_signals();
}
} // extern "C"

driver_libevent::driver_libevent()
    : _etimer(0), fdactive_(0), _egroup(0), _efree(0), _ecap(0)
{
    ::event_init();
    ::event_priority_init(3);
#if HAVE_EVENT_GET_STRUCT_EVENT_SIZE
    assert(sizeof(::event) >= event_get_struct_event_size());
#endif
    set_now();
    at_signal(0, event<>());	// create signal_fd pipe
    ::event_set(&signal_base_, sig_pipe[0], EV_READ | EV_PERSIST,
		libevent_sigtrigger, this);
    ::event_priority_set(&signal_base_, 0);
    ::event_add(&signal_base_, 0);
}

driver_libevent::~driver_libevent() {
    // discard all active events
    while (_etimer) {
	_etimer->se->simple_trigger(false);
	::event_del(&_etimer->libevent);
	_etimer = _etimer->next;
    }
    ::event_del(&signal_base_);

    // free event groups
    while (_egroup) {
	event_group *next = _egroup->next;
	delete[] reinterpret_cast<unsigned char *>(_egroup);
	_egroup = next;
    }
}

void driver_libevent::expand_events() {
    size_t ncap = (_ecap ? _ecap * 2 : 16);

    event_group *ngroup = reinterpret_cast<event_group *>(new unsigned char[sizeof(event_group) + sizeof(eevent) * (ncap - 1)]);
    ngroup->next = _egroup;
    _egroup = ngroup;
    for (size_t i = 0; i < ncap; i++) {
	ngroup->e[i].driver = this;
	ngroup->e[i].next = _efree;
	_efree = &ngroup->e[i];
    }
}

void driver_libevent::fd_disinterest(void *arg, int fd) {
    driver_libevent *d = static_cast<driver_libevent *>(arg);
    d->fds_.push_change(fd);
}

void driver_libevent::at_fd(int fd, int action, event<int> e) {
    assert(fd >= 0);
    if (e && (action == 0 || action == 1)) {
	fds_.expand(this, fd);
	driver_fd<fdp> &x = fds_[fd];
	if (x.e[action])
	    e = tamer::distribute(TAMER_MOVE(x.e[action]), TAMER_MOVE(e));
	x.e[action] = e;
	tamerpriv::simple_event::at_trigger(e.__get_simple(),
					    fd_disinterest, this, fd);
	fds_.push_change(fd);
    }
}

void driver_libevent::kill_fd(int fd) {
    if (fd >= 0 && fd < fds_.nfds_) {
	driver_fd<fdp> &x = fds_[fd];
	for (int action = 0; action < 2; ++action)
	    x.e[action].trigger(-ECANCELED);
	fds_.push_change(fd);
    }
}

void driver_libevent::update_fds() {
    int fd;
    while ((fd = fds_.pop_change()) >= 0) {
	driver_fd<fdp> &x = fds_[fd];
	int want_what = (x.e[0] ? EV_READ : 0) | (x.e[1] ? EV_WRITE : 0);
	int have_what = ::event_pending(&x.base, EV_READ | EV_WRITE, 0)
	    & (EV_READ | EV_WRITE);
	if (want_what != have_what) {
	    fdactive_ += (want_what != 0) - (have_what != 0);
	    if (have_what != 0)
		::event_del(&x.base);
	    if (want_what != 0) {
		::event_set(&x.base, fd, want_what | EV_PERSIST,
			    libevent_fdtrigger, this);
		::event_add(&x.base, 0);
	    }
	}
    }
}

void driver_libevent::at_time(const timeval &expiry, event<> e)
{
    if (!_efree)
	expand_events();
    if (e) {
	eevent *ee = _efree;
	_efree = ee->next;

	evtimer_set(&ee->libevent, libevent_trigger, ee);
	timeval timeout = expiry;
	timersub(&timeout, &now, &timeout);
	evtimer_add(&ee->libevent, &timeout);

	ee->se = e.__take_simple();
	ee->next = _etimer;
	ee->pprev = &_etimer;
	if (_etimer)
	    _etimer->pprev = &ee->next;
	_etimer = ee;
    }
}

void driver_libevent::cull() {
    while (_etimer && !*_etimer->se) {
	eevent *e = _etimer;
	::event_del(&e->libevent);
	tamerpriv::simple_event::unuse_clean(_etimer->se);
	if ((_etimer = e->next))
	    _etimer->pprev = &_etimer;
	e->next = _efree;
	_efree = e;
    }
}

void driver_libevent::loop(loop_flags flags)
{
 again:
    // fix file descriptors
    if (fds_.has_change())
	update_fds();

    int event_flags = EVLOOP_ONCE;
    if (sig_any_active
	|| tamerpriv::abstract_rendezvous::has_unblocked())
	event_flags |= EVLOOP_NONBLOCK;
    else {
	cull();
	if (!_etimer && fdactive_ == 0 && sig_nforeground == 0)
	    // no events scheduled
	    return;
    }

    ::event_loop(event_flags);

    set_now();
    while (tamerpriv::abstract_rendezvous *r = tamerpriv::abstract_rendezvous::pop_unblocked())
	r->run();
    if (flags == loop_forever)
	goto again;
}

} // namespace
#endif

driver *driver::make_libevent()
{
#if HAVE_LIBEVENT
    return new driver_libevent;
#else
    return 0;
#endif
}

} // namespace tamer
<|endoftext|>


<commit_before>#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup(){
    ofBackground(0);
    ofSetLogLevel(OF_LOG_VERBOSE);
    // basic connection:
    // client.connect("echo.websocket.org");
    // OR optionally use SSL
    // client.connect("echo.websocket.org", true);

    // advanced: set keep-alive timeouts for events like
    // loss of internet

    // 1 - get default options
    ofxLibwebsockets::ClientOptions options = ofxLibwebsockets::defaultClientOptions();

    // 2 - set basic params
    options.host = "echo.websocket.org";

    // 3 - set keep alive params
    // BIG GOTCHA: on BSD systems, e.g. Mac OS X, these time params are system-wide
    // ...so ka_time just says "check if alive when you want" instead of "check if
    // alive after X seconds"
    options.ka_time     = 1;
//    options.ka_probes   = 1;
//    options.ka_interval = 1;

    // 4 - connect
    client.connect(options);

    ofSetLogLevel(OF_LOG_ERROR);

    client.addListener(this);
    ofSetFrameRate(60);
}

//--------------------------------------------------------------
void ofApp::update(){
}

//--------------------------------------------------------------
void ofApp::draw(){
    ofDrawBitmapString("Type anywhere to send 'hello' to your server\nCheck the console for output!", 10,20);
    ofDrawBitmapString(client.isConnected() ? "Client is connected" : "Client disconnected :(", 10,50);
}

//--------------------------------------------------------------
void ofApp::onConnect( ofxLibwebsockets::Event& args ){
    cout<<"on connected"<<endl;
}

//--------------------------------------------------------------
void ofApp::onOpen( ofxLibwebsockets::Event& args ){
    cout<<"on open"<<endl;
}

//--------------------------------------------------------------
void ofApp::onClose( ofxLibwebsockets::Event& args ){
    cout<<"on close"<<endl;
}

//--------------------------------------------------------------
void ofApp::onIdle( ofxLibwebsockets::Event& args ){
    cout<<"on idle"<<endl;
}

//--------------------------------------------------------------
void ofApp::onMessage( ofxLibwebsockets::Event& args ){
    cout<<"got message "<<args.message<<endl;
}

//--------------------------------------------------------------
void ofApp::onBroadcast( ofxLibwebsockets::Event& args ){
    cout<<"got broadcast "<<args.message<<endl;
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){

    client.send("Hello");
    cout << "sending hello" <<endl;
}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}<commit_msg>Defaulting to simplest connection in 'Hello World'<commit_after>#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup(){
    ofBackground(0);
    ofSetLogLevel(OF_LOG_VERBOSE);
    // basic connection:
     client.connect("echo.websocket.org");
    // OR optionally use SSL
//     client.connect("echo.websocket.org", true);

    // advanced: set keep-alive timeouts for events like
    // loss of internet

    // 1 - get default options
//    ofxLibwebsockets::ClientOptions options = ofxLibwebsockets::defaultClientOptions();

    // 2 - set basic params
//    options.host = "echo.websocket.org";

    // 3 - set keep alive params
    // BIG GOTCHA: on BSD systems, e.g. Mac OS X, these time params are system-wide
    // ...so ka_time just says "check if alive when you want" instead of "check if
    // alive after X seconds"
//    options.ka_time     = 1;
//    options.ka_probes   = 1;
//    options.ka_interval = 1;

    // 4 - connect
//    client.connect(options);

    ofSetLogLevel(OF_LOG_ERROR);

    client.addListener(this);
    ofSetFrameRate(60);
}

//--------------------------------------------------------------
void ofApp::update(){
}

//--------------------------------------------------------------
void ofApp::draw(){
    ofDrawBitmapString("Type anywhere to send 'hello' to your server\nCheck the console for output!", 10,20);
    ofDrawBitmapString(client.isConnected() ? "Client is connected" : "Client disconnected :(", 10,50);
}

//--------------------------------------------------------------
void ofApp::onConnect( ofxLibwebsockets::Event& args ){
    cout<<"on connected"<<endl;
}

//--------------------------------------------------------------
void ofApp::onOpen( ofxLibwebsockets::Event& args ){
    cout<<"on open"<<endl;
}

//--------------------------------------------------------------
void ofApp::onClose( ofxLibwebsockets::Event& args ){
    cout<<"on close"<<endl;
}

//--------------------------------------------------------------
void ofApp::onIdle( ofxLibwebsockets::Event& args ){
    cout<<"on idle"<<endl;
}

//--------------------------------------------------------------
void ofApp::onMessage( ofxLibwebsockets::Event& args ){
    cout<<"got message "<<args.message<<endl;
}

//--------------------------------------------------------------
void ofApp::onBroadcast( ofxLibwebsockets::Event& args ){
    cout<<"got broadcast "<<args.message<<endl;
}

//--------------------------------------------------------------
void ofApp::keyPressed(int key){

    client.send("Hello");
    cout << "sending hello" <<endl;
}

//--------------------------------------------------------------
void ofApp::keyReleased(int key){

}

//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){

}

//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}

//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){

}

//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){

}

//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){

}

//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){

}<|endoftext|>


<commit_before>
/*
 * Copyright 2013 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkPathUtils.h"

#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkRandom.h"
#include "SkTime.h"
#include "Test.h"

class SkBitmap;

const int kNumIt = 100;

static void fill_random_bits( int chars, char* bits ){
    SkMWCRandom rand(SkTime::GetMSecs());

    for (int i = 0; i < chars; ++i){
        bits[i] = rand.nextU();
    }
}

static int get_bit( const char* buffer, int x ) {
    int byte = x >> 3;
    int bit = x & 7;

    return buffer[byte] & (128 >> bit);
}

/* // useful for debugging errors
   #include <iostream>
static void print_bits( const char* bits, int w, int h) {

    for (int y = 0; y < h; ++y) {
        for (int x = 0; x < w; ++x){
            bool bit = get_bit(&bits[y], x)!=0;
            std::cout << bit;
            }
        std::cout << std::endl;
    }
}

static void print_bmp( SkBitmap* bmp, int w, int h){

    for (int y = 0; y < h; ++y) {
        for (int x = 0; x < w; ++x) {
            int d = *bmp->getAddr32(x,y);
            if (d == -1)
                std::cout << 0;
            else
                std::cout << 1;
        }
        std::cout << std::endl;
    }
}
*/

static void binary_to_skbitmap(const char* bin_bmp, SkBitmap* sk_bmp,
                         int w, int h, int rowBytes){
    //init the SkBitmap
    sk_bmp->setConfig(SkBitmap::kARGB_8888_Config, w, h);
    sk_bmp->allocPixels();

    for (int y = 0; y < h; ++y) { // for every row

        const char* curLine = &bin_bmp[y * rowBytes];
        for (int x = 0; x < w; ++x) {// for every pixel
            if (get_bit(curLine, x)) {
                *sk_bmp->getAddr32(x,y) = SK_ColorBLACK;
            }
            else {
                *sk_bmp->getAddr32(x,y) = SK_ColorWHITE;
            }
        }
    }
}

static bool test_bmp(skiatest::Reporter* reporter,
                      const SkBitmap* bmp1, const SkBitmap* bmp2,
                      int w, int h) {
    for (int y = 0; y < h; ++y) { // loop through all pixels
        for (int x = 0; x < w; ++x) {
            REPORTER_ASSERT( reporter, *bmp1->getAddr32(x,y) == *bmp2->getAddr32(x,y) );
        }
    }
    return true;
}

static void test_path_eq(skiatest::Reporter* reporter, const SkPath* path,
                      const SkBitmap* truth, int w, int h){
    // make paint
    SkPaint bmpPaint;
    bmpPaint.setAntiAlias(true);  // Black paint for bitmap
    bmpPaint.setStyle(SkPaint::kFill_Style);
    bmpPaint.setColor(SK_ColorBLACK);

    // make bmp
    SkBitmap bmp;
    bmp.setConfig(SkBitmap::kARGB_8888_Config, w, h);
    bmp.allocPixels();
    SkCanvas canvas(bmp);
    canvas.clear(SK_ColorWHITE);
    canvas.drawPath(*path, bmpPaint);

    // test bmp
    test_bmp(reporter, truth, &bmp, w, h);
}

static void test_path(skiatest::Reporter* reporter, const SkBitmap* truth,
                            const char* bin_bmp, int w, int h, int rowBytes){
    // make path
    SkPath path;
    SkPathUtils::BitsToPath_Path(&path, bin_bmp, w, h, rowBytes);

    //test for correctness
    test_path_eq(reporter, &path, truth, w, h);
}

static void test_region(skiatest::Reporter* reporter, const SkBitmap* truth,
                            const char* bin_bmp, int w, int h, int rowBytes){
    //generate bitmap
    SkPath path;
    SkPathUtils::BitsToPath_Region(&path, bin_bmp, w, h, rowBytes);

    //test for correctness
    test_path_eq(reporter, &path, truth, w, h);
}

static void TestPathUtils(skiatest::Reporter* reporter) {
    const int w[] = {4, 8, 12, 16};
    const int h = 8, rowBytes = 4;

    char bits[ h * rowBytes ];
    static char* binBmp = &bits[0];

    //loop to run randomized test lots of times
    for (int it = 0; it < kNumIt; ++it)
    {
        // generate a random binary bitmap
        fill_random_bits( h * rowBytes, binBmp); // generate random bitmap

        // for each bitmap width, use subset of binary bitmap
        for (unsigned int i = 0; i < SK_ARRAY_COUNT(w); ++i) {
            // generate truth bitmap
            SkBitmap bmpTruth;
            binary_to_skbitmap(binBmp, &bmpTruth, w[i], h, rowBytes);

            test_path(reporter, &bmpTruth, binBmp, w[i], h, rowBytes);
            test_region(reporter, &bmpTruth, binBmp, w[i], h, rowBytes);
        }
    }
}

#include "TestClassDef.h"
DEFINE_TESTCLASS("PathUtils", PathUtils, TestPathUtils)
<commit_msg>NIT MASTER 9000<commit_after>
/*
 * Copyright 2013 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkPathUtils.h"

#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkRandom.h"
#include "SkTime.h"
#include "Test.h"

const int kNumIt = 100;

static void fill_random_bits(int chars, char* bits){
    SkMWCRandom rand(SkTime::GetMSecs());

    for (int i = 0; i < chars; ++i){
        bits[i] = rand.nextU();
    }
}

static int get_bit(const char* buffer, int x) {
    int byte = x >> 3;
    int bit = x & 7;

    return buffer[byte] & (128 >> bit);
}

/* // useful for debugging errors
   #include <iostream>
static void print_bits( const char* bits, int w, int h) {

    for (int y = 0; y < h; ++y) {
        for (int x = 0; x < w; ++x){
            bool bit = get_bit(&bits[y], x)!=0;
            std::cout << bit;
            }
        std::cout << std::endl;
    }
}

static void print_bmp( SkBitmap* bmp, int w, int h){

    for (int y = 0; y < h; ++y) {
        for (int x = 0; x < w; ++x) {
            int d = *bmp->getAddr32(x,y);
            if (d == -1)
                std::cout << 0;
            else
                std::cout << 1;
        }
        std::cout << std::endl;
    }
}
*/

static void binary_to_skbitmap(const char* bin_bmp, SkBitmap* sk_bmp,
                         int w, int h, int rowBytes){
    //init the SkBitmap
    sk_bmp->setConfig(SkBitmap::kARGB_8888_Config, w, h);
    sk_bmp->allocPixels();

    for (int y = 0; y < h; ++y) { // for every row

        const char* curLine = &bin_bmp[y * rowBytes];
        for (int x = 0; x < w; ++x) {// for every pixel
            if (get_bit(curLine, x)) {
                *sk_bmp->getAddr32(x,y) = SK_ColorBLACK;
            }
            else {
                *sk_bmp->getAddr32(x,y) = SK_ColorWHITE;
            }
        }
    }
}

static bool test_bmp(skiatest::Reporter* reporter,
                      const SkBitmap* bmp1, const SkBitmap* bmp2,
                      int w, int h) {
    for (int y = 0; y < h; ++y) { // loop through all pixels
        for (int x = 0; x < w; ++x) {
            REPORTER_ASSERT( reporter, *bmp1->getAddr32(x,y) == *bmp2->getAddr32(x,y) );
        }
    }
    return true;
}

static void test_path_eq(skiatest::Reporter* reporter, const SkPath* path,
                      const SkBitmap* truth, int w, int h){
    // make paint
    SkPaint bmpPaint;
    bmpPaint.setAntiAlias(true);  // Black paint for bitmap
    bmpPaint.setStyle(SkPaint::kFill_Style);
    bmpPaint.setColor(SK_ColorBLACK);

    // make bmp
    SkBitmap bmp;
    bmp.setConfig(SkBitmap::kARGB_8888_Config, w, h);
    bmp.allocPixels();
    SkCanvas canvas(bmp);
    canvas.clear(SK_ColorWHITE);
    canvas.drawPath(*path, bmpPaint);

    // test bmp
    test_bmp(reporter, truth, &bmp, w, h);
}

static void test_path(skiatest::Reporter* reporter, const SkBitmap* truth,
                            const char* bin_bmp, int w, int h, int rowBytes){
    // make path
    SkPath path;
    SkPathUtils::BitsToPath_Path(&path, bin_bmp, w, h, rowBytes);

    //test for correctness
    test_path_eq(reporter, &path, truth, w, h);
}

static void test_region(skiatest::Reporter* reporter, const SkBitmap* truth,
                            const char* bin_bmp, int w, int h, int rowBytes){
    //generate bitmap
    SkPath path;
    SkPathUtils::BitsToPath_Region(&path, bin_bmp, w, h, rowBytes);

    //test for correctness
    test_path_eq(reporter, &path, truth, w, h);
}

static void TestPathUtils(skiatest::Reporter* reporter) {
    const int w[] = {4, 8, 12, 16};
    const int h = 8, rowBytes = 4;

    char bits[ h * rowBytes ];
    static char* binBmp = &bits[0];

    //loop to run randomized test lots of times
    for (int it = 0; it < kNumIt; ++it)
    {
        // generate a random binary bitmap
        fill_random_bits( h * rowBytes, binBmp); // generate random bitmap

        // for each bitmap width, use subset of binary bitmap
        for (unsigned int i = 0; i < SK_ARRAY_COUNT(w); ++i) {
            // generate truth bitmap
            SkBitmap bmpTruth;
            binary_to_skbitmap(binBmp, &bmpTruth, w[i], h, rowBytes);

            test_path(reporter, &bmpTruth, binBmp, w[i], h, rowBytes);
            test_region(reporter, &bmpTruth, binBmp, w[i], h, rowBytes);
        }
    }
}

#include "TestClassDef.h"
DEFINE_TESTCLASS("PathUtils", PathUtils, TestPathUtils)
<|endoftext|>


<commit_before>/*
 * LARObj.cpp
 *
 *  Created on: 08 apr 2016
 *  Author: Salvati Danilo
 *  License: MIT License https://opensource.org/licenses/MIT
 *
 */
#include "LARObj.h"
#include "LARcpp.h"
#include <iostream>
#include <fstream>

std::pair<std::deque<Eigen::Vector3f>,
		std::deque<Eigen::SparseMatrix<int, Eigen::RowMajor, int> > > LAR::IO::LARObj::readModel(
		const std::string filePath) {

	std::string line;
	std::ifstream myfile();
        myfile.std::open(filePath);

	std::deque<Eigen::Vector3f> vectorList;
	std::deque<Eigen::SparseMatrix<int, Eigen::RowMajor, int> > relationships;
	std::deque<std::vector<int> > facesList;
	if (myfile.std::is_open()) {
		std::vector<std::string> tokens;
		while (std::getline(myfile, line)) {
			tokens = tokenize(line);
			if (tokens[0] == "v") {
				// I am reading a vertex line
                                float coordinatesArray[] = {atof(tokens[1].c_str()), atof(tokens[2].c_str()), atof(tokens[3].c_str())};
                                std::vector<float> coordinates(coordinatesArray, coordinatesArray + sizeof(coordinatesArray) / sizeof(float));
				vectorList.push_back(
						Eigen::Vector3f(coordinates.data());
			} else {
				// I am reading a face line
                                std::vector<int> facesArray = {atoi(tokens[1].c_str()), atoi(tokens[2].c_str()), atoi(tokens[3].c_str())}
                                std::vector<float> faces(facesArray, facesArray + sizeof(facesArray) / sizeof(int));
				facesList.push_back(
						std::vector<int>(faces.data()));
			}
			myfile.close();
		}
	} else {
		throw "Unable to open file " + filePath;
	}

	LAR::LARcpp larcpp;
	relationships.push_back(larcpp.brcToMatrix(facesList));
	return std::pair(vectorList, relationships);
}

void LAR::IO::LARObj::writeModel(std::deque<Eigen::Vector3f> verticesList,
		Eigen::SparseMatrix<int, Eigen::RowMajor, int> topologicalRelationship,
		std::string outputPath) {

}

/** tokenizer function for strings **/
std::vector<std::string> LAR::IO::LARObj::tokenize(const std::string& str,
		const std::string& delimiters = " ") {

	std::vector<std::string> tokens;

	// Skip delimiters at beginning.
	std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);

	// Find first "non-delimiter".
	std::string::size_type pos = str.find_first_of(delimiters, lastPos);

	while (std::string::npos != pos || std::string::npos != lastPos) {
		// Found a token, add it to the vector.
		tokens.push_back(str.substr(lastPos, pos - lastPos));

		// Skip delimiters.  Note the "not_of"
		lastPos = str.find_first_not_of(delimiters, pos);

		// Find next "non-delimiter"
		pos = str.find_first_of(delimiters, lastPos);
	}
	return tokens;
}
<commit_msg>Fixed some bugs<commit_after>/*
 * LARObj.cpp
 *
 *  Created on: 08 apr 2016
 *  Author: Salvati Danilo
 *  License: MIT License https://opensource.org/licenses/MIT
 *
 */
#include "LARObj.h"
#include "LARcpp.h"
#include <iostream>
#include <string>
#include <fstream>

std::pair<std::deque<Eigen::Vector3f>,
		std::deque<Eigen::SparseMatrix<int, Eigen::RowMajor, int> > > LAR::IO::LARObj::readModel(
		const std::string filePath) {

	std::string line;
	std::ifstream myfile();
        myfile.open(filePath);

	std::deque<Eigen::Vector3f> vectorList;
	std::deque<Eigen::SparseMatrix<int, Eigen::RowMajor, int> > relationships;
	std::deque<std::vector<int> > facesList;
	if (myfile.is_open()) {
		std::vector<std::string> tokens;
		while (std::getline(myfile, line)) {
			tokens = tokenize(line, " ");
			if (tokens[0] == "v") {
				// I am reading a vertex line
                                float coordinatesArray[] = {atof(tokens[1].c_str()), atof(tokens[2].c_str()), atof(tokens[3].c_str())};
                                std::vector<float> coordinates(coordinatesArray, coordinatesArray + sizeof(coordinatesArray) / sizeof(float));
				vectorList.push_back(
						Eigen::Vector3f(coordinates.data());
			} else {
				// I am reading a face line
                                int facesArray[] = {atoi(tokens[1].c_str()), atoi(tokens[2].c_str()), atoi(tokens[3].c_str())};
                                std::vector<float> faces(facesArray, facesArray + sizeof(facesArray) / sizeof(int));
				facesList.push_back(
						std::vector<int>(faces.data()));
			}
			myfile.close();
		}
	} else {
		throw "Unable to open file " + filePath;
	}

	LAR::LARcpp larcpp;
	relationships.push_back(larcpp.brcToMatrix(facesList));
	return std::pair<std::deque<Eigen::Vector3f>,
		std::deque<Eigen::SparseMatrix<int, Eigen::RowMajor, int> > > (vectorList, relationships);
}

void LAR::IO::LARObj::writeModel(std::deque<Eigen::Vector3f> verticesList,
		Eigen::SparseMatrix<int, Eigen::RowMajor, int> topologicalRelationship,
		std::string outputPath) {

}

/** tokenizer function for strings **/
std::vector<std::string> LAR::IO::LARObj::tokenize(const std::string& str,
		const std::string& delimiters = " ") {

	std::vector<std::string> tokens;

	// Skip delimiters at beginning.
	std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);

	// Find first "non-delimiter".
	std::string::size_type pos = str.find_first_of(delimiters, lastPos);

	while (std::string::npos != pos || std::string::npos != lastPos) {
		// Found a token, add it to the vector.
		tokens.push_back(str.substr(lastPos, pos - lastPos));

		// Skip delimiters.  Note the "not_of"
		lastPos = str.find_first_not_of(delimiters, pos);

		// Find next "non-delimiter"
		pos = str.find_first_of(delimiters, lastPos);
	}
	return tokens;
}<|endoftext|>


<commit_before>/*
* Copyright (C) 2008-2012 J-P Nurmi <jpnurmi@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*/

#include "messageview.h"
#include "menufactory.h"
#include "completer.h"
#include "usermodel.h"
#include "session.h"
#include <QAbstractTextDocumentLayout>
#include <QDesktopServices>
#include <QStringListModel>
#include <QTextBlock>
#include <QShortcut>
#include <QKeyEvent>
#include <QDateTime>
#include <QDebug>
#include <QUrl>
#include <ircmessage.h>
#include <irccommand.h>
#include <ircutil.h>
#include <irc.h>

static QStringListModel* command_model = 0;
static const int VERTICAL_MARGIN = 1; // matches qlineedit_p.cpp

MessageView::MessageView(MessageView::ViewType type, Session* session, QWidget* parent) :
    QWidget(parent)
{
    d.setupUi(this);
    d.viewType = type;

    d.topicLabel->setMinimumHeight(d.lineEditor->sizeHint().height());
    d.helpLabel->setMinimumHeight(d.lineEditor->sizeHint().height());

    connect(d.splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(onSplitterMoved()));

    setFocusProxy(d.lineEditor);
    d.textBrowser->setBuddy(d.lineEditor);
    d.textBrowser->viewport()->installEventFilter(this);
    connect(d.textBrowser, SIGNAL(anchorClicked(QUrl)), SLOT(onAnchorClicked(QUrl)));

    d.formatter = new MessageFormatter(this);
    d.formatter->setHighlights(QStringList(session->nickName()));
    d.formatter->setMessageFormat("class='message'");
    d.formatter->setEventFormat("class='event'");
    d.formatter->setNoticeFormat("class='notice'");
    d.formatter->setActionFormat("class='action'");
    d.formatter->setUnknownFormat("class='unknown'");
    d.formatter->setHighlightFormat("class='highlight'");
    d.formatter->setTimeStampFormat("class='timestamp'");

    d.session = session;
    connect(&d.parser, SIGNAL(customCommand(QString, QStringList)), this, SLOT(onCustomCommand(QString, QStringList)));

    d.topicLabel->setVisible(type == ChannelView);
    d.listView->setVisible(type == ChannelView);
    if (type == ChannelView) {
        d.listView->setSession(session);
        connect(d.listView, SIGNAL(queried(QString)), this, SIGNAL(queried(QString)));
        connect(d.listView, SIGNAL(doubleClicked(QString)), this, SIGNAL(queried(QString)));
        connect(d.listView, SIGNAL(commandRequested(IrcCommand*)), d.session, SLOT(sendCommand(IrcCommand*)));
    }

    if (!command_model) {
        CommandParser::addCustomCommand("QUERY", "<user>");

        QStringList prefixedCommands;
        foreach(const QString & command, CommandParser::availableCommands())
        prefixedCommands += "/" + command;

        command_model = new QStringListModel(qApp);
        command_model->setStringList(prefixedCommands);
    }

    d.lineEditor->completer()->setDefaultModel(d.listView->userModel());
    d.lineEditor->completer()->setSlashModel(command_model);

    connect(d.lineEditor, SIGNAL(send(QString)), this, SLOT(onSend(QString)));
    connect(d.lineEditor, SIGNAL(typed(QString)), this, SLOT(showHelp(QString)));

    d.helpLabel->hide();
    d.searchEditor->setTextEdit(d.textBrowser);

    QShortcut* shortcut = new QShortcut(Qt::Key_Escape, this);
    connect(shortcut, SIGNAL(activated()), this, SLOT(onEscPressed()));

    applySettings(d.settings);
}

MessageView::~MessageView()
{
}

MessageView::ViewType MessageView::viewType() const
{
    return d.viewType;
}

Session* MessageView::session() const
{
    return d.session;
}

QTextBrowser* MessageView::textBrowser() const
{
    return d.textBrowser;
}

MessageFormatter* MessageView::messageFormatter() const
{
    return d.formatter;
}

QString MessageView::receiver() const
{
    return d.receiver;
}

void MessageView::setReceiver(const QString& receiver)
{
    d.receiver = receiver;
    if (d.viewType == ChannelView)
        d.listView->setChannel(receiver);
}

MenuFactory* MessageView::menuFactory() const
{
    return d.listView->menuFactory();
}

void MessageView::setMenuFactory(MenuFactory* factory)
{
    d.listView->setMenuFactory(factory);
}

QByteArray MessageView::saveSplitter() const
{
    if (d.viewType != ServerView)
        return d.splitter->saveState();
    return QByteArray();
}

void MessageView::restoreSplitter(const QByteArray& state)
{
    d.splitter->restoreState(state);
}

void MessageView::showHelp(const QString& text, bool error)
{
    QString syntax;
    if (text == "/") {
        QStringList commands = CommandParser::availableCommands();
        syntax = commands.join(" ");
    } else if (text.startsWith('/')) {
        QStringList words = text.mid(1).split(' ');
        QString command = words.value(0);
        QStringList suggestions = CommandParser::suggestedCommands(command, words.mid(1));
        if (suggestions.count() == 1)
            syntax = CommandParser::syntax(suggestions.first());
        else
            syntax = suggestions.join(" ");

        if (syntax.isEmpty() && error)
            syntax = tr("Unknown command '%1'").arg(command.toUpper());
    }

    d.helpLabel->setVisible(!syntax.isEmpty());
    QPalette pal;
    if (error)
        pal.setColor(QPalette::WindowText, d.settings.colors[Settings::Highlight]);
    d.helpLabel->setPalette(pal);
    d.helpLabel->setText(syntax);
}

void MessageView::appendMessage(const QString& message)
{
    if (!message.isEmpty()) {
        // workaround the link activation merge char format bug
        QString copy = message;
        if (copy.endsWith("</a>"))
            copy += " ";

        d.textBrowser->append(copy);
        if (!isVisible() && d.textBrowser->unseenBlock() == -1)
            d.textBrowser->setUnseenBlock(d.textBrowser->document()->blockCount() - 1);

#if QT_VERSION >= 0x040800
        QTextBlock block = d.textBrowser->document()->lastBlock();
        QTextBlockFormat format = block.blockFormat();
        format.setLineHeight(120, QTextBlockFormat::ProportionalHeight);
        QTextCursor cursor(block);
        cursor.setBlockFormat(format);
#endif // QT_VERSION
    }
}

void MessageView::hideEvent(QHideEvent* event)
{
    QWidget::hideEvent(event);
    d.textBrowser->setUnseenBlock(-1);
}

bool MessageView::eventFilter(QObject* object, QEvent* event)
{
    if (object == d.textBrowser->viewport() && event->type() == QEvent::ContextMenu) {
        QContextMenuEvent* menuEvent = static_cast<QContextMenuEvent*>(event);
        QAbstractTextDocumentLayout* layout = d.textBrowser->document()->documentLayout();
        QUrl link(layout->anchorAt(menuEvent->pos()));
        if (link.scheme() == "nick") {
            QMenu* standardMenu = d.textBrowser->createStandardContextMenu(menuEvent->pos());
            QMenu* customMenu = d.listView->menuFactory()->createUserViewMenu(link.toString(QUrl::RemoveScheme), this);
            customMenu->addSeparator();
            customMenu->insertActions(0, standardMenu->actions());
            customMenu->exec(menuEvent->globalPos());
            customMenu->deleteLater();
            delete standardMenu;
            return true;
        }
    }
    return QWidget::eventFilter(object, event);
}

void MessageView::onEscPressed()
{
    d.helpLabel->hide();
    d.searchEditor->hide();
    setFocus(Qt::OtherFocusReason);
}

void MessageView::onSplitterMoved()
{
    emit splitterChanged(d.splitter->saveState());
}

void MessageView::onSend(const QString& text)
{
    IrcCommand* cmd = d.parser.parseCommand(receiver(), text);
    if (cmd) {
        d.session->sendCommand(cmd);

        if (cmd->type() == IrcCommand::Message || cmd->type() == IrcCommand::CtcpAction) {
            IrcMessage* msg = IrcMessage::fromCommand(d.session->nickName(), cmd, d.session);
            receiveMessage(msg);
            delete msg;
        }
    } else if (d.parser.hasError()) {
        showHelp(text, true);
    }
}

void MessageView::onAnchorClicked(const QUrl& link)
{
    if (link.scheme() == "nick")
        emit queried(link.toString(QUrl::RemoveScheme));
    else
        QDesktopServices::openUrl(link);
}

void MessageView::applySettings(const Settings& settings)
{
    d.formatter->setTimeStamp(settings.timeStamp);
    d.formatter->setStripNicks(settings.stripNicks);

    if (!settings.font.isEmpty())
        d.textBrowser->setFont(settings.font);
    d.textBrowser->document()->setMaximumBlockCount(settings.maxBlockCount);
    d.topicLabel->setProperty("gradient", settings.layout == "tree");

    QTextDocument* doc = d.topicLabel->findChild<QTextDocument*>();
    if (doc)
        doc->setDefaultStyleSheet(QString("a { color: %1 }").arg(settings.colors.value(Settings::Link)));

    QString backgroundColor = settings.colors.value(Settings::Background);
    d.textBrowser->setStyleSheet(QString("QTextBrowser { background-color: %1 }").arg(backgroundColor));

    d.textBrowser->document()->setDefaultStyleSheet(
        QString(
            ".highlight { color: %1 }"
            ".message   { color: %2 }"
            ".notice    { color: %3 }"
            ".action    { color: %4 }"
            ".event     { color: %5 }"
            ".timestamp { color: %6; font-size: small }"
            "a { color: %7 }"
        ).arg(settings.colors.value(Settings::Highlight))
        .arg(settings.colors.value(Settings::Message))
        .arg(settings.colors.value(Settings::Notice))
        .arg(settings.colors.value(Settings::Action))
        .arg(settings.colors.value(Settings::Event))
        .arg(settings.colors.value(Settings::TimeStamp))
        .arg(settings.colors.value(Settings::Link)));
    d.settings = settings;
}

void MessageView::receiveMessage(IrcMessage* message)
{
    if (d.viewType == ChannelView)
        d.listView->processMessage(message);

    bool append = true;
    bool hilite = false;
    bool matches = false;

    switch (message->type()) {
        case IrcMessage::Join:
            append = d.settings.messages.value(Settings::Joins);
            hilite = d.settings.highlights.value(Settings::Joins);
            break;
        case IrcMessage::Kick:
            append = d.settings.messages.value(Settings::Kicks);
            hilite = d.settings.highlights.value(Settings::Kicks);
            break;
        case IrcMessage::Mode:
            append = d.settings.messages.value(Settings::Modes);
            hilite = d.settings.highlights.value(Settings::Modes);
            break;
        case IrcMessage::Nick:
            append = d.settings.messages.value(Settings::Nicks);
            hilite = d.settings.highlights.value(Settings::Nicks);
            break;
        case IrcMessage::Notice:
            matches = static_cast<IrcNoticeMessage*>(message)->message().contains(d.session->nickName());
            hilite = true;
            break;
        case IrcMessage::Part:
            append = d.settings.messages.value(Settings::Parts);
            hilite = d.settings.highlights.value(Settings::Parts);
            break;
        case IrcMessage::Private:
            matches = d.viewType != ChannelView || static_cast<IrcPrivateMessage*>(message)->message().contains(d.session->nickName());
            hilite = true;
            break;
        case IrcMessage::Quit:
            append = d.settings.messages.value(Settings::Quits);
            hilite = d.settings.highlights.value(Settings::Quits);
            break;
        case IrcMessage::Topic:
            append = d.settings.messages.value(Settings::Topics);
            hilite = d.settings.highlights.value(Settings::Topics);
            d.topicLabel->setText(d.formatter->formatHtml(static_cast<IrcTopicMessage*>(message)->topic()));
            if (d.topicLabel->text().isEmpty())
                d.topicLabel->setText(tr("-"));
            break;
        case IrcMessage::Unknown:
            qWarning() << "unknown:" << message;
            append = false;
            break;
        case IrcMessage::Invite:
        case IrcMessage::Ping:
        case IrcMessage::Pong:
        case IrcMessage::Error:
            break;
        case IrcMessage::Numeric:
            switch (static_cast<IrcNumericMessage*>(message)->code()) {
                case Irc::RPL_NOTOPIC:
                    d.topicLabel->setText(tr("-"));
                    break;
                case Irc::RPL_TOPIC:
                    d.topicLabel->setText(d.formatter->formatHtml(message->parameters().value(2)));
                    break;
                case Irc::RPL_TOPICWHOTIME: {
                    QDateTime dateTime = QDateTime::fromTime_t(message->parameters().value(3).toInt());
                    d.topicLabel->setToolTip(tr("Set %1 by %2").arg(dateTime.toString(), message->parameters().value(2)));
                    break;
                }
                default:
                    break;
            }
            break;
        default:
            break;
    }

    QString formatted = d.formatter->formatMessage(message, d.listView->userModel());
    if (append && formatted.length()) {
        if (matches)
            emit alerted(message);
        else if (hilite) // TODO: || (!d.receivedCodes.contains(Irc::RPL_ENDOFMOTD) && d.viewType == ServerView))
            emit highlighted(message);

        appendMessage(formatted);
    }
}

bool MessageView::hasUser(const QString& user) const
{
    return (!d.session->nickName().compare(user, Qt::CaseInsensitive)) ||
           (d.viewType == QueryView && !d.receiver.compare(user, Qt::CaseInsensitive)) ||
           (d.viewType == ChannelView && d.listView->hasUser(user));
}

void MessageView::onCustomCommand(const QString& command, const QStringList& params)
{
    if (command == "QUERY")
        emit queried(params.value(0));
    else if (command == "WHOIS")
        d.session->sendCommand(IrcCommand::createWhois(params.value(0)));
}
<commit_msg>MessageView: remove references to Settings::messages/highlights<commit_after>/*
* Copyright (C) 2008-2012 J-P Nurmi <jpnurmi@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*/

#include "messageview.h"
#include "menufactory.h"
#include "completer.h"
#include "usermodel.h"
#include "session.h"
#include <QAbstractTextDocumentLayout>
#include <QDesktopServices>
#include <QStringListModel>
#include <QTextBlock>
#include <QShortcut>
#include <QKeyEvent>
#include <QDateTime>
#include <QDebug>
#include <QUrl>
#include <ircmessage.h>
#include <irccommand.h>
#include <ircutil.h>
#include <irc.h>

static QStringListModel* command_model = 0;
static const int VERTICAL_MARGIN = 1; // matches qlineedit_p.cpp

MessageView::MessageView(MessageView::ViewType type, Session* session, QWidget* parent) :
    QWidget(parent)
{
    d.setupUi(this);
    d.viewType = type;

    d.topicLabel->setMinimumHeight(d.lineEditor->sizeHint().height());
    d.helpLabel->setMinimumHeight(d.lineEditor->sizeHint().height());

    connect(d.splitter, SIGNAL(splitterMoved(int, int)), this, SLOT(onSplitterMoved()));

    setFocusProxy(d.lineEditor);
    d.textBrowser->setBuddy(d.lineEditor);
    d.textBrowser->viewport()->installEventFilter(this);
    connect(d.textBrowser, SIGNAL(anchorClicked(QUrl)), SLOT(onAnchorClicked(QUrl)));

    d.formatter = new MessageFormatter(this);
    d.formatter->setHighlights(QStringList(session->nickName()));
    d.formatter->setMessageFormat("class='message'");
    d.formatter->setEventFormat("class='event'");
    d.formatter->setNoticeFormat("class='notice'");
    d.formatter->setActionFormat("class='action'");
    d.formatter->setUnknownFormat("class='unknown'");
    d.formatter->setHighlightFormat("class='highlight'");
    d.formatter->setTimeStampFormat("class='timestamp'");

    d.session = session;
    connect(&d.parser, SIGNAL(customCommand(QString, QStringList)), this, SLOT(onCustomCommand(QString, QStringList)));

    d.topicLabel->setVisible(type == ChannelView);
    d.listView->setVisible(type == ChannelView);
    if (type == ChannelView) {
        d.listView->setSession(session);
        connect(d.listView, SIGNAL(queried(QString)), this, SIGNAL(queried(QString)));
        connect(d.listView, SIGNAL(doubleClicked(QString)), this, SIGNAL(queried(QString)));
        connect(d.listView, SIGNAL(commandRequested(IrcCommand*)), d.session, SLOT(sendCommand(IrcCommand*)));
    }

    if (!command_model) {
        CommandParser::addCustomCommand("QUERY", "<user>");

        QStringList prefixedCommands;
        foreach(const QString & command, CommandParser::availableCommands())
        prefixedCommands += "/" + command;

        command_model = new QStringListModel(qApp);
        command_model->setStringList(prefixedCommands);
    }

    d.lineEditor->completer()->setDefaultModel(d.listView->userModel());
    d.lineEditor->completer()->setSlashModel(command_model);

    connect(d.lineEditor, SIGNAL(send(QString)), this, SLOT(onSend(QString)));
    connect(d.lineEditor, SIGNAL(typed(QString)), this, SLOT(showHelp(QString)));

    d.helpLabel->hide();
    d.searchEditor->setTextEdit(d.textBrowser);

    QShortcut* shortcut = new QShortcut(Qt::Key_Escape, this);
    connect(shortcut, SIGNAL(activated()), this, SLOT(onEscPressed()));

    applySettings(d.settings);
}

MessageView::~MessageView()
{
}

MessageView::ViewType MessageView::viewType() const
{
    return d.viewType;
}

Session* MessageView::session() const
{
    return d.session;
}

QTextBrowser* MessageView::textBrowser() const
{
    return d.textBrowser;
}

MessageFormatter* MessageView::messageFormatter() const
{
    return d.formatter;
}

QString MessageView::receiver() const
{
    return d.receiver;
}

void MessageView::setReceiver(const QString& receiver)
{
    d.receiver = receiver;
    if (d.viewType == ChannelView)
        d.listView->setChannel(receiver);
}

MenuFactory* MessageView::menuFactory() const
{
    return d.listView->menuFactory();
}

void MessageView::setMenuFactory(MenuFactory* factory)
{
    d.listView->setMenuFactory(factory);
}

QByteArray MessageView::saveSplitter() const
{
    if (d.viewType != ServerView)
        return d.splitter->saveState();
    return QByteArray();
}

void MessageView::restoreSplitter(const QByteArray& state)
{
    d.splitter->restoreState(state);
}

void MessageView::showHelp(const QString& text, bool error)
{
    QString syntax;
    if (text == "/") {
        QStringList commands = CommandParser::availableCommands();
        syntax = commands.join(" ");
    } else if (text.startsWith('/')) {
        QStringList words = text.mid(1).split(' ');
        QString command = words.value(0);
        QStringList suggestions = CommandParser::suggestedCommands(command, words.mid(1));
        if (suggestions.count() == 1)
            syntax = CommandParser::syntax(suggestions.first());
        else
            syntax = suggestions.join(" ");

        if (syntax.isEmpty() && error)
            syntax = tr("Unknown command '%1'").arg(command.toUpper());
    }

    d.helpLabel->setVisible(!syntax.isEmpty());
    QPalette pal;
    if (error)
        pal.setColor(QPalette::WindowText, d.settings.colors[Settings::Highlight]);
    d.helpLabel->setPalette(pal);
    d.helpLabel->setText(syntax);
}

void MessageView::appendMessage(const QString& message)
{
    if (!message.isEmpty()) {
        // workaround the link activation merge char format bug
        QString copy = message;
        if (copy.endsWith("</a>"))
            copy += " ";

        d.textBrowser->append(copy);
        if (!isVisible() && d.textBrowser->unseenBlock() == -1)
            d.textBrowser->setUnseenBlock(d.textBrowser->document()->blockCount() - 1);

#if QT_VERSION >= 0x040800
        QTextBlock block = d.textBrowser->document()->lastBlock();
        QTextBlockFormat format = block.blockFormat();
        format.setLineHeight(120, QTextBlockFormat::ProportionalHeight);
        QTextCursor cursor(block);
        cursor.setBlockFormat(format);
#endif // QT_VERSION
    }
}

void MessageView::hideEvent(QHideEvent* event)
{
    QWidget::hideEvent(event);
    d.textBrowser->setUnseenBlock(-1);
}

bool MessageView::eventFilter(QObject* object, QEvent* event)
{
    if (object == d.textBrowser->viewport() && event->type() == QEvent::ContextMenu) {
        QContextMenuEvent* menuEvent = static_cast<QContextMenuEvent*>(event);
        QAbstractTextDocumentLayout* layout = d.textBrowser->document()->documentLayout();
        QUrl link(layout->anchorAt(menuEvent->pos()));
        if (link.scheme() == "nick") {
            QMenu* standardMenu = d.textBrowser->createStandardContextMenu(menuEvent->pos());
            QMenu* customMenu = d.listView->menuFactory()->createUserViewMenu(link.toString(QUrl::RemoveScheme), this);
            customMenu->addSeparator();
            customMenu->insertActions(0, standardMenu->actions());
            customMenu->exec(menuEvent->globalPos());
            customMenu->deleteLater();
            delete standardMenu;
            return true;
        }
    }
    return QWidget::eventFilter(object, event);
}

void MessageView::onEscPressed()
{
    d.helpLabel->hide();
    d.searchEditor->hide();
    setFocus(Qt::OtherFocusReason);
}

void MessageView::onSplitterMoved()
{
    emit splitterChanged(d.splitter->saveState());
}

void MessageView::onSend(const QString& text)
{
    IrcCommand* cmd = d.parser.parseCommand(receiver(), text);
    if (cmd) {
        d.session->sendCommand(cmd);

        if (cmd->type() == IrcCommand::Message || cmd->type() == IrcCommand::CtcpAction) {
            IrcMessage* msg = IrcMessage::fromCommand(d.session->nickName(), cmd, d.session);
            receiveMessage(msg);
            delete msg;
        }
    } else if (d.parser.hasError()) {
        showHelp(text, true);
    }
}

void MessageView::onAnchorClicked(const QUrl& link)
{
    if (link.scheme() == "nick")
        emit queried(link.toString(QUrl::RemoveScheme));
    else
        QDesktopServices::openUrl(link);
}

void MessageView::applySettings(const Settings& settings)
{
    d.formatter->setTimeStamp(settings.timeStamp);
    d.formatter->setStripNicks(settings.stripNicks);

    if (!settings.font.isEmpty())
        d.textBrowser->setFont(settings.font);
    d.textBrowser->document()->setMaximumBlockCount(settings.maxBlockCount);
    d.topicLabel->setProperty("gradient", settings.layout == "tree");

    QTextDocument* doc = d.topicLabel->findChild<QTextDocument*>();
    if (doc)
        doc->setDefaultStyleSheet(QString("a { color: %1 }").arg(settings.colors.value(Settings::Link)));

    QString backgroundColor = settings.colors.value(Settings::Background);
    d.textBrowser->setStyleSheet(QString("QTextBrowser { background-color: %1 }").arg(backgroundColor));

    d.textBrowser->document()->setDefaultStyleSheet(
        QString(
            ".highlight { color: %1 }"
            ".message   { color: %2 }"
            ".notice    { color: %3 }"
            ".action    { color: %4 }"
            ".event     { color: %5 }"
            ".timestamp { color: %6; font-size: small }"
            "a { color: %7 }"
        ).arg(settings.colors.value(Settings::Highlight))
        .arg(settings.colors.value(Settings::Message))
        .arg(settings.colors.value(Settings::Notice))
        .arg(settings.colors.value(Settings::Action))
        .arg(settings.colors.value(Settings::Event))
        .arg(settings.colors.value(Settings::TimeStamp))
        .arg(settings.colors.value(Settings::Link)));
    d.settings = settings;
}

void MessageView::receiveMessage(IrcMessage* message)
{
    if (d.viewType == ChannelView)
        d.listView->processMessage(message);

    bool hilite = false;
    bool matches = false;

    switch (message->type()) {
        case IrcMessage::Notice:
            matches = static_cast<IrcNoticeMessage*>(message)->message().contains(d.session->nickName());
            hilite = true;
            break;
        case IrcMessage::Private:
            matches = d.viewType != ChannelView || static_cast<IrcPrivateMessage*>(message)->message().contains(d.session->nickName());
            hilite = true;
            break;
        case IrcMessage::Topic:
            d.topicLabel->setText(d.formatter->formatHtml(static_cast<IrcTopicMessage*>(message)->topic()));
            if (d.topicLabel->text().isEmpty())
                d.topicLabel->setText(tr("-"));
            break;
        case IrcMessage::Unknown:
            qWarning() << "unknown:" << message;
            break;
        case IrcMessage::Invite:
        case IrcMessage::Ping:
        case IrcMessage::Pong:
        case IrcMessage::Error:
            break;
        case IrcMessage::Numeric:
            switch (static_cast<IrcNumericMessage*>(message)->code()) {
                case Irc::RPL_NOTOPIC:
                    d.topicLabel->setText(tr("-"));
                    break;
                case Irc::RPL_TOPIC:
                    d.topicLabel->setText(d.formatter->formatHtml(message->parameters().value(2)));
                    break;
                case Irc::RPL_TOPICWHOTIME: {
                    QDateTime dateTime = QDateTime::fromTime_t(message->parameters().value(3).toInt());
                    d.topicLabel->setToolTip(tr("Set %1 by %2").arg(dateTime.toString(), message->parameters().value(2)));
                    break;
                }
                default:
                    break;
            }
            break;
        default:
            break;
    }

    QString formatted = d.formatter->formatMessage(message, d.listView->userModel());
    if (formatted.length()) {
        if (matches)
            emit alerted(message);
        else if (hilite) // TODO: || (!d.receivedCodes.contains(Irc::RPL_ENDOFMOTD) && d.viewType == ServerView))
            emit highlighted(message);

        appendMessage(formatted);
    }
}

bool MessageView::hasUser(const QString& user) const
{
    return (!d.session->nickName().compare(user, Qt::CaseInsensitive)) ||
           (d.viewType == QueryView && !d.receiver.compare(user, Qt::CaseInsensitive)) ||
           (d.viewType == ChannelView && d.listView->hasUser(user));
}

void MessageView::onCustomCommand(const QString& command, const QStringList& params)
{
    if (command == "QUERY")
        emit queried(params.value(0));
    else if (command == "WHOIS")
        d.session->sendCommand(IrcCommand::createWhois(params.value(0)));
}
<|endoftext|>


<commit_before>#include "callback.hpp"

#include <memory>
#include <iostream>

#include <cassert>

int foo( int x, int y )
{
	return x - y + 31337;
}

struct Foo
{
	int Bar( int x, int y )
	{
		return x + y + 31337;
	}
};

void basic_func()
{
	pac::callback<int( int, int )> cb( foo );

	assert( cb( 1, 1 ) == foo( 1, 1 ) );
}

void basic_memfunc()
{
	Foo f;
	pac::callback<int( int, int )> cb( &f, &Foo::Bar );

	assert( cb( 1, 1 ) == f.Bar( 1, 1 ) );

	Foo *f2 = new Foo;
	pac::callback<int( int, int )> cb2( f2, &Foo::Bar );

	assert( cb2( 1, 1 ) == f2->Bar( 1, 1 ) );
	delete f2;

	std::unique_ptr<Foo> f3( new Foo );
	pac::callback<int( int, int )> cb3( f3, &Foo::Bar );

	assert( cb3( 1, 1 ) == f3->Bar( 1, 1 ) );

	std::cout << "f3 @ " << &f3 << "\n";

	std::shared_ptr<Foo> f4( new Foo );
	pac::callback<int( int, int )> cb4( f4, &Foo::Bar );
	std::cout << f4.use_count() << "\n";

	assert( cb4( 1, 1 ) == f4->Bar( 1, 1 ) );
}

void functor_test()
{
	std::function< int( int, int )> func = foo;
	pac::callback< int( int, int )> cb( func );

	assert( cb( 1, 1 ) == func( 1, 1 ) );

	auto bound = std::bind( func, std::placeholders::_1,
	                        std::placeholders::_2 );
	pac::callback< int( int, int )> cb2( bound );

	assert( cb2( 1, 1 ) == bound( 1, 1 ) );
}

void lambda_test()
{
	auto func = [](int x, int y) { return x + y + 200; };
	pac::callback< int( int, int )> cb( func );

	assert( cb( 1, 1 ) == func( 1, 1 ) );
}

void makecallback_test()
{
	Foo f;
	std::unique_ptr<Foo> f2( new Foo );

	auto cb = pac::make_callback( &f, &Foo::Bar );

	auto cb2 = pac::make_callback( foo );

	assert( cb2( 1, 2 ) == foo( 1, 2 ) );
}

template<class T>
T template_testme( T t )
{
	return t;
}

void templated_test()
{
	pac::callback<int( int )> cb2( template_testme<int> );
	pac::callback<int( int )> cb3( &template_testme<int> );
}

int main(int argc, char *argv[])
{
	basic_func();

	basic_memfunc();

	functor_test();

	lambda_test();

	makecallback_test();

	templated_test();

	std::cout << "Success: All tests passed!\n";

	return 0;
}
<commit_msg>Add a class operator() based 'functor' callback test<commit_after>#include "callback.hpp"

#include <memory>
#include <iostream>

#include <cassert>

int foo( int x, int y )
{
	return x - y + 31337;
}

struct Foo
{
	int Bar( int x, int y )
	{
		return x + y + 31337;
	}
};

void basic_func()
{
	pac::callback<int( int, int )> cb( foo );

	assert( cb( 1, 1 ) == foo( 1, 1 ) );
}

void basic_memfunc()
{
	Foo f;
	pac::callback<int( int, int )> cb( &f, &Foo::Bar );

	assert( cb( 1, 1 ) == f.Bar( 1, 1 ) );

	Foo *f2 = new Foo;
	pac::callback<int( int, int )> cb2( f2, &Foo::Bar );

	assert( cb2( 1, 1 ) == f2->Bar( 1, 1 ) );
	delete f2;

	std::unique_ptr<Foo> f3( new Foo );
	pac::callback<int( int, int )> cb3( f3, &Foo::Bar );

	assert( cb3( 1, 1 ) == f3->Bar( 1, 1 ) );

	std::cout << "f3 @ " << &f3 << "\n";

	std::shared_ptr<Foo> f4( new Foo );
	pac::callback<int( int, int )> cb4( f4, &Foo::Bar );
	std::cout << f4.use_count() << "\n";

	assert( cb4( 1, 1 ) == f4->Bar( 1, 1 ) );
}

struct Functor
{
	int operator()(int x, int y )
	{
		return x - y + 1337;
	}
};

void functor_test()
{
	std::function< int( int, int )> func = foo;
	pac::callback< int( int, int )> cb( func );

	assert( cb( 1, 1 ) == func( 1, 1 ) );

	auto bound = std::bind( func, std::placeholders::_1,
	                        std::placeholders::_2 );
	pac::callback< int( int, int )> cb2( bound );

	assert( cb2( 1, 1 ) == bound( 1, 1 ) );

	Functor f;
	pac::callback< int( int, int )> cb3( f );

	assert( cb3( 1, 1 ) == Functor()( 1, 1 ) );
}

void lambda_test()
{
	auto func = [](int x, int y) { return x + y + 200; };
	pac::callback< int( int, int )> cb( func );

	assert( cb( 1, 1 ) == func( 1, 1 ) );
}

void makecallback_test()
{
	Foo f;
	std::unique_ptr<Foo> f2( new Foo );

	auto cb = pac::make_callback( &f, &Foo::Bar );

	auto cb2 = pac::make_callback( foo );

	assert( cb2( 1, 2 ) == foo( 1, 2 ) );
}

template<class T>
T template_testme( T t )
{
	return t;
}

void templated_test()
{
	pac::callback<int( int )> cb2( template_testme<int> );
	pac::callback<int( int )> cb3( &template_testme<int> );
}

int main(int argc, char *argv[])
{
	basic_func();

	basic_memfunc();

	functor_test();

	lambda_test();

	makecallback_test();

	templated_test();

	std::cout << "Success: All tests passed!\n";

	return 0;
}
<|endoftext|>