<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

#include "AuthManager.h"
#include "NebulaLog.h"

#include "Nebula.h"

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

time_t AuthManager::_time_out;

const char * AuthManager::auth_driver_name = "auth_exe";

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

extern "C" void * authm_action_loop(void *arg)
{
    AuthManager *  authm;

    if ( arg == 0 )
    {
        return 0;
    }

    authm = static_cast<AuthManager *>(arg);

    NebulaLog::log("AuM",Log::INFO,"Authorization Manager started.");

    authm->am.loop(authm->timer_period,0);

    NebulaLog::log("AuM",Log::INFO,"Authorization Manager stopped.");

    return 0;
}

/* -------------------------------------------------------------------------- */

int AuthManager::start()
{
    int               rc;
    pthread_attr_t    pattr;

    rc = MadManager::start();

    if ( rc != 0 )
    {
        return -1;
    }

    NebulaLog::log("AuM",Log::INFO,"Starting Auth Manager...");

    pthread_attr_init (&pattr);
    pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);

    rc = pthread_create(&authm_thread,&pattr,authm_action_loop,(void *) this);

    return rc;
};

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void AuthManager::trigger(Actions action, AuthRequest * request)
{
    string  aname;

    switch (action)
    {
    case AUTHENTICATE:
        aname = "AUTHENTICATE";
        break;

    case AUTHORIZE:
        aname = "AUTHORIZE";
        break;

    case FINALIZE:
        aname = ACTION_FINALIZE;
        break;

    default:
        return;
    }

    am.trigger(aname,request);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void AuthManager::do_action(const string &action, void * arg)
{
    AuthRequest * request;

    request  = static_cast<AuthRequest *>(arg);

    if (action == "AUTHENTICATE" && request != 0)
    {
        authenticate_action(request);
    }
    else if (action == "AUTHORIZE"  && request != 0)
    {
        authorize_action(request);
    }
    else if (action == ACTION_TIMER)
    {
        timer_action();
    }
    else if (action == ACTION_FINALIZE)
    {
        NebulaLog::log("AuM",Log::INFO,"Stopping Authorization Manager...");

        MadManager::stop();
    }
    else
    {
        ostringstream oss;
        oss << "Unknown action name: " << action;

        NebulaLog::log("AuM", Log::ERROR, oss);
    }
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void AuthManager::authenticate_action(AuthRequest * ar)
{
    const AuthManagerDriver * authm_md;

    // ------------------------------------------------------------------------
    // Get the driver
    // ------------------------------------------------------------------------

    authm_md = get();

    if (authm_md == 0)
    {
        goto error_driver;
    }

    // ------------------------------------------------------------------------
    // Queue the request
    // ------------------------------------------------------------------------

    ar->id = add_request(ar);

    // ------------------------------------------------------------------------
    // Make the request to the driver
    // ---- --------------------------------------------------------------------

    authm_md->authenticate(ar->id,
                           ar->uid,
                           ar->username,
                           ar->password,
                           ar->session);
    return;

error_driver:
    ar->result  = false;
    ar->message = "Could not find Authorization driver";
    ar->notify();
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void AuthManager::authorize_action(AuthRequest * ar)
{
    const AuthManagerDriver * authm_md;
    string auths;

    // ------------------------------------------------------------------------
    // Get the driver
    // ------------------------------------------------------------------------

    authm_md = get();

    if (authm_md == 0)
    {
        goto error_driver;
    }

    // ------------------------------------------------------------------------
    // Queue the request
    // ------------------------------------------------------------------------

    ar->id = add_request(ar);

    // ------------------------------------------------------------------------
    // Make the request to the driver
    // ------------------------------------------------------------------------

    auths = ar->get_auths();

    authm_md->authorize(ar->id, ar->uid, auths);

    return;

error_driver:
    ar->result  = false;
    ar->message = "Could not find Authorization driver";
    ar->notify();
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void AuthManager::timer_action()
{
    map<int,AuthRequest *>::iterator it;

    time_t the_time = time(0);

    lock();

    for (it=auth_requests.begin();it!=auth_requests.end();it++)
    {
        if (the_time > it->second->time_out)
        {
            AuthRequest * ar = it->second;
            auth_requests.erase(it);

            ar->result  = false;
            ar->timeout = true;
            ar->message.clear();

            ar->notify();
        }
    }

    unlock();

}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int AuthManager::add_request(AuthRequest *ar)
{
    static int auth_id = 0;
    int id;

    lock();

    id = auth_id++;

    auth_requests.insert(auth_requests.end(),make_pair(id,ar));

    unlock();

    return id;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

AuthRequest * AuthManager::get_request(int id)
{
    AuthRequest * ar = 0;
    map<int,AuthRequest *>::iterator it;
    ostringstream oss;

    lock();

    it=auth_requests.find(id);

    if ( it != auth_requests.end())
    {
        ar = it->second;

        auth_requests.erase(it);
    }

    unlock();

    return ar;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void AuthManager::notify_request(int auth_id,bool result,const string& message)
{

    AuthRequest * ar;

    ar = get_request(auth_id);

    if ( ar == 0 )
    {
        return;
    }

    ar->result = result;
    ar->message= message;

    ar->notify();
}

/* ************************************************************************** */
/* MAD Loading                                                                */
/* ************************************************************************** */

void AuthManager::load_mads(int uid)
{
    ostringstream                   oss;
    const VectorAttribute *         vattr;
    int                             rc;
    string                          name;
    AuthManagerDriver *             authm_driver = 0;

    oss << "Loading Auth. Manager driver.";

    NebulaLog::log("AuM",Log::INFO,oss);

    vattr = static_cast<const VectorAttribute *>(mad_conf[0]);

    if ( vattr == 0 )
    {
        NebulaLog::log("AuM",Log::ERROR,"Failed to load Auth. Manager driver.");
        return;
    }

    VectorAttribute auth_conf("AUTH_MAD",vattr->value());

    auth_conf.replace("NAME",auth_driver_name);

    authm_driver = new AuthManagerDriver(uid,auth_conf.value(),(uid!=0),this);

    rc = add(authm_driver);

    if ( rc == 0 )
    {
        oss.str("");
        oss << "\tAuth Manager loaded";

        NebulaLog::log("AuM",Log::INFO,oss);
    }
}
<commit_msg>feature #203: Default message for timeouts<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.org)             */
/*                                                                            */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may    */
/* not use this file except in compliance with the License. You may obtain    */
/* a copy of the License at                                                   */
/*                                                                            */
/* http://www.apache.org/licenses/LICENSE-2.0                                 */
/*                                                                            */
/* Unless required by applicable law or agreed to in writing, software        */
/* distributed under the License is distributed on an "AS IS" BASIS,          */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   */
/* See the License for the specific language governing permissions and        */
/* limitations under the License.                                             */
/* -------------------------------------------------------------------------- */

#include "AuthManager.h"
#include "NebulaLog.h"

#include "Nebula.h"

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

time_t AuthManager::_time_out;

const char * AuthManager::auth_driver_name = "auth_exe";

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

extern "C" void * authm_action_loop(void *arg)
{
    AuthManager *  authm;

    if ( arg == 0 )
    {
        return 0;
    }

    authm = static_cast<AuthManager *>(arg);

    NebulaLog::log("AuM",Log::INFO,"Authorization Manager started.");

    authm->am.loop(authm->timer_period,0);

    NebulaLog::log("AuM",Log::INFO,"Authorization Manager stopped.");

    return 0;
}

/* -------------------------------------------------------------------------- */

int AuthManager::start()
{
    int               rc;
    pthread_attr_t    pattr;

    rc = MadManager::start();

    if ( rc != 0 )
    {
        return -1;
    }

    NebulaLog::log("AuM",Log::INFO,"Starting Auth Manager...");

    pthread_attr_init (&pattr);
    pthread_attr_setdetachstate (&pattr, PTHREAD_CREATE_JOINABLE);

    rc = pthread_create(&authm_thread,&pattr,authm_action_loop,(void *) this);

    return rc;
};

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void AuthManager::trigger(Actions action, AuthRequest * request)
{
    string  aname;

    switch (action)
    {
    case AUTHENTICATE:
        aname = "AUTHENTICATE";
        break;

    case AUTHORIZE:
        aname = "AUTHORIZE";
        break;

    case FINALIZE:
        aname = ACTION_FINALIZE;
        break;

    default:
        return;
    }

    am.trigger(aname,request);
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void AuthManager::do_action(const string &action, void * arg)
{
    AuthRequest * request;

    request  = static_cast<AuthRequest *>(arg);

    if (action == "AUTHENTICATE" && request != 0)
    {
        authenticate_action(request);
    }
    else if (action == "AUTHORIZE"  && request != 0)
    {
        authorize_action(request);
    }
    else if (action == ACTION_TIMER)
    {
        timer_action();
    }
    else if (action == ACTION_FINALIZE)
    {
        NebulaLog::log("AuM",Log::INFO,"Stopping Authorization Manager...");

        MadManager::stop();
    }
    else
    {
        ostringstream oss;
        oss << "Unknown action name: " << action;

        NebulaLog::log("AuM", Log::ERROR, oss);
    }
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void AuthManager::authenticate_action(AuthRequest * ar)
{
    const AuthManagerDriver * authm_md;

    // ------------------------------------------------------------------------
    // Get the driver
    // ------------------------------------------------------------------------

    authm_md = get();

    if (authm_md == 0)
    {
        goto error_driver;
    }

    // ------------------------------------------------------------------------
    // Queue the request
    // ------------------------------------------------------------------------

    ar->id = add_request(ar);

    // ------------------------------------------------------------------------
    // Make the request to the driver
    // ---- --------------------------------------------------------------------

    authm_md->authenticate(ar->id,
                           ar->uid,
                           ar->username,
                           ar->password,
                           ar->session);
    return;

error_driver:
    ar->result  = false;
    ar->message = "Could not find Authorization driver";
    ar->notify();
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void AuthManager::authorize_action(AuthRequest * ar)
{
    const AuthManagerDriver * authm_md;
    string auths;

    // ------------------------------------------------------------------------
    // Get the driver
    // ------------------------------------------------------------------------

    authm_md = get();

    if (authm_md == 0)
    {
        goto error_driver;
    }

    // ------------------------------------------------------------------------
    // Queue the request
    // ------------------------------------------------------------------------

    ar->id = add_request(ar);

    // ------------------------------------------------------------------------
    // Make the request to the driver
    // ------------------------------------------------------------------------

    auths = ar->get_auths();

    authm_md->authorize(ar->id, ar->uid, auths);

    return;

error_driver:
    ar->result  = false;
    ar->message = "Could not find Authorization driver";
    ar->notify();
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void AuthManager::timer_action()
{
    map<int,AuthRequest *>::iterator it;

    time_t the_time = time(0);

    lock();

    for (it=auth_requests.begin();it!=auth_requests.end();it++)
    {
        if (the_time > it->second->time_out)
        {
            AuthRequest * ar = it->second;
            auth_requests.erase(it);

            ar->result  = false;
            ar->timeout = true;
            ar->message = "Auth request timeout";

            ar->notify();
        }
    }

    unlock();

}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

int AuthManager::add_request(AuthRequest *ar)
{
    static int auth_id = 0;
    int id;

    lock();

    id = auth_id++;

    auth_requests.insert(auth_requests.end(),make_pair(id,ar));

    unlock();

    return id;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

AuthRequest * AuthManager::get_request(int id)
{
    AuthRequest * ar = 0;
    map<int,AuthRequest *>::iterator it;
    ostringstream oss;

    lock();

    it=auth_requests.find(id);

    if ( it != auth_requests.end())
    {
        ar = it->second;

        auth_requests.erase(it);
    }

    unlock();

    return ar;
}

/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */

void AuthManager::notify_request(int auth_id,bool result,const string& message)
{

    AuthRequest * ar;

    ar = get_request(auth_id);

    if ( ar == 0 )
    {
        return;
    }

    ar->result = result;
    ar->message= message;

    ar->notify();
}

/* ************************************************************************** */
/* MAD Loading                                                                */
/* ************************************************************************** */

void AuthManager::load_mads(int uid)
{
    ostringstream                   oss;
    const VectorAttribute *         vattr;
    int                             rc;
    string                          name;
    AuthManagerDriver *             authm_driver = 0;

    oss << "Loading Auth. Manager driver.";

    NebulaLog::log("AuM",Log::INFO,oss);

    vattr = static_cast<const VectorAttribute *>(mad_conf[0]);

    if ( vattr == 0 )
    {
        NebulaLog::log("AuM",Log::ERROR,"Failed to load Auth. Manager driver.");
        return;
    }

    VectorAttribute auth_conf("AUTH_MAD",vattr->value());

    auth_conf.replace("NAME",auth_driver_name);

    authm_driver = new AuthManagerDriver(uid,auth_conf.value(),(uid!=0),this);

    rc = add(authm_driver);

    if ( rc == 0 )
    {
        oss.str("");
        oss << "\tAuth Manager loaded";

        NebulaLog::log("AuM",Log::INFO,oss);
    }
}
<|endoftext|>


<commit_before>#pragma once

#include <asyncio/common.hpp>
#include <deque>
#include <queue>

BEGIN_ASYNCIO_NAMESPACE;
template <class T> class ExtendedQueue : public std::queue<T> {
public:
  template <class V> bool erase(V &&elem) {
    for (auto i = this->c.begin(); i != this->c.end(); i++) {
      if (*i == elem) {
        this->c.erase(i);
        return true;
      }
    }
    return false;
  }
};
END_ASYNCIO_NAMESPACE;<commit_msg>using a set to avoid O(N^2) complexity in UVAsyncTimerService::processTimer()<commit_after>#pragma once

#include <asyncio/common.hpp>
#include <deque>
#include <exception>
#include <queue>
#include <unordered_set>

BEGIN_ASYNCIO_NAMESPACE;
template <class T> class ExtendedQueue : public std::queue<T> {
public: // optimized me when needed
  template <class V> bool erase(V &&elem) {
    if (_set.erase(elem) == 0) {
      return false;
    }
    for (auto i = this->c.begin(); i != this->c.end(); i++) {
      if (*i == elem) {
        this->c.erase(i);
        break;
      }
    }
    return true;
  }

  template <class V> void push(V &&v) {
    auto pair = _set.insert(v);
    if (pair.second) {
      std::queue<T>::push(v);
    } else {
      throw std::logic_error("duplicate elements detected!");
    }
  }

  void pop() {
    _set.erase(this->front());
    std::queue<T>::pop();
  }

private:
  std::unordered_set<T> _set;
};
END_ASYNCIO_NAMESPACE;<|endoftext|>


<commit_before>#include <Io.h>
#include <Windows.h>
#include <Winbase.h>

#include <stdio.h>
#include <stdlib.h>

#include <osg/Notify>
#include <osg/Node>
#include <osg/Geode>
#include <osg/Group>

#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgDB/Registry>

using namespace osg;
using namespace osgDB;

#define FILEUTILS_MAX_PATH_LENGTH 2048

char *PathDelimitor = ";";
static const char *s_default_file_path = ".;";
static const char *s_default_dso_path = "C:/Windows/System/;";
static char *s_filePath = ".;";

#define F_OK 4

static bool s_filePathInitialized = false;

void osgDB::initFilePath( void )
{
    char *ptr;
    if( (ptr = getenv( "OSGFILEPATH" ))  )
    {
        notify(DEBUG_INFO) << "osgDB::Init("<<ptr<<")"<<std::endl;
        setFilePath( ptr );
    }
    else
    {
        notify(DEBUG_INFO) << "osgDB::Init(NULL)"<<std::endl;
    }
    s_filePathInitialized = true;
}

void osgDB::setFilePath( const char *_path )
{
    char buff[FILEUTILS_MAX_PATH_LENGTH];

    notify(DEBUG_INFO) << "In osgDB::setFilePath("<<_path<<")"<<std::endl;

    buff[0] = 0;

    if( s_filePath != s_default_file_path )
    {
        strcpy( buff, s_filePath );
    }

    strcat( buff, PathDelimitor );
    strcat( buff, _path );

    s_filePath = strdup( buff );

    s_filePathInitialized = true;
}

const char* osgDB::getFilePath()
{
    return s_filePath;
}

char *osgDB::findFileInPath( const char *_file, const char * filePath )
{

    char pathbuff[FILEUTILS_MAX_PATH_LENGTH];
    char *tptr, *tmppath;
    char *path = 0L;

    notify(DEBUG_INFO) << "FindFileInPath() : trying " << _file << " ...\n";
    if( access( _file, F_OK ) == 0 )
    {
        return strdup(_file);
    }

    tptr    = strdup( filePath );
    tmppath = strtok(  tptr, PathDelimitor );

    do
    {
        sprintf( pathbuff, "%s/%s", tmppath, _file );
        notify(DEBUG_INFO) << "FindFileInPath() : trying " << pathbuff << " ...\n";
        if( access( pathbuff, F_OK ) == 0 ) break;
    } while( (tmppath = strtok( 0, PathDelimitor )) );

    if( tmppath != (char *)0L )
        path = strdup( pathbuff );

    ::free(tptr);

    if (path) notify( DEBUG_INFO ) << "FindFileInPath() : returning " << path << std::endl;
	else notify( DEBUG_INFO ) << "FindFileInPath() : returning NULL" << std::endl;

    return path;
}

char *osgDB::findFile( const char *file )
{
    if (!file) return NULL;

    if (!s_filePathInitialized) initFilePath();

    char* newFileName = findFileInPath( file, s_filePath );
    if (newFileName) return newFileName;

    // need to check here to see if file has a path on it.

    // now strip the file of an previous path if one exists.
    std::string simpleFileName = getSimpleFileName(file);
    newFileName = findFileInPath( simpleFileName.c_str(), s_filePath );
    return newFileName;
}

/*

Order of precedence for

Under UNIX.

  ./
  OSG_LD_LIBRARY_PATH
  s_default_dso_path
  LD_LIBRARY*_PATH

Under Windows

  ./
  OSG_LD_LIBRARY_PATH
  s_default_dso_path
  PATH

*/

char *osgDB::findDSO( const char *name )
{

    if ((ptr = getenv( "PATH" )))
    {
        notify(DEBUG_INFO) << "PATH = "<<ptr<<std::endl;
        strcat( path, PathDelimitor );
        strcat( path, ptr );
    }

    // check existance of dso assembled direct paths.
    char* fileFound = NULL;
    fileFound = findFileInPath( name , path );
    if (fileFound) return fileFound;

    // failed with direct paths,
    // now try prepending the filename with "osgPlugins/"
    char* prependosgPlugins = osgNew char[strlen(name)+12];
    strcpy(prependosgPlugins,"osgPlugins/");
    strcat(prependosgPlugins,name);

    fileFound = findFileInPath( prependosgPlugins , path );
    osgDelete [] prependosgPlugins;

    return fileFound;
}

std::string osgDB::findFileInDirectory(const std::string& fileName,const std::string& dirName,bool caseInsensitive)
{
    bool needFollowingBackslash = false;
    bool needDirectoryName = true;
    osgDB::DirectoryContents dc;

    if (dirName.empty())
    {
        dc = osgDB::getDirectoryContents(".");
        needFollowingBackslash = false;
        needDirectoryName = false;
    }
    else if (dirName=="." || dirName=="./" || dirName==".\\")
    {
        dc = osgDB::getDirectoryContents(".");
        needFollowingBackslash = false;
        needDirectoryName = false;
    }
    else
    {
        dc = osgDB::getDirectoryContents(dirName);
        char lastChar = dirName[dirName.size()-1];
        if (lastChar=='/') needFollowingBackslash = false;
        else if (lastChar=='\\') needFollowingBackslash = false;
        else needFollowingBackslash = true;
        needDirectoryName = true;
    }

    for(osgDB::DirectoryContents::iterator itr=dc.begin();
        itr!=dc.end();
        ++itr)
    {
        if ((caseInsensitive && osgDB::equalCaseInsensitive(fileName,*itr)) ||
            (fileName==*itr))
        {
            if (!needDirectoryName) return *itr;
            else if (needFollowingBackslash) return dirName+'/'+*itr;
            else return dirName+*itr;
        }
    }
    return "";
}

#include <io.h>
#include <direct.h>

osgDB::DirectoryContents osgDB::getDirectoryContents(const std::string& dirName)
{
    osgDB::DirectoryContents contents;

    WIN32_FIND_DATA data;
    HANDLE handle = FindFirstFile((dirName + "\\*").c_str(), &data);
    if (handle != INVALID_HANDLE_VALUE)
    {
        do
        {
            contents.push_back(data.cFileName);
        }
        while (FindNextFile(handle, &data) != 0);

        FindClose(handle);
    }
    return contents;
}
<commit_msg>Fixed compilation problem associated wirh moving FileUtils source out into seperate files.<commit_after>#include <Io.h>
#include <Windows.h>
#include <Winbase.h>

#include <stdio.h>
#include <stdlib.h>

#include <osg/Notify>
#include <osg/Node>
#include <osg/Geode>
#include <osg/Group>

#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osgDB/Registry>

using namespace osg;
using namespace osgDB;

#define FILEUTILS_MAX_PATH_LENGTH 2048

char *PathDelimitor = ";";
static const char *s_default_file_path = ".;";
static const char *s_default_dso_path = "C:/Windows/System/;";
static char *s_filePath = ".;";

#define F_OK 4

static bool s_filePathInitialized = false;

void osgDB::initFilePath( void )
{
    char *ptr;
    if( (ptr = getenv( "OSGFILEPATH" ))  )
    {
        notify(DEBUG_INFO) << "osgDB::Init("<<ptr<<")"<<std::endl;
        setFilePath( ptr );
    }
    else
    {
        notify(DEBUG_INFO) << "osgDB::Init(NULL)"<<std::endl;
    }
    s_filePathInitialized = true;
}

void osgDB::setFilePath( const char *_path )
{
    char buff[FILEUTILS_MAX_PATH_LENGTH];

    notify(DEBUG_INFO) << "In osgDB::setFilePath("<<_path<<")"<<std::endl;

    buff[0] = 0;

    if( s_filePath != s_default_file_path )
    {
        strcpy( buff, s_filePath );
    }

    strcat( buff, PathDelimitor );
    strcat( buff, _path );

    s_filePath = strdup( buff );

    s_filePathInitialized = true;
}

const char* osgDB::getFilePath()
{
    return s_filePath;
}

char *osgDB::findFileInPath( const char *_file, const char * filePath )
{

    char pathbuff[FILEUTILS_MAX_PATH_LENGTH];
    char *tptr, *tmppath;
    char *path = 0L;

    notify(DEBUG_INFO) << "FindFileInPath() : trying " << _file << " ...\n";
    if( access( _file, F_OK ) == 0 )
    {
        return strdup(_file);
    }

    tptr    = strdup( filePath );
    tmppath = strtok(  tptr, PathDelimitor );

    do
    {
        sprintf( pathbuff, "%s/%s", tmppath, _file );
        notify(DEBUG_INFO) << "FindFileInPath() : trying " << pathbuff << " ...\n";
        if( access( pathbuff, F_OK ) == 0 ) break;
    } while( (tmppath = strtok( 0, PathDelimitor )) );

    if( tmppath != (char *)0L )
        path = strdup( pathbuff );

    ::free(tptr);

    if (path) notify( DEBUG_INFO ) << "FindFileInPath() : returning " << path << std::endl;
	else notify( DEBUG_INFO ) << "FindFileInPath() : returning NULL" << std::endl;

    return path;
}

char *osgDB::findFile( const char *file )
{
    if (!file) return NULL;

    if (!s_filePathInitialized) initFilePath();

    char* newFileName = findFileInPath( file, s_filePath );
    if (newFileName) return newFileName;

    // need to check here to see if file has a path on it.

    // now strip the file of an previous path if one exists.
    std::string simpleFileName = getSimpleFileName(file);
    newFileName = findFileInPath( simpleFileName.c_str(), s_filePath );
    return newFileName;
}

/*

Order of precedence for

Under UNIX.

  ./
  OSG_LD_LIBRARY_PATH
  s_default_dso_path
  LD_LIBRARY*_PATH

Under Windows

  ./
  OSG_LD_LIBRARY_PATH
  s_default_dso_path
  PATH

*/

char *osgDB::findDSO( const char *name )
{

    char path[FILEUTILS_MAX_PATH_LENGTH];
    char *ptr;

    strcpy( path, "./" );

    if((ptr = getenv( "OSG_LD_LIBRARY_PATH" )))
    {
        strcat( path, PathDelimitor );
        strcat( path, ptr );
    }

    strcat( path, PathDelimitor );
    strcat( path, s_default_dso_path );

    if ((ptr = getenv( "PATH" )))
    {
        notify(DEBUG_INFO) << "PATH = "<<ptr<<std::endl;
        strcat( path, PathDelimitor );
        strcat( path, ptr );
    }

    // check existance of dso assembled direct paths.
    char* fileFound = NULL;
    fileFound = findFileInPath( name , path );
    if (fileFound) return fileFound;

    // failed with direct paths,
    // now try prepending the filename with "osgPlugins/"
    char* prependosgPlugins = osgNew char[strlen(name)+12];
    strcpy(prependosgPlugins,"osgPlugins/");
    strcat(prependosgPlugins,name);

    fileFound = findFileInPath( prependosgPlugins , path );
    osgDelete [] prependosgPlugins;

    return fileFound;
}

std::string osgDB::findFileInDirectory(const std::string& fileName,const std::string& dirName,bool caseInsensitive)
{
    bool needFollowingBackslash = false;
    bool needDirectoryName = true;
    osgDB::DirectoryContents dc;

    if (dirName.empty())
    {
        dc = osgDB::getDirectoryContents(".");
        needFollowingBackslash = false;
        needDirectoryName = false;
    }
    else if (dirName=="." || dirName=="./" || dirName==".\\")
    {
        dc = osgDB::getDirectoryContents(".");
        needFollowingBackslash = false;
        needDirectoryName = false;
    }
    else
    {
        dc = osgDB::getDirectoryContents(dirName);
        char lastChar = dirName[dirName.size()-1];
        if (lastChar=='/') needFollowingBackslash = false;
        else if (lastChar=='\\') needFollowingBackslash = false;
        else needFollowingBackslash = true;
        needDirectoryName = true;
    }

    for(osgDB::DirectoryContents::iterator itr=dc.begin();
        itr!=dc.end();
        ++itr)
    {
        if ((caseInsensitive && osgDB::equalCaseInsensitive(fileName,*itr)) ||
            (fileName==*itr))
        {
            if (!needDirectoryName) return *itr;
            else if (needFollowingBackslash) return dirName+'/'+*itr;
            else return dirName+*itr;
        }
    }
    return "";
}

#include <io.h>
#include <direct.h>

osgDB::DirectoryContents osgDB::getDirectoryContents(const std::string& dirName)
{
    osgDB::DirectoryContents contents;

    WIN32_FIND_DATA data;
    HANDLE handle = FindFirstFile((dirName + "\\*").c_str(), &data);
    if (handle != INVALID_HANDLE_VALUE)
    {
        do
        {
            contents.push_back(data.cFileName);
        }
        while (FindNextFile(handle, &data) != 0);

        FindClose(handle);
    }
    return contents;
}
<|endoftext|>


<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * 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
 * OpenSceneGraph Public License for more details.
*/

#include <osgShadow/ShadowTexture>
#include <osgShadow/ShadowedScene>
#include <osg/Notify>
#include <osg/io_utils>

using namespace osgShadow;

class CameraCullCallback : public osg::NodeCallback
{
    public:

        CameraCullCallback(ShadowTexture* st):
            _shadowTexture(st)
        {
        }

        virtual void operator()(osg::Node*, osg::NodeVisitor* nv)
        {
            unsigned int traversalMask = nv->getTraversalMask();

            nv->setTraversalMask( traversalMask &
                                  _shadowTexture->getShadowedScene()->getCastsShadowTraversalMask() );

            _shadowTexture->getShadowedScene()->osg::Group::traverse(*nv);

            nv->setTraversalMask( traversalMask );
        }

    protected:

        ShadowTexture* _shadowTexture;
};

ShadowTexture::ShadowTexture():
    _textureUnit(1)
{
    osg::notify(osg::NOTICE)<<"Warning: osgShadow::ShadowTexture technique is in development."<<std::endl;
}

ShadowTexture::ShadowTexture(const ShadowTexture& copy, const osg::CopyOp& copyop):
    ShadowTechnique(copy,copyop),
    _textureUnit(copy._textureUnit)
{
}

void ShadowTexture::init()
{
    if (!_shadowedScene) return;

    unsigned int tex_width = 512;
    unsigned int tex_height = 512;

    _texture = new osg::Texture2D;
    _texture->setTextureSize(tex_width, tex_height);
    _texture->setInternalFormat(GL_RGB);
    _texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
    _texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
    _texture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::CLAMP_TO_BORDER);
    _texture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::CLAMP_TO_BORDER);
    _texture->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));

    // set up the render to texture camera.
    {
        // create the camera
        _camera = new osg::Camera;

        _camera->setClearColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));

        _camera->setCullCallback(new CameraCullCallback(this));

        // set viewport
        _camera->setViewport(0,0,tex_width,tex_height);

        // set the camera to render before the main camera.
        _camera->setRenderOrder(osg::Camera::PRE_RENDER);

        // tell the camera to use OpenGL frame buffer object where supported.
        //_camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
        _camera->setRenderTargetImplementation(osg::Camera::SEPERATE_WINDOW);

        // attach the texture and use it as the color buffer.
        _camera->attach(osg::Camera::COLOR_BUFFER, _texture.get());

        _material = new osg::Material;
        _material->setAmbient(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
        _material->setDiffuse(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
        _material->setEmission(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
        _material->setShininess(osg::Material::FRONT_AND_BACK,0.0f);

        osg::StateSet* stateset = _camera->getOrCreateStateSet();
        stateset->setAttribute(_material.get(),osg::StateAttribute::OVERRIDE);
    }

    {
        _stateset = new osg::StateSet;
        _stateset->setTextureAttributeAndModes(_textureUnit,_texture.get(),osg::StateAttribute::ON);
        _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON);
        _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON);
        _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
        _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON);
    }

    _dirty = false;
}

void ShadowTexture::update(osg::NodeVisitor& nv)
{
    _shadowedScene->osg::Group::traverse(nv);
}

void ShadowTexture::cull(osgUtil::CullVisitor& cv)
{
    // record the traversal mask on entry so we can reapply it later.
    unsigned int traversalMask = cv.getTraversalMask();

    osgUtil::RenderStage* orig_rs = cv.getRenderStage();

    // do traversal of shadow casting scene which does not need to be decorated by the shadow texture
    {
        cv.setTraversalMask( traversalMask &
                             getShadowedScene()->getCastsShadowTraversalMask() );

        _shadowedScene->osg::Group::traverse(cv);
    }

    // do traversal of shadow recieving scene which does need to be decorated by the shadow texture
    {
        cv.pushStateSet(_stateset.get());

        cv.setTraversalMask( traversalMask &
                             getShadowedScene()->getRecievesShadowTraversalMask() );

        _shadowedScene->osg::Group::traverse(cv);

        cv.popStateSet();

    }

    // need to compute view frustum for RTT camera.
    // 1) get the light position
    // 2) get the center and extents of the view frustum

    const osg::Light* selectLight = 0;
    osg::Vec4 lightpos;

    osgUtil::PositionalStateContainer::AttrMatrixList& aml = orig_rs->getPositionalStateContainer()->getAttrMatrixList();
    for(osgUtil::PositionalStateContainer::AttrMatrixList::iterator itr = aml.begin();
        itr != aml.end();
        ++itr)
    {
        const osg::Light* light = dynamic_cast<const osg::Light*>(itr->first.get());
        if (light)
        {
            osg::RefMatrix* matrix = itr->second.get();
            if (matrix) lightpos = light->getPosition() * (*matrix);
            else lightpos = light->getPosition();

            selectLight = light;
        }
    }

    if (selectLight)
    {
        osg::notify(osg::NOTICE)<<"Selected light "<<lightpos<<std::endl;

        // do RTT camera traversal
        _camera->accept(cv);

    }

    // reapply the original traversal mask
    cv.setTraversalMask( traversalMask );
}

void ShadowTexture::cleanSceneGraph()
{
}
<commit_msg>Added basic set up of the RTT camera.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * 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
 * OpenSceneGraph Public License for more details.
*/

#include <osgShadow/ShadowTexture>
#include <osgShadow/ShadowedScene>
#include <osg/Notify>
#include <osg/ComputeBoundsVisitor>
#include <osg/io_utils>

using namespace osgShadow;

class CameraCullCallback : public osg::NodeCallback
{
    public:

        CameraCullCallback(ShadowTexture* st):
            _shadowTexture(st)
        {
        }

        virtual void operator()(osg::Node*, osg::NodeVisitor* nv)
        {
            _shadowTexture->getShadowedScene()->osg::Group::traverse(*nv);
        }

    protected:

        ShadowTexture* _shadowTexture;
};

ShadowTexture::ShadowTexture():
    _textureUnit(1)
{
    osg::notify(osg::NOTICE)<<"Warning: osgShadow::ShadowTexture technique is in development."<<std::endl;
}

ShadowTexture::ShadowTexture(const ShadowTexture& copy, const osg::CopyOp& copyop):
    ShadowTechnique(copy,copyop),
    _textureUnit(copy._textureUnit)
{
}

void ShadowTexture::init()
{
    if (!_shadowedScene) return;

    unsigned int tex_width = 512;
    unsigned int tex_height = 512;

    _texture = new osg::Texture2D;
    _texture->setTextureSize(tex_width, tex_height);
    _texture->setInternalFormat(GL_RGB);
    _texture->setFilter(osg::Texture2D::MIN_FILTER,osg::Texture2D::LINEAR);
    _texture->setFilter(osg::Texture2D::MAG_FILTER,osg::Texture2D::LINEAR);
    _texture->setWrap(osg::Texture2D::WRAP_S,osg::Texture2D::CLAMP_TO_BORDER);
    _texture->setWrap(osg::Texture2D::WRAP_T,osg::Texture2D::CLAMP_TO_BORDER);
    _texture->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));

    // set up the render to texture camera.
    {
        // create the camera
        _camera = new osg::Camera;

        _camera->setClearColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));

        _camera->setCullCallback(new CameraCullCallback(this));

        // set viewport
        _camera->setViewport(0,0,tex_width,tex_height);

        // set the camera to render before the main camera.
        _camera->setRenderOrder(osg::Camera::PRE_RENDER);

        // tell the camera to use OpenGL frame buffer object where supported.
        //_camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT);
        _camera->setRenderTargetImplementation(osg::Camera::SEPERATE_WINDOW);

        // attach the texture and use it as the color buffer.
        _camera->attach(osg::Camera::COLOR_BUFFER, _texture.get());

        _material = new osg::Material;
        _material->setAmbient(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
        _material->setDiffuse(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
        _material->setEmission(osg::Material::FRONT_AND_BACK,osg::Vec4(0.0f,0.0f,0.0f,1.0f));
        _material->setShininess(osg::Material::FRONT_AND_BACK,0.0f);

        osg::StateSet* stateset = _camera->getOrCreateStateSet();
        stateset->setAttribute(_material.get(),osg::StateAttribute::OVERRIDE);

    }

    {
        _stateset = new osg::StateSet;
        _stateset->setTextureAttributeAndModes(_textureUnit,_texture.get(),osg::StateAttribute::ON);
        _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_S,osg::StateAttribute::ON);
        _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_T,osg::StateAttribute::ON);
        _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_R,osg::StateAttribute::ON);
        _stateset->setTextureMode(_textureUnit,GL_TEXTURE_GEN_Q,osg::StateAttribute::ON);

        _texgen = new osg::TexGen;
    }

    _dirty = false;
}

