<commit_before>// $Id: $
/**
 * \ingroup trigger_menus
 * \file HM_PHYSICS_V0002.C
 * \brief Macro for generating the trigger menu for min-bias p+p triggering.
 *
 * This macro generates the HM-PHYSICS-V0002 global trigger configuration.
 *
 * You can run this macro with defaults using the following shell command:
 * \code
 *   > aliroot -b -q $ALICE_ROOT/HLT/trigger/HM_PHYSICS_V0002.C
 * \endcode
 *
 * Configuration:
 *  Only triggering on min-bias CTP triggers, pass through all other triggers.
 *  Scale down the trigger rate and store HLT ESD for rejected events.
 *  Triggering on high pT tracks as defined by CDB entries:
 *   H_._Barrel_pT_Single_._V0001.001
 *   H_._Barrel_pT_Single_._V0002.001
 *   H_._Barrel_pT_Single_._V0003.001
 *
 * \note The above mentioned CDB entries must already exist. They are not created
 *    by this macro.
 *
 * \author Artur Szostak <artursz@iafrica.com>
 */

#if !defined(__CINT__) || defined(__MAKECINT__)
#include "AliCDBManager.h"
#include "AliCDBStorage.h"
#include "AliCDBEntry.h"
#include "AliHLTTriggerMenu.h"
#include "AliHLTReadoutList.h"
#include "AliHLTGlobalTriggerConfig.h"
#include "TObjString.h"
#include "TString.h"
#include "TSystem.h"
#include "Riostream.h"
using std::cerr;
using std::endl;
#endif

/**
 * Generates a default CDB entry for the trigger menu in the given CDB storage
 * (local by default).
 * \param cdbPath  The path to the default CDB storage.
 */
void HM_PHYSICS_V0002(
		      const char* cdbPath = "local://$ALICE_ROOT/OCDB",
		      Int_t version = 0,
		      Int_t firstRun = 0,
		      Int_t lastRun = AliCDBRunRange::Infinity()
		     )
{
  gSystem->Load("libANALYSIS.so");
  gSystem->Load("libANALYSISalice.so");
  gSystem->Load("libAliHLTUtil.so");
  gSystem->Load("libAliHLTMUON.so");
  gSystem->Load("libAliHLTTRD.so");
  gSystem->Load("libAliHLTTrigger.so");

  // Setup the CDB default storage and run number.
  AliCDBManager* cdbManager = AliCDBManager::Instance();
  if (cdbManager == NULL) {
    cerr << "ERROR: Global CDB manager object does not exist." << endl;
    return;
  }

  AliCDBStorage* storage = cdbManager->GetStorage(cdbPath);
  if (storage == NULL) {
    cerr << "ERROR: Could not get storage for: " << cdbPath << endl;
    return;
  }

  ///////////////////////////////////////////////////////////////////////////////////////////
  // Create the trigger menu:

  AliHLTGlobalTriggerConfig config("HM-PHYSICS-V0002");

  ///////////////////////////////////////////////////////////////////////////////////////////
  // Predefine some explicit domain definitions used in the trigger menu.
  config.AddSymbol("domainTObject"   , "AliHLTTriggerDomain", "", "AliHLTTriggerDomain(\"ROOTTOBJ:HLT \")");
  config.AddSymbol("domainESD"       , "AliHLTTriggerDomain", "", "AliHLTTriggerDomain(\"ALIESDV0:HLT \")");
  config.AddSymbol("domainHistogram" , "AliHLTTriggerDomain", "", "AliHLTTriggerDomain(\"ROOTHIST:HLT \")");
  config.AddSymbol("domainSPDCluster", "AliHLTTriggerDomain", "", "AliHLTTriggerDomain(\"CLUSTERS:ISPD\")");
  config.AddSymbol("domainSDDCluster", "AliHLTTriggerDomain", "", "AliHLTTriggerDomain(\"CLUSTERS:ISDD\")");
  config.AddSymbol("domainSSDCluster", "AliHLTTriggerDomain", "", "AliHLTTriggerDomain(\"CLUSTERS:ISSD\")");
  config.AddSymbol("domainTPCCluster", "AliHLTTriggerDomain", "", "AliHLTTriggerDomain(\"CLUSTERS:TPC \")");

  config.AddSymbol("domainHLTOUT", "AliHLTTriggerDomain", "",
		   "domainTObject    | "
		   "domainESD        | "
		   "domainHistogram  | "
		   "domainSPDCluster | "
		   "domainSDDCluster | "
		   "domainSSDCluster | "
		   "domainTPCCluster"
		   );

  config.AddSymbol("domainALLDDL", "AliHLTTriggerDomain", "", "AliHLTTriggerDomain(\"DAQRDOUT:***\")");
  config.AddSymbol("domainHLTDDL", "AliHLTTriggerDomain", "", "AliHLTTriggerDomain(\"DAQRDOUT:HLT\")");

  ///////////////////////////////////////////////////////////////////////////////////////////
  // Setup the trigger items in 5 priority groups.
  // Group 5 is for the HLT triggers.
  // Group 4 is for scaling down min-bias CTP interaction triggers.
  // Group 2 and 3 are used to readout only HLT ESDs for rejected min bias events.
  // The last group (1) handles special software triggers.

  config.AddItem(
		 5, // priority group.
		 "(CINT1WU-B-NOPF-ALL || CINT1-B-NOPF-ALLNOTRD) && H-Barrel_pT_Single-V0001.001",
		 "domainHLTOUT | domainALLDDL",
		 5,  // scaledown factor 1/5
		 "H-Barrel_pT_Single-V0001.001-ALL-ALL"
		 );

  config.AddItem(
		 5, // priority group.
		 "(CINT1WU-B-NOPF-ALL || CINT1-B-NOPF-ALLNOTRD) && H-Barrel_pT_Single-V0002.001",
		 "domainHLTOUT | domainALLDDL",
		 2,  // scaledown factor 1/2
		 "H-Barrel_pT_Single-V0002.001-ALL-ALL"
		 );

  config.AddItem(
		 5, // priority group.
		 "(CINT1WU-B-NOPF-ALL || CINT1-B-NOPF-ALLNOTRD) && H-Barrel_pT_Single-V0003.001",
		 "domainHLTOUT | domainALLDDL",
		 "H-Barrel_pT_Single-V0003.001-ALL-ALL"
		 );

  config.AddItem(
		 4, // priority group.
		 "CINT1WU-B-NOPF-ALL || CINT1-B-NOPF-ALLNOTRD",
		 "domainHLTOUT | domainALLDDL",
		 "H-MINBIAS_SCALE_DOWN-V0003.001-CENTRAL-ALL",
		 15.  // scaledown factor 0.15
		 );

  // Readout only 50% of HLT ESDs for min bias.
  config.AddItem(
		 3, // priority group.
		 "CINT1WU-B-NOPF-ALL || CINT1-B-NOPF-ALLNOTRD",
		 "domainESD | domainHLTDDL",
		 2,  // scaledown factor 1/2
		 "Rejected min-bias with HLT ESD readout",
		 false  // default global trigger decision result
		 );

  // Reject completely the other 50% min bias.
  config.AddItem(
		 2, // priority group.
		 "CINT1WU-B-NOPF-ALL || CINT1-B-NOPF-ALLNOTRD",
		 "domainHLTDDL",  // Only HLT DDL to deliver at least the decision.
		 0,  // No prescalar (no scaledown)
		 "Rejected min-bias",
		 false  // default global trigger decision result
		 );

  config.AddItem(
		 1, // priority group.
		 "SOFTWARE || CALIBRATION || START_OF_DATA || END_OF_DATA",
		 //"domainHLTOUT | domainALLDDL",
		 "SOFTWARE | CALIBRATION | START_OF_DATA | END_OF_DATA",
		 "H-SoftwareTrigger-V0001.001-ALL-ALL"
		 );

  ///////////////////////////////////////////////////////////////////////////////////////////
  // Setup defaults in case there is no global trigger.
  // For non-triggered events store everything from HLT and readout all detectors.
  config.SetDefaultTriggerDescription("No HLT global trigger");
  AliHLTTriggerDomain defaultDomain("*******:***");
  AliHLTReadoutList readoutlist;
  readoutlist.Enable(AliHLTReadoutList::kALLDET);
  defaultDomain.Add(readoutlist);
  config.SetDefaultTriggerDomain(defaultDomain);
  config.SetDefaultResult(true);

  TObject* menu = AliHLTGlobalTriggerConfig::Menu()->Clone();
  menu->Print();

  ///////////////////////////////////////////////////////////////////////////////////////////
  // Write the trigger menu object to the CDB.
  AliCDBId id("HLT/ConfigHLT/HLTGlobalTrigger", firstRun, lastRun, version);
  AliCDBMetaData* metaData = new AliCDBMetaData();
  metaData->SetResponsible("ALICE HLT Artur.Szostak@cern.ch");
  metaData->SetComment("HM-PHYSICS-V0002");
  storage->Put(menu, id, metaData);
}
<commit_msg>Minor fix for software triggers.<commit_after>// $Id: $
/**
 * \ingroup trigger_menus
 * \file HM_PHYSICS_V0002.C
 * \brief Macro for generating the trigger menu for min-bias p+p triggering.
 *
 * This macro generates the HM-PHYSICS-V0002 global trigger configuration.
 *
 * You can run this macro with defaults using the following shell command:
 * \code
 *   > aliroot -b -q $ALICE_ROOT/HLT/trigger/HM_PHYSICS_V0002.C
 * \endcode
 *
 * Configuration:
 *  Only triggering on min-bias CTP triggers, pass through all other triggers.
 *  Scale down the trigger rate and store HLT ESD for rejected events.
 *  Triggering on high pT tracks as defined by CDB entries:
 *   H_._Barrel_pT_Single_._V0001.001
 *   H_._Barrel_pT_Single_._V0002.001
 *   H_._Barrel_pT_Single_._V0003.001
 *
 * \note The above mentioned CDB entries must already exist. They are not created
 *    by this macro.
 *
 * \author Artur Szostak <artursz@iafrica.com>
 */

#if !defined(__CINT__) || defined(__MAKECINT__)
#include "AliCDBManager.h"
#include "AliCDBStorage.h"
#include "AliCDBEntry.h"
#include "AliHLTTriggerMenu.h"
#include "AliHLTReadoutList.h"
#include "AliHLTGlobalTriggerConfig.h"
#include "TObjString.h"
#include "TString.h"
#include "TSystem.h"
#include "Riostream.h"
using std::cerr;
using std::endl;
#endif

/**
 * Generates a default CDB entry for the trigger menu in the given CDB storage
 * (local by default).
 * \param cdbPath  The path to the default CDB storage.
 */
