<commit_before>/*
    Copyright (c) 2007 Volker Krause <vkrause@kde.org>

    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., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "querybuilder.h"

#ifndef QUERYBUILDER_UNITTEST
#include "storage/datastore.h"
#endif

using namespace Akonadi;

static QString compareOperatorToString( Query::CompareOperator op )
{
  switch ( op ) {
    case Query::Equals:
      return QLatin1String( " = " );
    case Query::NotEquals:
      return QLatin1String( " <> " );
    case Query::Is:
      return QLatin1String( " IS " );
    case Query::IsNot:
      return QLatin1String( " IS NOT " );
    case Query::Less:
      return QLatin1String( " < " );
    case Query::LessOrEqual:
      return QLatin1String( " <= " );
    case Query::Greater:
      return QLatin1String( " > " );
    case Query::GreaterOrEqual:
      return QLatin1String( " >= " );
    case Query::In:
      return QLatin1String( " IN " );
    case Query::NotIn:
      return QLatin1String( " NOT IN " );
  }
  Q_ASSERT_X( false, "QueryBuilder::compareOperatorToString()", "Unknown compare operator." );
  return QString();
}

static QString logicOperatorToString( Query::LogicOperator op )
{
  switch ( op ) {
    case Query::And:
      return QLatin1String( " AND " );
    case Query::Or:
      return QLatin1String( " OR " );
  }
  Q_ASSERT_X( false, "QueryBuilder::logicOperatorToString()", "Unknown logic operator." );
  return QString();
}

static QString sortOrderToString( Query::SortOrder order )
{
  switch ( order ) {
    case Query::Ascending:
      return QLatin1String( " ASC" );
    case Query::Descending:
      return QLatin1String( " DESC" );
  }
  Q_ASSERT_X( false, "QueryBuilder::sortOrderToString()", "Unknown sort order." );
  return QString();
}

QueryBuilder::QueryBuilder( QueryType type ) :
#ifndef QUERYBUILDER_UNITTEST
    mQuery( DataStore::self()->database() ),
#endif
    mType( type )
{
}

void QueryBuilder::addTable(const QString & table)
{
  mTables << table;
}

void QueryBuilder::addValueCondition(const QString & column, Query::CompareOperator op, const QVariant & value)
{
  mRootCondition.addValueCondition( column, op, value );
}

void QueryBuilder::addColumnCondition(const QString & column, Query::CompareOperator op, const QString & column2)
{
  mRootCondition.addColumnCondition( column, op, column2 );
}

QSqlQuery& QueryBuilder::query()
{
  return mQuery;
}

bool QueryBuilder::exec()
{
  QString statement;

  switch ( mType ) {
    case Select:
      statement += QLatin1String( "SELECT " );
      if ( mDistinct )
        statement += QLatin1String( "DISTINCT " );
      Q_ASSERT_X( mColumns.count() > 0, "QueryBuilder::exec()", "No columns specified" );
      statement += mColumns.join( QLatin1String( ", " ) );
      statement += QLatin1String(" FROM ");
      Q_ASSERT_X( mTables.count() > 0, "QueryBuilder::exec()", "No tables specified" );
      statement += mTables.join( QLatin1String( ", " ) );
     break;
    case Update:
    {
      statement += QLatin1String( "UPDATE " );
      Q_ASSERT_X( mTables.count() > 0, "QueryBuilder::exec()", "No tables specified" );
      statement += mTables.join( QLatin1String( ", " ) );
      statement += QLatin1String( " SET " );
      Q_ASSERT_X( mUpdateColumns.count() >= 1, "QueryBuilder::exec()", "At least one column needs to be changed" );
      typedef QPair<QString,QVariant> StringVariantPair;
      QStringList updStmts;
      foreach ( const StringVariantPair &p, mUpdateColumns ) {
        QString updStmt = p.first;
        updStmt += QLatin1String( " = " );
        updStmt += bindValue( p.second );
        updStmts << updStmt;
      }
      statement += updStmts.join( QLatin1String( ", " ) );
      break;
    }
    case Delete:
      statement += QLatin1String( "DELETE FROM " );
      Q_ASSERT_X( mTables.count() == 1, "QueryBuilder::exec()", "Exactly one table needed" );
      statement += mTables.first();
      break;
    default:
      Q_ASSERT_X( false, "QueryBuilder::exec()", "Unknown enum value" );
  }

  if ( !mRootCondition.isEmpty() ) {
    statement += QLatin1String(" WHERE ");
    statement += buildWhereCondition( mRootCondition );
  }

  if ( !mSortColumns.isEmpty() ) {
    Q_ASSERT_X( mType == Select, "QueryBuilder::exec()", "Order statements are only valid for SELECT queries" );
    QStringList orderStmts;
    typedef QPair<QString, Query::SortOrder> SortColumnInfo;
    foreach ( const SortColumnInfo &order, mSortColumns ) {
      QString orderStmt;
      orderStmt += order.first;
      orderStmt += sortOrderToString( order.second );
      orderStmts << orderStmt;
    }
    statement += QLatin1String( " ORDER BY " );
    statement += orderStmts.join( QLatin1String( ", " ) );
  }

#ifndef QUERYBUILDER_UNITTEST
  mQuery.prepare( statement );
  for ( int i = 0; i < mBindValues.count(); ++i )
    mQuery.bindValue( QString::fromLatin1( ":%1" ).arg( i ), mBindValues[i] );
  if ( !mQuery.exec() ) {
    qDebug() << "Error during executing query" << statement << ": " << mQuery.lastError().text();
    return false;
  }
#else
  mStatement = statement;
#endif
  return true;
}

void QueryBuilder::addColumns(const QStringList & cols)
{
  mColumns << cols;
}

void QueryBuilder::addColumn(const QString & col)
{
  mColumns << col;
}

QString QueryBuilder::bindValue(const QVariant & value)
{
  mBindValues << value;
  return QString::fromLatin1( ":%1" ). arg( mBindValues.count() - 1 );
}

QString QueryBuilder::buildWhereCondition(const Query::Condition & cond)
{
  if ( !cond.isEmpty() ) {
    QStringList conds;
    foreach ( const Query::Condition &c, cond.subConditions() ) {
      conds << buildWhereCondition( c );
    }
    return QLatin1String( "( " ) + conds.join( logicOperatorToString( cond.mCombineOp ) ) + QLatin1String( " )" );
  } else {
    QString stmt = cond.mColumn;
    stmt += compareOperatorToString( cond.mCompareOp );
    if ( cond.mComparedColumn.isEmpty() ) {
      if ( cond.mComparedValue.isValid() ) {
        if ( cond.mComparedValue.canConvert( QVariant::StringList ) ) {
          stmt += QLatin1String( "( " );
          QStringList entries;
          Q_ASSERT_X( !cond.mComparedValue.toStringList().isEmpty(),
                      "QueryBuilder::buildWhereCondition()", "No values given for IN condition." );
          foreach ( const QString &entry, cond.mComparedValue.toStringList() ) {
            entries << bindValue( entry );
          }
          stmt += entries.join( QLatin1String( ", " ) );
          stmt += QLatin1String( " )" );
        } else {
          stmt += bindValue( cond.mComparedValue );
        }
      } else {
        stmt += QLatin1String( "NULL" );
      }
    } else {
      stmt += cond.mComparedColumn;
    }
    return stmt;
  }
}

void QueryBuilder::setSubQueryMode(Query::LogicOperator op)
{
  mRootCondition.setSubQueryMode( op );
}

void QueryBuilder::addCondition(const Query::Condition & condition)
{
  mRootCondition.addCondition( condition );
}

void QueryBuilder::addSortColumn(const QString & column, Query::SortOrder order )
{
  mSortColumns << qMakePair( column, order );
}

void QueryBuilder::updateColumnValue(const QString & column, const QVariant & value)
{
  mUpdateColumns << qMakePair( column, value );
}

void QueryBuilder::setDistinct(bool distinct)
{
  mDistinct = distinct;
}
<commit_msg>initialize<commit_after>/*
    Copyright (c) 2007 Volker Krause <vkrause@kde.org>

    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., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301, USA.
*/

#include "querybuilder.h"

#ifndef QUERYBUILDER_UNITTEST
#include "storage/datastore.h"
#endif

using namespace Akonadi;

static QString compareOperatorToString( Query::CompareOperator op )
{
  switch ( op ) {
    case Query::Equals:
      return QLatin1String( " = " );
    case Query::NotEquals:
      return QLatin1String( " <> " );
    case Query::Is:
      return QLatin1String( " IS " );
    case Query::IsNot:
      return QLatin1String( " IS NOT " );
    case Query::Less:
      return QLatin1String( " < " );
    case Query::LessOrEqual:
      return QLatin1String( " <= " );
    case Query::Greater:
      return QLatin1String( " > " );
    case Query::GreaterOrEqual:
      return QLatin1String( " >= " );
    case Query::In:
      return QLatin1String( " IN " );
    case Query::NotIn:
      return QLatin1String( " NOT IN " );
  }
  Q_ASSERT_X( false, "QueryBuilder::compareOperatorToString()", "Unknown compare operator." );
  return QString();
}

static QString logicOperatorToString( Query::LogicOperator op )
{
  switch ( op ) {
    case Query::And:
      return QLatin1String( " AND " );
    case Query::Or:
      return QLatin1String( " OR " );
  }
  Q_ASSERT_X( false, "QueryBuilder::logicOperatorToString()", "Unknown logic operator." );
  return QString();
}

static QString sortOrderToString( Query::SortOrder order )
{
  switch ( order ) {
    case Query::Ascending:
      return QLatin1String( " ASC" );
    case Query::Descending:
      return QLatin1String( " DESC" );
  }
  Q_ASSERT_X( false, "QueryBuilder::sortOrderToString()", "Unknown sort order." );
  return QString();
}

QueryBuilder::QueryBuilder( QueryType type ) :
#ifndef QUERYBUILDER_UNITTEST
    mQuery( DataStore::self()->database() ),
#endif
    mType( type ),
    mDistinct( false )
{
}

void QueryBuilder::addTable(const QString & table)
{
  mTables << table;
}

void QueryBuilder::addValueCondition(const QString & column, Query::CompareOperator op, const QVariant & value)
{
  mRootCondition.addValueCondition( column, op, value );
}

void QueryBuilder::addColumnCondition(const QString & column, Query::CompareOperator op, const QString & column2)
{
  mRootCondition.addColumnCondition( column, op, column2 );
}

QSqlQuery& QueryBuilder::query()
{
  return mQuery;
}