void ShadowTexture::update(osg::NodeVisitor& nv)
{
    _shadowedScene->osg::Group::traverse(nv);
}

void ShadowTexture::cull(osgUtil::CullVisitor& cv)
{
    // record the traversal mask on entry so we can reapply it later.
    unsigned int traversalMask = cv.getTraversalMask();

    osgUtil::RenderStage* orig_rs = cv.getRenderStage();

    // do traversal of shadow casting scene which does not need to be decorated by the shadow texture
    {
        cv.setTraversalMask( traversalMask &
                             getShadowedScene()->getCastsShadowTraversalMask() );

        _shadowedScene->osg::Group::traverse(cv);
    }

    // do traversal of shadow recieving scene which does need to be decorated by the shadow texture
    {
        cv.pushStateSet(_stateset.get());

        cv.setTraversalMask( traversalMask &
                             getShadowedScene()->getRecievesShadowTraversalMask() );

        _shadowedScene->osg::Group::traverse(cv);

        cv.popStateSet();

    }

    // need to compute view frustum for RTT camera.
    // 1) get the light position
    // 2) get the center and extents of the view frustum

    const osg::Light* selectLight = 0;
    osg::Vec4 lightpos;

    osgUtil::PositionalStateContainer::AttrMatrixList& aml = orig_rs->getPositionalStateContainer()->getAttrMatrixList();
    for(osgUtil::PositionalStateContainer::AttrMatrixList::iterator itr = aml.begin();
        itr != aml.end();
        ++itr)
    {
        const osg::Light* light = dynamic_cast<const osg::Light*>(itr->first.get());
        if (light)
        {
            osg::RefMatrix* matrix = itr->second.get();
            if (matrix) lightpos = light->getPosition() * (*matrix);
            else lightpos = light->getPosition();

            selectLight = light;
        }
    }

    osg::Matrix eyeToWorld;
    eyeToWorld.invert(cv.getModelViewMatrix());

    lightpos = lightpos * eyeToWorld;

    if (selectLight)
    {

        // get the bounds of the model.
        osg::ComputeBoundsVisitor cbbv(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN);
        cbbv.setTraversalMask(getShadowedScene()->getCastsShadowTraversalMask());

        _shadowedScene->osg::Group::traverse(cbbv);

        osg::BoundingBox bb = cbbv.getBoundingBox();

        if (lightpos[3]!=0.0)
        {
            osg::Vec3 position(lightpos.x(), lightpos.y(), lightpos.z());

            float centerDistance = (position-bb.center()).length();

            float znear = centerDistance-bb.radius();
            float zfar  = centerDistance+bb.radius();
            float zNearRatio = 0.001f;
            if (znear<zfar*zNearRatio) znear = zfar*zNearRatio;

            float top   = (bb.radius()/centerDistance)*znear;
            float right = top;

            _camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF);
            _camera->setProjectionMatrixAsFrustum(-right,right,-top,top,znear,zfar);
            _camera->setViewMatrixAsLookAt(position,bb.center(),osg::Vec3(0.0f,1.0f,0.0f));

            // compute the matrix which takes a vertex from local coords into tex coords
            // will use this later to specify osg::TexGen..
            osg::Matrix MVPT = _camera->getViewMatrix() *
                               _camera->getProjectionMatrix() *
                               osg::Matrix::translate(1.0,1.0,1.0) *
                               osg::Matrix::scale(0.5f,0.5f,0.5f);

            _texgen->setMode(osg::TexGen::EYE_LINEAR);
            _texgen->setPlanesFromMatrix(MVPT);
        }

        cv.setTraversalMask( traversalMask &
                             getShadowedScene()->getCastsShadowTraversalMask() );

        // do RTT camera traversal
        _camera->accept(cv);

    }

    // reapply the original traversal mask
    cv.setTraversalMask( traversalMask );
}