void HM_PHYSICS_V0002(
		      const char* cdbPath = "local://$ALICE_ROOT/OCDB",
		      Int_t version = 0,
		      Int_t firstRun = 0,
		      Int_t lastRun = AliCDBRunRange::Infinity()
		     )
{
  gSystem->Load("libANALYSIS.so");
  gSystem->Load("libANALYSISalice.so");
  gSystem->Load("libAliHLTUtil.so");
  gSystem->Load("libAliHLTMUON.so");
  gSystem->Load("libAliHLTTRD.so");
  gSystem->Load("libAliHLTTrigger.so");

  // Setup the CDB default storage and run number.
  AliCDBManager* cdbManager = AliCDBManager::Instance();
  if (cdbManager == NULL) {
    cerr << "ERROR: Global CDB manager object does not exist." << endl;
    return;
  }

  AliCDBStorage* storage = cdbManager->GetStorage(cdbPath);
  if (storage == NULL) {
    cerr << "ERROR: Could not get storage for: " << cdbPath << endl;
    return;
  }

  ///////////////////////////////////////////////////////////////////////////////////////////
  // Create the trigger menu:

  AliHLTGlobalTriggerConfig config("HM-PHYSICS-V0002");

  ///////////////////////////////////////////////////////////////////////////////////////////
  // Predefine some explicit domain definitions used in the trigger menu.
  config.AddSymbol("domainTObject"   , "AliHLTTriggerDomain", "", "AliHLTTriggerDomain(\"ROOTTOBJ:HLT \")");
  config.AddSymbol("domainESD"       , "AliHLTTriggerDomain", "", "AliHLTTriggerDomain(\"ALIESDV0:HLT \")");
  config.AddSymbol("domainHistogram" , "AliHLTTriggerDomain", "", "AliHLTTriggerDomain(\"ROOTHIST:HLT \")");
  config.AddSymbol("domainSPDCluster", "AliHLTTriggerDomain", "", "AliHLTTriggerDomain(\"CLUSTERS:ISPD\")");
  config.AddSymbol("domainSDDCluster", "AliHLTTriggerDomain", "", "AliHLTTriggerDomain(\"CLUSTERS:ISDD\")");
  config.AddSymbol("domainSSDCluster", "AliHLTTriggerDomain", "", "AliHLTTriggerDomain(\"CLUSTERS:ISSD\")");
  config.AddSymbol("domainTPCCluster", "AliHLTTriggerDomain", "", "AliHLTTriggerDomain(\"CLUSTERS:TPC \")");

  config.AddSymbol("domainHLTOUT", "AliHLTTriggerDomain", "",
		   "domainTObject    | "
		   "domainESD        | "
		   "domainHistogram  | "
		   "domainSPDCluster | "
		   "domainSDDCluster | "
		   "domainSSDCluster | "
		   "domainTPCCluster"
		   );

  config.AddSymbol("domainALLDDL", "AliHLTTriggerDomain", "", "AliHLTTriggerDomain(\"DAQRDOUT:***\")");
  config.AddSymbol("domainHLTDDL", "AliHLTTriggerDomain", "", "AliHLTTriggerDomain(\"DAQRDOUT:HLT\")");

  ///////////////////////////////////////////////////////////////////////////////////////////
  // Setup the trigger items in 5 priority groups.
  // Group 5 is for the HLT triggers.
  // Group 4 is for scaling down min-bias CTP interaction triggers.
  // Group 2 and 3 are used to readout only HLT ESDs for rejected min bias events.
  // The last group (1) handles special software triggers.

  config.AddItem(
		 5, // priority group.
		 "(CINT1WU-B-NOPF-ALL || CINT1-B-NOPF-ALLNOTRD) && H-Barrel_pT_Single-V0001.001",
		 "domainHLTOUT | domainALLDDL",
		 5,  // scaledown factor 1/5
		 "H-Barrel_pT_Single-V0001.001-ALL-ALL"
		 );

  config.AddItem(
		 5, // priority group.
		 "(CINT1WU-B-NOPF-ALL || CINT1-B-NOPF-ALLNOTRD) && H-Barrel_pT_Single-V0002.001",
		 "domainHLTOUT | domainALLDDL",
		 2,  // scaledown factor 1/2
		 "H-Barrel_pT_Single-V0002.001-ALL-ALL"
		 );

  config.AddItem(
		 5, // priority group.
		 "(CINT1WU-B-NOPF-ALL || CINT1-B-NOPF-ALLNOTRD) && H-Barrel_pT_Single-V0003.001",
		 "domainHLTOUT | domainALLDDL",
		 "H-Barrel_pT_Single-V0003.001-ALL-ALL"
		 );

  config.AddItem(
		 4, // priority group.
		 "CINT1WU-B-NOPF-ALL || CINT1-B-NOPF-ALLNOTRD",
		 "domainHLTOUT | domainALLDDL",
		 "H-MINBIAS_SCALE_DOWN-V0003.001-CENTRAL-ALL",
		 15.  // scaledown factor 0.15
		 );

  // Readout only 50% of HLT ESDs for min bias.
  config.AddItem(
		 3, // priority group.
		 "CINT1WU-B-NOPF-ALL || CINT1-B-NOPF-ALLNOTRD",
		 "domainESD | domainHLTDDL",
		 2,  // scaledown factor 1/2
		 "Rejected min-bias with HLT ESD readout",
		 false  // default global trigger decision result
		 );

  // Reject completely the other 50% min bias.
  config.AddItem(
		 2, // priority group.
		 "CINT1WU-B-NOPF-ALL || CINT1-B-NOPF-ALLNOTRD",
		 "domainHLTDDL",  // Only HLT DDL to deliver at least the decision.
		 0,  // No prescalar (no scaledown)
		 "Rejected min-bias",
		 false  // default global trigger decision result
		 );

  config.AddItem(
		 1, // priority group.
		 "SOFTWARE || CALIBRATION || START_OF_DATA || END_OF_DATA",
		 "SOFTWARE | CALIBRATION | START_OF_DATA | END_OF_DATA | domainHLTDDL",
		 "H-SoftwareTrigger-V0001.001-ALL-ALL"
		 );

  ///////////////////////////////////////////////////////////////////////////////////////////
  // Setup defaults in case there is no global trigger.
  // For non-triggered events store everything from HLT and readout all detectors.
  config.SetDefaultTriggerDescription("No HLT global trigger");
  AliHLTTriggerDomain defaultDomain("*******:***");
  AliHLTReadoutList readoutlist;
  readoutlist.Enable(AliHLTReadoutList::kALLDET);
  defaultDomain.Add(readoutlist);
  config.SetDefaultTriggerDomain(defaultDomain);
  config.SetDefaultResult(true);

  TObject* menu = AliHLTGlobalTriggerConfig::Menu()->Clone();
  menu->Print();

  ///////////////////////////////////////////////////////////////////////////////////////////
  // Write the trigger menu object to the CDB.
  AliCDBId id("HLT/ConfigHLT/HLTGlobalTrigger", firstRun, lastRun, version);
  AliCDBMetaData* metaData = new AliCDBMetaData();
  metaData->SetResponsible("ALICE HLT Artur.Szostak@cern.ch");
  metaData->SetComment("HM-PHYSICS-V0002");
  storage->Put(menu, id, metaData);
}
<|endoftext|>


<commit_before>/**
 * @file   Strings.hpp
 * @brief  Strings class prototype.
 * @author zer0
 * @date   2016-04-04
 */

#ifndef __INCLUDE_LIBTBAG__LIBTBAG_STRINGS_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_STRINGS_HPP__

// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif

#include <libtbag/config.h>
#include <libtbag/Noncopyable.hpp>

#include <string>
#include <set>

// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------

/**
 * String utility class.
 *
 * @author zer0
 * @date   2016-04-04
 *
 * @remarks
 *  Without using the inline function, class for using static method.
 *
 * @translate{ko, inline function을 사용하지 않고, static method를 사용하기 위한 클래스.}
 */
template <typename T = char>
class Strings : public Noncopyable
{
public:
    using BaseType = T;
    using BaseString = std::basic_string<BaseType>;

public:
    constexpr Strings() = default;
    ~Strings() = default;

public:
    /**
     * Separate tokens.
     *
     * @param source    [in] Original string.
     * @param delimiter [in] Delimiter string.
     *
     * @return
     *  Token set.
     */
    static std::set<BaseString> splitTokens(BaseString const & source, BaseString const & delimiter)
    {
        std::set<BaseString> result;
        std::string token;

        std::size_t start = 0;
        std::size_t end = source.find(delimiter);

        while (end != std::string::npos) {
            token = source.substr(start, end - start);
            if (token.size() > 0) {
                result.insert(token);
            }

            // Calculate next token index.
            start = end + delimiter.length();
            end = source.find(delimiter, start);
        }

        // Last token.
        token = source.substr(start, end);
        if (token.size() > 0) {
            result.insert(token);
        }

        return result;
    }
};

using strings  = Strings<char>;
using wstrings = Strings<wchar_t>;

// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------

#endif // __INCLUDE_LIBTBAG__LIBTBAG_STRINGS_HPP__

<commit_msg>Fix the unknown command warning.<commit_after>/**
 * @file   Strings.hpp
 * @brief  Strings class prototype.
 * @author zer0
 * @date   2016-04-04
 */

#ifndef __INCLUDE_LIBTBAG__LIBTBAG_STRINGS_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_STRINGS_HPP__

// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif

#include <libtbag/config.h>
#include <libtbag/Noncopyable.hpp>

#include <string>
#include <set>

// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------

/**
 * String utility class.
 *
 * @author zer0
 * @date   2016-04-04
 *
 * @remarks
 *  Without using the inline function, class for using static method.
 *
 * @translate{ko, inline function을 사용하지 않고\, static method를 사용하기 위한 클래스.}
 */
template <typename T = char>
class Strings : public Noncopyable
{
public:
    using BaseType = T;
    using BaseString = std::basic_string<BaseType>;

public:
    constexpr Strings() = default;
    ~Strings() = default;

public:
    /**
     * Separate tokens.
     *
     * @param source    [in] Original string.
     * @param delimiter [in] Delimiter string.
     *
     * @return
     *  Token set.
     */
    static std::set<BaseString> splitTokens(BaseString const & source, BaseString const & delimiter)
    {
        std::set<BaseString> result;
        std::string token;

        std::size_t start = 0;
        std::size_t end = source.find(delimiter);

        while (end != std::string::npos) {
            token = source.substr(start, end - start);
            if (token.size() > 0) {
                result.insert(token);
            }

            // Calculate next token index.
            start = end + delimiter.length();
            end = source.find(delimiter, start);
        }

        // Last token.
        token = source.substr(start, end);
        if (token.size() > 0) {
            result.insert(token);
        }

        return result;
    }
};

using strings  = Strings<char>;
using wstrings = Strings<wchar_t>;

// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------

#endif // __INCLUDE_LIBTBAG__LIBTBAG_STRINGS_HPP__

<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2009 Artem Pavlenko
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id$

#ifndef MAPNIK_EXPRESSIONS_GRAMMAR_HPP
#define MAPNIK_EXPRESSIONS_GRAMMAR_HPP

// mapnik
#include <mapnik/value.hpp>
#include <mapnik/expression_node.hpp>

// boost
#include <boost/version.hpp>
#include <boost/variant.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/concept_check.hpp>
//spirit2
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_action.hpp>
//fusion
#include <boost/fusion/include/adapt_struct.hpp>
//phoenix
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/home/phoenix/object/construct.hpp>

namespace mapnik
{

namespace qi = boost::spirit::qi;
namespace standard_wide =  boost::spirit::standard_wide;
using standard_wide::space_type;

struct unicode_impl
{
    template <typename T>
    struct result
    {
        typedef UnicodeString type;
    };

    explicit unicode_impl(mapnik::transcoder const& tr)
        : tr_(tr) {}

    UnicodeString operator()(std::string const& str) const
    {
        return tr_.transcode(str.c_str());
    }

    mapnik::transcoder const& tr_;
};

struct regex_match_impl
{
    template <typename T0, typename T1>
    struct result
    {
        typedef expr_node type;
    };

    explicit regex_match_impl(mapnik::transcoder const& tr)
        : tr_(tr) {}

    template <typename T0,typename T1>
    expr_node operator() (T0 & node, T1 const& pattern) const
    {
        return regex_match_node(node,tr_.transcode(pattern.c_str()));
    }

    mapnik::transcoder const& tr_;
};

struct regex_replace_impl
{
    template <typename T0, typename T1, typename T2>
    struct result
    {
        typedef expr_node type;
    };

    explicit regex_replace_impl(mapnik::transcoder const& tr)
        : tr_(tr) {}

    template <typename T0,typename T1,typename T2>
    expr_node operator() (T0 & node, T1 const& pattern, T2 const& format) const
    {
        return regex_replace_node(node,tr_.transcode(pattern.c_str()),tr_.transcode(format.c_str()));
    }

    mapnik::transcoder const& tr_;
};

template <typename Iterator>
struct expression_grammar : qi::grammar<Iterator, expr_node(), space_type>
{
    typedef qi::rule<Iterator, expr_node(), space_type> rule_type;