bool QueryBuilder::exec()
{
  QString statement;

  switch ( mType ) {
    case Select:
      statement += QLatin1String( "SELECT " );
      if ( mDistinct )
        statement += QLatin1String( "DISTINCT " );
      Q_ASSERT_X( mColumns.count() > 0, "QueryBuilder::exec()", "No columns specified" );
      statement += mColumns.join( QLatin1String( ", " ) );
      statement += QLatin1String(" FROM ");
      Q_ASSERT_X( mTables.count() > 0, "QueryBuilder::exec()", "No tables specified" );
      statement += mTables.join( QLatin1String( ", " ) );
     break;
    case Update:
    {
      statement += QLatin1String( "UPDATE " );
      Q_ASSERT_X( mTables.count() > 0, "QueryBuilder::exec()", "No tables specified" );
      statement += mTables.join( QLatin1String( ", " ) );
      statement += QLatin1String( " SET " );
      Q_ASSERT_X( mUpdateColumns.count() >= 1, "QueryBuilder::exec()", "At least one column needs to be changed" );
      typedef QPair<QString,QVariant> StringVariantPair;
      QStringList updStmts;
      foreach ( const StringVariantPair &p, mUpdateColumns ) {
        QString updStmt = p.first;
        updStmt += QLatin1String( " = " );
        updStmt += bindValue( p.second );
        updStmts << updStmt;
      }
      statement += updStmts.join( QLatin1String( ", " ) );
      break;
    }
    case Delete:
      statement += QLatin1String( "DELETE FROM " );
      Q_ASSERT_X( mTables.count() == 1, "QueryBuilder::exec()", "Exactly one table needed" );
      statement += mTables.first();
      break;
    default:
      Q_ASSERT_X( false, "QueryBuilder::exec()", "Unknown enum value" );
  }

  if ( !mRootCondition.isEmpty() ) {
    statement += QLatin1String(" WHERE ");
    statement += buildWhereCondition( mRootCondition );
  }

  if ( !mSortColumns.isEmpty() ) {
    Q_ASSERT_X( mType == Select, "QueryBuilder::exec()", "Order statements are only valid for SELECT queries" );
    QStringList orderStmts;
    typedef QPair<QString, Query::SortOrder> SortColumnInfo;
    foreach ( const SortColumnInfo &order, mSortColumns ) {
      QString orderStmt;
      orderStmt += order.first;
      orderStmt += sortOrderToString( order.second );
      orderStmts << orderStmt;
    }
    statement += QLatin1String( " ORDER BY " );
    statement += orderStmts.join( QLatin1String( ", " ) );
  }

#ifndef QUERYBUILDER_UNITTEST
  mQuery.prepare( statement );
  for ( int i = 0; i < mBindValues.count(); ++i )
    mQuery.bindValue( QString::fromLatin1( ":%1" ).arg( i ), mBindValues[i] );
  if ( !mQuery.exec() ) {
    qDebug() << "Error during executing query" << statement << ": " << mQuery.lastError().text();
    return false;
  }
#else
  mStatement = statement;
#endif
  return true;
}

void QueryBuilder::addColumns(const QStringList & cols)
{
  mColumns << cols;
}

void QueryBuilder::addColumn(const QString & col)
{
  mColumns << col;
}

QString QueryBuilder::bindValue(const QVariant & value)
{
  mBindValues << value;
  return QString::fromLatin1( ":%1" ). arg( mBindValues.count() - 1 );
}

QString QueryBuilder::buildWhereCondition(const Query::Condition & cond)
{
  if ( !cond.isEmpty() ) {
    QStringList conds;
    foreach ( const Query::Condition &c, cond.subConditions() ) {
      conds << buildWhereCondition( c );
    }
    return QLatin1String( "( " ) + conds.join( logicOperatorToString( cond.mCombineOp ) ) + QLatin1String( " )" );
  } else {
    QString stmt = cond.mColumn;
    stmt += compareOperatorToString( cond.mCompareOp );
    if ( cond.mComparedColumn.isEmpty() ) {
      if ( cond.mComparedValue.isValid() ) {
        if ( cond.mComparedValue.canConvert( QVariant::StringList ) ) {
          stmt += QLatin1String( "( " );
          QStringList entries;
          Q_ASSERT_X( !cond.mComparedValue.toStringList().isEmpty(),
                      "QueryBuilder::buildWhereCondition()", "No values given for IN condition." );
          foreach ( const QString &entry, cond.mComparedValue.toStringList() ) {
            entries << bindValue( entry );
          }
          stmt += entries.join( QLatin1String( ", " ) );
          stmt += QLatin1String( " )" );
        } else {
          stmt += bindValue( cond.mComparedValue );
        }
      } else {
        stmt += QLatin1String( "NULL" );
      }
    } else {
      stmt += cond.mComparedColumn;
    }
    return stmt;
  }
}

void QueryBuilder::setSubQueryMode(Query::LogicOperator op)
{
  mRootCondition.setSubQueryMode( op );
}

void QueryBuilder::addCondition(const Query::Condition & condition)
{
  mRootCondition.addCondition( condition );
}

void QueryBuilder::addSortColumn(const QString & column, Query::SortOrder order )
{
  mSortColumns << qMakePair( column, order );
}

void QueryBuilder::updateColumnValue(const QString & column, const QVariant & value)
{
  mUpdateColumns << qMakePair( column, value );
}