void ShadowTexture::cleanSceneGraph()
{
}
<|endoftext|>


<commit_before>/** @file
    @brief Implementation

    @date 2014

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)

// Internal Includes
#include "VRPNContext.h"
#include "RouterPredicates.h"
#include "RouterTransforms.h"
#include "ImagingRouter.h"
#include "VRPNAnalogRouter.h"
#include "VRPNButtonRouter.h"
#include "VRPNTrackerRouter.h"
#include <osvr/Util/ClientCallbackTypesC.h>
#include <osvr/Client/ClientContext.h>
#include <osvr/Client/ClientInterface.h>
#include <osvr/Util/Verbosity.h>
#include <osvr/Transform/JSONTransformVisitor.h>
#include <osvr/Transform/ChangeOfBasis.h>
#include <osvr/Common/CreateDevice.h>
#include <osvr/Common/SystemComponent.h>
#include <osvr/Common/RoutingKeys.h>

#include <osvr/Client/display_json.h>

// Library/third-party includes
#include <json/value.h>
#include <json/reader.h>

#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>

// Standard includes
#include <cstring>

namespace osvr {
namespace client {
    RouterEntry::~RouterEntry() {}

    VRPNContext::VRPNContext(const char appId[], const char host[])
        : ::OSVR_ClientContextObject(appId), m_host(host) {

        std::string sysDeviceName =
            std::string(common::SystemComponent::deviceName()) + "@" + m_host;
        /// Get connection, forcing a re-open for improved thread-safety.
        m_conn =
            vrpn_get_connection_by_name(sysDeviceName.c_str(), nullptr, nullptr,
                                        nullptr, nullptr, nullptr, true);
        m_conn->removeReference(); // Remove extra reference.

        /// Create the system client device.
        m_systemDevice = common::createClientDevice(sysDeviceName, m_conn);
        m_systemComponent =
            m_systemDevice->addComponent(common::SystemComponent::create());
        m_systemComponent->registerRoutesHandler(
            &VRPNContext::m_handleRoutingMessage, static_cast<void *>(this));

        setParameter("/display",
                     std::string(display_json, sizeof(display_json)));
    }

    VRPNContext::~VRPNContext() {}

    int VRPNContext::m_handleRoutingMessage(void *userdata,
                                            vrpn_HANDLERPARAM p) {
        VRPNContext *self = static_cast<VRPNContext *>(userdata);
        common::RouteContainer newDirectives(
            std::string(p.buffer, p.payload_len));
        self->m_replaceRoutes(newDirectives);
        return 0;
    }

    void
    VRPNContext::m_replaceRoutes(common::RouteContainer const &newDirectives) {
        OSVR_DEV_VERBOSE("Replacing routing directives: had "
                         << m_routingDirectives.size() << ", received "
                         << newDirectives.size());

        m_routers.clear();
        m_routingDirectives = newDirectives;
        Json::Reader reader;
        for (auto const &routeString : newDirectives.getRouteList()) {
            Json::Value route;
            if (!reader.parse(routeString, route)) {
                OSVR_DEV_VERBOSE("Got a bad route!");
                continue;
            }

            std::string dest =
                route[common::routing_keys::destination()].asString();

            Json::Value src = route[common::routing_keys::source()];
            if (src.isString()) {
                m_handleStringRouteEntry(dest, src.asString());
            } else {
                m_handleTrackerRouteEntry(dest, src);
            }
        }

#define OSVR_HYDRA_BUTTON(SENSOR, NAME)                                        \
    m_addButtonRouter("org_opengoggles_bundled_Multiserver/RazerHydra0",       \
                      "/controller/left/" NAME, SensorPredicate(SENSOR));      \
    m_addButtonRouter("org_opengoggles_bundled_Multiserver/RazerHydra0",       \
                      "/controller/right/" NAME, SensorPredicate(SENSOR + 8))

        OSVR_HYDRA_BUTTON(0, "middle");
        OSVR_HYDRA_BUTTON(1, "1");
        OSVR_HYDRA_BUTTON(2, "2");
        OSVR_HYDRA_BUTTON(3, "3");
        OSVR_HYDRA_BUTTON(4, "4");
        OSVR_HYDRA_BUTTON(5, "bumper");
        OSVR_HYDRA_BUTTON(6, "joystick/button");

#undef OSVR_HYDRA_BUTTON

#define OSVR_HYDRA_ANALOG(SENSOR, NAME)                                        \
    m_addAnalogRouter("org_opengoggles_bundled_Multiserver/RazerHydra0",       \
                      "/controller/left/" NAME, SENSOR);                       \
    m_addAnalogRouter("org_opengoggles_bundled_Multiserver/RazerHydra0",       \
                      "/controller/right/" NAME, SENSOR + 3)

        OSVR_HYDRA_ANALOG(0, "joystick/x");
        OSVR_HYDRA_ANALOG(1, "joystick/y");
        OSVR_HYDRA_ANALOG(2, "trigger");

#undef OSVR_HYDRA_ANALOG

        OSVR_DEV_VERBOSE("Now have " << m_routers.size() << " routes.");
    }

    static const char SENSOR_KEY[] = "sensor";
    static const char TRACKER_KEY[] = "tracker";
    void VRPNContext::m_handleTrackerRouteEntry(std::string const &dest,
                                                Json::Value src) {

        boost::optional<int> sensor;
        transform::JSONTransformVisitor xformParse(src);
        Json::Value srcLeaf = xformParse.getLeaf();
        std::string srcDevice = srcLeaf[TRACKER_KEY].asString();
        // OSVR_DEV_VERBOSE("Source device: " << srcDevice);
        srcDevice.erase(begin(srcDevice)); // remove leading slash
        if (srcLeaf.isMember(SENSOR_KEY)) {
            sensor = srcLeaf[SENSOR_KEY].asInt();
        }

        m_addTrackerRouter(srcDevice.c_str(), dest.c_str(), sensor,
                           xformParse.getTransform());
    }

    static const char IMAGING_NAME[] = "imaging";
    void VRPNContext::m_handleStringRouteEntry(std::string const &dest,
                                               std::string src) {
        std::vector<std::string> components;

        /// @todo replace literal with getPathSeparator
        boost::algorithm::split(components, src,
                                boost::algorithm::is_any_of("/"));
        if (!components.empty()) {
            if (components.front().empty()) {
                components.erase(begin(components));
            }
        }
        if (components.size() < 4) {
            OSVR_DEV_VERBOSE("Could not parse source for route, skipping: "
                             << src << " => " << dest);
            return;
        }

        std::string deviceName =
            components[0] + "/" + components[1] + "@" + m_host;
        std::reverse(begin(components), end(components));
        components.pop_back();
        components.pop_back();

        std::string interfaceType = components.back();
        components.pop_back();
        if (interfaceType == IMAGING_NAME) {
            OSVR_DEV_VERBOSE("Adding imaging route for " << dest);
            m_routers.emplace_back(
                new ImagingRouter(this, m_conn, deviceName, components, dest));
        } else {
            OSVR_DEV_VERBOSE(
                "Could not handle route message for interface type "
                << interfaceType << ", skipping: " << src << " => " << dest);
        }
    }

    void VRPNContext::m_sendRoute(std::string const &route) {
        m_systemComponent->sendClientRouteUpdate(route);
    }

    void VRPNContext::m_update() {
        // mainloop the VRPN connection.
        m_conn->mainloop();
        // Mainloop the system device
        m_systemDevice->update();

        // Process each of the routers.
        for (auto const &p : m_routers) {
            (*p)();
        }
    }

    void VRPNContext::m_addAnalogRouter(const char *src, const char *dest,
                                        int channel) {
        OSVR_DEV_VERBOSE("Adding analog route for " << dest);

        m_routers.emplace_back(
            new VRPNAnalogRouter<SensorPredicate, NullTransform>(
                this, m_conn.get(), (src + ("@" + m_host)).c_str(), dest,
                SensorPredicate(channel), NullTransform(), channel));
    }

    template <typename Predicate>
    void VRPNContext::m_addButtonRouter(const char *src, const char *dest,
                                        Predicate pred) {
        OSVR_DEV_VERBOSE("Adding button route for " << dest);
        m_routers.emplace_back(new VRPNButtonRouter<Predicate>(
            this, m_conn.get(), (src + ("@" + m_host)).c_str(), dest, pred));
    }

    void VRPNContext::m_addTrackerRouter(const char *src, const char *dest,
                                         boost::optional<int> sensor,
                                         transform::Transform const &xform) {
        OSVR_DEV_VERBOSE("Adding tracker route for " << dest);
        std::string source(src);
        if (std::string::npos != source.find('@')) {
            // We found an @ - so this is a device we need a new connection for.
            m_routers.emplace_back(
                new VRPNTrackerRouter(this, nullptr, src, sensor, dest, xform));
        } else {
            // No @: assume to be at the same location as the context.
            m_routers.emplace_back(new VRPNTrackerRouter(
                this, m_conn.get(), (src + ("@" + m_host)).c_str(), sensor,
                dest, xform));
        }
    }

} // namespace client
} // namespace osvr<commit_msg>Update after sending route.<commit_after>/** @file
    @brief Implementation

    @date 2014

    @author
    Sensics, Inc.
    <http://sensics.com/osvr>
*/

// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)

// Internal Includes
#include "VRPNContext.h"
#include "RouterPredicates.h"
#include "RouterTransforms.h"
#include "ImagingRouter.h"
#include "VRPNAnalogRouter.h"
#include "VRPNButtonRouter.h"
#include "VRPNTrackerRouter.h"
#include <osvr/Util/ClientCallbackTypesC.h>
#include <osvr/Client/ClientContext.h>
#include <osvr/Client/ClientInterface.h>
#include <osvr/Util/Verbosity.h>
#include <osvr/Transform/JSONTransformVisitor.h>
#include <osvr/Transform/ChangeOfBasis.h>
#include <osvr/Common/CreateDevice.h>
#include <osvr/Common/SystemComponent.h>
#include <osvr/Common/RoutingKeys.h>

#include <osvr/Client/display_json.h>

// Library/third-party includes
#include <json/value.h>
#include <json/reader.h>

#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/classification.hpp>

// Standard includes
#include <cstring>

namespace osvr {
namespace client {
    RouterEntry::~RouterEntry() {}

    VRPNContext::VRPNContext(const char appId[], const char host[])
        : ::OSVR_ClientContextObject(appId), m_host(host) {

        std::string sysDeviceName =
            std::string(common::SystemComponent::deviceName()) + "@" + m_host;
        /// Get connection, forcing a re-open for improved thread-safety.
        m_conn =
            vrpn_get_connection_by_name(sysDeviceName.c_str(), nullptr, nullptr,
                                        nullptr, nullptr, nullptr, true);
        m_conn->removeReference(); // Remove extra reference.

        /// Create the system client device.
        m_systemDevice = common::createClientDevice(sysDeviceName, m_conn);
        m_systemComponent =
            m_systemDevice->addComponent(common::SystemComponent::create());
        m_systemComponent->registerRoutesHandler(
            &VRPNContext::m_handleRoutingMessage, static_cast<void *>(this));

        setParameter("/display",
                     std::string(display_json, sizeof(display_json)));
    }