    explicit expression_grammar(mapnik::transcoder const& tr)
        : expression_grammar::base_type(expr),
          unicode_(unicode_impl(tr)),
          regex_match_(regex_match_impl(tr)),
          regex_replace_(regex_replace_impl(tr))
    {
        using boost::phoenix::construct;
        using qi::_1;
        using qi::_a;
        using qi::_b;
        using qi::_r1;
#if BOOST_VERSION > 104200
        using qi::no_skip;
#else
        using qi::lexeme;
#endif
        using qi::_val;
        using qi::lit;
        using qi::int_;
        using qi::double_;
        using standard_wide::char_;

        expr = logical_expr.alias();

        logical_expr = not_expr [_val = _1]
            >>
            *(  (  ( lit("and") | lit("&&")) >> not_expr [_val && _1] )
                | (( lit("or") | lit("||")) >> not_expr [_val || _1])
                )
            ;

        not_expr =
            cond_expr [_val = _1 ]
            | ((lit("not") | lit('!')) >> cond_expr [ _val = !_1 ])
            ;

        cond_expr = equality_expr [_val = _1] | additive_expr [_val = _1]
            ;

        equality_expr =
            relational_expr [_val = _1]
            >> *(  ( (lit("=") | lit("eq")) >> relational_expr [_val == _1])
                   | (( lit("!=") | lit("<>") | lit("neq") ) >> relational_expr [_val != _1])
                )
            ;

        regex_match_expr = lit(".match")
            >> lit('(')
            >> ustring [_val = _1]
            >> lit(')')
            ;

        regex_replace_expr =
            lit(".replace")
            >> lit('(')
            >> ustring           [_a = _1]
            >> lit(',')
            >> ustring           [_b = _1]
            >> lit(')')          [_val = regex_replace_(_r1,_a,_b)]
            ;

        relational_expr = additive_expr[_val = _1]
            >>
            *(  (   (lit("<=") | lit("le") ) >> additive_expr [ _val <= _1 ])
                | ( (lit('<')  | lit("lt") ) >> additive_expr [ _val <  _1 ])
                | ( (lit(">=") | lit("ge") ) >> additive_expr [ _val >= _1 ])
                | ( (lit('>')  | lit("gt") ) >> additive_expr [ _val >  _1 ])
                )
            ;
        additive_expr = multiplicative_expr [_val = _1]
            >> * (   '+' >> multiplicative_expr[_val += _1]
                     | '-' >> multiplicative_expr[_val -= _1]
                )
            ;

        multiplicative_expr = primary_expr [_val = _1]
            >> *(     '*' >> primary_expr [_val *= _1]
                      | '/' >> primary_expr [_val /= _1]
                      | '%' >> primary_expr [_val %= _1]
                      |  regex_match_expr[_val = regex_match_(_val, _1)]
                      |  regex_replace_expr(_val) [_val = _1]
                )
            ;

        primary_expr = strict_double [_val = _1]
            | int_ [_val = _1]
            | lit("true") [_val = true]
            | lit("false") [_val = false]
            | ustring [_val = unicode_(_1) ]
            | attr [_val = construct<attribute>( _1 ) ]
            | '(' >> expr [_val = _1 ] >> ')'
            ;

        attr %= '[' >> +(char_ - ']') >> ']';
#if BOOST_VERSION > 104200
        ustring %= '\'' >> no_skip[*~char_('\'')] >> '\'';
#else
        ustring %= '\'' >> lexeme[*(char_-'\'')] >> '\'';
#endif
    }

    qi::real_parser<double, qi::strict_real_policies<double> > strict_double;
    boost::phoenix::function<unicode_impl> unicode_;
    boost::phoenix::function<regex_match_impl> regex_match_;
    boost::phoenix::function<regex_replace_impl> regex_replace_;
    //
    rule_type expr;
    rule_type equality_expr;
    rule_type cond_expr;
    rule_type relational_expr;
    rule_type logical_expr;
    rule_type additive_expr;
    rule_type multiplicative_expr;
    rule_type not_expr;
    rule_type primary_expr;
    qi::rule<Iterator, std::string() > regex_match_expr;
    qi::rule<Iterator, expr_node(expr_node), qi::locals<std::string,std::string>, space_type> regex_replace_expr;
    qi::rule<Iterator, std::string() , space_type> attr;
    qi::rule<Iterator, std::string() > ustring;
};

} // namespace

#endif  // MAPNIK_EXPRESSIONS_GRAMMAR_HPP
<commit_msg>+ add 'is' keyword (same as 'eq', '=') + parse 'null' as  value_null()<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2009 Artem Pavlenko
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id$

#ifndef MAPNIK_EXPRESSIONS_GRAMMAR_HPP
#define MAPNIK_EXPRESSIONS_GRAMMAR_HPP

// mapnik
#include <mapnik/value.hpp>
#include <mapnik/expression_node.hpp>

// boost
#include <boost/version.hpp>
#include <boost/variant.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/concept_check.hpp>
//spirit2
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/qi_action.hpp>
//fusion
#include <boost/fusion/include/adapt_struct.hpp>
//phoenix
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_function.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/spirit/home/phoenix/object/construct.hpp>

namespace mapnik
{

namespace qi = boost::spirit::qi;
namespace standard_wide =  boost::spirit::standard_wide;
using standard_wide::space_type;

struct unicode_impl
{
    template <typename T>
    struct result
    {
        typedef UnicodeString type;
    };

    explicit unicode_impl(mapnik::transcoder const& tr)
        : tr_(tr) {}

    UnicodeString operator()(std::string const& str) const
    {
        return tr_.transcode(str.c_str());
    }

    mapnik::transcoder const& tr_;
};

struct regex_match_impl
{
    template <typename T0, typename T1>
    struct result
    {
        typedef expr_node type;
    };

    explicit regex_match_impl(mapnik::transcoder const& tr)
        : tr_(tr) {}

    template <typename T0,typename T1>
    expr_node operator() (T0 & node, T1 const& pattern) const
    {
        return regex_match_node(node,tr_.transcode(pattern.c_str()));
    }

    mapnik::transcoder const& tr_;
};

struct regex_replace_impl
{
    template <typename T0, typename T1, typename T2>
    struct result
    {
        typedef expr_node type;
    };

    explicit regex_replace_impl(mapnik::transcoder const& tr)
        : tr_(tr) {}

    template <typename T0,typename T1,typename T2>
    expr_node operator() (T0 & node, T1 const& pattern, T2 const& format) const
    {
        return regex_replace_node(node,tr_.transcode(pattern.c_str()),tr_.transcode(format.c_str()));
    }

    mapnik::transcoder const& tr_;
};

template <typename Iterator>
struct expression_grammar : qi::grammar<Iterator, expr_node(), space_type>
{
    typedef qi::rule<Iterator, expr_node(), space_type> rule_type;

    explicit expression_grammar(mapnik::transcoder const& tr)
        : expression_grammar::base_type(expr),
          unicode_(unicode_impl(tr)),
          regex_match_(regex_match_impl(tr)),
          regex_replace_(regex_replace_impl(tr))
    {
        using boost::phoenix::construct;
        using qi::_1;
        using qi::_a;
        using qi::_b;
        using qi::_r1;
#if BOOST_VERSION > 104200
        using qi::no_skip;
#else
        using qi::lexeme;
#endif
        using qi::_val;
        using qi::lit;
        using qi::int_;
        using qi::double_;
        using standard_wide::char_;

        expr = logical_expr.alias();

        logical_expr = not_expr [_val = _1]
            >>
            *(  (  ( lit("and") | lit("&&")) >> not_expr [_val && _1] )
                | (( lit("or") | lit("||")) >> not_expr [_val || _1])
                )
            ;

        not_expr =
            cond_expr [_val = _1 ]
            | ((lit("not") | lit('!')) >> cond_expr [ _val = !_1 ])
            ;

        cond_expr = equality_expr [_val = _1] | additive_expr [_val = _1]
            ;

        equality_expr =
            relational_expr [_val = _1]
            >> *(  ( (lit("=") | lit("eq") | lit("is")) >> relational_expr [_val == _1])
                   | (( lit("!=") | lit("<>") | lit("neq") ) >> relational_expr [_val != _1])
                )
            ;

        regex_match_expr = lit(".match")
            >> lit('(')
            >> ustring [_val = _1]
            >> lit(')')
            ;

        regex_replace_expr =
            lit(".replace")
            >> lit('(')
            >> ustring           [_a = _1]
            >> lit(',')
            >> ustring           [_b = _1]
            >> lit(')')          [_val = regex_replace_(_r1,_a,_b)]
            ;

        relational_expr = additive_expr[_val = _1]
            >>
            *(  (   (lit("<=") | lit("le") ) >> additive_expr [ _val <= _1 ])
                | ( (lit('<')  | lit("lt") ) >> additive_expr [ _val <  _1 ])
                | ( (lit(">=") | lit("ge") ) >> additive_expr [ _val >= _1 ])
                | ( (lit('>')  | lit("gt") ) >> additive_expr [ _val >  _1 ])
                )
            ;
        additive_expr = multiplicative_expr [_val = _1]
            >> * (   '+' >> multiplicative_expr[_val += _1]
                     | '-' >> multiplicative_expr[_val -= _1]
                )
            ;

        multiplicative_expr = primary_expr [_val = _1]
            >> *(     '*' >> primary_expr [_val *= _1]
                      | '/' >> primary_expr [_val /= _1]
                      | '%' >> primary_expr [_val %= _1]
                      |  regex_match_expr[_val = regex_match_(_val, _1)]
                      |  regex_replace_expr(_val) [_val = _1]
                )
            ;

        primary_expr = strict_double [_val = _1]
            | int_ [_val = _1]
            | lit("true") [_val = true]
            | lit("false") [_val = false]
            | lit("null") [_val = value_null() ]
            | ustring [_val = unicode_(_1) ]
            | attr [_val = construct<attribute>( _1 ) ]
            | '(' >> expr [_val = _1 ] >> ')'
            ;

        attr %= '[' >> +(char_ - ']') >> ']';
#if BOOST_VERSION > 104200
        ustring %= '\'' >> no_skip[*~char_('\'')] >> '\'';
#else
        ustring %= '\'' >> lexeme[*(char_-'\'')] >> '\'';
#endif
    }

    qi::real_parser<double, qi::strict_real_policies<double> > strict_double;
    boost::phoenix::function<unicode_impl> unicode_;
    boost::phoenix::function<regex_match_impl> regex_match_;
    boost::phoenix::function<regex_replace_impl> regex_replace_;
    //
    rule_type expr;
    rule_type equality_expr;
    rule_type cond_expr;
    rule_type relational_expr;
    rule_type logical_expr;
    rule_type additive_expr;
    rule_type multiplicative_expr;
    rule_type not_expr;
    rule_type primary_expr;
    qi::rule<Iterator, std::string() > regex_match_expr;
    qi::rule<Iterator, expr_node(expr_node), qi::locals<std::string,std::string>, space_type> regex_replace_expr;
    qi::rule<Iterator, std::string() , space_type> attr;
    qi::rule<Iterator, std::string() > ustring;
};

} // namespace

#endif  // MAPNIK_EXPRESSIONS_GRAMMAR_HPP
<|endoftext|>


<commit_before>/*
 * File:   BMPProcessor.cpp
 * Author: heshan
 *
 * Created on December 3, 2017, 12:29 AM
 */

#include "BMPProcessor.h"

BMPProcessor::BMPProcessor() { }

BMPProcessor::BMPProcessor(const BMPProcessor& orig) { }

BMPProcessor::~BMPProcessor() { }

/**
 * @param height of the image
 * @return 1
 */
int BMPProcessor::setHeight(int height) {
    this->imgHeight = height;
    return 1;
}

/**
 * @param width of the image
 * @return 1
 */
int BMPProcessor::setWidth(int width) {
    this->imgWidth = width;
    return 1;
}

/**
 * @return height of the image
 */
int BMPProcessor::getHeight() {
    return this->imgHeight;
}

/**
 * @return width of the image
 */
int BMPProcessor::getWidth() {
    return this->imgWidth;
}

/**
 * @param filename the path to the image
 * @return 1 if read the image without any errors
 */
int BMPProcessor::readImage(char * filename) {

    int i;
    FILE* file = fopen(filename, "rb");
    if (file == NULL) {
        std::cout<<"error in the file '"<<filename<<"'";
        return 0;
    }
    unsigned char info[54];
    fread(info, sizeof(unsigned char), 54, file); // read the 54-byte header

    // extract image height and width from header
    setWidth(*(int*)&info[18]);
    setHeight(*(int*)&info[22]);

    imgDataStruct.imgPixArray = new RGBApixel[imgWidth*imgHeight];
    imgDataStruct.imgHeight = imgHeight;
    imgDataStruct.imgWidth = imgWidth;

    int rowPadded = (imgWidth*3 + 3) & (~3);
    unsigned char* data = new unsigned char[rowPadded];

    int row = imgHeight;
    for(int i = 0; i < imgHeight; i++) {
        fread(data, sizeof(unsigned char), rowPadded, file); row--;
        fillRGBApixelArray(data,row);
    }

    return 1;
}

/**
 * @param filename target fie path
 * @param imageDataStruct pixel array of the image to be written
 * @return 1 if write the image without any errors
 */