void QueryBuilder::setDistinct(bool distinct)
{
  mDistinct = distinct;
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006-2012, Paul Beckingham, Federico Hernandez.
//
// 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, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#define L10N                                           // Localization complete.

#include <iostream>
#include <stdlib.h>
#include <Context.h>
#include <Date.h>
#include <text.h>
#include <util.h>
#include <main.h>

extern Context context;

static std::map <std::string, Color> gsColor;
static std::vector <std::string> gsPrecedence;

////////////////////////////////////////////////////////////////////////////////
void initializeColorRules ()
{
  gsColor.clear ();
  gsPrecedence.clear ();

  // Load all the configuration values, filter to only the ones that begin with
  // "color.", then store name/value in gsColor, and name in rules.
  std::vector <std::string> rules;
  std::vector <std::string> variables;
  context.config.all (variables);
  std::vector <std::string>::iterator v;
  for (v = variables.begin (); v != variables.end (); ++v)
  {
    if (v->substr (0, 6) == "color.")
    {
      Color c (context.config.get (*v));
      gsColor[*v] = c;

      rules.push_back (*v);
    }
  }

  // Load the rule.precedence.color list, split it, then autocomplete against
  // the 'rules' vector loaded above.
  std::vector <std::string> results;
  std::vector <std::string> precedence;
  split (precedence, context.config.get ("rule.precedence.color"), ',');

  std::vector <std::string>::iterator p;
  for (p = precedence.begin (); p != precedence.end (); ++p)
  {
    // Add the leading "color." string.
    std::string rule = "color." + *p;
    autoComplete (rule, rules, results, 3); // Hard-coded 3.

    std::vector <std::string>::iterator r;
    for (r = results.begin (); r != results.end (); ++r)
      gsPrecedence.push_back (*r);
  }
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeBlocked (Task& task, const std::string& rule, Color& c)
{
  if (gsColor[rule].nontrivial ())
    if (dependencyIsBlocked (task))
      c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeTagged (Task& task, const std::string& rule, Color& c)
{
  if (gsColor[rule].nontrivial ())
    if (task.getTagCount ())
      c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizePriorityL (Task& task, const std::string& rule, Color& c)
{
  if (gsColor[rule].nontrivial ())
    if (task.get ("priority") == "L")
      c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizePriorityM (Task& task, const std::string& rule, Color& c)
{
  if (gsColor[rule].nontrivial ())
    if (task.get ("priority") == "M")
      c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizePriorityH (Task& task, const std::string& rule, Color& c)
{
  if (gsColor[rule].nontrivial ())
    if (task.get ("priority") == "H")
      c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizePriorityNone (Task& task, const std::string& rule, Color& c)
{
  if (gsColor[rule].nontrivial ())
    if (task.get ("priority") == "")
      c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeActive (Task& task, const std::string& rule, Color& c)
{
  if (gsColor[rule].nontrivial () &&
      task.has ("start")          &&
      !task.has ("end"))
    c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeScheduled (Task& task, const std::string& rule, Color& c)
{
  if (gsColor[rule].nontrivial () &&
      task.has ("scheduled"))
    c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeTag (Task& task, const std::string& rule, Color& c)
{
  if (task.hasTag (rule.substr (10)))
    c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeProject (Task& task, const std::string& rule, Color& c)
{
  // Observe the case sensitivity setting.
  bool sensitive = context.config.getBoolean ("search.case.sensitive");

  std::string project = task.get ("project");
  std::string rule_trunc = rule.substr (14);

  // Match project names leftmost.
  if (rule_trunc.length () <= project.length ())
    if (compare (rule_trunc, project.substr (0, rule_trunc.length ()), sensitive))
      c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeProjectNone (Task& task, const std::string& rule, Color& c)
{
  if (task.get ("project") == "")
    c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeTagNone (Task& task, const std::string& rule, Color& c)
{
  if (task.getTagCount () == 0)
    c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeKeyword (Task& task, const std::string& rule, Color& c)
{
  // Observe the case sensitivity setting.
  bool sensitive = context.config.getBoolean ("search.case.sensitive");

  // The easiest thing to check is the description, because it is just one
  // attribute.
  if (find (task.get ("description"), rule.substr (14), sensitive) != std::string::npos)
    c.blend (gsColor[rule]);

  // Failing the description check, look at all annotations, returning on the
  // first match.
  else
  {
    Task::iterator it;
    for (it = task.begin (); it != task.end (); ++it)
    {
      if (it->first.substr (0, 11) == "annotation_" &&
          find (it->second, rule.substr (14), sensitive) != std::string::npos)
      {
        c.blend (gsColor[rule]);
        return;
      }
    }
  }
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeDue (Task& task, const std::string& rule, Color& c)
{
  Task::status status = task.getStatus ();

  if (task.has ("due")          &&
      status != Task::completed &&
      status != Task::deleted)
  {
    if (getDueState (task.get ("due")) == 1)
      c.blend (gsColor[rule]);
  }
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeDueToday (Task& task, const std::string& rule, Color& c)
{
  Task::status status = task.getStatus ();

  if (task.has ("due")          &&
      status != Task::completed &&
      status != Task::deleted)
  {
    if (getDueState (task.get ("due")) == 2)
      c.blend (gsColor[rule]);
  }
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeOverdue (Task& task, const std::string& rule, Color& c)
{
  Task::status status = task.getStatus ();

  if (task.has ("due")          &&
      status != Task::completed &&
      status != Task::deleted)
  {
    if (getDueState (task.get ("due")) == 3)
      c.blend (gsColor[rule]);
  }
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeRecurring (Task& task, const std::string& rule, Color& c)
{
  if (gsColor[rule].nontrivial ())
    if (task.has ("recur"))
      c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeCompleted (Task& task, const std::string& rule, Color& c)
{
  if (task.getStatus () == Task::completed)
    c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeDeleted (Task& task, const std::string& rule, Color& c)
{
  if (task.getStatus () == Task::completed)
    c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
void autoColorize (Task& task, Color& c)
{
  // The special tag 'nocolor' overrides all auto and specific colorization.
  if (!context.color () ||
      task.hasTag ("nocolor"))
  {
    c = Color ();
    return;
  }

  // Note: c already contains colors specifically assigned via command.
  // Note: These rules form a hierarchy - the last rule is King, hence the
  //       reverse iterator.
  std::vector <std::string>::reverse_iterator r;
  for (r = gsPrecedence.rbegin (); r != gsPrecedence.rend (); ++r)
  {
         if (*r == "color.blocked")                colorizeBlocked      (task, *r, c);
    else if (*r == "color.tagged")                 colorizeTagged       (task, *r, c);
    else if (*r == "color.pri.L")                  colorizePriorityL    (task, *r, c);
    else if (*r == "color.pri.M")                  colorizePriorityM    (task, *r, c);
    else if (*r == "color.pri.H")                  colorizePriorityH    (task, *r, c);
    else if (*r == "color.pri.none")               colorizePriorityNone (task, *r, c);
    else if (*r == "color.active")                 colorizeActive       (task, *r, c);
    else if (*r == "color.scheduled")              colorizeScheduled    (task, *r, c);
    else if (*r == "color.project.none")           colorizeProjectNone  (task, *r, c);
    else if (*r == "color.tag.none")               colorizeTagNone      (task, *r, c);
    else if (*r == "color.due")                    colorizeDue          (task, *r, c);
    else if (*r == "color.due.today")              colorizeDueToday     (task, *r, c);
    else if (*r == "color.overdue")                colorizeOverdue      (task, *r, c);
    else if (*r == "color.recurring")              colorizeRecurring    (task, *r, c);
    else if (*r == "color.completed")              colorizeCompleted    (task, *r, c);
    else if (*r == "color.deleted")                colorizeDeleted      (task, *r, c);

    // Wildcards
    else if (r->substr (0,  9) == "color.tag")     colorizeTag          (task, *r, c);
    else if (r->substr (0, 13) == "color.project") colorizeProject      (task, *r, c);
    else if (r->substr (0, 13) == "color.keyword") colorizeKeyword      (task, *r, c);
  }
}

////////////////////////////////////////////////////////////////////////////////
std::string colorizeHeader (const std::string& input)
{
  if (gsColor["color.header"].nontrivial ())
    return gsColor["color.header"].colorize (input);

  return input;
}

////////////////////////////////////////////////////////////////////////////////
std::string colorizeFootnote (const std::string& input)
{
  if (gsColor["color.footnote"].nontrivial ())
    return gsColor["color.footnote"].colorize (input);

  return input;
}

////////////////////////////////////////////////////////////////////////////////
std::string colorizeDebug (const std::string& input)
{
  if (gsColor["color.debug"].nontrivial ())
    return gsColor["color.debug"].colorize (input);

  return input;
}

////////////////////////////////////////////////////////////////////////////////
<commit_msg>Color Rules<commit_after>////////////////////////////////////////////////////////////////////////////////
// taskwarrior - a command line task list manager.
//
// Copyright 2006-2012, Paul Beckingham, Federico Hernandez.
//
// 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, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// http://www.opensource.org/licenses/mit-license.php
//
////////////////////////////////////////////////////////////////////////////////

#define L10N                                           // Localization complete.

#include <iostream>
#include <stdlib.h>
#include <Context.h>
#include <Date.h>
#include <text.h>
#include <util.h>
#include <main.h>

extern Context context;

static std::map <std::string, Color> gsColor;
static std::vector <std::string> gsPrecedence;
static Date now;

////////////////////////////////////////////////////////////////////////////////
void initializeColorRules ()
{
  gsColor.clear ();
  gsPrecedence.clear ();

  // Load all the configuration values, filter to only the ones that begin with
  // "color.", then store name/value in gsColor, and name in rules.
  std::vector <std::string> rules;
  std::vector <std::string> variables;
  context.config.all (variables);
  std::vector <std::string>::iterator v;
  for (v = variables.begin (); v != variables.end (); ++v)
  {
    if (v->substr (0, 6) == "color.")
    {
      Color c (context.config.get (*v));
      gsColor[*v] = c;

      rules.push_back (*v);
    }
  }

  // Load the rule.precedence.color list, split it, then autocomplete against
  // the 'rules' vector loaded above.
  std::vector <std::string> results;
  std::vector <std::string> precedence;
  split (precedence, context.config.get ("rule.precedence.color"), ',');

  std::vector <std::string>::iterator p;
  for (p = precedence.begin (); p != precedence.end (); ++p)
  {
    // Add the leading "color." string.
    std::string rule = "color." + *p;
    autoComplete (rule, rules, results, 3); // Hard-coded 3.

    std::vector <std::string>::iterator r;
    for (r = results.begin (); r != results.end (); ++r)
      gsPrecedence.push_back (*r);
  }
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeBlocked (Task& task, const std::string& rule, Color& c)
{
  if (gsColor[rule].nontrivial ())
    if (dependencyIsBlocked (task))
      c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeTagged (Task& task, const std::string& rule, Color& c)
{
  if (gsColor[rule].nontrivial ())
    if (task.getTagCount ())
      c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizePriorityL (Task& task, const std::string& rule, Color& c)
{
  if (gsColor[rule].nontrivial ())
    if (task.get ("priority") == "L")
      c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizePriorityM (Task& task, const std::string& rule, Color& c)
{
  if (gsColor[rule].nontrivial ())
    if (task.get ("priority") == "M")
      c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizePriorityH (Task& task, const std::string& rule, Color& c)
{
  if (gsColor[rule].nontrivial ())
    if (task.get ("priority") == "H")
      c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizePriorityNone (Task& task, const std::string& rule, Color& c)
{
  if (gsColor[rule].nontrivial ())
    if (task.get ("priority") == "")
      c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeActive (Task& task, const std::string& rule, Color& c)
{
  if (gsColor[rule].nontrivial () &&
      task.has ("start")          &&
      !task.has ("end"))
    c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeScheduled (Task& task, const std::string& rule, Color& c)
{
  if (gsColor[rule].nontrivial () &&
      task.has ("scheduled") &&
      Date (task.get_date ("scheduled")) < now)
    c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeTag (Task& task, const std::string& rule, Color& c)
{
  if (task.hasTag (rule.substr (10)))
    c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeProject (Task& task, const std::string& rule, Color& c)
{
  // Observe the case sensitivity setting.
  bool sensitive = context.config.getBoolean ("search.case.sensitive");

  std::string project = task.get ("project");
  std::string rule_trunc = rule.substr (14);

  // Match project names leftmost.
  if (rule_trunc.length () <= project.length ())
    if (compare (rule_trunc, project.substr (0, rule_trunc.length ()), sensitive))
      c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeProjectNone (Task& task, const std::string& rule, Color& c)
{
  if (task.get ("project") == "")
    c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeTagNone (Task& task, const std::string& rule, Color& c)
{
  if (task.getTagCount () == 0)
    c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeKeyword (Task& task, const std::string& rule, Color& c)
{
  // Observe the case sensitivity setting.
  bool sensitive = context.config.getBoolean ("search.case.sensitive");

  // The easiest thing to check is the description, because it is just one
  // attribute.
  if (find (task.get ("description"), rule.substr (14), sensitive) != std::string::npos)
    c.blend (gsColor[rule]);

  // Failing the description check, look at all annotations, returning on the
  // first match.
  else
  {
    Task::iterator it;
    for (it = task.begin (); it != task.end (); ++it)
    {
      if (it->first.substr (0, 11) == "annotation_" &&
          find (it->second, rule.substr (14), sensitive) != std::string::npos)
      {
        c.blend (gsColor[rule]);
        return;
      }
    }
  }
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeDue (Task& task, const std::string& rule, Color& c)
{
  Task::status status = task.getStatus ();

  if (task.has ("due")          &&
      status != Task::completed &&
      status != Task::deleted)
  {
    if (getDueState (task.get ("due")) == 1)
      c.blend (gsColor[rule]);
  }
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeDueToday (Task& task, const std::string& rule, Color& c)
{
  Task::status status = task.getStatus ();

  if (task.has ("due")          &&
      status != Task::completed &&
      status != Task::deleted)
  {
    if (getDueState (task.get ("due")) == 2)
      c.blend (gsColor[rule]);
  }
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeOverdue (Task& task, const std::string& rule, Color& c)
{
  Task::status status = task.getStatus ();

  if (task.has ("due")          &&
      status != Task::completed &&
      status != Task::deleted)
  {
    if (getDueState (task.get ("due")) == 3)
      c.blend (gsColor[rule]);
  }
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeRecurring (Task& task, const std::string& rule, Color& c)
{
  if (gsColor[rule].nontrivial ())
    if (task.has ("recur"))
      c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeCompleted (Task& task, const std::string& rule, Color& c)
{
  if (task.getStatus () == Task::completed)
    c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
static void colorizeDeleted (Task& task, const std::string& rule, Color& c)
{
  if (task.getStatus () == Task::completed)
    c.blend (gsColor[rule]);
}

////////////////////////////////////////////////////////////////////////////////
void autoColorize (Task& task, Color& c)
{
  // The special tag 'nocolor' overrides all auto and specific colorization.
  if (!context.color () ||
      task.hasTag ("nocolor"))
  {
    c = Color ();
    return;
  }

  // Note: c already contains colors specifically assigned via command.
  // Note: These rules form a hierarchy - the last rule is King, hence the
  //       reverse iterator.
  std::vector <std::string>::reverse_iterator r;
  for (r = gsPrecedence.rbegin (); r != gsPrecedence.rend (); ++r)
  {
         if (*r == "color.blocked")                colorizeBlocked      (task, *r, c);
    else if (*r == "color.tagged")                 colorizeTagged       (task, *r, c);
    else if (*r == "color.pri.L")                  colorizePriorityL    (task, *r, c);
    else if (*r == "color.pri.M")                  colorizePriorityM    (task, *r, c);
    else if (*r == "color.pri.H")                  colorizePriorityH    (task, *r, c);
    else if (*r == "color.pri.none")               colorizePriorityNone (task, *r, c);
    else if (*r == "color.active")                 colorizeActive       (task, *r, c);
    else if (*r == "color.scheduled")              colorizeScheduled    (task, *r, c);
    else if (*r == "color.project.none")           colorizeProjectNone  (task, *r, c);
    else if (*r == "color.tag.none")               colorizeTagNone      (task, *r, c);
    else if (*r == "color.due")                    colorizeDue          (task, *r, c);
    else if (*r == "color.due.today")              colorizeDueToday     (task, *r, c);
    else if (*r == "color.overdue")                colorizeOverdue      (task, *r, c);
    else if (*r == "color.recurring")              colorizeRecurring    (task, *r, c);
    else if (*r == "color.completed")              colorizeCompleted    (task, *r, c);
    else if (*r == "color.deleted")                colorizeDeleted      (task, *r, c);

    // Wildcards
    else if (r->substr (0,  9) == "color.tag")     colorizeTag          (task, *r, c);
    else if (r->substr (0, 13) == "color.project") colorizeProject      (task, *r, c);
    else if (r->substr (0, 13) == "color.keyword") colorizeKeyword      (task, *r, c);
  }
}

////////////////////////////////////////////////////////////////////////////////
std::string colorizeHeader (const std::string& input)
{
  if (gsColor["color.header"].nontrivial ())
    return gsColor["color.header"].colorize (input);

  return input;
}

////////////////////////////////////////////////////////////////////////////////
std::string colorizeFootnote (const std::string& input)
{
  if (gsColor["color.footnote"].nontrivial ())
    return gsColor["color.footnote"].colorize (input);

  return input;
}

////////////////////////////////////////////////////////////////////////////////
std::string colorizeDebug (const std::string& input)
{
  if (gsColor["color.debug"].nontrivial ())
    return gsColor["color.debug"].colorize (input);

  return input;
}

////////////////////////////////////////////////////////////////////////////////
<|endoftext|>


<commit_before>// Copyright[2015] <kangic21@gmail.com>

#include "../include/runner.h"

#include "../include/if_server.h"
#include "../include/if_client.h"

namespace eznetpp {

runner::runner(void) {
}

runner::~runner(void) {
  _server_container.clear();
  _client_container.clear();
}

// not thread safe
void runner::add_to_running_list(if_server* server) {
  std::vector<if_server*>::iterator iter;

  for (iter = _server_container.begin();
       iter != _server_container.end();
       ++iter) {
    if (*iter == server) {
      // todo : print error log
    }
  }

  _server_container.push_back(server);
}

// not thread safe
void runner::del_from_running_list(if_server* server) {
  std::vector<if_server*>::iterator iter;

  for (iter = _server_container.begin();
       iter != _server_container.end();
       ++iter) {
    if (*iter == server) {
      iter = _server_container.erase(iter);
    }
  }

  if (iter == _server_container.end()) {
    // todo : print error log
  }
}

// not thread safe
void runner::add_to_running_list(if_client* client) {
  std::vector<if_client*>::iterator iter;

  for (iter = _client_container.begin();
       iter != _client_container.end();
       ++iter) {
    if (*iter == client) {
      // todo : print error log
    }
  }

  _client_container.push_back(client);
}

// not thread safe
void runner::del_from_running_list(if_client* client) {
  std::vector<if_client*>::iterator iter;

  for (iter = _client_container.begin();
       iter != _client_container.end();
       ++iter) {
    if (*iter == client) {
      iter = _client_container.erase(iter);
    }
  }

  if (iter == _client_container.end()) {
    // todo : print error log
  }
}

void runner::run(void) {
  std::vector<if_server*>::iterator iter_server;
  std::vector<if_client*>::iterator iter_client;

  for (iter_server = _server_container.begin();
       iter_server != _server_container.end();
       ++iter_server) {
    if (0 != (*iter_server)->start_async_io())
      // todo : all stop to run the server already, print error log
      return;
  }

  for (iter_client = _client_container.begin();
       iter_client != _client_container.end();
       ++iter_client) {
    if (0 != (*iter_client)->start_async_io())
      // todo : all stop to run the server already, print error log
      return;
  }

  while (true) {
    // todo : catch for interrupting stop signal
  }
}

}  // namespace eznetpp
<commit_msg>change the push_back() to the emplace_back()<commit_after>// Copyright[2015] <kangic21@gmail.com>

#include "../include/runner.h"

#include "../include/if_server.h"
#include "../include/if_client.h"

namespace eznetpp {

runner::runner(void) {
}

runner::~runner(void) {
  _server_container.clear();
  _client_container.clear();
}

// not thread safe
void runner::add_to_running_list(if_server* server) {
  std::vector<if_server*>::iterator iter;

  for (iter = _server_container.begin();
       iter != _server_container.end();
       ++iter) {
    if (*iter == server) {
      // todo : print error log
    }
  }

  _server_container.emplace_back(server);
}

// not thread safe
void runner::del_from_running_list(if_server* server) {
  std::vector<if_server*>::iterator iter;

  for (iter = _server_container.begin();
       iter != _server_container.end();
       ++iter) {
    if (*iter == server) {
      iter = _server_container.erase(iter);
    }
  }

  if (iter == _server_container.end()) {
    // todo : print error log
  }
}

// not thread safe
void runner::add_to_running_list(if_client* client) {
  std::vector<if_client*>::iterator iter;

  for (iter = _client_container.begin();
       iter != _client_container.end();
       ++iter) {
    if (*iter == client) {
      // todo : print error log
    }
  }

  _client_container.push_back(client);
}

// not thread safe
void runner::del_from_running_list(if_client* client) {
  std::vector<if_client*>::iterator iter;

  for (iter = _client_container.begin();
       iter != _client_container.end();
       ++iter) {
    if (*iter == client) {
      iter = _client_container.erase(iter);
    }
  }

  if (iter == _client_container.end()) {
    // todo : print error log
  }
}

void runner::run(void) {
  std::vector<if_server*>::iterator iter_server;
  std::vector<if_client*>::iterator iter_client;

  for (iter_server = _server_container.begin();
       iter_server != _server_container.end();
       ++iter_server) {
    if (0 != (*iter_server)->start_async_io())
      // todo : all stop to run the server already, print error log
      return;
  }

  for (iter_client = _client_container.begin();
       iter_client != _client_container.end();
       ++iter_client) {
    if (0 != (*iter_client)->start_async_io())
      // todo : all stop to run the server already, print error log
      return;
  }

  while (true) {
    // todo : catch for interrupting stop signal
  }
}

}  // namespace eznetpp
<|endoftext|>


<commit_before>/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You 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.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee++ Internals --- Configuration Directives Tests
 *
 * @author Christopher Alfeld <calfeld@qualys.com>
 **/

#include <ironbeepp/configuration_directives.hpp>
#include <ironbeepp/configuration_parser.hpp>
#include <ironbeepp/context.hpp>
#include <ironbeepp/site.hpp>
#include "fixture.hpp"

#include "gtest/gtest.h"

#include <ironbee/engine.h>
#include <ironbee/config.h>

#include <boost/foreach.hpp>

using namespace std;
using namespace IronBee;

class TestConfigurationDirectives :
    public ::testing::Test, public IBPPTestFixture
{
};

struct Info
{
    Info() : which(0) {}

    int                 which;
    ConfigurationParser parser;
    string              name;
    string              param1;
    string              param2;
    bool                on;
    vector<string>      nparam;
    uint32_t            mask;
    uint32_t            value;
};

class Handler
{
public:
    explicit Handler(
        Info& out_info
    ) :
        m_out_info(out_info)
    {
        // nop
    }

    void operator()(
        ConfigurationParser parser,
        const char*         name,
        const char*         param1
    )
    {
        m_out_info.which  = 1;
        m_out_info.parser = parser;
        m_out_info.name   = name;
        m_out_info.param1 = param1;
    }

    void operator()(
        ConfigurationParser parser,
        const char*         name,
        const char*         param1,
        const char*         param2
    )
    {
        m_out_info.which  = 2;
        m_out_info.parser = parser;
        m_out_info.name   = name;
        m_out_info.param1 = param1;
        m_out_info.param2 = param2;
    }

    void operator()(
        ConfigurationParser parser,
        const char*         name
    )
    {
        m_out_info.which  = 3;
        m_out_info.parser = parser;
        m_out_info.name   = name;
    }

    void operator()(
        ConfigurationParser parser,
        const char*         name,
        bool                on
    )
    {
        m_out_info.which  = 4;
        m_out_info.parser = parser;
        m_out_info.name   = name;
        m_out_info.on     = on;
    }

    void operator()(
        ConfigurationParser parser,
        const char*         name,
        List<const char*>   args
    )
    {
        m_out_info.which  = 5;
        m_out_info.parser = parser;
        m_out_info.name   = name;

        BOOST_FOREACH(const char* a, args) {
            m_out_info.nparam.push_back(a);
        }
    }
    void operator()(
        ConfigurationParser parser,
        const char*         name,
        uint32_t            value,
        uint32_t            mask
    )
    {
        m_out_info.which  = 6;
        m_out_info.parser = parser;
        m_out_info.name   = name;
        m_out_info.value  = value;
        m_out_info.mask   = mask;
    }

private:
    Info& m_out_info;
};

TEST_F(TestConfigurationDirectives, Registrar)
{
    ib_cfgparser_t* parser = NULL;
    ib_status_t rc;

    rc = ib_cfgparser_create(&parser, m_engine.ib());
    ASSERT_EQ(IB_OK, rc);
    ASSERT_TRUE(parser);
    rc = ib_engine_config_started(m_engine.ib(), parser);
    ASSERT_EQ(IB_OK, rc);
    ConfigurationParser P(parser);

    Info info;
    Handler handler(info);
    Info info2;
    Handler handler2(info2);

    ConfigurationDirectivesRegistrar R(m_engine);
    R.param1("Param1", handler);
    R.param2("Param2", handler);
    R.block("Block", handler, handler2);
    R.on_off("OnOff", handler);
    R.list("List", handler);
    map<string,int64_t> value_map;
    value_map["a"] = (1 << 1) & (1 << 3);
    value_map["b"] = (1 << 7);
    R.op_flags("OpFlags", handler, value_map);

    info = Info();
    P.parse_buffer("Param1 HelloWorld\n", true);
    ib_cfgparser_apply(P.ib(), m_engine.ib());
    EXPECT_EQ(1,            info.which);
    EXPECT_EQ(P,            info.parser);
    EXPECT_EQ("Param1",     info.name);
    EXPECT_EQ("HelloWorld", info.param1);

    info = Info();
    P.parse_buffer("Param2 Foo Bar\n", true);
    ib_cfgparser_apply(P.ib(), m_engine.ib());
    EXPECT_EQ(2,        info.which);
    EXPECT_EQ(P,        info.parser);
    EXPECT_EQ("Param2", info.name);
    EXPECT_EQ("Foo",    info.param1);
    EXPECT_EQ("Bar",    info.param2);

    info = Info();
    info2 = Info();
    P.parse_buffer("<Block Foo>\n</Block>\n", true);
    ib_cfgparser_apply(P.ib(), m_engine.ib());
    EXPECT_EQ(1,       info.which);
    EXPECT_EQ(P,       info.parser);
    EXPECT_EQ("Block", info.name);
    EXPECT_EQ("Foo",   info.param1);
    EXPECT_EQ(3,       info2.which);
    EXPECT_EQ(P,       info2.parser);
    EXPECT_EQ("Block", info2.name);

    info = Info();
    P.parse_buffer("OnOff true\n", true);
    ib_cfgparser_apply(P.ib(), m_engine.ib());
    EXPECT_EQ(4,       info.which);
    EXPECT_EQ(P,       info.parser);
    EXPECT_EQ("OnOff", info.name);
    EXPECT_TRUE(info.on);

    info = Info();
    P.parse_buffer("OnOff false\n", true);
    ib_cfgparser_apply(P.ib(), m_engine.ib());
    EXPECT_EQ(4,       info.which);
    EXPECT_EQ(P,       info.parser);
    EXPECT_EQ("OnOff", info.name);
    EXPECT_FALSE(info.on);    info = Info();

    info = Info();
    P.parse_buffer("List a b c d\n", true);
    ib_cfgparser_apply(P.ib(), m_engine.ib());
    EXPECT_EQ(5,      info.which);
    EXPECT_EQ(P,      info.parser);
    EXPECT_EQ("List", info.name);
    EXPECT_EQ(4UL,    info.nparam.size());
    EXPECT_EQ("a",    info.nparam[0]);
    EXPECT_EQ("b",    info.nparam[1]);
    EXPECT_EQ("c",    info.nparam[2]);
    EXPECT_EQ("d",    info.nparam[3]);

    info = Info();
    P.parse_buffer("OpFlags +a -b\n", true);
    ib_cfgparser_apply(P.ib(), m_engine.ib());
    EXPECT_EQ(6,         info.which);
    EXPECT_EQ(P,         info.parser);
    EXPECT_EQ("OpFlags", info.name);
    EXPECT_EQ(value_map["a"] | value_map["b"], info.mask);
    EXPECT_EQ(value_map["a"], info.value & info.mask);
    EXPECT_EQ(value_map["b"], ~info.value & info.mask);

    rc = ib_engine_config_finished(m_engine.ib());
    ASSERT_EQ(IB_OK, rc);
    rc = ib_cfgparser_destroy(parser);
    ASSERT_EQ(IB_OK, rc);
}
<commit_msg>test_configuration_directives: Temporarily disabled the 'Registrar' test<commit_after>/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You 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.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee++ Internals --- Configuration Directives Tests
 *
 * @author Christopher Alfeld <calfeld@qualys.com>
 **/

#include <ironbeepp/configuration_directives.hpp>
#include <ironbeepp/configuration_parser.hpp>
#include <ironbeepp/context.hpp>
#include <ironbeepp/site.hpp>
#include "fixture.hpp"

#include "gtest/gtest.h"

#include <ironbee/engine.h>
#include <ironbee/config.h>

#include <boost/foreach.hpp>

using namespace std;
using namespace IronBee;

class TestConfigurationDirectives :
    public ::testing::Test, public IBPPTestFixture
{
};

struct Info
{
    Info() : which(0) {}

    int                 which;
    ConfigurationParser parser;
    string              name;
    string              param1;
    string              param2;
    bool                on;
    vector<string>      nparam;
    uint32_t            mask;
    uint32_t            value;
};

class Handler
{
public:
    explicit Handler(
        Info& out_info
    ) :
        m_out_info(out_info)
    {
        // nop
    }

    void operator()(
        ConfigurationParser parser,
        const char*         name,
        const char*         param1
    )
    {
        m_out_info.which  = 1;
        m_out_info.parser = parser;
        m_out_info.name   = name;
        m_out_info.param1 = param1;
    }

    void operator()(
        ConfigurationParser parser,
        const char*         name,
        const char*         param1,
        const char*         param2
    )
    {
        m_out_info.which  = 2;
        m_out_info.parser = parser;
        m_out_info.name   = name;
        m_out_info.param1 = param1;
        m_out_info.param2 = param2;
    }

    void operator()(
        ConfigurationParser parser,
        const char*         name
    )
    {
        m_out_info.which  = 3;
        m_out_info.parser = parser;
        m_out_info.name   = name;
    }

    void operator()(
        ConfigurationParser parser,
        const char*         name,
        bool                on
    )
    {
        m_out_info.which  = 4;
        m_out_info.parser = parser;
        m_out_info.name   = name;
        m_out_info.on     = on;
    }

    void operator()(
        ConfigurationParser parser,
        const char*         name,
        List<const char*>   args
    )
    {
        m_out_info.which  = 5;
        m_out_info.parser = parser;
        m_out_info.name   = name;

        BOOST_FOREACH(const char* a, args) {
            m_out_info.nparam.push_back(a);
        }
    }
    void operator()(
        ConfigurationParser parser,
        const char*         name,
        uint32_t            value,
        uint32_t            mask
    )
    {
        m_out_info.which  = 6;
        m_out_info.parser = parser;
        m_out_info.name   = name;
        m_out_info.value  = value;
        m_out_info.mask   = mask;
    }

private:
    Info& m_out_info;
};

TEST_F(TestConfigurationDirectives, DISABLED_Registrar)
{
    ib_cfgparser_t* parser = NULL;
    ib_status_t rc;

    rc = ib_cfgparser_create(&parser, m_engine.ib());
    ASSERT_EQ(IB_OK, rc);
    ASSERT_TRUE(parser);
    rc = ib_engine_config_started(m_engine.ib(), parser);
    ASSERT_EQ(IB_OK, rc);
    ConfigurationParser P(parser);

    Info info;
    Handler handler(info);
    Info info2;
    Handler handler2(info2);

    ConfigurationDirectivesRegistrar R(m_engine);
    R.param1("Param1", handler);
    R.param2("Param2", handler);
    R.block("Block", handler, handler2);
    R.on_off("OnOff", handler);
    R.list("List", handler);
    map<string,int64_t> value_map;
    value_map["a"] = (1 << 1) & (1 << 3);
    value_map["b"] = (1 << 7);
    R.op_flags("OpFlags", handler, value_map);

    info = Info();
    P.parse_buffer("Param1 HelloWorld\n", true);
    ib_cfgparser_apply(P.ib(), m_engine.ib());
    EXPECT_EQ(1,            info.which);
    EXPECT_EQ(P,            info.parser);
    EXPECT_EQ("Param1",     info.name);
    EXPECT_EQ("HelloWorld", info.param1);

    info = Info();
    P.parse_buffer("Param2 Foo Bar\n", true);
    ib_cfgparser_apply(P.ib(), m_engine.ib());
    EXPECT_EQ(2,        info.which);
    EXPECT_EQ(P,        info.parser);
    EXPECT_EQ("Param2", info.name);
    EXPECT_EQ("Foo",    info.param1);
    EXPECT_EQ("Bar",    info.param2);

    info = Info();
    info2 = Info();
    P.parse_buffer("<Block Foo>\n</Block>\n", true);
    ib_cfgparser_apply(P.ib(), m_engine.ib());
    EXPECT_EQ(1,       info.which);
    EXPECT_EQ(P,       info.parser);
    EXPECT_EQ("Block", info.name);
    EXPECT_EQ("Foo",   info.param1);
    EXPECT_EQ(3,       info2.which);
    EXPECT_EQ(P,       info2.parser);
    EXPECT_EQ("Block", info2.name);

    info = Info();
    P.parse_buffer("OnOff true\n", true);
    ib_cfgparser_apply(P.ib(), m_engine.ib());
    EXPECT_EQ(4,       info.which);
    EXPECT_EQ(P,       info.parser);
    EXPECT_EQ("OnOff", info.name);
    EXPECT_TRUE(info.on);

    info = Info();
    P.parse_buffer("OnOff false\n", true);
    ib_cfgparser_apply(P.ib(), m_engine.ib());
    EXPECT_EQ(4,       info.which);
    EXPECT_EQ(P,       info.parser);
    EXPECT_EQ("OnOff", info.name);
    EXPECT_FALSE(info.on);    info = Info();

    info = Info();
    P.parse_buffer("List a b c d\n", true);
    ib_cfgparser_apply(P.ib(), m_engine.ib());
    EXPECT_EQ(5,      info.which);
    EXPECT_EQ(P,      info.parser);
    EXPECT_EQ("List", info.name);
    EXPECT_EQ(4UL,    info.nparam.size());
    EXPECT_EQ("a",    info.nparam[0]);
    EXPECT_EQ("b",    info.nparam[1]);
    EXPECT_EQ("c",    info.nparam[2]);
    EXPECT_EQ("d",    info.nparam[3]);

    info = Info();
    P.parse_buffer("OpFlags +a -b\n", true);
    ib_cfgparser_apply(P.ib(), m_engine.ib());
    EXPECT_EQ(6,         info.which);
    EXPECT_EQ(P,         info.parser);
    EXPECT_EQ("OpFlags", info.name);
    EXPECT_EQ(value_map["a"] | value_map["b"], info.mask);
    EXPECT_EQ(value_map["a"], info.value & info.mask);
    EXPECT_EQ(value_map["b"], ~info.value & info.mask);

    rc = ib_engine_config_finished(m_engine.ib());
    ASSERT_EQ(IB_OK, rc);
    rc = ib_cfgparser_destroy(parser);
    ASSERT_EQ(IB_OK, rc);
}
<|endoftext|>


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

#include <Carbon/Carbon.h>

#include "base/gfx/rect.h"
#include "webkit/glue/plugins/fake_plugin_window_tracker_mac.h"

namespace webkit_glue {

void NotifyBrowserOfPluginSelectWindow(uint32 window_id, CGRect bounds);
void NotifyBrowserOfPluginShowWindow(uint32 window_id, CGRect bounds);
void NotifyBrowserOfPluginHideWindow(uint32 window_id, CGRect bounds);
void NotifyBrowserOfPluginDisposeWindow(uint32 window_id, CGRect bounds);

}  // namespace webkit_glue

// The process that was frontmost when a plugin created a new window; generally
// we expect this to be the browser UI process.
static ProcessSerialNumber g_saved_front_process = { 0, 0 };

// Bring the plugin process to the front so that the user can see it.
// TODO: Make this an IPC to order the plugin process above the browser
// process but not necessarily the frontmost.
static void SwitchToPluginProcess() {
  ProcessSerialNumber this_process, front_process;
  if (GetCurrentProcess(&this_process) != noErr)
    return;
  if (GetFrontProcess(&front_process) != noErr)
    return;
  Boolean matched = false;
  if (SameProcess(&this_process, &front_process, &matched) != noErr)
    return;
  if (!matched) {
    // TODO: We may need to keep a stack, or at least check the total window
    // count, since this won't work if a plugin opens more than one window at
    // a time.
    g_saved_front_process = front_process;
    SetFrontProcess(&this_process);
  }
}

// If the plugin process is still the front process, bring the prior
// front process (normally this will be the browser process) back to
// the front.
// TODO: Make this an IPC message so that the browser can properly
// reactivate the window.
static void SwitchToSavedProcess() {
  ProcessSerialNumber this_process, front_process;
  if (GetCurrentProcess(&this_process) != noErr)
    return;
  if (GetFrontProcess(&front_process) != noErr)
    return;
  Boolean matched = false;
  if (SameProcess(&this_process, &front_process, &matched) != noErr)
    return;
  if (matched) {
    SetFrontProcess(&g_saved_front_process);
  }
}

#pragma mark -

static Boolean ChromePluginIsWindowHilited(WindowRef window) {
  // TODO(stuartmorgan): Always returning true (instead of the real answer,
  // which would be false) means that clicking works, but it's not correct
  // either. Ideally we need a way to find out if the delegate corresponds
  // to a browser window that is active.
  const WebPluginDelegateImpl* delegate =
      FakePluginWindowTracker::SharedInstance()->GetDelegateForFakeWindow(
          window);
  Boolean isHilited = delegate ? true : IsWindowHilited(window);
  return isHilited;
}

static CGRect CGRectForWindow(WindowRef window) {
  CGRect bounds = { { 0, 0 }, { 0, 0 } };
  HIWindowGetBounds(window, kWindowContentRgn, kHICoordSpace72DPIGlobal,
                    &bounds);
  return bounds;
}

static void ChromePluginSelectWindow(WindowRef window) {
  SwitchToPluginProcess();
  SelectWindow(window);
  webkit_glue::NotifyBrowserOfPluginSelectWindow(HIWindowGetCGWindowID(window),
                                                 CGRectForWindow(window));
}

static void ChromePluginShowWindow(WindowRef window) {
  SwitchToPluginProcess();
  ShowWindow(window);
  webkit_glue::NotifyBrowserOfPluginShowWindow(HIWindowGetCGWindowID(window),
                                               CGRectForWindow(window));
}

static void ChromePluginDisposeWindow(WindowRef window) {
  SwitchToSavedProcess();
  webkit_glue::NotifyBrowserOfPluginDisposeWindow(HIWindowGetCGWindowID(window),
                                                  CGRectForWindow(window));
  DisposeWindow(window);
}

static void ChromePluginHideWindow(WindowRef window) {
  SwitchToSavedProcess();
  webkit_glue::NotifyBrowserOfPluginHideWindow(HIWindowGetCGWindowID(window),
                                               CGRectForWindow(window));
  HideWindow(window);
}

#pragma mark -

struct interpose_substitution {
  const void* replacement;
  const void* original;
};

#define INTERPOSE_FUNCTION(function) \
    { reinterpret_cast<const void*>(ChromePlugin##function), \
      reinterpret_cast<const void*>(function) }

__attribute__((used)) static const interpose_substitution substitutions[]
    __attribute__((section("__DATA, __interpose"))) = {
  INTERPOSE_FUNCTION(IsWindowHilited),
  INTERPOSE_FUNCTION(SelectWindow),
  INTERPOSE_FUNCTION(ShowWindow),
  INTERPOSE_FUNCTION(DisposeWindow),
  INTERPOSE_FUNCTION(HideWindow),
};
<commit_msg>Switch from plugin to browser process only when all windows close (Mac)<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <Carbon/Carbon.h>

#include "base/gfx/rect.h"
#include "webkit/glue/plugins/fake_plugin_window_tracker_mac.h"

namespace webkit_glue {

void NotifyBrowserOfPluginSelectWindow(uint32 window_id, CGRect bounds);
void NotifyBrowserOfPluginShowWindow(uint32 window_id, CGRect bounds);
void NotifyBrowserOfPluginHideWindow(uint32 window_id, CGRect bounds);
void NotifyBrowserOfPluginDisposeWindow(uint32 window_id, CGRect bounds);

}  // namespace webkit_glue

// The process that was frontmost when a plugin created a new window; generally
// we expect this to be the browser UI process.
static ProcessSerialNumber g_saved_front_process = { 0, 0 };

// Bring the plugin process to the front so that the user can see it.
// TODO: Make this an IPC to order the plugin process above the browser
// process but not necessarily the frontmost.
static void SwitchToPluginProcess() {
  ProcessSerialNumber this_process, front_process;
  if (GetCurrentProcess(&this_process) != noErr)
    return;
  if (GetFrontProcess(&front_process) != noErr)
    return;
  Boolean matched = false;
  if (SameProcess(&this_process, &front_process, &matched) != noErr)
    return;
  if (!matched) {
    g_saved_front_process = front_process;
    SetFrontProcess(&this_process);
  }
}

// If the plugin process is still the front process, bring the prior
// front process (normally this will be the browser process) back to
// the front.
// TODO: Make this an IPC message so that the browser can properly
// reactivate the window.
static void SwitchToSavedProcess() {
  ProcessSerialNumber this_process, front_process;
  if (GetCurrentProcess(&this_process) != noErr)
    return;
  if (GetFrontProcess(&front_process) != noErr)
    return;
  Boolean matched = false;
  if (SameProcess(&this_process, &front_process, &matched) != noErr)
    return;
  if (matched) {
    SetFrontProcess(&g_saved_front_process);
  }
}

// Checks to see if there are any plugin-opened windows still showing, and if
// not reactivates the saved process.
// Should be called after any window has been closed.
static void MaybeReactivateSavedProcess() {
  bool window_is_visible = false;
  WindowRef window = GetWindowList();
  while (window != NULL) {
    if (IsWindowVisible(window)) {
      window_is_visible = true;
      break;
    }
    window = GetNextWindow(window);
  }

  if (!window_is_visible)
    SwitchToSavedProcess();
}

#pragma mark -

static Boolean ChromePluginIsWindowHilited(WindowRef window) {
  // TODO(stuartmorgan): Always returning true (instead of the real answer,
  // which would be false) means that clicking works, but it's not correct
  // either. Ideally we need a way to find out if the delegate corresponds
  // to a browser window that is active.
  const WebPluginDelegateImpl* delegate =
      FakePluginWindowTracker::SharedInstance()->GetDelegateForFakeWindow(
          window);
  Boolean isHilited = delegate ? true : IsWindowHilited(window);
  return isHilited;
}

static CGRect CGRectForWindow(WindowRef window) {
  CGRect bounds = { { 0, 0 }, { 0, 0 } };
  HIWindowGetBounds(window, kWindowContentRgn, kHICoordSpace72DPIGlobal,
                    &bounds);
  return bounds;
}

static void ChromePluginSelectWindow(WindowRef window) {
  SwitchToPluginProcess();
  SelectWindow(window);
  webkit_glue::NotifyBrowserOfPluginSelectWindow(HIWindowGetCGWindowID(window),
                                                 CGRectForWindow(window));
}

static void ChromePluginShowWindow(WindowRef window) {
  SwitchToPluginProcess();
  ShowWindow(window);
  webkit_glue::NotifyBrowserOfPluginShowWindow(HIWindowGetCGWindowID(window),
                                               CGRectForWindow(window));
}

static void ChromePluginDisposeWindow(WindowRef window) {
  MaybeReactivateSavedProcess();
  webkit_glue::NotifyBrowserOfPluginDisposeWindow(HIWindowGetCGWindowID(window),
                                                  CGRectForWindow(window));
  DisposeWindow(window);
}

static void ChromePluginHideWindow(WindowRef window) {
  MaybeReactivateSavedProcess();
  webkit_glue::NotifyBrowserOfPluginHideWindow(HIWindowGetCGWindowID(window),
                                               CGRectForWindow(window));
  HideWindow(window);
}

#pragma mark -

struct interpose_substitution {
  const void* replacement;
  const void* original;
};

#define INTERPOSE_FUNCTION(function) \
    { reinterpret_cast<const void*>(ChromePlugin##function), \
      reinterpret_cast<const void*>(function) }

__attribute__((used)) static const interpose_substitution substitutions[]
    __attribute__((section("__DATA, __interpose"))) = {
  INTERPOSE_FUNCTION(IsWindowHilited),
  INTERPOSE_FUNCTION(SelectWindow),
  INTERPOSE_FUNCTION(ShowWindow),
  INTERPOSE_FUNCTION(DisposeWindow),
  INTERPOSE_FUNCTION(HideWindow),
};
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright (C) 2015 Felix Rohrbach <kde@fxrh.de>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "checkauthmethods.h"

#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <QtCore/QJsonParseError>

#include "../connectiondata.h"

using namespace QMatrixClient;

class CheckAuthMethods::Private
{
    public:
        Private() {}

        QString session;
};

CheckAuthMethods::CheckAuthMethods(ConnectionData* connection)
    : BaseJob(connection, JobHttpType::GetJob, "CheckAuthMethods", false)
    , d(new Private)
{
}

CheckAuthMethods::~CheckAuthMethods()
{
    delete d;
}

QString CheckAuthMethods::session()
{
    return d->session;
}

QString CheckAuthMethods::apiPath() const
{
    return "_matrix/client/r0/login";
}

BaseJob::Status CheckAuthMethods::parseJson(const QJsonDocument& data)
{
    // TODO
}
<commit_msg>CheckAuthMethods: fixed parseJson() to return some value<commit_after>/******************************************************************************
 * Copyright (C) 2015 Felix Rohrbach <kde@fxrh.de>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "checkauthmethods.h"

#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <QtCore/QJsonParseError>

#include "../connectiondata.h"

using namespace QMatrixClient;

class CheckAuthMethods::Private
{
    public:
        Private() {}

        QString session;
};

CheckAuthMethods::CheckAuthMethods(ConnectionData* connection)
    : BaseJob(connection, JobHttpType::GetJob, "CheckAuthMethods", false)
    , d(new Private)
{
}

CheckAuthMethods::~CheckAuthMethods()
{
    delete d;
}

QString CheckAuthMethods::session()
{
    return d->session;
}

QString CheckAuthMethods::apiPath() const
{
    return "_matrix/client/r0/login";
}

BaseJob::Status CheckAuthMethods::parseJson(const QJsonDocument& data)
{
    // TODO
    return { BaseJob::StatusCode::UserDefinedError, "Not implemented" };
}
<|endoftext|>


<commit_before>/* The Halfling Project - A Graphics Engine and Projects
 *
 * The Halfling Project is the legal property of Adrian Astley
 * Copyright Adrian Astley 2013
 */

#include "lighting_demo/graphics_manager.h"

#include "common/d3d_util.h"

#include "lighting_demo/game_state_manager.h"

#include "assert.h"
#include <AntTweakBar.h>

namespace LightingDemo {

GraphicsManager::GraphicsManager(GameStateManager *gameStateManager)
	: Common::GraphicsManagerBase(),
	  m_gameStateManager(gameStateManager),
	  m_vsync(false),
	  m_renderTargetView(nullptr),
	  m_inputLayout(nullptr),
	  m_vertexShaderFrameConstantsBuffer(nullptr),
	  m_vertexShaderObjectConstantsBuffer(nullptr),
	  m_pixelShaderFrameConstantsBuffer(nullptr),
	  m_pixelShaderObjectConstantsBuffer(nullptr),
	  m_pointLightBuffer(nullptr),
	  m_spotLightBuffer(nullptr),
	  m_vertexShader(nullptr),
	  m_pixelShader(nullptr),
	  m_wireframeRS(nullptr) {
}

bool GraphicsManager::Initialize(int clientWidth, int clientHeight, HWND hwnd, bool fullscreen) {
	if (!Common::GraphicsManagerBase::Initialize(clientWidth, clientHeight, hwnd, fullscreen))
		return false;

	InitTweakBar();

	if (!m_gameStateManager->Initialize(hwnd, &m_device))
		return false;

	LoadShaders();

	D3D11_RASTERIZER_DESC wireframeDesc;
	ZeroMemory(&wireframeDesc, sizeof(D3D11_RASTERIZER_DESC));
	wireframeDesc.FillMode = D3D11_FILL_WIREFRAME;
	wireframeDesc.CullMode = D3D11_CULL_BACK;
	wireframeDesc.FrontCounterClockwise = false;
	wireframeDesc.DepthClipEnable = true;

	HR(m_device->CreateRasterizerState(&wireframeDesc, &m_wireframeRS));

	return true;
}

void GraphicsManager::Shutdown() {
	// Release in the opposite order we initialized in
	ReleaseCOM(m_vertexShaderFrameConstantsBuffer);
	ReleaseCOM(m_vertexShaderObjectConstantsBuffer);
	ReleaseCOM(m_pixelShaderFrameConstantsBuffer);
	ReleaseCOM(m_pixelShaderObjectConstantsBuffer);
	delete m_pointLightBuffer;
	delete m_spotLightBuffer;
	ReleaseCOM(m_wireframeRS);
	ReleaseCOM(m_vertexShader);
	ReleaseCOM(m_pixelShader);
	ReleaseCOM(m_inputLayout);
	ReleaseCOM(m_renderTargetView);

	TwTerminate();

	Common::GraphicsManagerBase::Shutdown();
}

void GraphicsManager::DrawFrame(float deltaTime) {
	m_immediateContext->ClearRenderTargetView(m_renderTargetView, reinterpret_cast<const float*>(&Colors::Blue));
	m_immediateContext->ClearDepthStencilView(m_depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);

	// Transpose the matrices to prepare them for the shader.
	DirectX::XMMATRIX worldMatrix = m_gameStateManager->WorldViewProj.world;
	DirectX::XMMATRIX viewMatrix = m_gameStateManager->WorldViewProj.view;
	DirectX::XMMATRIX projectionMatrix = m_gameStateManager->WorldViewProj.projection;

	// Cache the matrix multiplications
	DirectX::XMMATRIX viewProj = DirectX::XMMatrixTranspose(viewMatrix * projectionMatrix);
	DirectX::XMMATRIX worldViewProjection = DirectX::XMMatrixTranspose(worldMatrix * viewMatrix * projectionMatrix);

	SetFrameConstants(DirectX::XMMatrixTranspose(projectionMatrix), viewProj);

	SetObjectConstants(DirectX::XMMatrixTranspose(worldMatrix), worldViewProjection, m_gameStateManager->Models[0].GetSubsetMaterial(0));
	SetLightBuffers(viewMatrix);

	m_immediateContext->IASetInputLayout(m_inputLayout);
	m_immediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	// Set the vertex and pixel shaders that will be used to render this triangle.
	m_immediateContext->VSSetShader(m_vertexShader, NULL, 0);
	m_immediateContext->PSSetShader(m_pixelShader, NULL, 0);

	m_gameStateManager->Models[0].DrawSubset(m_immediateContext);

	TwDraw();

	if (m_vsync)
		m_swapChain->Present(1, 0);
	else
		m_swapChain->Present(0, 0);
}

void GraphicsManager::SetFrameConstants(DirectX::XMMATRIX &projMatrix, DirectX::XMMATRIX &viewProjMatrix) {
	// Fill in frame constants
	D3D11_MAPPED_SUBRESOURCE mappedResource;

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_vertexShaderFrameConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	VertexShaderFrameConstants *vertexShaderFrameConstants = static_cast<VertexShaderFrameConstants *>(mappedResource.pData);
	vertexShaderFrameConstants->proj = projMatrix;
	vertexShaderFrameConstants->viewProj = viewProjMatrix;

	m_immediateContext->Unmap(m_vertexShaderFrameConstantsBuffer, 0);
	m_immediateContext->VSSetConstantBuffers(0, 1, &m_vertexShaderFrameConstantsBuffer);
}

void GraphicsManager::SetObjectConstants(DirectX::XMMATRIX &worldMatrix, DirectX::XMMATRIX &worldViewProjMatrix, const Common::Material &material) {
	// Fill in object constants
	D3D11_MAPPED_SUBRESOURCE mappedResource;

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_vertexShaderObjectConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	VertexShaderObjectConstants *vertexShaderObjectConstants = static_cast<VertexShaderObjectConstants *>(mappedResource.pData);
	vertexShaderObjectConstants->world = worldMatrix;
	vertexShaderObjectConstants->worldViewProj = worldViewProjMatrix;

	m_immediateContext->Unmap(m_vertexShaderObjectConstantsBuffer, 0);
	m_immediateContext->VSSetConstantBuffers(1, 1, &m_vertexShaderObjectConstantsBuffer);

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_pixelShaderObjectConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	PixelShaderObjectConstants *pixelShaderObjectConstants = static_cast<PixelShaderObjectConstants *>(mappedResource.pData);
	pixelShaderObjectConstants->material = material;

	m_immediateContext->Unmap(m_pixelShaderObjectConstantsBuffer, 0);
	m_immediateContext->PSSetConstantBuffers(3, 1, &m_pixelShaderObjectConstantsBuffer);

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_pixelShaderFrameConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	PixelShaderFrameConstants *pixelShaderFrameConstants = static_cast<PixelShaderFrameConstants *>(mappedResource.pData);
	pixelShaderFrameConstants->directionalLight = *(m_gameStateManager->LightManager.GetDirectionalLight());
	pixelShaderFrameConstants->eyePosition = m_gameStateManager->GetCameraPosition();

	m_immediateContext->Unmap(m_pixelShaderFrameConstantsBuffer, 0);
	m_immediateContext->PSSetConstantBuffers(2, 1, &m_pixelShaderFrameConstantsBuffer);
}

void GraphicsManager::SetLightBuffers(DirectX::XMMATRIX &viewMatrix) {
	//{
	//	Common::PointLight* light = m_pointLightBuffer->MapDiscard(m_immediateContext);
	//	for (unsigned int i = 0; i < mActiveLights; ++i) {
	//		light[i] = mPointLightParameters[i];
	//	}
	//	mLightBuffer->Unmap(d3dDeviceContext);
	//}
}

void GraphicsManager::OnResize(int newClientWidth, int newClientHeight) {
	if (!m_d3dInitialized) {
		return;
	}

	// Release the render target view
	ReleaseCOM(m_renderTargetView);

	Common::GraphicsManagerBase::OnResize(newClientWidth, newClientHeight);

	// Recreate the render target view.
	ID3D11Texture2D* backBuffer;
	HR(m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&backBuffer)));
	HR(m_device->CreateRenderTargetView(backBuffer, 0, &m_renderTargetView));
	ReleaseCOM(backBuffer);

	// Bind the render target view and depth/stencil view to the pipeline.
	m_immediateContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView);
}

void GraphicsManager::InitTweakBar() {
	int success = TwInit(TW_DIRECT3D11, m_device);

	m_tweakBar = TwNewBar("RootMenu");
	TwAddVarRW(m_tweakBar, "V-Sync", TwType::TW_TYPE_BOOLCPP, &m_vsync, "");
	TwDefine(" RootMenu movable=false resizable=false fontresizable=false contained=true ");
}

void GraphicsManager::LoadShaders() {
	D3D11_INPUT_ELEMENT_DESC vertexDesc[] = {
		{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
		{"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}
	};

	HR(Common::LoadVertexShader("vertex_shader.cso", m_device, vertexDesc, 2, &m_vertexShader, &m_inputLayout));
	HR(Common::LoadPixelShader("pixel_shader.cso", m_device, &m_pixelShader));

	// Create the constant shader buffers
	D3D11_BUFFER_DESC vertexShaderFrameBufferDesc;
	vertexShaderFrameBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	vertexShaderFrameBufferDesc.ByteWidth = sizeof(VertexShaderFrameConstants);
	vertexShaderFrameBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	vertexShaderFrameBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	vertexShaderFrameBufferDesc.MiscFlags = 0;
	vertexShaderFrameBufferDesc.StructureByteStride = 0;

	m_device->CreateBuffer(&vertexShaderFrameBufferDesc, NULL, &m_vertexShaderFrameConstantsBuffer);

	D3D11_BUFFER_DESC vertexShaderObjectBufferDesc;
	vertexShaderObjectBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	vertexShaderObjectBufferDesc.ByteWidth = sizeof(VertexShaderObjectConstants);
	vertexShaderObjectBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	vertexShaderObjectBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	vertexShaderObjectBufferDesc.MiscFlags = 0;
	vertexShaderObjectBufferDesc.StructureByteStride = 0;

	m_device->CreateBuffer(&vertexShaderObjectBufferDesc, NULL, &m_vertexShaderObjectConstantsBuffer);

	D3D11_BUFFER_DESC pixelShaderFrameBufferDesc;
	pixelShaderFrameBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	pixelShaderFrameBufferDesc.ByteWidth = sizeof(PixelShaderFrameConstants);
	pixelShaderFrameBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	pixelShaderFrameBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	pixelShaderFrameBufferDesc.MiscFlags = 0;
	pixelShaderFrameBufferDesc.StructureByteStride = 0;

	m_device->CreateBuffer(&pixelShaderFrameBufferDesc, NULL, &m_pixelShaderFrameConstantsBuffer);

	D3D11_BUFFER_DESC pixelShaderObjectBufferDesc;
	pixelShaderObjectBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	pixelShaderObjectBufferDesc.ByteWidth = sizeof(PixelShaderObjectConstants);
	pixelShaderObjectBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	pixelShaderObjectBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	pixelShaderObjectBufferDesc.MiscFlags = 0;
	pixelShaderObjectBufferDesc.StructureByteStride = 0;

	m_device->CreateBuffer(&pixelShaderObjectBufferDesc, NULL, &m_pixelShaderObjectConstantsBuffer);

	m_pointLightBuffer = new Common::StructuredBuffer<Common::PointLight>(m_device, 1, D3D11_BIND_SHADER_RESOURCE, true);
	m_spotLightBuffer = new Common::StructuredBuffer<Common::SpotLight>(m_device, 1, D3D11_BIND_SHADER_RESOURCE, true);
}

} // End of namespace CrateDemo
<commit_msg>LIGHTING_DEMO: Calculate frame stats every frame<commit_after>/* The Halfling Project - A Graphics Engine and Projects
 *
 * The Halfling Project is the legal property of Adrian Astley
 * Copyright Adrian Astley 2013
 */

#include "lighting_demo/graphics_manager.h"

#include "common/d3d_util.h"

#include "lighting_demo/game_state_manager.h"

#include "assert.h"
#include <AntTweakBar.h>

namespace LightingDemo {

GraphicsManager::GraphicsManager(GameStateManager *gameStateManager)
	: Common::GraphicsManagerBase(),
	  m_gameStateManager(gameStateManager),
	  m_vsync(false),
	  m_renderTargetView(nullptr),
	  m_inputLayout(nullptr),
	  m_vertexShaderFrameConstantsBuffer(nullptr),
	  m_vertexShaderObjectConstantsBuffer(nullptr),
	  m_pixelShaderFrameConstantsBuffer(nullptr),
	  m_pixelShaderObjectConstantsBuffer(nullptr),
	  m_pointLightBuffer(nullptr),
	  m_spotLightBuffer(nullptr),
	  m_vertexShader(nullptr),
	  m_pixelShader(nullptr),
	  m_wireframeRS(nullptr) {
}

bool GraphicsManager::Initialize(int clientWidth, int clientHeight, HWND hwnd, bool fullscreen) {
	if (!Common::GraphicsManagerBase::Initialize(clientWidth, clientHeight, hwnd, fullscreen))
		return false;

	InitTweakBar();

	if (!m_gameStateManager->Initialize(hwnd, &m_device))
		return false;

	LoadShaders();

	D3D11_RASTERIZER_DESC wireframeDesc;
	ZeroMemory(&wireframeDesc, sizeof(D3D11_RASTERIZER_DESC));
	wireframeDesc.FillMode = D3D11_FILL_WIREFRAME;
	wireframeDesc.CullMode = D3D11_CULL_BACK;
	wireframeDesc.FrontCounterClockwise = false;
	wireframeDesc.DepthClipEnable = true;

	HR(m_device->CreateRasterizerState(&wireframeDesc, &m_wireframeRS));

	return true;
}

void GraphicsManager::Shutdown() {
	// Release in the opposite order we initialized in
	ReleaseCOM(m_vertexShaderFrameConstantsBuffer);
	ReleaseCOM(m_vertexShaderObjectConstantsBuffer);
	ReleaseCOM(m_pixelShaderFrameConstantsBuffer);
	ReleaseCOM(m_pixelShaderObjectConstantsBuffer);
	delete m_pointLightBuffer;
	delete m_spotLightBuffer;
	ReleaseCOM(m_wireframeRS);
	ReleaseCOM(m_vertexShader);
	ReleaseCOM(m_pixelShader);
	ReleaseCOM(m_inputLayout);
	ReleaseCOM(m_renderTargetView);

	TwTerminate();

	Common::GraphicsManagerBase::Shutdown();
}

void GraphicsManager::DrawFrame(float deltaTime) {
	CalculateFrameStats(deltaTime);

	m_immediateContext->ClearRenderTargetView(m_renderTargetView, reinterpret_cast<const float*>(&Colors::Blue));
	m_immediateContext->ClearDepthStencilView(m_depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);

	// Transpose the matrices to prepare them for the shader.
	DirectX::XMMATRIX worldMatrix = m_gameStateManager->WorldViewProj.world;
	DirectX::XMMATRIX viewMatrix = m_gameStateManager->WorldViewProj.view;
	DirectX::XMMATRIX projectionMatrix = m_gameStateManager->WorldViewProj.projection;

	// Cache the matrix multiplications
	DirectX::XMMATRIX viewProj = DirectX::XMMatrixTranspose(viewMatrix * projectionMatrix);
	DirectX::XMMATRIX worldViewProjection = DirectX::XMMatrixTranspose(worldMatrix * viewMatrix * projectionMatrix);

	SetFrameConstants(DirectX::XMMatrixTranspose(projectionMatrix), viewProj);

	SetObjectConstants(DirectX::XMMatrixTranspose(worldMatrix), worldViewProjection, m_gameStateManager->Models[0].GetSubsetMaterial(0));
	SetLightBuffers(viewMatrix);

	m_immediateContext->IASetInputLayout(m_inputLayout);
	m_immediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	// Set the vertex and pixel shaders that will be used to render this triangle.
	m_immediateContext->VSSetShader(m_vertexShader, NULL, 0);
	m_immediateContext->PSSetShader(m_pixelShader, NULL, 0);

	m_gameStateManager->Models[0].DrawSubset(m_immediateContext);

	TwDraw();

	if (m_vsync)
		m_swapChain->Present(1, 0);
	else
		m_swapChain->Present(0, 0);
}

void GraphicsManager::SetFrameConstants(DirectX::XMMATRIX &projMatrix, DirectX::XMMATRIX &viewProjMatrix) {
	// Fill in frame constants
	D3D11_MAPPED_SUBRESOURCE mappedResource;

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_vertexShaderFrameConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	VertexShaderFrameConstants *vertexShaderFrameConstants = static_cast<VertexShaderFrameConstants *>(mappedResource.pData);
	vertexShaderFrameConstants->proj = projMatrix;
	vertexShaderFrameConstants->viewProj = viewProjMatrix;

	m_immediateContext->Unmap(m_vertexShaderFrameConstantsBuffer, 0);
	m_immediateContext->VSSetConstantBuffers(0, 1, &m_vertexShaderFrameConstantsBuffer);
}

void GraphicsManager::SetObjectConstants(DirectX::XMMATRIX &worldMatrix, DirectX::XMMATRIX &worldViewProjMatrix, const Common::Material &material) {
	// Fill in object constants
	D3D11_MAPPED_SUBRESOURCE mappedResource;

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_vertexShaderObjectConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	VertexShaderObjectConstants *vertexShaderObjectConstants = static_cast<VertexShaderObjectConstants *>(mappedResource.pData);
	vertexShaderObjectConstants->world = worldMatrix;
	vertexShaderObjectConstants->worldViewProj = worldViewProjMatrix;

	m_immediateContext->Unmap(m_vertexShaderObjectConstantsBuffer, 0);
	m_immediateContext->VSSetConstantBuffers(1, 1, &m_vertexShaderObjectConstantsBuffer);

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_pixelShaderObjectConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	PixelShaderObjectConstants *pixelShaderObjectConstants = static_cast<PixelShaderObjectConstants *>(mappedResource.pData);
	pixelShaderObjectConstants->material = material;

	m_immediateContext->Unmap(m_pixelShaderObjectConstantsBuffer, 0);
	m_immediateContext->PSSetConstantBuffers(3, 1, &m_pixelShaderObjectConstantsBuffer);

	// Lock the constant buffer so it can be written to.
	HR(m_immediateContext->Map(m_pixelShaderFrameConstantsBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource));

	PixelShaderFrameConstants *pixelShaderFrameConstants = static_cast<PixelShaderFrameConstants *>(mappedResource.pData);
	pixelShaderFrameConstants->directionalLight = *(m_gameStateManager->LightManager.GetDirectionalLight());
	pixelShaderFrameConstants->eyePosition = m_gameStateManager->GetCameraPosition();

	m_immediateContext->Unmap(m_pixelShaderFrameConstantsBuffer, 0);
	m_immediateContext->PSSetConstantBuffers(2, 1, &m_pixelShaderFrameConstantsBuffer);
}

void GraphicsManager::SetLightBuffers(DirectX::XMMATRIX &viewMatrix) {
	//{
	//	Common::PointLight* light = m_pointLightBuffer->MapDiscard(m_immediateContext);
	//	for (unsigned int i = 0; i < mActiveLights; ++i) {
	//		light[i] = mPointLightParameters[i];
	//	}
	//	mLightBuffer->Unmap(d3dDeviceContext);
	//}
}

void GraphicsManager::OnResize(int newClientWidth, int newClientHeight) {
	if (!m_d3dInitialized) {
		return;
	}

	// Release the render target view
	ReleaseCOM(m_renderTargetView);

	Common::GraphicsManagerBase::OnResize(newClientWidth, newClientHeight);

	// Recreate the render target view.
	ID3D11Texture2D* backBuffer;
	HR(m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(&backBuffer)));
	HR(m_device->CreateRenderTargetView(backBuffer, 0, &m_renderTargetView));
	ReleaseCOM(backBuffer);

	// Bind the render target view and depth/stencil view to the pipeline.
	m_immediateContext->OMSetRenderTargets(1, &m_renderTargetView, m_depthStencilView);
}

void GraphicsManager::InitTweakBar() {
	int success = TwInit(TW_DIRECT3D11, m_device);

	m_tweakBar = TwNewBar("RootMenu");
	TwAddVarRW(m_tweakBar, "V-Sync", TwType::TW_TYPE_BOOLCPP, &m_vsync, "");
	TwDefine(" RootMenu movable=false resizable=false fontresizable=false contained=true ");
}

void GraphicsManager::LoadShaders() {
	D3D11_INPUT_ELEMENT_DESC vertexDesc[] = {
		{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
		{"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0}
	};

	HR(Common::LoadVertexShader("vertex_shader.cso", m_device, vertexDesc, 2, &m_vertexShader, &m_inputLayout));
	HR(Common::LoadPixelShader("pixel_shader.cso", m_device, &m_pixelShader));

	// Create the constant shader buffers
	D3D11_BUFFER_DESC vertexShaderFrameBufferDesc;
	vertexShaderFrameBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	vertexShaderFrameBufferDesc.ByteWidth = sizeof(VertexShaderFrameConstants);
	vertexShaderFrameBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	vertexShaderFrameBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	vertexShaderFrameBufferDesc.MiscFlags = 0;
	vertexShaderFrameBufferDesc.StructureByteStride = 0;

	m_device->CreateBuffer(&vertexShaderFrameBufferDesc, NULL, &m_vertexShaderFrameConstantsBuffer);

	D3D11_BUFFER_DESC vertexShaderObjectBufferDesc;
	vertexShaderObjectBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	vertexShaderObjectBufferDesc.ByteWidth = sizeof(VertexShaderObjectConstants);
	vertexShaderObjectBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	vertexShaderObjectBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	vertexShaderObjectBufferDesc.MiscFlags = 0;
	vertexShaderObjectBufferDesc.StructureByteStride = 0;

	m_device->CreateBuffer(&vertexShaderObjectBufferDesc, NULL, &m_vertexShaderObjectConstantsBuffer);

	D3D11_BUFFER_DESC pixelShaderFrameBufferDesc;
	pixelShaderFrameBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	pixelShaderFrameBufferDesc.ByteWidth = sizeof(PixelShaderFrameConstants);
	pixelShaderFrameBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	pixelShaderFrameBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	pixelShaderFrameBufferDesc.MiscFlags = 0;
	pixelShaderFrameBufferDesc.StructureByteStride = 0;

	m_device->CreateBuffer(&pixelShaderFrameBufferDesc, NULL, &m_pixelShaderFrameConstantsBuffer);

	D3D11_BUFFER_DESC pixelShaderObjectBufferDesc;
	pixelShaderObjectBufferDesc.Usage = D3D11_USAGE_DYNAMIC;
	pixelShaderObjectBufferDesc.ByteWidth = sizeof(PixelShaderObjectConstants);
	pixelShaderObjectBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
	pixelShaderObjectBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
	pixelShaderObjectBufferDesc.MiscFlags = 0;
	pixelShaderObjectBufferDesc.StructureByteStride = 0;

	m_device->CreateBuffer(&pixelShaderObjectBufferDesc, NULL, &m_pixelShaderObjectConstantsBuffer);

	m_pointLightBuffer = new Common::StructuredBuffer<Common::PointLight>(m_device, 1, D3D11_BIND_SHADER_RESOURCE, true);
	m_spotLightBuffer = new Common::StructuredBuffer<Common::SpotLight>(m_device, 1, D3D11_BIND_SHADER_RESOURCE, true);
}

} // End of namespace CrateDemo
<|endoftext|>