    VRPNContext::~VRPNContext() {}

    int VRPNContext::m_handleRoutingMessage(void *userdata,
                                            vrpn_HANDLERPARAM p) {
        VRPNContext *self = static_cast<VRPNContext *>(userdata);
        common::RouteContainer newDirectives(
            std::string(p.buffer, p.payload_len));
        self->m_replaceRoutes(newDirectives);
        return 0;
    }

    void
    VRPNContext::m_replaceRoutes(common::RouteContainer const &newDirectives) {
        OSVR_DEV_VERBOSE("Replacing routing directives: had "
                         << m_routingDirectives.size() << ", received "
                         << newDirectives.size());

        m_routers.clear();
        m_routingDirectives = newDirectives;
        Json::Reader reader;
        for (auto const &routeString : newDirectives.getRouteList()) {
            Json::Value route;
            if (!reader.parse(routeString, route)) {
                OSVR_DEV_VERBOSE("Got a bad route!");
                continue;
            }

            std::string dest =
                route[common::routing_keys::destination()].asString();

            Json::Value src = route[common::routing_keys::source()];
            if (src.isString()) {
                m_handleStringRouteEntry(dest, src.asString());
            } else {
                m_handleTrackerRouteEntry(dest, src);
            }
        }

#define OSVR_HYDRA_BUTTON(SENSOR, NAME)                                        \
    m_addButtonRouter("org_opengoggles_bundled_Multiserver/RazerHydra0",       \
                      "/controller/left/" NAME, SensorPredicate(SENSOR));      \
    m_addButtonRouter("org_opengoggles_bundled_Multiserver/RazerHydra0",       \
                      "/controller/right/" NAME, SensorPredicate(SENSOR + 8))

        OSVR_HYDRA_BUTTON(0, "middle");
        OSVR_HYDRA_BUTTON(1, "1");
        OSVR_HYDRA_BUTTON(2, "2");
        OSVR_HYDRA_BUTTON(3, "3");
        OSVR_HYDRA_BUTTON(4, "4");
        OSVR_HYDRA_BUTTON(5, "bumper");
        OSVR_HYDRA_BUTTON(6, "joystick/button");

#undef OSVR_HYDRA_BUTTON

#define OSVR_HYDRA_ANALOG(SENSOR, NAME)                                        \
    m_addAnalogRouter("org_opengoggles_bundled_Multiserver/RazerHydra0",       \
                      "/controller/left/" NAME, SENSOR);                       \
    m_addAnalogRouter("org_opengoggles_bundled_Multiserver/RazerHydra0",       \
                      "/controller/right/" NAME, SENSOR + 3)

        OSVR_HYDRA_ANALOG(0, "joystick/x");
        OSVR_HYDRA_ANALOG(1, "joystick/y");
        OSVR_HYDRA_ANALOG(2, "trigger");

#undef OSVR_HYDRA_ANALOG

        OSVR_DEV_VERBOSE("Now have " << m_routers.size() << " routes.");
    }