int BMPProcessor::writeImage (char * filename, ImageDataStruct imageDataStruct) {

    unsigned char file[14] = {
        'B','M', // magic
        0,0,0,0, // size in bytes
        0,0, // app data
        0,0, // app data
        40+14,0,0,0 // start of data offset
    };
    unsigned char info[40] = {
        40,0,0,0, // info hd size
        0,0,0,0, // width
        0,0,0,0, // heigth
        1,0, // number color planes
        24,0, // bits per pixel
        0,0,0,0, // compression is none
        0,0,0,0, // image bits size
        0x13,0x0B,0,0, // horz resoluition in pixel / m
        0x13,0x0B,0,0, // vert resolutions (0x03C3 = 96 dpi, 0x0B13 = 72 dpi)
        0,0,0,0, // #colors in pallete
        0,0,0,0, // #important colors
        };

    int w=imageDataStruct.imgWidth;
    int h=imageDataStruct.imgHeight;

    int padSize  = (4-(w*3)%4)%4;
    int sizeData = w*h*3 + h*padSize;
    int sizeAll  = sizeData + sizeof(file) + sizeof(info);

    file[ 2] = (unsigned char)( sizeAll    );
    file[ 3] = (unsigned char)( sizeAll>> 8);
    file[ 4] = (unsigned char)( sizeAll>>16);
    file[ 5] = (unsigned char)( sizeAll>>24);

    info[ 4] = (unsigned char)( w   );
    info[ 5] = (unsigned char)( w>> 8);
    info[ 6] = (unsigned char)( w>>16);
    info[ 7] = (unsigned char)( w>>24);

    info[ 8] = (unsigned char)( h    );
    info[ 9] = (unsigned char)( h>> 8);
    info[10] = (unsigned char)( h>>16);
    info[11] = (unsigned char)( h>>24);

    info[20] = (unsigned char)( sizeData    );
    info[21] = (unsigned char)( sizeData>> 8);
    info[22] = (unsigned char)( sizeData>>16);
    info[23] = (unsigned char)( sizeData>>24);

//    stream.write( (char*)file, sizeof(file) );
//    stream.write( (char*)info, sizeof(info) );
//
//    unsigned char pad[3] = {0,0,0};
//
//    for ( int y=0; y<h; y++ )
//    {
//        for ( int x=0; x<w; x++ )
//        {
//            long red = lround( 255.0 * waterfall[x][y] );
//            if ( red < 0 ) red=0;
//            if ( red > 255 ) red=255;
//            long green = red;
//            long blue = red;
//
//            unsigned char pixel[3];
//            pixel[0] = blue;
//            pixel[1] = green;
//            pixel[2] = red;
//
//            stream.write( (char*)pixel, 3 );
//        }
//        stream.write( (char*)pad, padSize );
//    }

    return 1;
}

/**
 * @return ImageDataStruct that contains pixel array and image meta data
 */
ImageDataStruct BMPProcessor::getImageDataStruct(){
    return this->imgDataStruct;
}

/**
 * @param buffer that contains decompressed image pixels
 * @param pixPos pixel position
 * @param row_stride physical row width in image buffer
 * @return 1
 */
int BMPProcessor::fillRGBApixelArray(unsigned char* data, int row){

    int col = 0;
    int pixPos = row*imgWidth;
    for(int bytePos = 0; bytePos < imgWidth*3; bytePos += 3) {
        // pixel Order is Convert (B, G, R) in Bitmap
        imgDataStruct.imgPixArray[pixPos+col].r = (int)data[bytePos+2];
        imgDataStruct.imgPixArray[pixPos+col].g = (int)data[bytePos+1];
        imgDataStruct.imgPixArray[pixPos+col].b = (int)data[bytePos];
        imgDataStruct.imgPixArray[pixPos+col].a = 255;
        col++;
    }
    return 1;
}

/**
 * free the pixel array in imageDataStruct
 * @return 1
 */
int BMPProcessor::freeImageData(){
    imgDataStruct.imgPixArray = NULL;
    return 1;
}<commit_msg>changes in BMPProcessor class<commit_after>/*
 * File:   BMPProcessor.cpp
 * Author: heshan
 *
 * Created on December 3, 2017, 12:29 AM
 */

#include "BMPProcessor.h"

BMPProcessor::BMPProcessor() { }

BMPProcessor::BMPProcessor(const BMPProcessor& orig) { }

BMPProcessor::~BMPProcessor() { }

/**
 * @param height of the image
 * @return 1
 */
int BMPProcessor::setHeight(int height) {
    this->imgHeight = height;
    return 1;
}

/**
 * @param width of the image
 * @return 1
 */
int BMPProcessor::setWidth(int width) {
    this->imgWidth = width;
    return 1;
}

/**
 * @return height of the image
 */
int BMPProcessor::getHeight() {
    return this->imgHeight;
}

/**
 * @return width of the image
 */
int BMPProcessor::getWidth() {
    return this->imgWidth;
}

/**
 * @param filename the path to the image
 * @return 1 if read the image without any errors
 */
int BMPProcessor::readImage(char * filename) {

    int i;
    FILE* file = fopen(filename, "rb");
    if (file == NULL) {
        std::cout<<"error in the file '"<<filename<<"'";
        return 0;
    }
    unsigned char info[54];
    fread(info, sizeof(unsigned char), 54, file); // read the 54-byte header

    // extract image height and width from header
    setWidth(*(int*)&info[18]);
    setHeight(*(int*)&info[22]);

    imgDataStruct.imgPixArray = new RGBApixel[imgWidth*imgHeight];
    imgDataStruct.imgHeight = imgHeight;
    imgDataStruct.imgWidth = imgWidth;

    int rowPadded = (imgWidth*3 + 3) & (~3);
    unsigned char* data = new unsigned char[rowPadded];

    int row = imgHeight;
    for(int i = 0; i < imgHeight; i++) {
        fread(data, sizeof(unsigned char), rowPadded, file); row--;
        fillRGBApixelArray(data,row);
    }

    return 1;
}

/**
 * @param filename target fie path
 * @param imageDataStruct pixel array of the image to be written
 * @return 1 if write the image without any errors
 */
int BMPProcessor::writeImage (char * filename, ImageDataStruct imageDataStruct) {

    unsigned int headers[13];
    FILE * outfile;
    int extrabytes;
    int paddedsize;
    int x; int y; int n;
    int red, green, blue;

    int WIDTH = imageDataStruct.imgWidth;
    int HEIGHT = imageDataStruct.imgHeight;

    extrabytes = 4 - ((WIDTH * 3) % 4);                 // How many bytes of padding to add to each
                                                        // horizontal line - the size of which must
                                                        // be a multiple of 4 bytes.
    if (extrabytes == 4)
       extrabytes = 0;

    paddedsize = ((WIDTH * 3) + extrabytes) * HEIGHT;

    // Headers...
    // Note that the "BM" identifier in bytes 0 and 1 is NOT included in these "headers".

    headers[0]  = paddedsize + 54;      // bfSize (whole file size)
    headers[1]  = 0;                    // bfReserved (both)
    headers[2]  = 54;                   // bfOffbits
    headers[3]  = 40;                   // biSize
    headers[4]  = WIDTH;  // biWidth
    headers[5]  = HEIGHT; // biHeight

    // Would have biPlanes and biBitCount in position 6, but they're shorts.
    // It's easier to write them out separately (see below) than pretend
    // they're a single int, especially with endian issues...

    headers[7]  = 0;                    // biCompression
    headers[8]  = paddedsize;           // biSizeImage
    headers[9]  = 0;                    // biXPelsPerMeter
    headers[10] = 0;                    // biYPelsPerMeter
    headers[11] = 0;                    // biClrUsed
    headers[12] = 0;                    // biClrImportant

    outfile = fopen(filename, "wb");

    //
    // Headers begin...
    // When printing ints and shorts, we write out 1 character at a time to avoid endian issues.
    //

    fprintf(outfile, "BM");

    for (n = 0; n <= 5; n++)
    {
       fprintf(outfile, "%c", headers[n] & 0x000000FF);
       fprintf(outfile, "%c", (headers[n] & 0x0000FF00) >> 8);
       fprintf(outfile, "%c", (headers[n] & 0x00FF0000) >> 16);
       fprintf(outfile, "%c", (headers[n] & (unsigned int) 0xFF000000) >> 24);
    }

    // These next 4 characters are for the biPlanes and biBitCount fields.

    fprintf(outfile, "%c", 1);
    fprintf(outfile, "%c", 0);
    fprintf(outfile, "%c", 24);
    fprintf(outfile, "%c", 0);

    for (n = 7; n <= 12; n++)
    {
       fprintf(outfile, "%c", headers[n] & 0x000000FF);
       fprintf(outfile, "%c", (headers[n] & 0x0000FF00) >> 8);
       fprintf(outfile, "%c", (headers[n] & 0x00FF0000) >> 16);
       fprintf(outfile, "%c", (headers[n] & (unsigned int) 0xFF000000) >> 24);
    }

    //
    // Headers done, now write the data...
    //

    for (y = HEIGHT - 1; y >= 0; y--)     // BMP image format is written from bottom to top...
    {
       for (x = 0; x <= WIDTH - 1; x++)
       {

//          red = reduce(redcount[x][y] + COLOUR_OFFSET) * red_multiplier;
//          green = reduce(greencount[x][y] + COLOUR_OFFSET) * green_multiplier;
//          blue = reduce(bluecount[x][y] + COLOUR_OFFSET) * blue_multiplier;

          if (red > 255) red = 255; if (red < 0) red = 0;
          if (green > 255) green = 255; if (green < 0) green = 0;
          if (blue > 255) blue = 255; if (blue < 0) blue = 0;

          // Also, it's written in (b,g,r) format...

          fprintf(outfile, "%c", blue);
          fprintf(outfile, "%c", green);
          fprintf(outfile, "%c", red);
       }
       if (extrabytes)      // See above - BMP lines must be of lengths divisible by 4.
       {
          for (n = 1; n <= extrabytes; n++)
          {
             fprintf(outfile, "%c", 0);
          }
       }
    }

    fclose(outfile);

    return 1;
}

/**
 * @return ImageDataStruct that contains pixel array and image meta data
 */
ImageDataStruct BMPProcessor::getImageDataStruct(){
    return this->imgDataStruct;
}

/**
 * @param buffer that contains decompressed image pixels
 * @param pixPos pixel position
 * @param row_stride physical row width in image buffer
 * @return 1
 */
int BMPProcessor::fillRGBApixelArray(unsigned char* data, int row){

    int col = 0;
    int pixPos = row*imgWidth;
    for(int bytePos = 0; bytePos < imgWidth*3; bytePos += 3) {
        // pixel Order is Convert (B, G, R) in Bitmap
        imgDataStruct.imgPixArray[pixPos+col].r = (int)data[bytePos+2];
        imgDataStruct.imgPixArray[pixPos+col].g = (int)data[bytePos+1];
        imgDataStruct.imgPixArray[pixPos+col].b = (int)data[bytePos];
        imgDataStruct.imgPixArray[pixPos+col].a = 255;
        col++;
    }
    return 1;
}

/**
 * free the pixel array in imageDataStruct
 * @return 1
 */
int BMPProcessor::freeImageData(){
    imgDataStruct.imgPixArray = NULL;
    return 1;
}<|endoftext|>


<commit_before>// Copyright (c) 2016, Tom Honermann
//
// This file is distributed under the MIT License. See the accompanying file
// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms
// and conditions.

#ifndef TEXT_VIEW_CONCEPTS_HPP // {
#define TEXT_VIEW_CONCEPTS_HPP

#include <origin/core/traits.hpp>
#include <origin/algorithm/concepts.hpp>
#include <origin/range/range.hpp>
#include <text_view_detail/traits.hpp>

namespace std {
namespace experimental {
inline namespace text {

namespace text_detail {
template<typename T, T t1, T t2>
concept bool Same_value() {
    return t1 == t2;
}
} // text_detail namespace

/*
 * Code unit concept
 */
template<typename T>
concept bool Code_unit() {
    return origin::Integral_type<T>()
        && (origin::Unsigned_type<T>()
            || origin::Same<T, origin::Remove_cv<char>>()
            || origin::Same<T, origin::Remove_cv<wchar_t>>());
}

/*
 * Code point concept
 */
template<typename T>
concept bool Code_point() {
    return origin::Integral_type<T>()
        && (origin::Unsigned_type<T>()
            || origin::Same<T, origin::Remove_cv<char>>()
            || origin::Same<T, origin::Remove_cv<wchar_t>>());
}

/*
 * Character set concept
 */
template<typename T>
concept bool Character_set() {
    return requires () {
               typename T::code_point_type;
               { T::get_name() } noexcept -> const char *;
           }
        && Code_point<typename T::code_point_type>();
}

/*
 * Character concept
 */
template<typename T>
concept bool Character() {
    return Character_set<character_set_type_of<T>>()
        && origin::Regular<T>()
        && origin::Copyable<T>()
        && requires (T t, code_point_type_of<character_set_type_of<T>> cp) {
               t.set_code_point(cp);
               { t.get_code_point() } -> code_point_type_of<character_set_type_of<T>>;
               { t.get_character_set_id() } -> character_set_id;
           };
}

/*
 * Code unit iterator concept
 */
template<typename T>
concept bool Code_unit_iterator() {
    return origin::Iterator<T>()
        && Code_unit<origin::Value_type<T>>();
}

/*
 * Text encoding state concept
 * These requirements are intended to match the char_traits<T>::state_type
 * requirements described in C++11 [char.traits.typedefs] 21.2.2p4.
 */
template<typename T>
concept bool Text_encoding_state() {
    return origin::Default_constructible<T>()
        && origin::Copyable<T>();
}

/*
 * Text encoding state transition concept
 */
template<typename T>
concept bool Text_encoding_state_transition() {
    return origin::Default_constructible<T>()
        && origin::Copyable<T>();
}

/*
 * Text encoding concept
 */
template<typename T>
concept bool Text_encoding() {
    return requires () {
               typename T::state_type;
               typename T::state_transition_type;
               typename T::code_unit_type;
               typename T::character_type;
               { T::min_code_units } noexcept -> int;
               { T::max_code_units } noexcept -> int;
           }
        && Text_encoding_state<typename T::state_type>()
        && Text_encoding_state_transition<typename T::state_transition_type>()
        && Code_unit<typename T::code_unit_type>()
        && Character<typename T::character_type>()
        && requires () {
               { T::initial_state() }
                   -> const typename T::state_type&;
           };
}

/*
 * Text encoder concept
 */
template<typename T, typename CUIT>
concept bool Text_encoder() {
    return Text_encoding<T>()
        && origin::Output_iterator<CUIT, typename T::code_unit_type>()
        && requires (
               typename T::state_type &state,
               CUIT &out,
               typename T::state_transition_type stt,
               int &encoded_code_units)
           {
               T::encode_state_transition(state, out, stt, encoded_code_units);
           }
        && requires (
               typename T::state_type &state,
               CUIT &out,
               typename T::character_type c,
               int &encoded_code_units)
           {
               T::encode(state, out, c, encoded_code_units);
           };
}

/*
 * Text decoder concept
 */
template<typename T, typename CUIT>
concept bool Text_decoder() {
    return Text_encoding<T>()
        && origin::Input_iterator<CUIT>()
        && origin::Convertible<origin::Value_type<CUIT>,
                               typename T::code_unit_type>()
        && requires (
               typename T::state_type &state,
               CUIT &in_next,
               CUIT in_end,
               typename T::character_type &c,
               int &decoded_code_units)
           {
               { T::decode(state, in_next, in_end, c, decoded_code_units) } -> bool;
           };
}

/*
 * Text forward decoder concept
 */
template<typename T, typename CUIT>
concept bool Text_forward_decoder() {
    return Text_decoder<T, CUIT>()
        && origin::Forward_iterator<CUIT>();
}

/*
 * Text bidirectional decoder concept
 */
template<typename T, typename CUIT>
concept bool Text_bidirectional_decoder() {
    return Text_forward_decoder<T, CUIT>()
        && origin::Bidirectional_iterator<CUIT>()
        && requires (
               typename T::state_type &state,
               CUIT &in_next,
               CUIT in_end,
               typename T::character_type &c,
               int &decoded_code_units)
           {
               { T::rdecode(state, in_next, in_end, c, decoded_code_units) } -> bool;
           };
}

/*
 * Text random access decoder concept
 */
template<typename T, typename CUIT>
concept bool Text_random_access_decoder() {
    return Text_bidirectional_decoder<T, CUIT>()
        && origin::Random_access_iterator<CUIT>()
        && text_detail::Same_value<int, T::min_code_units, T::max_code_units>()
        && origin::Empty_type<typename T::state_type>();
}

/*
 * Text iterator concept
 */
template<typename T>
concept bool Text_iterator() {
    return requires () {
               typename T::encoding_type;
               typename T::state_type;
           }
        && Text_encoding<typename T::encoding_type>()
        && Text_encoding_state<typename T::state_type>()
        && origin::Iterator<T>()
        && Character<origin::Value_type<T>>()
        && requires (T t, const T ct) {
               { t.state() } noexcept
                   -> typename T::encoding_type::state_type&;
               { ct.state() } noexcept
                   -> const typename T::encoding_type::state_type&;
           };
}

/*
 * Text sentinel concept
 */
template<typename T, typename I>
concept bool Text_sentinel() {
    return origin::Sentinel<T, I>()
        && Text_iterator<I>();
}

/*
 * Text view concept
 */
template<typename T>
concept bool Text_view() {
    return requires () {
               typename T::encoding_type;
               typename T::range_type;
               typename T::state_type;
               typename T::code_unit_iterator;
           }
        && Text_encoding<typename T::encoding_type>()
        && origin::Input_range<typename T::range_type>()
        && Text_encoding_state<typename T::state_type>()
        && origin::Iterator<typename T::code_unit_iterator>()
        && origin::Input_range<T>()
        && Text_iterator<origin::Iterator_type<T>>()
        && requires (T t, const T ct) {
               { t.base() } noexcept
                   -> typename T::range_type&;
               { ct.base() } noexcept
                   -> const typename T::range_type&;
               { t.initial_state() } noexcept
                   -> typename T::state_type&;
               { ct.initial_state() } noexcept
                   -> const typename T::state_type&;
           };
}

} // inline namespace text
} // namespace experimental
} // namespace std

#endif // } TEXT_VIEW_CONCEPTS_HPP
<commit_msg>Removed redundant member type requirements for a few concept definitions.<commit_after>// Copyright (c) 2016, Tom Honermann
//
// This file is distributed under the MIT License. See the accompanying file
// LICENSE.txt or http://www.opensource.org/licenses/mit-license.php for terms
// and conditions.

#ifndef TEXT_VIEW_CONCEPTS_HPP // {
#define TEXT_VIEW_CONCEPTS_HPP

#include <origin/core/traits.hpp>
#include <origin/algorithm/concepts.hpp>
#include <origin/range/range.hpp>
#include <text_view_detail/traits.hpp>

namespace std {
namespace experimental {
inline namespace text {

namespace text_detail {
template<typename T, T t1, T t2>
concept bool Same_value() {
    return t1 == t2;
}
} // text_detail namespace

/*
 * Code unit concept
 */
template<typename T>
concept bool Code_unit() {
    return origin::Integral_type<T>()
        && (origin::Unsigned_type<T>()
            || origin::Same<T, origin::Remove_cv<char>>()
            || origin::Same<T, origin::Remove_cv<wchar_t>>());
}

/*
 * Code point concept
 */
template<typename T>
concept bool Code_point() {
    return origin::Integral_type<T>()
        && (origin::Unsigned_type<T>()
            || origin::Same<T, origin::Remove_cv<char>>()
            || origin::Same<T, origin::Remove_cv<wchar_t>>());
}

/*
 * Character set concept
 */
template<typename T>
concept bool Character_set() {
    return requires () {
               { T::get_name() } noexcept -> const char *;
           }
        && Code_point<typename T::code_point_type>();
}

/*
 * Character concept
 */
template<typename T>
concept bool Character() {
    return Character_set<character_set_type_of<T>>()
        && origin::Regular<T>()
        && origin::Copyable<T>()
        && requires (T t, code_point_type_of<character_set_type_of<T>> cp) {
               t.set_code_point(cp);
               { t.get_code_point() } -> code_point_type_of<character_set_type_of<T>>;
               { t.get_character_set_id() } -> character_set_id;
           };
}

/*
 * Code unit iterator concept
 */
template<typename T>
concept bool Code_unit_iterator() {
    return origin::Iterator<T>()
        && Code_unit<origin::Value_type<T>>();
}

/*
 * Text encoding state concept
 * These requirements are intended to match the char_traits<T>::state_type
 * requirements described in C++11 [char.traits.typedefs] 21.2.2p4.
 */
template<typename T>
concept bool Text_encoding_state() {
    return origin::Default_constructible<T>()
        && origin::Copyable<T>();
}

/*
 * Text encoding state transition concept
 */
template<typename T>
concept bool Text_encoding_state_transition() {
    return origin::Default_constructible<T>()
        && origin::Copyable<T>();
}

/*
 * Text encoding concept
 */
template<typename T>
concept bool Text_encoding() {
    return requires () {
               { T::min_code_units } noexcept -> int;
               { T::max_code_units } noexcept -> int;
           }
        && Text_encoding_state<typename T::state_type>()
        && Text_encoding_state_transition<typename T::state_transition_type>()
        && Code_unit<typename T::code_unit_type>()
        && Character<typename T::character_type>()
        && requires () {
               { T::initial_state() }
                   -> const typename T::state_type&;
           };
}

/*
 * Text encoder concept
 */
template<typename T, typename CUIT>
concept bool Text_encoder() {
    return Text_encoding<T>()
        && origin::Output_iterator<CUIT, typename T::code_unit_type>()
        && requires (
               typename T::state_type &state,
               CUIT &out,
               typename T::state_transition_type stt,
               int &encoded_code_units)
           {
               T::encode_state_transition(state, out, stt, encoded_code_units);
           }
        && requires (
               typename T::state_type &state,
               CUIT &out,
               typename T::character_type c,
               int &encoded_code_units)
           {
               T::encode(state, out, c, encoded_code_units);
           };
}

/*
 * Text decoder concept
 */
template<typename T, typename CUIT>
concept bool Text_decoder() {
    return Text_encoding<T>()
        && origin::Input_iterator<CUIT>()
        && origin::Convertible<origin::Value_type<CUIT>,
                               typename T::code_unit_type>()
        && requires (
               typename T::state_type &state,
               CUIT &in_next,
               CUIT in_end,
               typename T::character_type &c,
               int &decoded_code_units)
           {
               { T::decode(state, in_next, in_end, c, decoded_code_units) } -> bool;
           };
}

/*
 * Text forward decoder concept
 */
template<typename T, typename CUIT>
concept bool Text_forward_decoder() {
    return Text_decoder<T, CUIT>()
        && origin::Forward_iterator<CUIT>();
}

/*
 * Text bidirectional decoder concept
 */
template<typename T, typename CUIT>
concept bool Text_bidirectional_decoder() {
    return Text_forward_decoder<T, CUIT>()
        && origin::Bidirectional_iterator<CUIT>()
        && requires (
               typename T::state_type &state,
               CUIT &in_next,
               CUIT in_end,
               typename T::character_type &c,
               int &decoded_code_units)
           {
               { T::rdecode(state, in_next, in_end, c, decoded_code_units) } -> bool;
           };
}

/*
 * Text random access decoder concept
 */
template<typename T, typename CUIT>
concept bool Text_random_access_decoder() {
    return Text_bidirectional_decoder<T, CUIT>()
        && origin::Random_access_iterator<CUIT>()
        && text_detail::Same_value<int, T::min_code_units, T::max_code_units>()
        && origin::Empty_type<typename T::state_type>();
}

/*
 * Text iterator concept
 */
template<typename T>
concept bool Text_iterator() {
    return origin::Iterator<T>()
        && Character<origin::Value_type<T>>()
        && Text_encoding<typename T::encoding_type>()
        && Text_encoding_state<typename T::state_type>()
        && requires (T t, const T ct) {
               { t.state() } noexcept
                   -> typename T::encoding_type::state_type&;
               { ct.state() } noexcept
                   -> const typename T::encoding_type::state_type&;
           };
}

/*
 * Text sentinel concept
 */
template<typename T, typename I>
concept bool Text_sentinel() {
    return origin::Sentinel<T, I>()
        && Text_iterator<I>();
}

/*
 * Text view concept
 */
template<typename T>
concept bool Text_view() {
    return origin::Input_range<T>()
        && Text_iterator<origin::Iterator_type<T>>()
        && Text_encoding<typename T::encoding_type>()
        && origin::Input_range<typename T::range_type>()
        && Text_encoding_state<typename T::state_type>()
        && Code_unit_iterator<typename T::code_unit_iterator>()
        && requires (T t, const T ct) {
               { t.base() } noexcept
                   -> typename T::range_type&;
               { ct.base() } noexcept
                   -> const typename T::range_type&;
               { t.initial_state() } noexcept
                   -> typename T::state_type&;
               { ct.initial_state() } noexcept
                   -> const typename T::state_type&;
           };
}

} // inline namespace text
} // namespace experimental
} // namespace std

#endif // } TEXT_VIEW_CONCEPTS_HPP
<|endoftext|>


<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetHLDReaderTest
#include <boost/test/unit_test.hpp>

#define private public
#define protected public
#include "../JPetHLDReader/JPetHLDReader.h"
#undef private
#undef protected

#include <cstddef>
#include <iostream>
#include <vector>

#include <TError.h> /// gErrorIgnoreLevel
#include <TObjString.h>

// method list

BOOST_AUTO_TEST_SUITE (FirstSuite)