    static const char SENSOR_KEY[] = "sensor";
    static const char TRACKER_KEY[] = "tracker";
    void VRPNContext::m_handleTrackerRouteEntry(std::string const &dest,
                                                Json::Value src) {

        boost::optional<int> sensor;
        transform::JSONTransformVisitor xformParse(src);
        Json::Value srcLeaf = xformParse.getLeaf();
        std::string srcDevice = srcLeaf[TRACKER_KEY].asString();
        // OSVR_DEV_VERBOSE("Source device: " << srcDevice);
        srcDevice.erase(begin(srcDevice)); // remove leading slash
        if (srcLeaf.isMember(SENSOR_KEY)) {
            sensor = srcLeaf[SENSOR_KEY].asInt();
        }

        m_addTrackerRouter(srcDevice.c_str(), dest.c_str(), sensor,
                           xformParse.getTransform());
    }

    static const char IMAGING_NAME[] = "imaging";
    void VRPNContext::m_handleStringRouteEntry(std::string const &dest,
                                               std::string src) {
        std::vector<std::string> components;

        /// @todo replace literal with getPathSeparator
        boost::algorithm::split(components, src,
                                boost::algorithm::is_any_of("/"));
        if (!components.empty()) {
            if (components.front().empty()) {
                components.erase(begin(components));
            }
        }
        if (components.size() < 4) {
            OSVR_DEV_VERBOSE("Could not parse source for route, skipping: "
                             << src << " => " << dest);
            return;
        }

        std::string deviceName =
            components[0] + "/" + components[1] + "@" + m_host;
        std::reverse(begin(components), end(components));
        components.pop_back();
        components.pop_back();

        std::string interfaceType = components.back();
        components.pop_back();
        if (interfaceType == IMAGING_NAME) {
            OSVR_DEV_VERBOSE("Adding imaging route for " << dest);
            m_routers.emplace_back(
                new ImagingRouter(this, m_conn, deviceName, components, dest));
        } else {
            OSVR_DEV_VERBOSE(
                "Could not handle route message for interface type "
                << interfaceType << ", skipping: " << src << " => " << dest);
        }
    }

    void VRPNContext::m_sendRoute(std::string const &route) {
        m_systemComponent->sendClientRouteUpdate(route);
        m_update();
    }

    void VRPNContext::m_update() {
        // mainloop the VRPN connection.
        m_conn->mainloop();
        // Mainloop the system device
        m_systemDevice->update();

        // Process each of the routers.
        for (auto const &p : m_routers) {
            (*p)();
        }
    }

    void VRPNContext::m_addAnalogRouter(const char *src, const char *dest,
                                        int channel) {
        OSVR_DEV_VERBOSE("Adding analog route for " << dest);

        m_routers.emplace_back(
            new VRPNAnalogRouter<SensorPredicate, NullTransform>(
                this, m_conn.get(), (src + ("@" + m_host)).c_str(), dest,
                SensorPredicate(channel), NullTransform(), channel));
    }

    template <typename Predicate>
    void VRPNContext::m_addButtonRouter(const char *src, const char *dest,
                                        Predicate pred) {
        OSVR_DEV_VERBOSE("Adding button route for " << dest);
        m_routers.emplace_back(new VRPNButtonRouter<Predicate>(
            this, m_conn.get(), (src + ("@" + m_host)).c_str(), dest, pred));
    }

    void VRPNContext::m_addTrackerRouter(const char *src, const char *dest,
                                         boost::optional<int> sensor,
                                         transform::Transform const &xform) {
        OSVR_DEV_VERBOSE("Adding tracker route for " << dest);
        std::string source(src);
        if (std::string::npos != source.find('@')) {
            // We found an @ - so this is a device we need a new connection for.
            m_routers.emplace_back(
                new VRPNTrackerRouter(this, nullptr, src, sensor, dest, xform));
        } else {
            // No @: assume to be at the same location as the context.
            m_routers.emplace_back(new VRPNTrackerRouter(
                this, m_conn.get(), (src + ("@" + m_host)).c_str(), sensor,
                dest, xform));
        }
    }

} // namespace client
} // namespace osvr<|endoftext|>


<commit_before>/*
* @Author: Ubi de Feo | Future Tailors
* @Date:   2017-07-09 16:34:07
* @Last Modified by:   ubi
* @Last Modified time: 2017-07-09 16:41:17
*/

#include "FTDebouncer.h"

/*	CONSTRUCTORS/DESTRUCTOR						*/
FTDebouncer::FTDebouncer() : _debounceDelay(40) {
}

FTDebouncer::FTDebouncer(uint16_t debounceDelay) : _debounceDelay(debounceDelay) {
}

FTDebouncer::~FTDebouncer() {
}

/*	METHODS										*/

void FTDebouncer::addPin(uint8_t pinNr, uint8_t restState, PinMode pullUpMode) {
	DebounceItem *debounceItem = new DebounceItem();

	debounceItem->pinNumber = pinNr;
	debounceItem->restState = restState;

	if (_firstDebounceItem == nullptr) {
		_firstDebounceItem = debounceItem;
	} else {
		_lastDebounceItem->nextItem = debounceItem;
	}

	_lastDebounceItem = debounceItem;

	pinMode(pinNr, static_cast<uint8_t>(pullUpMode));

	++_debouncedItemsCount;
}

void FTDebouncer::init() {
	unsigned long currentMilliseconds = millis();
	DebounceItem *debounceItem = _firstDebounceItem;

	while (debounceItem != nullptr) {
		debounceItem->lastTimeChecked = currentMilliseconds;
		debounceItem->currentState = debounceItem->previousState = debounceItem->restState;
		debounceItem->currentDebouncedState = debounceItem->previousDebouncedState = debounceItem->restState;
		debounceItem = debounceItem->nextItem;
	}
}

void FTDebouncer::run() {
	DebounceItem *debounceItem = _firstDebounceItem;
	while (debounceItem != nullptr) {
		debounceItem->currentState = digitalRead(debounceItem->pinNumber);
		debounceItem = debounceItem->nextItem;
	}

	this->debouncePins();
	this->checkStateChange();
}

void FTDebouncer::debouncePins() {
	unsigned long currentMilliseconds = millis();
	DebounceItem *debounceItem = _firstDebounceItem;
	while (debounceItem != nullptr) {
		if (debounceItem->currentState != debounceItem->previousState) {
			debounceItem->lastTimeChecked = currentMilliseconds;
		}
		if (currentMilliseconds - debounceItem->lastTimeChecked > _debounceDelay) {
			if (debounceItem->previousState == debounceItem->currentState) {
				debounceItem->lastTimeChecked = currentMilliseconds;
				debounceItem->currentDebouncedState = debounceItem->currentState;
			}
		}
		debounceItem->previousState = debounceItem->currentState;
		debounceItem = debounceItem->nextItem;
	}
}

void FTDebouncer::checkStateChange() {
	DebounceItem *debounceItem = _firstDebounceItem;

	while (debounceItem != nullptr) {
		if (debounceItem->previousDebouncedState != debounceItem->currentDebouncedState) {
			if (debounceItem->currentDebouncedState == !debounceItem->restState) {
				pinActivated(debounceItem->pinNumber);
			}
			if (debounceItem->currentDebouncedState == debounceItem->restState) {
				pinDeactivated(debounceItem->pinNumber);
			}
		}
		debounceItem->previousDebouncedState = debounceItem->currentDebouncedState;
		debounceItem = debounceItem->nextItem;
	}
}

uint8_t FTDebouncer::getPinCount(){
	return _debouncedItemsCount;
}
<commit_msg>Use for instead of while loop to simplify code<commit_after>/*
* @Author: Ubi de Feo | Future Tailors
* @Date:   2017-07-09 16:34:07
* @Last Modified by:   ubi
* @Last Modified time: 2017-07-09 16:41:17
*/

#include "FTDebouncer.h"

/*	CONSTRUCTORS/DESTRUCTOR						*/
FTDebouncer::FTDebouncer() : _debounceDelay(40) {
}

FTDebouncer::FTDebouncer(uint16_t debounceDelay) : _debounceDelay(debounceDelay) {
}

FTDebouncer::~FTDebouncer() {
}

/*	METHODS										*/

void FTDebouncer::addPin(uint8_t pinNr, uint8_t restState, PinMode pullUpMode) {
	DebounceItem *debounceItem = new DebounceItem();

	debounceItem->pinNumber = pinNr;
	debounceItem->restState = restState;

	if (_firstDebounceItem == nullptr) {
		_firstDebounceItem = debounceItem;
	} else {
		_lastDebounceItem->nextItem = debounceItem;
	}

	_lastDebounceItem = debounceItem;

	pinMode(pinNr, static_cast<uint8_t>(pullUpMode));

	++_debouncedItemsCount;
}

void FTDebouncer::init() {
	unsigned long currentMilliseconds = millis();

	for(DebounceItem * debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
		debounceItem->lastTimeChecked = currentMilliseconds;
		debounceItem->currentState = debounceItem->previousState = debounceItem->restState;
		debounceItem->currentDebouncedState = debounceItem->previousDebouncedState = debounceItem->restState;
	}
}

void FTDebouncer::run() {
	for(DebounceItem * debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
		debounceItem->currentState = digitalRead(debounceItem->pinNumber);
	}

	this->debouncePins();
	this->checkStateChange();
}

void FTDebouncer::debouncePins() {
	unsigned long currentMilliseconds = millis();

	for(DebounceItem * debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
		if (debounceItem->currentState != debounceItem->previousState) {
			debounceItem->lastTimeChecked = currentMilliseconds;
		}
		if (currentMilliseconds - debounceItem->lastTimeChecked > _debounceDelay) {
			if (debounceItem->previousState == debounceItem->currentState) {
				debounceItem->lastTimeChecked = currentMilliseconds;
				debounceItem->currentDebouncedState = debounceItem->currentState;
			}
		}
		debounceItem->previousState = debounceItem->currentState;
	}
}

void FTDebouncer::checkStateChange() {

	for(DebounceItem * debounceItem = _firstDebounceItem; debounceItem != nullptr; debounceItem = debounceItem->nextItem){
		if (debounceItem->previousDebouncedState != debounceItem->currentDebouncedState) {
			if (debounceItem->currentDebouncedState == !debounceItem->restState) {
				pinActivated(debounceItem->pinNumber);
			}
			if (debounceItem->currentDebouncedState == debounceItem->restState) {
				pinDeactivated(debounceItem->pinNumber);
			}
		}
		debounceItem->previousDebouncedState = debounceItem->currentDebouncedState;
	}
}

uint8_t FTDebouncer::getPinCount(){
	return _debouncedItemsCount;
}
<|endoftext|>


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

#include "webkit/tools/test_shell/test_shell_request_context.h"

#include "build/build_config.h"

#include "base/compiler_specific.h"
#include "base/file_path.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/worker_pool.h"
#include "net/base/cert_verifier.h"
#include "net/base/default_server_bound_cert_store.h"
#include "net/base/host_resolver.h"
#include "net/base/server_bound_cert_service.h"
#include "net/base/ssl_config_service_defaults.h"
#include "net/cookies/cookie_monster.h"
#include "net/ftp/ftp_network_layer.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_network_session.h"
#include "net/http/http_server_properties_impl.h"
#include "net/proxy/proxy_config_service.h"
#include "net/proxy/proxy_config_service_fixed.h"
#include "net/proxy/proxy_service.h"
#include "net/url_request/http_user_agent_settings.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "third_party/WebKit/Source/Platform/chromium/public/Platform.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h"
#include "webkit/blob/blob_storage_controller.h"
#include "webkit/blob/blob_url_request_job_factory.h"
#include "webkit/fileapi/file_system_context.h"
#include "webkit/fileapi/file_system_url_request_job_factory.h"
#include "webkit/tools/test_shell/simple_file_system.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/user_agent/user_agent.h"

class TestShellHttpUserAgentSettings : public net::HttpUserAgentSettings {
 public:
  TestShellHttpUserAgentSettings() {}
  virtual ~TestShellHttpUserAgentSettings() {}

  // hard-code A-L and A-C for test shells
  virtual std::string GetAcceptLanguage() const OVERRIDE {
    return "en-us,en";
  }
  virtual std::string GetAcceptCharset() const OVERRIDE {
    return "iso-8859-1,*,utf-8";
  }

  virtual std::string GetUserAgent(const GURL& url) const OVERRIDE {
    return webkit_glue::GetUserAgent(url);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(TestShellHttpUserAgentSettings);
};

TestShellRequestContext::TestShellRequestContext()
    : ALLOW_THIS_IN_INITIALIZER_LIST(storage_(this)) {
  Init(base::FilePath(), net::HttpCache::NORMAL, false);
}

TestShellRequestContext::TestShellRequestContext(
    const base::FilePath& cache_path,
    net::HttpCache::Mode cache_mode,
    bool no_proxy)
    : ALLOW_THIS_IN_INITIALIZER_LIST(storage_(this)) {
  Init(cache_path, cache_mode, no_proxy);
}

void TestShellRequestContext::Init(
    const base::FilePath& cache_path,
    net::HttpCache::Mode cache_mode,
    bool no_proxy) {
  storage_.set_cookie_store(new net::CookieMonster(NULL, NULL));
  storage_.set_server_bound_cert_service(new net::ServerBoundCertService(
      new net::DefaultServerBoundCertStore(NULL),
      base::WorkerPool::GetTaskRunner(true)));

  storage_.set_http_user_agent_settings(new TestShellHttpUserAgentSettings);

#if defined(OS_POSIX) && !defined(OS_MACOSX)
  // Use no proxy to avoid ProxyConfigServiceLinux.
  // Enabling use of the ProxyConfigServiceLinux requires:
  // -Calling from a thread with a TYPE_UI MessageLoop,
  // -If at all possible, passing in a pointer to the IO thread's MessageLoop,
  // -Keep in mind that proxy auto configuration is also
  //  non-functional on linux in this context because of v8 threading
  //  issues.
  // TODO(port): rename "linux" to some nonspecific unix.
  scoped_ptr<net::ProxyConfigService> proxy_config_service(
      new net::ProxyConfigServiceFixed(net::ProxyConfig()));
#else
  // Use the system proxy settings.
  scoped_ptr<net::ProxyConfigService> proxy_config_service(
      net::ProxyService::CreateSystemProxyConfigService(
          base::ThreadTaskRunnerHandle::Get(), NULL));
#endif
  storage_.set_host_resolver(net::HostResolver::CreateDefaultResolver(NULL));
  storage_.set_cert_verifier(net::CertVerifier::CreateDefault());
  storage_.set_proxy_service(net::ProxyService::CreateUsingSystemProxyResolver(
      proxy_config_service.release(), 0, NULL));
  storage_.set_ssl_config_service(
      new net::SSLConfigServiceDefaults);

  storage_.set_http_auth_handler_factory(
      net::HttpAuthHandlerFactory::CreateDefault(host_resolver()));
  storage_.set_http_server_properties(
      new net::HttpServerPropertiesImpl);

  net::HttpCache::DefaultBackend* backend = new net::HttpCache::DefaultBackend(
      cache_path.empty() ? net::MEMORY_CACHE : net::DISK_CACHE,
      cache_path, 0, SimpleResourceLoaderBridge::GetCacheThread());

  net::HttpNetworkSession::Params network_session_params;
  network_session_params.host_resolver = host_resolver();
  network_session_params.cert_verifier = cert_verifier();
  network_session_params.server_bound_cert_service =
      server_bound_cert_service();
  network_session_params.proxy_service = proxy_service();
  network_session_params.ssl_config_service = ssl_config_service();
  network_session_params.http_auth_handler_factory =
      http_auth_handler_factory();
  network_session_params.http_server_properties = http_server_properties();
  network_session_params.host_resolver = host_resolver();

  net::HttpCache* cache = new net::HttpCache(
      network_session_params, backend);
  cache->set_mode(cache_mode);
  storage_.set_http_transaction_factory(cache);

  storage_.set_ftp_transaction_factory(
      new net::FtpNetworkLayer(host_resolver()));

  blob_storage_controller_.reset(new webkit_blob::BlobStorageController());
  file_system_context_ = static_cast<SimpleFileSystem*>(
      WebKit::Platform::current()->fileSystem())->file_system_context();

  net::URLRequestJobFactoryImpl* job_factory =
      new net::URLRequestJobFactoryImpl();
  job_factory->SetProtocolHandler(
      "blob",
      new webkit_blob::BlobProtocolHandler(
          blob_storage_controller_.get(),
          file_system_context_,
          SimpleResourceLoaderBridge::GetIoThread()));
  job_factory->SetProtocolHandler(
      "filesystem",
      fileapi::CreateFileSystemProtocolHandler(file_system_context_.get()));
  storage_.set_job_factory(job_factory);
}

TestShellRequestContext::~TestShellRequestContext() {
}
<commit_msg>Turn off the network proxy for mac and win in DRT<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/tools/test_shell/test_shell_request_context.h"

#include "build/build_config.h"

#include "base/compiler_specific.h"
#include "base/file_path.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/worker_pool.h"
#include "net/base/cert_verifier.h"
#include "net/base/default_server_bound_cert_store.h"
#include "net/base/host_resolver.h"
#include "net/base/server_bound_cert_service.h"
#include "net/base/ssl_config_service_defaults.h"
#include "net/cookies/cookie_monster.h"
#include "net/ftp/ftp_network_layer.h"
#include "net/http/http_auth_handler_factory.h"
#include "net/http/http_network_session.h"
#include "net/http/http_server_properties_impl.h"
#include "net/proxy/proxy_config_service.h"
#include "net/proxy/proxy_config_service_fixed.h"
#include "net/proxy/proxy_service.h"
#include "net/url_request/http_user_agent_settings.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "third_party/WebKit/Source/Platform/chromium/public/Platform.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebKit.h"
#include "webkit/blob/blob_storage_controller.h"
#include "webkit/blob/blob_url_request_job_factory.h"
#include "webkit/fileapi/file_system_context.h"
#include "webkit/fileapi/file_system_url_request_job_factory.h"
#include "webkit/tools/test_shell/simple_file_system.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/user_agent/user_agent.h"

class TestShellHttpUserAgentSettings : public net::HttpUserAgentSettings {
 public:
  TestShellHttpUserAgentSettings() {}
  virtual ~TestShellHttpUserAgentSettings() {}

  // hard-code A-L and A-C for test shells
  virtual std::string GetAcceptLanguage() const OVERRIDE {
    return "en-us,en";
  }
  virtual std::string GetAcceptCharset() const OVERRIDE {
    return "iso-8859-1,*,utf-8";
  }