BOOST_AUTO_TEST_CASE (default_constructor)
{
  JPetHLDReader reader;
  BOOST_REQUIRE(!reader.isOpen());
  BOOST_REQUIRE(!reader.nextEvent());
  BOOST_REQUIRE(!reader.firstEvent());
  BOOST_REQUIRE(!reader.lastEvent());
  BOOST_REQUIRE(!reader.nthEvent(0));
  BOOST_REQUIRE(!reader.nthEvent(1));
  BOOST_REQUIRE(!reader.nthEvent(-1));
  BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), -1);
  BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 0);
}

BOOST_AUTO_TEST_CASE (bad_file)
{
  gErrorIgnoreLevel = 6000; /// we turn off the ROOT error messages
  JPetHLDReader reader;
  /// not a ROOT file
  BOOST_REQUIRE(!reader.openFileAndLoadData("bad_file.txt", "tree"));
  BOOST_REQUIRE(!reader.isOpen());
  BOOST_REQUIRE(!reader.nextEvent());
  BOOST_REQUIRE(!reader.firstEvent());
  BOOST_REQUIRE(!reader.lastEvent());
  BOOST_REQUIRE(!reader.nthEvent(0));
  BOOST_REQUIRE(!reader.nthEvent(1));
  BOOST_REQUIRE(!reader.nthEvent(-1));
  BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), -1);
  BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 0);
}

BOOST_AUTO_TEST_CASE (good_file_with_constructor)
{
  JPetHLDReader reader("unitTestData/JPetHLDReaderTest/small_hld.root");
  BOOST_REQUIRE(reader.isOpen());
  BOOST_REQUIRE(reader.nextEvent());
  BOOST_REQUIRE(reader.firstEvent());
  BOOST_REQUIRE(reader.lastEvent());
  BOOST_REQUIRE(reader.nthEvent(0));
  BOOST_REQUIRE(reader.nthEvent(5));
  BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), 5);
  BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 10);
}

BOOST_AUTO_TEST_CASE (good_file_openFileAndLoadData)
{
  JPetHLDReader reader;
  BOOST_REQUIRE(reader.openFileAndLoadData("unitTestData/JPetHLDReaderTest/small_hld.root","T"));
  BOOST_REQUIRE(reader.isOpen());
  BOOST_REQUIRE(reader.firstEvent());
  BOOST_REQUIRE(reader.nextEvent());
  BOOST_REQUIRE(reader.lastEvent());
  BOOST_REQUIRE(reader.nthEvent(0));
  BOOST_REQUIRE(reader.nthEvent(5));
  BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), 5);
  BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 10);

}

BOOST_AUTO_TEST_CASE (good_file_closeFile)
{
  JPetHLDReader reader;
  BOOST_REQUIRE(reader.openFileAndLoadData("unitTestData/JPetHLDReaderTest/small_hld.root","T"));
  BOOST_REQUIRE(reader.isOpen());
  reader.closeFile();
  BOOST_REQUIRE(!reader.isOpen());
  BOOST_REQUIRE(!reader.nextEvent());
  BOOST_REQUIRE(!reader.firstEvent());
  BOOST_REQUIRE(!reader.lastEvent());
  BOOST_REQUIRE(!reader.nthEvent(0));
  BOOST_REQUIRE(!reader.nthEvent(1));
  BOOST_REQUIRE(!reader.nthEvent(-1));
  BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), -1);
  BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 0);
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Fix JPetHLDReader unit test after changes from c81110e3<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE JPetHLDReaderTest
#include <boost/test/unit_test.hpp>

#define private public
#define protected public
#include "../JPetHLDReader/JPetHLDReader.h"
#undef private
#undef protected

#include <cstddef>
#include <iostream>
#include <vector>

#include <TError.h> /// gErrorIgnoreLevel
#include <TObjString.h>

// method list

BOOST_AUTO_TEST_SUITE (FirstSuite)

BOOST_AUTO_TEST_CASE (default_constructor)
{
  JPetHLDReader reader;
  BOOST_REQUIRE(!reader.isOpen());
  BOOST_REQUIRE(!reader.nextEvent());
  BOOST_REQUIRE(!reader.firstEvent());
  BOOST_REQUIRE(!reader.lastEvent());
  BOOST_REQUIRE(!reader.nthEvent(0));
  BOOST_REQUIRE(!reader.nthEvent(1));
  BOOST_REQUIRE(!reader.nthEvent(-1));
  BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), -1);
  BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 0);
}

BOOST_AUTO_TEST_CASE (bad_file)
{
  gErrorIgnoreLevel = 6000; /// we turn off the ROOT error messages
  JPetHLDReader reader;
  /// not a ROOT file
  BOOST_REQUIRE(!reader.openFileAndLoadData("bad_file.txt", "tree"));
  BOOST_REQUIRE(!reader.isOpen());
  BOOST_REQUIRE(!reader.nextEvent());
  BOOST_REQUIRE(!reader.firstEvent());
  BOOST_REQUIRE(!reader.lastEvent());
  BOOST_REQUIRE(!reader.nthEvent(0));
  BOOST_REQUIRE(!reader.nthEvent(1));
  BOOST_REQUIRE(!reader.nthEvent(-1));
  BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), -1);
  BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 0);
}

BOOST_AUTO_TEST_CASE (good_file_with_constructor)
{
  JPetHLDReader reader("unitTestData/JPetHLDReaderTest/small_hld.root");
  BOOST_REQUIRE(reader.isOpen());
  BOOST_REQUIRE(reader.nextEvent());
  BOOST_REQUIRE(reader.firstEvent());
  BOOST_REQUIRE(reader.lastEvent());
  BOOST_REQUIRE(reader.nthEvent(0));
  BOOST_REQUIRE(reader.nthEvent(5));
  BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), 5);
  BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 6);
}

BOOST_AUTO_TEST_CASE (good_file_openFileAndLoadData)
{
  JPetHLDReader reader;
  BOOST_REQUIRE(reader.openFileAndLoadData("unitTestData/JPetHLDReaderTest/small_hld.root","T"));
  BOOST_REQUIRE(reader.isOpen());
  BOOST_REQUIRE(reader.firstEvent());
  BOOST_REQUIRE(reader.nextEvent());
  BOOST_REQUIRE(reader.lastEvent());
  BOOST_REQUIRE(reader.nthEvent(0));
  BOOST_REQUIRE(reader.nthEvent(5));
  BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), 5);
  BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 6);

}