  virtual std::string GetUserAgent(const GURL& url) const OVERRIDE {
    return webkit_glue::GetUserAgent(url);
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(TestShellHttpUserAgentSettings);
};

TestShellRequestContext::TestShellRequestContext()
    : ALLOW_THIS_IN_INITIALIZER_LIST(storage_(this)) {
  Init(base::FilePath(), net::HttpCache::NORMAL, false);
}

TestShellRequestContext::TestShellRequestContext(
    const base::FilePath& cache_path,
    net::HttpCache::Mode cache_mode,
    bool no_proxy)
    : ALLOW_THIS_IN_INITIALIZER_LIST(storage_(this)) {
  Init(cache_path, cache_mode, no_proxy);
}

void TestShellRequestContext::Init(
    const base::FilePath& cache_path,
    net::HttpCache::Mode cache_mode,
    bool no_proxy) {
  storage_.set_cookie_store(new net::CookieMonster(NULL, NULL));
  storage_.set_server_bound_cert_service(new net::ServerBoundCertService(
      new net::DefaultServerBoundCertStore(NULL),
      base::WorkerPool::GetTaskRunner(true)));

  storage_.set_http_user_agent_settings(new TestShellHttpUserAgentSettings);

  // Use no proxy; it's not needed for testing and just breaks things.
  scoped_ptr<net::ProxyConfigService> proxy_config_service(
      new net::ProxyConfigServiceFixed(net::ProxyConfig()));

  storage_.set_host_resolver(net::HostResolver::CreateDefaultResolver(NULL));
  storage_.set_cert_verifier(net::CertVerifier::CreateDefault());
  storage_.set_proxy_service(net::ProxyService::CreateUsingSystemProxyResolver(
      proxy_config_service.release(), 0, NULL));
  storage_.set_ssl_config_service(
      new net::SSLConfigServiceDefaults);

  storage_.set_http_auth_handler_factory(
      net::HttpAuthHandlerFactory::CreateDefault(host_resolver()));
  storage_.set_http_server_properties(
      new net::HttpServerPropertiesImpl);

  net::HttpCache::DefaultBackend* backend = new net::HttpCache::DefaultBackend(
      cache_path.empty() ? net::MEMORY_CACHE : net::DISK_CACHE,
      cache_path, 0, SimpleResourceLoaderBridge::GetCacheThread());

  net::HttpNetworkSession::Params network_session_params;
  network_session_params.host_resolver = host_resolver();
  network_session_params.cert_verifier = cert_verifier();
  network_session_params.server_bound_cert_service =
      server_bound_cert_service();
  network_session_params.proxy_service = proxy_service();
  network_session_params.ssl_config_service = ssl_config_service();
  network_session_params.http_auth_handler_factory =
      http_auth_handler_factory();
  network_session_params.http_server_properties = http_server_properties();
  network_session_params.host_resolver = host_resolver();

  net::HttpCache* cache = new net::HttpCache(
      network_session_params, backend);
  cache->set_mode(cache_mode);
  storage_.set_http_transaction_factory(cache);

  storage_.set_ftp_transaction_factory(
      new net::FtpNetworkLayer(host_resolver()));

  blob_storage_controller_.reset(new webkit_blob::BlobStorageController());
  file_system_context_ = static_cast<SimpleFileSystem*>(
      WebKit::Platform::current()->fileSystem())->file_system_context();

  net::URLRequestJobFactoryImpl* job_factory =
      new net::URLRequestJobFactoryImpl();
  job_factory->SetProtocolHandler(
      "blob",
      new webkit_blob::BlobProtocolHandler(
          blob_storage_controller_.get(),
          file_system_context_,
          SimpleResourceLoaderBridge::GetIoThread()));
  job_factory->SetProtocolHandler(
      "filesystem",
      fileapi::CreateFileSystemProtocolHandler(file_system_context_.get()));
  storage_.set_job_factory(job_factory);
}

TestShellRequestContext::~TestShellRequestContext() {
}
<|endoftext|>


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

#include "chrome/browser/chrome_thread.h"

// Friendly names for the well-known threads.
static const char* chrome_thread_names[ChromeThread::ID_COUNT] = {
  "",  // UI (name assembled in browser_main.cc).
  "Chrome_DBThread",  // DB
  "Chrome_WebKitThread",  // WEBKIT
  "Chrome_FileThread",  // FILE
  "Chrome_IOThread",  // IO
#if defined(OS_LINUX)
  "Chrome_Background_X11Thread",  // BACKGROUND_X11
#endif
};

Lock ChromeThread::lock_;

ChromeThread* ChromeThread::chrome_threads_[ID_COUNT];

ChromeThread::ChromeThread(ChromeThread::ID identifier)
    : Thread(chrome_thread_names[identifier]),
      identifier_(identifier) {
  Initialize();
}

ChromeThread::ChromeThread(ID identifier, MessageLoop* message_loop)
    : Thread(message_loop->thread_name().c_str()),
      identifier_(identifier) {
  set_message_loop(message_loop);
  Initialize();
}

void ChromeThread::Initialize() {
  AutoLock lock(lock_);
  DCHECK(identifier_ >= 0 && identifier_ < ID_COUNT);
  DCHECK(chrome_threads_[identifier_] == NULL);
  chrome_threads_[identifier_] = this;
}

ChromeThread::~ChromeThread() {
  AutoLock lock(lock_);
  chrome_threads_[identifier_] = NULL;
#ifndef NDEBUG
  // Double check that the threads are ordererd correctly in the enumeration.
  for (int i = identifier_ + 1; i < ID_COUNT; ++i) {
    DCHECK(!chrome_threads_[i]) <<
        "Threads must be listed in the reverse order that they die";
  }
#endif
}

// static
bool ChromeThread::CurrentlyOn(ID identifier) {
  AutoLock lock(lock_);
  DCHECK(identifier >= 0 && identifier < ID_COUNT);
  return chrome_threads_[identifier] &&
         chrome_threads_[identifier]->message_loop() == MessageLoop::current();
}

// static
bool ChromeThread::PostTask(ID identifier,
                            const tracked_objects::Location& from_here,
                            Task* task) {
  return PostTaskHelper(identifier, from_here, task, 0, true);
}

// static
bool ChromeThread::PostDelayedTask(ID identifier,
                                   const tracked_objects::Location& from_here,
                                   Task* task,
                                   int64 delay_ms) {
  return PostTaskHelper(identifier, from_here, task, delay_ms, true);
}

// static
bool ChromeThread::PostNonNestableTask(
    ID identifier,
    const tracked_objects::Location& from_here,
    Task* task) {
  return PostTaskHelper(identifier, from_here, task, 0, false);
}

// static
bool ChromeThread::PostNonNestableDelayedTask(
    ID identifier,
    const tracked_objects::Location& from_here,
    Task* task,
    int64 delay_ms) {
  return PostTaskHelper(identifier, from_here, task, delay_ms, false);
}

// static
bool ChromeThread::GetCurrentThreadIdentifier(ID* identifier) {
  MessageLoop* cur_message_loop = MessageLoop::current();
  for (int i = 0; i < ID_COUNT; ++i) {
    if (chrome_threads_[i] &&
        chrome_threads_[i]->message_loop() == cur_message_loop) {
      *identifier = chrome_threads_[i]->identifier_;
      return true;
    }
  }

  return false;
}

// static
bool ChromeThread::PostTaskHelper(
    ID identifier,
    const tracked_objects::Location& from_here,
    Task* task,
    int64 delay_ms,
    bool nestable) {
  DCHECK(identifier >= 0 && identifier < ID_COUNT);
  // Optimization: to avoid unnecessary locks, we listed the ID enumeration in
  // order of lifetime.  So no need to lock if we know that the other thread
  // outlives this one.
  // Note: since the array is so small, ok to loop instead of creating a map,
  // which would require a lock because std::map isn't thread safe, defeating
  // the whole purpose of this optimization.
  ID current_thread;
  bool guaranteed_to_outlive_target_thread =
      GetCurrentThreadIdentifier(&current_thread) &&
      current_thread >= identifier;

  if (!guaranteed_to_outlive_target_thread)
    lock_.Acquire();

  MessageLoop* message_loop = chrome_threads_[identifier] ?
      chrome_threads_[identifier]->message_loop() : NULL;
  if (message_loop) {
    if (nestable) {
      message_loop->PostDelayedTask(from_here, task, delay_ms);
    } else {
      message_loop->PostNonNestableDelayedTask(from_here, task, delay_ms);
    }
  } else {
    delete task;
  }

  if (!guaranteed_to_outlive_target_thread)
    lock_.Release();

  return !!message_loop;
}
<commit_msg>Stop each ChromeThread before nulling out the entry in chrome_threads_.  This allows DCHECKs that the code is running on the correct thread to succeed.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chrome_thread.h"

// Friendly names for the well-known threads.
static const char* chrome_thread_names[ChromeThread::ID_COUNT] = {
  "",  // UI (name assembled in browser_main.cc).
  "Chrome_DBThread",  // DB
  "Chrome_WebKitThread",  // WEBKIT
  "Chrome_FileThread",  // FILE
  "Chrome_IOThread",  // IO
#if defined(OS_LINUX)
  "Chrome_Background_X11Thread",  // BACKGROUND_X11
#endif
};

Lock ChromeThread::lock_;

ChromeThread* ChromeThread::chrome_threads_[ID_COUNT];

ChromeThread::ChromeThread(ChromeThread::ID identifier)
    : Thread(chrome_thread_names[identifier]),
      identifier_(identifier) {
  Initialize();
}

ChromeThread::ChromeThread(ID identifier, MessageLoop* message_loop)
    : Thread(message_loop->thread_name().c_str()),
      identifier_(identifier) {
  set_message_loop(message_loop);
  Initialize();
}

void ChromeThread::Initialize() {
  AutoLock lock(lock_);
  DCHECK(identifier_ >= 0 && identifier_ < ID_COUNT);
  DCHECK(chrome_threads_[identifier_] == NULL);
  chrome_threads_[identifier_] = this;
}

ChromeThread::~ChromeThread() {
  // Stop the thread here, instead of the parent's class destructor.  This is so
  // that if there are pending tasks that run, code that checks that it's on the
  // correct ChromeThread succeeds.
  Stop();

  AutoLock lock(lock_);
  chrome_threads_[identifier_] = NULL;
#ifndef NDEBUG
  // Double check that the threads are ordererd correctly in the enumeration.
  for (int i = identifier_ + 1; i < ID_COUNT; ++i) {
    DCHECK(!chrome_threads_[i]) <<
        "Threads must be listed in the reverse order that they die";
  }
#endif
}

// static
bool ChromeThread::CurrentlyOn(ID identifier) {
  AutoLock lock(lock_);
  DCHECK(identifier >= 0 && identifier < ID_COUNT);
  return chrome_threads_[identifier] &&
         chrome_threads_[identifier]->message_loop() == MessageLoop::current();
}

// static
bool ChromeThread::PostTask(ID identifier,
                            const tracked_objects::Location& from_here,
                            Task* task) {
  return PostTaskHelper(identifier, from_here, task, 0, true);
}

// static
bool ChromeThread::PostDelayedTask(ID identifier,
                                   const tracked_objects::Location& from_here,
                                   Task* task,
                                   int64 delay_ms) {
  return PostTaskHelper(identifier, from_here, task, delay_ms, true);
}

// static
bool ChromeThread::PostNonNestableTask(
    ID identifier,
    const tracked_objects::Location& from_here,
    Task* task) {
  return PostTaskHelper(identifier, from_here, task, 0, false);
}

// static
bool ChromeThread::PostNonNestableDelayedTask(
    ID identifier,
    const tracked_objects::Location& from_here,
    Task* task,
    int64 delay_ms) {
  return PostTaskHelper(identifier, from_here, task, delay_ms, false);
}

// static
bool ChromeThread::GetCurrentThreadIdentifier(ID* identifier) {
  MessageLoop* cur_message_loop = MessageLoop::current();
  for (int i = 0; i < ID_COUNT; ++i) {
    if (chrome_threads_[i] &&
        chrome_threads_[i]->message_loop() == cur_message_loop) {
      *identifier = chrome_threads_[i]->identifier_;
      return true;
    }
  }

  return false;
}

// static
bool ChromeThread::PostTaskHelper(
    ID identifier,
    const tracked_objects::Location& from_here,
    Task* task,
    int64 delay_ms,
    bool nestable) {
  DCHECK(identifier >= 0 && identifier < ID_COUNT);
  // Optimization: to avoid unnecessary locks, we listed the ID enumeration in
  // order of lifetime.  So no need to lock if we know that the other thread
  // outlives this one.
  // Note: since the array is so small, ok to loop instead of creating a map,
  // which would require a lock because std::map isn't thread safe, defeating
  // the whole purpose of this optimization.
  ID current_thread;
  bool guaranteed_to_outlive_target_thread =
      GetCurrentThreadIdentifier(&current_thread) &&
      current_thread >= identifier;

  if (!guaranteed_to_outlive_target_thread)
    lock_.Acquire();

  MessageLoop* message_loop = chrome_threads_[identifier] ?
      chrome_threads_[identifier]->message_loop() : NULL;
  if (message_loop) {
    if (nestable) {
      message_loop->PostDelayedTask(from_here, task, delay_ms);
    } else {
      message_loop->PostNonNestableDelayedTask(from_here, task, delay_ms);
    }
  } else {
    delete task;
  }

  if (!guaranteed_to_outlive_target_thread)
    lock_.Release();

  return !!message_loop;
}
<|endoftext|>