BOOST_AUTO_TEST_CASE (good_file_closeFile)
{
  JPetHLDReader reader;
  BOOST_REQUIRE(reader.openFileAndLoadData("unitTestData/JPetHLDReaderTest/small_hld.root","T"));
  BOOST_REQUIRE(reader.isOpen());
  reader.closeFile();
  BOOST_REQUIRE(!reader.isOpen());
  BOOST_REQUIRE(!reader.nextEvent());
  BOOST_REQUIRE(!reader.firstEvent());
  BOOST_REQUIRE(!reader.lastEvent());
  BOOST_REQUIRE(!reader.nthEvent(0));
  BOOST_REQUIRE(!reader.nthEvent(1));
  BOOST_REQUIRE(!reader.nthEvent(-1));
  BOOST_REQUIRE_EQUAL(reader.getCurrentEventNumber(), -1);
  BOOST_REQUIRE_EQUAL(reader.getNbOfAllEvents(), 0);
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/**
 * @file lleditingmotion.cpp
 * @brief Implementation of LLEditingMotion class.
 *
 * $LicenseInfo:firstyear=2001&license=viewergpl$
 *
 * Copyright (c) 2001-2009, Linden Research, Inc.
 *
 * Second Life Viewer Source Code
 * The source code in this file ("Source Code") is provided by Linden Lab
 * to you under the terms of the GNU General Public License, version 2.0
 * ("GPL"), unless you have obtained a separate licensing agreement
 * ("Other License"), formally executed by you and Linden Lab.  Terms of
 * the GPL can be found in doc/GPL-license.txt in this distribution, or
 * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
 *
 * There are special exceptions to the terms and conditions of the GPL as
 * it is applied to this Source Code. View the full text of the exception
 * in the file doc/FLOSS-exception.txt in this software distribution, or
 * online at
 * http://secondlifegrid.net/programs/open_source/licensing/flossexception
 *
 * By copying, modifying or distributing this software, you acknowledge
 * that you have read and understood your obligations described above,
 * and agree to abide by those obligations.
 *
 * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
 * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
 * COMPLETENESS OR PERFORMANCE.
 * $/LicenseInfo$
 */

//-----------------------------------------------------------------------------
// Header Files
//-----------------------------------------------------------------------------
#include "linden_common.h"

#include "lleditingmotion.h"
#include "llcharacter.h"
#include "llhandmotion.h"
#include "llcriticaldamp.h"

//-----------------------------------------------------------------------------
// Constants
//-----------------------------------------------------------------------------
const LLQuaternion EDIT_MOTION_WRIST_ROTATION(F_PI_BY_TWO * 0.7f, LLVector3(1.0f, 0.0f, 0.0f));
const F32 TARGET_LAG_HALF_LIFE	= 0.1f;		// half-life of IK targeting
const F32 TORSO_LAG_HALF_LIFE = 0.2f;
const F32 MAX_TIME_DELTA = 2.f; //max two seconds a frame for calculating interpolation

S32 LLEditingMotion::sHandPose = LLHandMotion::HAND_POSE_RELAXED_R;
S32 LLEditingMotion::sHandPosePriority = 3;

//-----------------------------------------------------------------------------
// LLEditingMotion()
// Class Constructor
//-----------------------------------------------------------------------------
LLEditingMotion::LLEditingMotion( const LLUUID &id) : LLMotion(id)
{
	mCharacter = NULL;

	// create kinematic chain
	mParentJoint.addChild( &mShoulderJoint );
	mShoulderJoint.addChild( &mElbowJoint );
	mElbowJoint.addChild( &mWristJoint );

	mName = "editing";

	mParentState = new LLJointState;
	mShoulderState = new LLJointState;
	mElbowState = new LLJointState;
	mWristState = new LLJointState;
	mTorsoState = new LLJointState;
}

//-----------------------------------------------------------------------------
// ~LLEditingMotion()
// Class Destructor
//-----------------------------------------------------------------------------
LLEditingMotion::~LLEditingMotion()
{
}

//-----------------------------------------------------------------------------
// LLEditingMotion::onInitialize(LLCharacter *character)
//-----------------------------------------------------------------------------
LLMotion::LLMotionInitStatus LLEditingMotion::onInitialize(LLCharacter *character)
{
	// save character for future use
	mCharacter = character;

	// make sure character skeleton is copacetic
	if (!mCharacter->getJoint("mShoulderLeft") ||
		!mCharacter->getJoint("mElbowLeft") ||
		!mCharacter->getJoint("mWristLeft"))
	{
		llwarns << "Invalid skeleton for editing motion!" << llendl;
		return STATUS_FAILURE;
	}

	// get the shoulder, elbow, wrist joints from the character
	mParentState->setJoint( mCharacter->getJoint("mShoulderLeft")->getParent() );
	mShoulderState->setJoint( mCharacter->getJoint("mShoulderLeft") );
	mElbowState->setJoint( mCharacter->getJoint("mElbowLeft") );
	mWristState->setJoint( mCharacter->getJoint("mWristLeft") );
	mTorsoState->setJoint( mCharacter->getJoint("mTorso"));

	if ( ! mParentState->getJoint() )
	{
		llinfos << getName() << ": Can't get parent joint." << llendl;
		return STATUS_FAILURE;
	}

	mWristOffset = LLVector3(0.0f, 0.2f, 0.0f);

	// add joint states to the pose
	mShoulderState->setUsage(LLJointState::ROT);
	mElbowState->setUsage(LLJointState::ROT);
	mTorsoState->setUsage(LLJointState::ROT);
	mWristState->setUsage(LLJointState::ROT);
	addJointState( mShoulderState );
	addJointState( mElbowState );
	addJointState( mTorsoState );
	addJointState( mWristState );

	// propagate joint positions to kinematic chain
	mParentJoint.setPosition(	mParentState->getJoint()->getWorldPosition() );
	mShoulderJoint.setPosition(	mShoulderState->getJoint()->getPosition() );
	mElbowJoint.setPosition(	mElbowState->getJoint()->getPosition() );
	mWristJoint.setPosition(	mWristState->getJoint()->getPosition() + mWristOffset );

	// propagate current joint rotations to kinematic chain
	mParentJoint.setRotation(	mParentState->getJoint()->getWorldRotation() );
	mShoulderJoint.setRotation(	mShoulderState->getJoint()->getRotation() );
	mElbowJoint.setRotation(	mElbowState->getJoint()->getRotation() );

	// connect the ikSolver to the chain
	mIKSolver.setPoleVector( LLVector3( -1.0f, 1.0f, 0.0f ) );
	// specifying the elbow's axis will prevent bad IK for the more
	// singular configurations, but the axis is limb-specific -- Leviathan
	mIKSolver.setBAxis( LLVector3( -0.682683f, 0.0f, -0.730714f ) );
	mIKSolver.setupJoints( &mShoulderJoint, &mElbowJoint, &mWristJoint, &mTarget );

	return STATUS_SUCCESS;
}

//-----------------------------------------------------------------------------
// LLEditingMotion::onActivate()
//-----------------------------------------------------------------------------
BOOL LLEditingMotion::onActivate()
{
	// propagate joint positions to kinematic chain
	mParentJoint.setPosition(	mParentState->getJoint()->getWorldPosition() );
	mShoulderJoint.setPosition(	mShoulderState->getJoint()->getPosition() );
	mElbowJoint.setPosition(	mElbowState->getJoint()->getPosition() );
	mWristJoint.setPosition(	mWristState->getJoint()->getPosition() + mWristOffset );

	// propagate current joint rotations to kinematic chain
	mParentJoint.setRotation(	mParentState->getJoint()->getWorldRotation() );
	mShoulderJoint.setRotation(	mShoulderState->getJoint()->getRotation() );
	mElbowJoint.setRotation(	mElbowState->getJoint()->getRotation() );

	return TRUE;
}

//-----------------------------------------------------------------------------
// LLEditingMotion::onUpdate()
//-----------------------------------------------------------------------------
BOOL LLEditingMotion::onUpdate(F32 time, U8* joint_mask)
{
	LLVector3 focus_pt;
	LLVector3* pointAtPt = (LLVector3*)mCharacter->getAnimationData("PointAtPoint");

	BOOL result = TRUE;

	if (!pointAtPt)
	{
		focus_pt = mLastSelectPt;
		result = FALSE;
	}
	else
	{
		focus_pt = *pointAtPt;
		mLastSelectPt = focus_pt;
	}

	focus_pt += mCharacter->getCharacterPosition();

	// propagate joint positions to kinematic chain
	mParentJoint.setPosition(	mParentState->getJoint()->getWorldPosition() );
	mShoulderJoint.setPosition(	mShoulderState->getJoint()->getPosition() );
	mElbowJoint.setPosition(	mElbowState->getJoint()->getPosition() );
	mWristJoint.setPosition(	mWristState->getJoint()->getPosition() + mWristOffset );

	// propagate current joint rotations to kinematic chain
	mParentJoint.setRotation(	mParentState->getJoint()->getWorldRotation() );
	mShoulderJoint.setRotation(	mShoulderState->getJoint()->getRotation() );
	mElbowJoint.setRotation(	mElbowState->getJoint()->getRotation() );

	// update target position from character
	LLVector3 target = focus_pt - mParentJoint.getPosition();
	F32 target_dist = target.normVec();

	LLVector3 edit_plane_normal(1.f / F_SQRT2, 1.f / F_SQRT2, 0.f);
	edit_plane_normal.normVec();

	edit_plane_normal.rotVec(mTorsoState->getJoint()->getWorldRotation());

	F32 dot = edit_plane_normal * target;

	if (dot < 0.f)
	{
		target = target + (edit_plane_normal * (dot * 2.f));
		target.mV[VZ] += clamp_rescale(dot, 0.f, -1.f, 0.f, 5.f);
		target.normVec();
	}

	target = target * target_dist;
	if (!target.isFinite())
	{
		llerrs << "Non finite target in editing motion with target distance of " << target_dist <<
			" and focus point " << focus_pt << " and pointAtPt: " << *pointAtPt << llendl;
	}

	mTarget.setPosition( target + mParentJoint.getPosition());

//	llinfos << "Point At: " << mTarget.getPosition() << llendl;

	// update the ikSolver
	if (!mTarget.getPosition().isExactlyZero())
	{
		LLQuaternion shoulderRot = mShoulderJoint.getRotation();
		LLQuaternion elbowRot = mElbowJoint.getRotation();
		mIKSolver.solve();

		// use blending...
		F32 slerp_amt = LLCriticalDamp::getInterpolant(TARGET_LAG_HALF_LIFE);
		shoulderRot = slerp(slerp_amt, mShoulderJoint.getRotation(), shoulderRot);
		elbowRot = slerp(slerp_amt, mElbowJoint.getRotation(), elbowRot);

		// now put blended values back into joints
		llassert(shoulderRot.isFinite());
		llassert(elbowRot.isFinite());
		mShoulderState->setRotation(shoulderRot);
		mElbowState->setRotation(elbowRot);
		mWristState->setRotation(LLQuaternion::DEFAULT);
	}

	mCharacter->setAnimationData("Hand Pose", &sHandPose);
	mCharacter->setAnimationData("Hand Pose Priority", &sHandPosePriority);
	return result;
}

//-----------------------------------------------------------------------------
// LLEditingMotion::onDeactivate()
//-----------------------------------------------------------------------------
void LLEditingMotion::onDeactivate()
{
}

// End
<commit_msg>CID-59<commit_after>/**
 * @file lleditingmotion.cpp
 * @brief Implementation of LLEditingMotion class.
 *
 * $LicenseInfo:firstyear=2001&license=viewergpl$
 *
 * Copyright (c) 2001-2009, Linden Research, Inc.
 *
 * Second Life Viewer Source Code
 * The source code in this file ("Source Code") is provided by Linden Lab
 * to you under the terms of the GNU General Public License, version 2.0
 * ("GPL"), unless you have obtained a separate licensing agreement
 * ("Other License"), formally executed by you and Linden Lab.  Terms of
 * the GPL can be found in doc/GPL-license.txt in this distribution, or
 * online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
 *
 * There are special exceptions to the terms and conditions of the GPL as
 * it is applied to this Source Code. View the full text of the exception
 * in the file doc/FLOSS-exception.txt in this software distribution, or
 * online at
 * http://secondlifegrid.net/programs/open_source/licensing/flossexception
 *
 * By copying, modifying or distributing this software, you acknowledge
 * that you have read and understood your obligations described above,
 * and agree to abide by those obligations.
 *
 * ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
 * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
 * COMPLETENESS OR PERFORMANCE.
 * $/LicenseInfo$
 */

//-----------------------------------------------------------------------------
// Header Files
//-----------------------------------------------------------------------------
#include "linden_common.h"

#include "lleditingmotion.h"
#include "llcharacter.h"
#include "llhandmotion.h"
#include "llcriticaldamp.h"

//-----------------------------------------------------------------------------
// Constants
//-----------------------------------------------------------------------------
const LLQuaternion EDIT_MOTION_WRIST_ROTATION(F_PI_BY_TWO * 0.7f, LLVector3(1.0f, 0.0f, 0.0f));
const F32 TARGET_LAG_HALF_LIFE	= 0.1f;		// half-life of IK targeting
const F32 TORSO_LAG_HALF_LIFE = 0.2f;
const F32 MAX_TIME_DELTA = 2.f; //max two seconds a frame for calculating interpolation

S32 LLEditingMotion::sHandPose = LLHandMotion::HAND_POSE_RELAXED_R;
S32 LLEditingMotion::sHandPosePriority = 3;

//-----------------------------------------------------------------------------
// LLEditingMotion()
// Class Constructor
//-----------------------------------------------------------------------------
LLEditingMotion::LLEditingMotion( const LLUUID &id) : LLMotion(id)
{
	mCharacter = NULL;

	// create kinematic chain
	mParentJoint.addChild( &mShoulderJoint );
	mShoulderJoint.addChild( &mElbowJoint );
	mElbowJoint.addChild( &mWristJoint );

	mName = "editing";

	mParentState = new LLJointState;
	mShoulderState = new LLJointState;
	mElbowState = new LLJointState;
	mWristState = new LLJointState;
	mTorsoState = new LLJointState;
}

//-----------------------------------------------------------------------------
// ~LLEditingMotion()
// Class Destructor
//-----------------------------------------------------------------------------
LLEditingMotion::~LLEditingMotion()
{
}

//-----------------------------------------------------------------------------
// LLEditingMotion::onInitialize(LLCharacter *character)
//-----------------------------------------------------------------------------
LLMotion::LLMotionInitStatus LLEditingMotion::onInitialize(LLCharacter *character)
{
	// save character for future use
	mCharacter = character;

	// make sure character skeleton is copacetic
	if (!mCharacter->getJoint("mShoulderLeft") ||
		!mCharacter->getJoint("mElbowLeft") ||
		!mCharacter->getJoint("mWristLeft"))
	{
		llwarns << "Invalid skeleton for editing motion!" << llendl;
		return STATUS_FAILURE;
	}

	// get the shoulder, elbow, wrist joints from the character
	mParentState->setJoint( mCharacter->getJoint("mShoulderLeft")->getParent() );
	mShoulderState->setJoint( mCharacter->getJoint("mShoulderLeft") );
	mElbowState->setJoint( mCharacter->getJoint("mElbowLeft") );
	mWristState->setJoint( mCharacter->getJoint("mWristLeft") );
	mTorsoState->setJoint( mCharacter->getJoint("mTorso"));

	if ( ! mParentState->getJoint() )
	{
		llinfos << getName() << ": Can't get parent joint." << llendl;
		return STATUS_FAILURE;
	}

	mWristOffset = LLVector3(0.0f, 0.2f, 0.0f);

	// add joint states to the pose
	mShoulderState->setUsage(LLJointState::ROT);
	mElbowState->setUsage(LLJointState::ROT);
	mTorsoState->setUsage(LLJointState::ROT);
	mWristState->setUsage(LLJointState::ROT);
	addJointState( mShoulderState );
	addJointState( mElbowState );
	addJointState( mTorsoState );
	addJointState( mWristState );

	// propagate joint positions to kinematic chain
	mParentJoint.setPosition(	mParentState->getJoint()->getWorldPosition() );
	mShoulderJoint.setPosition(	mShoulderState->getJoint()->getPosition() );
	mElbowJoint.setPosition(	mElbowState->getJoint()->getPosition() );
	mWristJoint.setPosition(	mWristState->getJoint()->getPosition() + mWristOffset );

	// propagate current joint rotations to kinematic chain
	mParentJoint.setRotation(	mParentState->getJoint()->getWorldRotation() );
	mShoulderJoint.setRotation(	mShoulderState->getJoint()->getRotation() );
	mElbowJoint.setRotation(	mElbowState->getJoint()->getRotation() );

	// connect the ikSolver to the chain
	mIKSolver.setPoleVector( LLVector3( -1.0f, 1.0f, 0.0f ) );
	// specifying the elbow's axis will prevent bad IK for the more
	// singular configurations, but the axis is limb-specific -- Leviathan
	mIKSolver.setBAxis( LLVector3( -0.682683f, 0.0f, -0.730714f ) );
	mIKSolver.setupJoints( &mShoulderJoint, &mElbowJoint, &mWristJoint, &mTarget );

	return STATUS_SUCCESS;
}

//-----------------------------------------------------------------------------
// LLEditingMotion::onActivate()
//-----------------------------------------------------------------------------
BOOL LLEditingMotion::onActivate()
{
	// propagate joint positions to kinematic chain
	mParentJoint.setPosition(	mParentState->getJoint()->getWorldPosition() );
	mShoulderJoint.setPosition(	mShoulderState->getJoint()->getPosition() );
	mElbowJoint.setPosition(	mElbowState->getJoint()->getPosition() );
	mWristJoint.setPosition(	mWristState->getJoint()->getPosition() + mWristOffset );

	// propagate current joint rotations to kinematic chain
	mParentJoint.setRotation(	mParentState->getJoint()->getWorldRotation() );
	mShoulderJoint.setRotation(	mShoulderState->getJoint()->getRotation() );
	mElbowJoint.setRotation(	mElbowState->getJoint()->getRotation() );

	return TRUE;
}

//-----------------------------------------------------------------------------
// LLEditingMotion::onUpdate()
//-----------------------------------------------------------------------------
BOOL LLEditingMotion::onUpdate(F32 time, U8* joint_mask)
{
	LLVector3 focus_pt;
	LLVector3* pointAtPt = (LLVector3*)mCharacter->getAnimationData("PointAtPoint");

	BOOL result = TRUE;

	if (!pointAtPt)
	{
		focus_pt = mLastSelectPt;
		result = FALSE;
	}
	else
	{
		focus_pt = *pointAtPt;
		mLastSelectPt = focus_pt;
	}

	focus_pt += mCharacter->getCharacterPosition();

	// propagate joint positions to kinematic chain
	mParentJoint.setPosition(	mParentState->getJoint()->getWorldPosition() );
	mShoulderJoint.setPosition(	mShoulderState->getJoint()->getPosition() );
	mElbowJoint.setPosition(	mElbowState->getJoint()->getPosition() );
	mWristJoint.setPosition(	mWristState->getJoint()->getPosition() + mWristOffset );

	// propagate current joint rotations to kinematic chain
	mParentJoint.setRotation(	mParentState->getJoint()->getWorldRotation() );
	mShoulderJoint.setRotation(	mShoulderState->getJoint()->getRotation() );
	mElbowJoint.setRotation(	mElbowState->getJoint()->getRotation() );

	// update target position from character
	LLVector3 target = focus_pt - mParentJoint.getPosition();
	F32 target_dist = target.normVec();

	LLVector3 edit_plane_normal(1.f / F_SQRT2, 1.f / F_SQRT2, 0.f);
	edit_plane_normal.normVec();

	edit_plane_normal.rotVec(mTorsoState->getJoint()->getWorldRotation());

	F32 dot = edit_plane_normal * target;

	if (dot < 0.f)
	{
		target = target + (edit_plane_normal * (dot * 2.f));
		target.mV[VZ] += clamp_rescale(dot, 0.f, -1.f, 0.f, 5.f);
		target.normVec();
	}

	target = target * target_dist;
	if (!target.isFinite())
	{
		llerrs << "Non finite target in editing motion with target distance of " << target_dist <<
			" and focus point " << focus_pt << llendl;
	}

	mTarget.setPosition( target + mParentJoint.getPosition());

//	llinfos << "Point At: " << mTarget.getPosition() << llendl;

	// update the ikSolver
	if (!mTarget.getPosition().isExactlyZero())
	{
		LLQuaternion shoulderRot = mShoulderJoint.getRotation();
		LLQuaternion elbowRot = mElbowJoint.getRotation();
		mIKSolver.solve();

		// use blending...
		F32 slerp_amt = LLCriticalDamp::getInterpolant(TARGET_LAG_HALF_LIFE);
		shoulderRot = slerp(slerp_amt, mShoulderJoint.getRotation(), shoulderRot);
		elbowRot = slerp(slerp_amt, mElbowJoint.getRotation(), elbowRot);

		// now put blended values back into joints
		llassert(shoulderRot.isFinite());
		llassert(elbowRot.isFinite());
		mShoulderState->setRotation(shoulderRot);
		mElbowState->setRotation(elbowRot);
		mWristState->setRotation(LLQuaternion::DEFAULT);
	}

	mCharacter->setAnimationData("Hand Pose", &sHandPose);
	mCharacter->setAnimationData("Hand Pose Priority", &sHandPosePriority);
	return result;
}

//-----------------------------------------------------------------------------
// LLEditingMotion::onDeactivate()
//-----------------------------------------------------------------------------
void LLEditingMotion::onDeactivate()
{
}

// End
<|endoftext|>


<commit_before>/*
 * Contact Chooser Dialog
 *
 * Copyright (C) 2011 David Edmundson <kde@davidedmundson.co.uk>
 * Copyright (C) 2012 Daniele E. Domenichelli <daniele.domenichelli@gmail.com>
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "contact-grid-dialog.h"

#include <KDE/KLineEdit>
#include <KDE/KPushButton>
#include <KDE/KLocalizedString>
#include <KDE/KDebug>

#include <TelepathyQt/AccountManager>
#include <TelepathyQt/AccountFactory>
#include <TelepathyQt/PendingReady>

#include <KTp/debug.h>
#include <KTp/Models/accounts-model.h>
#include <KTp/Models/accounts-filter-model.h>
#include <KTp/Widgets/contact-grid-widget.h>
#include <telepathy-qt4/TelepathyQt/PendingChannelRequest>

class KTp::ContactGridDialog::Private
{
public:
    Private(KTp::ContactGridDialog *parent) :
        q(parent),
        accountsModel(0),
        account(0),
        contact(0)
    {
    }

    KTp::ContactGridDialog * const q;

    Tp::AccountManagerPtr accountManager;
    AccountsModel *accountsModel;
    KTp::ContactGridWidget *contactGridWidget;
    Tp::AccountPtr account;
    Tp::ContactPtr contact;

public Q_SLOTS:
    void _k_onAccountManagerReady();
    void _k_onOkClicked();
    void _k_onChanged();
};

void KTp::ContactGridDialog::Private::_k_onAccountManagerReady()
{
    kDebug() << "Account manager is ready";
    accountsModel->setAccountManager(accountManager);
}

void KTp::ContactGridDialog::Private::_k_onOkClicked()
{
    // don't do anytghing if no contact has been selected
    if (!contactGridWidget->hasSelection()) {
        // show message box?
        return;
    }

    contact = contactGridWidget->selectedContact();
    account = contactGridWidget->selectedAccount();

    if (account.isNull()) {
        kWarning() << "Account is NULL";
    } else if (contact.isNull()) {
        kWarning() << "Contact is NULL";
    } else {
        kDebug() << "Account is: " << account->displayName();
        kDebug() << "Contact is: " << contact->alias();
    }
}

void KTp::ContactGridDialog::Private::_k_onChanged()
{
    q->button(KDialog::Ok)->setEnabled(contactGridWidget->hasSelection());
}

KTp::ContactGridDialog::ContactGridDialog(QWidget *parent) :
    KDialog(parent),
    d(new Private(this))
{
    resize(500,450);

    Tp::AccountFactoryPtr  accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(),
                                                                       Tp::Features() << Tp::Account::FeatureCore
                                                                                << Tp::Account::FeatureAvatar
                                                                                << Tp::Account::FeatureProtocolInfo
                                                                                << Tp::Account::FeatureProfile);

    Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(),
                                                                               Tp::Features() << Tp::Connection::FeatureCore
                                                                                << Tp::Connection::FeatureRosterGroups
                                                                                << Tp::Connection::FeatureRoster
                                                                                << Tp::Connection::FeatureSelfContact);

    Tp::ContactFactoryPtr contactFactory = Tp::ContactFactory::create(Tp::Features()  << Tp::Contact::FeatureAlias
                                                                                << Tp::Contact::FeatureAvatarData
                                                                                << Tp::Contact::FeatureSimplePresence
                                                                                << Tp::Contact::FeatureCapabilities);

    Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus());

    d->accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(),
                                                   accountFactory,
                                                   connectionFactory,
                                                   channelFactory,
                                                   contactFactory);

    d->accountsModel = new AccountsModel(this);
    connect(d->accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(_k_onAccountManagerReady()));

    d->contactGridWidget = new KTp::ContactGridWidget(d->accountsModel, this);
    d->contactGridWidget->contactFilterLineEdit()->setClickMessage(i18n("Search in Contacts..."));
    d->contactGridWidget->filter()->setPresenceTypeFilterFlags(AccountsFilterModel::ShowOnlyConnected);

    setMainWidget(d->contactGridWidget);

    connect(d->contactGridWidget,
            SIGNAL(selectionChanged(Tp::AccountPtr,Tp::ContactPtr)),
            SLOT(_k_onChanged()));

    button(KDialog::Ok)->setDisabled(true);

    connect(this, SIGNAL(okClicked()), SLOT(_k_onOkClicked()));
    connect(this, SIGNAL(rejected()), SLOT(close()));
}

KTp::ContactGridDialog::~ContactGridDialog()
{
    delete d;
}

Tp::AccountPtr KTp::ContactGridDialog::account()
{
    return d->account;
}

Tp::ContactPtr KTp::ContactGridDialog::contact()
{
    return d->contact;
}

AccountsFilterModel* KTp::ContactGridDialog::filter() const
{
    return d->contactGridWidget->filter();
}

#include "contact-grid-dialog.moc"
<commit_msg>Update features required to include Account::FeatureCaps, as this is now used by the AccountsModel<commit_after>/*
 * Contact Chooser Dialog
 *
 * Copyright (C) 2011 David Edmundson <kde@davidedmundson.co.uk>
 * Copyright (C) 2012 Daniele E. Domenichelli <daniele.domenichelli@gmail.com>
 *
 * 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 St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "contact-grid-dialog.h"

#include <KDE/KLineEdit>
#include <KDE/KPushButton>
#include <KDE/KLocalizedString>
#include <KDE/KDebug>

#include <TelepathyQt/AccountManager>
#include <TelepathyQt/AccountFactory>
#include <TelepathyQt/PendingReady>

#include <KTp/debug.h>
#include <KTp/Models/accounts-model.h>
#include <KTp/Models/accounts-filter-model.h>
#include <KTp/Widgets/contact-grid-widget.h>
#include <telepathy-qt4/TelepathyQt/PendingChannelRequest>

class KTp::ContactGridDialog::Private
{
public:
    Private(KTp::ContactGridDialog *parent) :
        q(parent),
        accountsModel(0),
        account(0),
        contact(0)
    {
    }

    KTp::ContactGridDialog * const q;

    Tp::AccountManagerPtr accountManager;
    AccountsModel *accountsModel;
    KTp::ContactGridWidget *contactGridWidget;
    Tp::AccountPtr account;
    Tp::ContactPtr contact;

public Q_SLOTS:
    void _k_onAccountManagerReady();
    void _k_onOkClicked();
    void _k_onChanged();
};

void KTp::ContactGridDialog::Private::_k_onAccountManagerReady()
{
    kDebug() << "Account manager is ready";
    accountsModel->setAccountManager(accountManager);
}

void KTp::ContactGridDialog::Private::_k_onOkClicked()
{
    // don't do anytghing if no contact has been selected
    if (!contactGridWidget->hasSelection()) {
        // show message box?
        return;
    }

    contact = contactGridWidget->selectedContact();
    account = contactGridWidget->selectedAccount();

    if (account.isNull()) {
        kWarning() << "Account is NULL";
    } else if (contact.isNull()) {
        kWarning() << "Contact is NULL";
    } else {
        kDebug() << "Account is: " << account->displayName();
        kDebug() << "Contact is: " << contact->alias();
    }
}

void KTp::ContactGridDialog::Private::_k_onChanged()
{
    q->button(KDialog::Ok)->setEnabled(contactGridWidget->hasSelection());
}

KTp::ContactGridDialog::ContactGridDialog(QWidget *parent) :
    KDialog(parent),
    d(new Private(this))
{
    resize(500,450);

    Tp::AccountFactoryPtr  accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(),
                                                                       Tp::Features() << Tp::Account::FeatureCore
                                                                                << Tp::Account::FeatureAvatar
                                                                                << Tp::Account::FeatureProtocolInfo
                                                                                << Tp::Account::FeatureProfile
                                                                                << Tp::Account::FeatureCapabilities);

    Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(),
                                                                               Tp::Features() << Tp::Connection::FeatureCore
                                                                                << Tp::Connection::FeatureRosterGroups
                                                                                << Tp::Connection::FeatureRoster
                                                                                << Tp::Connection::FeatureSelfContact);

    Tp::ContactFactoryPtr contactFactory = Tp::ContactFactory::create(Tp::Features()  << Tp::Contact::FeatureAlias
                                                                                << Tp::Contact::FeatureAvatarData
                                                                                << Tp::Contact::FeatureSimplePresence
                                                                                << Tp::Contact::FeatureCapabilities);

    Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus());

    d->accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(),
                                                   accountFactory,
                                                   connectionFactory,
                                                   channelFactory,
                                                   contactFactory);

    d->accountsModel = new AccountsModel(this);
    connect(d->accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(_k_onAccountManagerReady()));

    d->contactGridWidget = new KTp::ContactGridWidget(d->accountsModel, this);
    d->contactGridWidget->contactFilterLineEdit()->setClickMessage(i18n("Search in Contacts..."));
    d->contactGridWidget->filter()->setPresenceTypeFilterFlags(AccountsFilterModel::ShowOnlyConnected);

    setMainWidget(d->contactGridWidget);

    connect(d->contactGridWidget,
            SIGNAL(selectionChanged(Tp::AccountPtr,Tp::ContactPtr)),
            SLOT(_k_onChanged()));

    button(KDialog::Ok)->setDisabled(true);

    connect(this, SIGNAL(okClicked()), SLOT(_k_onOkClicked()));
    connect(this, SIGNAL(rejected()), SLOT(close()));
}

KTp::ContactGridDialog::~ContactGridDialog()
{
    delete d;
}

Tp::AccountPtr KTp::ContactGridDialog::account()
{
    return d->account;
}

Tp::ContactPtr KTp::ContactGridDialog::contact()
{
    return d->contact;
}

AccountsFilterModel* KTp::ContactGridDialog::filter() const
{
    return d->contactGridWidget->filter();
}

#include "contact-grid-dialog.moc"
<|endoftext|>