<commit_before>// Copyright (c) 2015 Andrew Sutton
// All rights reserved

#ifndef LINGO_LEXING_HPP
#define LINGO_LEXING_HPP

// The lexing module provides support for writing lexers
// by providing a number of generic scanners for different
// character sequences.
//
// These algorithms are based on a Lexer concept. Every
// lexer must expose a number of operations.

#include "lingo/string.hpp"
#include "lingo/location.hpp"
#include "lingo/token.hpp"
#include "lingo/algorithm.hpp"
#include "lingo/error.hpp"

namespace lingo
{

// -------------------------------------------------------------------------- //
//                             Character classes

// Returns true if c is white space.
inline bool
is_space(char c)
{
  return std::isspace(c);
}

// Returns true if c is alphabetical.
inline bool
is_alpha(char c)
{
  return std::isalpha(c);
}

// Returns true if c is a binary digit.
inline bool
is_binary_digit(char c)
{
  return c == '0' || c == '1';
}

// Returns true if c is an octal digit.
inline bool
is_octal_digit(char c)
{
  return '0' <= c && c <= '7';
}

// Returns true if c is a decimial digit.
inline bool
is_decimal_digit(char c)
{
  return std::isdigit(c);
}

// Returns true if c is a hexadecimal digit.
inline bool
is_hexadecimal_digit(char c)
{
  return std::isxdigit(c);
}

// Returns true if c starts an identifier.
inline bool
is_ident_head(char c)
{
  return is_alpha(c) || c == '_';
}

// Returns true if c can appear in the rest of an identifier.
inline bool
is_ident_tail(char c)
{
  return is_ident_tail(c) || is_decimal_digit(c);
}

// -------------------------------------------------------------------------- //
//                             Integer lexers
//
// TODO: Conditionally support a character as a digit separator
// in integer values.
//
// Note that an integer value like '0x' is an error. Note that the
// lexers for prefixed integer values require the lexer to define
// the following functions:
//
//    cxt.on_expected(loc, t)
//    cxt.on_expected(loc, str)

// Lexically analyze a decimal integer. The current character
// is `s` must be in the set of decimal digits.
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_decimal_integer(Lexer& lex, Stream& s, Location loc)
{
  auto pred = [](Stream& s) { return next_element_if(s, is_decimal_digit); };
  auto range = match_range_after_first(s, pred);
  return lex.on_decimal_integer(loc, range.begin(), range.end());
}

namespace
{

// A helper function for lexing integers with a specified
// base prefix. If successful, returns a character range
// that includes the 2-character prefix.
template<typename Stream, typename P>
inline Range_over<Stream>
match_integer_in_base(Stream& s, P pred)
{
  auto first = get_n(s, 2);
  auto range = match_range_after_first(s, pred);
  if (range)
    return {first, range.end()};
  else
    return range;
}

} // namespace

// Lex a binary integer where the first two characters are
// known to be '0b' or '0B'
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_binary_integer(Lexer& lex, Stream& s, Location loc)
{
  auto pred = [](Stream& s) { return next_element_if(s, is_binary_digit); };
  auto range = match_integer_in_base(s, pred);
  if (!range) {
    lex.on_expected(loc, "binary-digit");
    return {};
  }
  return lex.on_binary_integer(loc, range.begin(), range.end());
}

// Lex an octal integer where the first two characters are
// known to be '0o' or '0O' (that's a 0 and an O).
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_octal_integer(Lexer& lex, Stream& s, Location loc)
{
  auto pred = [](Stream& s) { return next_element_if(s, is_octal_digit); };
  auto range = match_integer_in_base(s, pred);
  if (!range) {
    lex.on_expected(loc, "octal-digit");
    return {};
  }
  return lex.on_octal_integer(loc, range.begin(), range.end());
}

// Lex a hexadecimal integer where the first two characters are
// known to be '0x' or '0X'.
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_hexadecimal_integer(Lexer& lex, Stream& s, Location loc)
{
  auto pred = [](Stream& s) { return next_element_if(s, is_hexadecimal_digit); };
  auto range = match_integer_in_base(s, pred);
  if (!range) {
    lex.on_expected(loc, "hexadecimal-digit");
    return {};
  }
  return lex.on_hexadecimal_integer(loc, range.begin(), range.end());
}

// Lex a numeric literal.
//
// TODO: If we know that we start with 0, then we can skip the
// first comparison. This could be two algorithms.
//
// TODO: Repeated comparisons for nth_element may repeatedly
// check for eof. This could be optimized.
//
// TODO: Add support for floating point values.
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_number(Lexer& l, Stream& s, Location loc)
{
  if (s.peek() == '0') {
    if (nth_element_is(s, 1, 'b'))
      return lex_binary_integer(l, s, loc);
    if (nth_element_is(s, 1, 'o'))
      return lex_octal_integer(l, s, loc);
    if (nth_element_is(s, 1, 'x'))
      return lex_hexadecimal_integer(l, s, loc);
  }
  return lex_decimal_integer(l, s, loc);
}

template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_identifier(Lexer& l, Stream& s, Location loc)
{
  auto first = s.begin();
  while (!s.eof() && is_ident_tail(s.peek()))
    s.get();
  return l.on_identifier(loc, first, s.begin());
}

} // namespace lingo

#endif
<commit_msg>Fix infinite recursion in identifier lex.<commit_after>// Copyright (c) 2015 Andrew Sutton
// All rights reserved

#ifndef LINGO_LEXING_HPP
#define LINGO_LEXING_HPP

// The lexing module provides support for writing lexers
// by providing a number of generic scanners for different
// character sequences.
//
// These algorithms are based on a Lexer concept. Every
// lexer must expose a number of operations.

#include "lingo/string.hpp"
#include "lingo/location.hpp"
#include "lingo/token.hpp"
#include "lingo/algorithm.hpp"
#include "lingo/error.hpp"

namespace lingo
{

// -------------------------------------------------------------------------- //
//                             Character classes

// Returns true if c is white space.
inline bool
is_space(char c)
{
  return std::isspace(c);
}

// Returns true if c is alphabetical.
inline bool
is_alpha(char c)
{
  return std::isalpha(c);
}

// Returns true if c is a binary digit.
inline bool
is_binary_digit(char c)
{
  return c == '0' || c == '1';
}

// Returns true if c is an octal digit.
inline bool
is_octal_digit(char c)
{
  return '0' <= c && c <= '7';
}

// Returns true if c is a decimial digit.
inline bool
is_decimal_digit(char c)
{
  return std::isdigit(c);
}

// Returns true if c is a hexadecimal digit.
inline bool
is_hexadecimal_digit(char c)
{
  return std::isxdigit(c);
}

// Returns true if c starts an identifier.
inline bool
is_ident_head(char c)
{
  return is_alpha(c) || c == '_';
}

// Returns true if c can appear in the rest of an identifier.
inline bool
is_ident_tail(char c)
{
  return is_ident_head(c) || is_decimal_digit(c);
}

// -------------------------------------------------------------------------- //
//                             Integer lexers
//
// TODO: Conditionally support a character as a digit separator
// in integer values.
//
// Note that an integer value like '0x' is an error. Note that the
// lexers for prefixed integer values require the lexer to define
// the following functions:
//
//    cxt.on_expected(loc, t)
//    cxt.on_expected(loc, str)

// Lexically analyze a decimal integer. The current character
// is `s` must be in the set of decimal digits.
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_decimal_integer(Lexer& lex, Stream& s, Location loc)
{
  auto pred = [](Stream& s) { return next_element_if(s, is_decimal_digit); };
  auto range = match_range_after_first(s, pred);
  return lex.on_decimal_integer(loc, range.begin(), range.end());
}

namespace
{

// A helper function for lexing integers with a specified
// base prefix. If successful, returns a character range
// that includes the 2-character prefix.
template<typename Stream, typename P>
inline Range_over<Stream>
match_integer_in_base(Stream& s, P pred)
{
  auto first = get_n(s, 2);
  auto range = match_range_after_first(s, pred);
  if (range)
    return {first, range.end()};
  else
    return range;
}

} // namespace

// Lex a binary integer where the first two characters are
// known to be '0b' or '0B'
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_binary_integer(Lexer& lex, Stream& s, Location loc)
{
  auto pred = [](Stream& s) { return next_element_if(s, is_binary_digit); };
  auto range = match_integer_in_base(s, pred);
  if (!range) {
    lex.on_expected(loc, "binary-digit");
    return {};
  }
  return lex.on_binary_integer(loc, range.begin(), range.end());
}

// Lex an octal integer where the first two characters are
// known to be '0o' or '0O' (that's a 0 and an O).
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_octal_integer(Lexer& lex, Stream& s, Location loc)
{
  auto pred = [](Stream& s) { return next_element_if(s, is_octal_digit); };
  auto range = match_integer_in_base(s, pred);
  if (!range) {
    lex.on_expected(loc, "octal-digit");
    return {};
  }
  return lex.on_octal_integer(loc, range.begin(), range.end());
}

// Lex a hexadecimal integer where the first two characters are
// known to be '0x' or '0X'.
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_hexadecimal_integer(Lexer& lex, Stream& s, Location loc)
{
  auto pred = [](Stream& s) { return next_element_if(s, is_hexadecimal_digit); };
  auto range = match_integer_in_base(s, pred);
  if (!range) {
    lex.on_expected(loc, "hexadecimal-digit");
    return {};
  }
  return lex.on_hexadecimal_integer(loc, range.begin(), range.end());
}

// Lex a numeric literal.
//
// TODO: If we know that we start with 0, then we can skip the
// first comparison. This could be two algorithms.
//
// TODO: Repeated comparisons for nth_element may repeatedly
// check for eof. This could be optimized.
//
// TODO: Add support for floating point values.
template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_number(Lexer& l, Stream& s, Location loc)
{
  if (s.peek() == '0') {
    if (nth_element_is(s, 1, 'b'))
      return lex_binary_integer(l, s, loc);
    if (nth_element_is(s, 1, 'o'))
      return lex_octal_integer(l, s, loc);
    if (nth_element_is(s, 1, 'x'))
      return lex_hexadecimal_integer(l, s, loc);
  }
  return lex_decimal_integer(l, s, loc);
}

template<typename Lexer, typename Stream>
inline Result_type<Lexer>
lex_identifier(Lexer& l, Stream& s, Location loc)
{
  auto first = s.begin();
  while (!s.eof() && is_ident_tail(s.peek()))
    s.get();
  return l.on_identifier(loc, first, s.begin());
}

} // namespace lingo

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: myucp_resultset.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 13:32:08 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef DBA_UCPRESULTSET_HXX
#define DBA_UCPRESULTSET_HXX

#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#ifndef _UCBHELPER_RESULTSETHELPER_HXX
#include <ucbhelper/resultsethelper.hxx>
#endif
#ifndef _DBA_COREDATAACCESS_DOCUMENTCONTAINER_HXX_
#include "documentcontainer.hxx"
#endif

// @@@ Adjust namespace name.
namespace dbaccess {

class DynamicResultSet : public ::ucb::ResultSetImplHelper
{
      rtl::Reference< ODocumentContainer > m_xContent;
    com::sun::star::uno::Reference<
        com::sun::star::ucb::XCommandEnvironment > m_xEnv;

private:
    virtual void initStatic();
    virtual void initDynamic();

public:
    DynamicResultSet(
            const com::sun::star::uno::Reference<
                com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
              const rtl::Reference< ODocumentContainer >& rxContent,
            const com::sun::star::ucb::OpenCommandArgument2& rCommand,
              const com::sun::star::uno::Reference<
                com::sun::star::ucb::XCommandEnvironment >& rxEnv );
};

}

#endif // DBA_UCPRESULTSET_HXX
<commit_msg>INTEGRATION: CWS bgdlremove (1.3.278); FILE MERGED 2007/05/18 09:03:13 kso 1.3.278.1: #i77419# - cleanup of ucbhelper namespaces.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: myucp_resultset.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: ihi $ $Date: 2007-06-05 14:40:12 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef DBA_UCPRESULTSET_HXX
#define DBA_UCPRESULTSET_HXX

#ifndef _RTL_REF_HXX_
#include <rtl/ref.hxx>
#endif
#ifndef _UCBHELPER_RESULTSETHELPER_HXX
#include <ucbhelper/resultsethelper.hxx>
#endif
#ifndef _DBA_COREDATAACCESS_DOCUMENTCONTAINER_HXX_
#include "documentcontainer.hxx"
#endif

// @@@ Adjust namespace name.
namespace dbaccess {

class DynamicResultSet : public ::ucbhelper::ResultSetImplHelper
{
      rtl::Reference< ODocumentContainer > m_xContent;
    com::sun::star::uno::Reference<
        com::sun::star::ucb::XCommandEnvironment > m_xEnv;

private:
    virtual void initStatic();
    virtual void initDynamic();

public:
    DynamicResultSet(
            const com::sun::star::uno::Reference<
                com::sun::star::lang::XMultiServiceFactory >& rxSMgr,
              const rtl::Reference< ODocumentContainer >& rxContent,
            const com::sun::star::ucb::OpenCommandArgument2& rCommand,
              const com::sun::star::uno::Reference<
                com::sun::star::ucb::XCommandEnvironment >& rxEnv );
};

}

#endif // DBA_UCPRESULTSET_HXX
<|endoftext|>


<commit_before>#include "nucleus/HighPerformanceTimer.h"

#include "nucleus/Config.h"
#include "nucleus/Logging.h"

#if OS(WIN)
#include "nucleus/Win/WindowsMixin.h"
#elif OS(MACOSX)
#include <mach/mach_time.h>
#elif OS(POSIX)
#include <time.h>
#ifdef CLOCK_MONOTONIC
#define CLOCKID CLOCK_MONOTONIC
#else
#define CLOCKID CLOCK_REALTIME
#endif
#else
#error Operating system not supported
#endif

namespace nu {

namespace {

struct FrequencyStorage {
  F64 ticksPerSecond;

  FrequencyStorage() noexcept {
#if OS(WIN)
    LARGE_INTEGER frequency;
    QueryPerformanceFrequency(&frequency);
    ticksPerSecond = static_cast<F64>(frequency.QuadPart);
#elif OS(MACOSX)
    mach_timebase_info_data_t rate;
    mach_timebase_info(&rate);
    ticksPerSecond = static_cast<F64>(rate.numer) * 1000.0 / static_cast<F64>(rate.denom);
#elif OS(POSIX)
    struct timespec rate;
    clock_getres(CLOCKID, &rate);
    ticksPerSecond = static_cast<F64>(rate.tv_nsec) * 1000.0;
#else
#error Operating system not supported
#endif
  }
};

FrequencyStorage s_frequencyStorage;

}  // namespace

F64 getCurrentHighPerformanceTick() {
#if OS(WIN)
  LARGE_INTEGER counter;
  QueryPerformanceCounter(&counter);
  return static_cast<F64>(counter.QuadPart) * 1000.0 * 1000.0 / s_frequencyStorage.ticksPerSecond;
#elif OS(MACOSX)
  auto time = mach_absolute_time();
  return static_cast<F64>(time) / s_frequencyStorage.ticksPerSecond;
#elif OS(POSIX)
  struct timespec specTime;
  clock_gettime(CLOCKID, &specTime);
  F64 now = static_cast<F64>(specTime.tv_sec) * 1000000.0 + static_cast<F64>(specTime.tv_nsec);
#else
#error Operating system not supported
#endif
}

}  // namespace nu
<commit_msg>Fix posix compilation error.<commit_after>#include "nucleus/HighPerformanceTimer.h"

#include "nucleus/Config.h"
#include "nucleus/Logging.h"

#if OS(WIN)
#include "nucleus/Win/WindowsMixin.h"
#elif OS(MACOSX)
#include <mach/mach_time.h>
#elif OS(POSIX)
#include <time.h>
#ifdef CLOCK_MONOTONIC
#define CLOCKID CLOCK_MONOTONIC
#else
#define CLOCKID CLOCK_REALTIME
#endif
#else
#error Operating system not supported
#endif

namespace nu {

namespace {

struct FrequencyStorage {
  F64 ticksPerSecond;

  FrequencyStorage() noexcept {
#if OS(WIN)
    LARGE_INTEGER frequency;
    QueryPerformanceFrequency(&frequency);
    ticksPerSecond = static_cast<F64>(frequency.QuadPart);
#elif OS(MACOSX)
    mach_timebase_info_data_t rate;
    mach_timebase_info(&rate);
    ticksPerSecond = static_cast<F64>(rate.numer) * 1000.0 / static_cast<F64>(rate.denom);
#elif OS(POSIX)
    struct timespec rate;
    clock_getres(CLOCKID, &rate);
    ticksPerSecond = static_cast<F64>(rate.tv_nsec) * 1000.0;
#else
#error Operating system not supported
#endif
  }
};

FrequencyStorage s_frequencyStorage;

}  // namespace

F64 getCurrentHighPerformanceTick() {
#if OS(WIN)
  LARGE_INTEGER counter;
  QueryPerformanceCounter(&counter);
  return static_cast<F64>(counter.QuadPart) * 1000.0 * 1000.0 / s_frequencyStorage.ticksPerSecond;
#elif OS(MACOSX)
  auto time = mach_absolute_time();
  return static_cast<F64>(time) / s_frequencyStorage.ticksPerSecond;
#elif OS(POSIX)
  struct timespec time;
  clock_gettime(CLOCKID, &time);
  return static_cast<F64>(time.tv_sec) * 1000000.0 + static_cast<F64>(time.tv_nsec);
#else
#error Operating system not supported
#endif
}

}  // namespace nu
<|endoftext|>


<commit_before>/* OpenSceneGraph example, osgtexture3D.
*
*  Permission is hereby granted, free of charge, to any person obtaining a copy
*  of this software and associated documentation files (the "Software"), to deal
*  in the Software without restriction, including without limitation the rights
*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
*  copies of the Software, and to permit persons to whom the Software is
*  furnished to do so, subject to the following conditions:
*
*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
*  THE SOFTWARE.
*/

#include <osg/Node>
#include <osg/Geometry>
#include <osg/Notify>
#include <osg/Texture1D>
#include <osg/Texture2D>
#include <osg/Texture3D>
#include <osg/TextureRectangle>
#include <osg/ImageSequence>
#include <osg/Geode>

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

#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>

#include <iostream>

static osgDB::DirectoryContents getSuitableFiles(osg::ArgumentParser& arguments)
{
    osgDB::DirectoryContents files;
    for(int i=1; i<arguments.argc(); ++i)
    {
        if (osgDB::fileType(arguments[i]) == osgDB::DIRECTORY)
        {
            const std::string& directory = arguments[i];
            osgDB::DirectoryContents dc = osgDB::getSortedDirectoryContents(directory);

            for(osgDB::DirectoryContents::iterator itr = dc.begin(); itr != dc.end(); ++itr)
            {
                std::string full_file_name = directory + "/" + (*itr);
                std::string ext = osgDB::getLowerCaseFileExtension(full_file_name);
                if ((ext == "jpg") || (ext == "png") || (ext == "gif") ||  (ext == "rgb") || (ext == "dds") )
                {
                    files.push_back(full_file_name);
                }
            }
        }
        else {
            files.push_back(arguments[i]);
        }
    }
    return files;
}

//
// A simple demo demonstrating how to set on an animated texture using an osg::ImageSequence
//

osg::StateSet* createState(osg::ArgumentParser& arguments)
{
    osg::ref_ptr<osg::ImageSequence> imageSequence = new osg::ImageSequence;

    bool preLoad = true;

    while (arguments.read("--page-and-discard"))
    {
        imageSequence->setMode(osg::ImageSequence::PAGE_AND_DISCARD_USED_IMAGES);
        preLoad = false;
    }

    while (arguments.read("--page-and-retain"))
    {
        imageSequence->setMode(osg::ImageSequence::PAGE_AND_RETAIN_IMAGES);
        preLoad = false;
    }

    while (arguments.read("--preload"))
    {
        imageSequence->setMode(osg::ImageSequence::PRE_LOAD_ALL_IMAGES);
        preLoad = true;
    }

    double length = -1.0;
    while (arguments.read("--length",length)) {}

    double fps = 30.0;
    while (arguments.read("--fps",fps)) {}

    osgDB::DirectoryContents files = getSuitableFiles(arguments);
    if (!files.empty())
    {
        for(osgDB::DirectoryContents::iterator itr = files.begin();
            itr != files.end();
            ++itr)
        {
            const std::string& filename = *itr;
            if (preLoad)
            {
                osg::ref_ptr<osg::Image> image = osgDB::readRefImageFile(filename);
                if (image.valid())
                {
                    imageSequence->addImage(image.get());
                }
            }
            else
            {
                imageSequence->addImageFile(filename);
            }

        }

        if (length>0.0)
        {
            imageSequence->setLength(length);
        }
        else
        {
            unsigned int maxNum = imageSequence->getNumImageData();
            imageSequence->setLength(double(maxNum)*(1.0/fps));
        }
    }
    else
    {
        if (length>0.0)
        {
            imageSequence->setLength(length);
        }
        else
        {
            imageSequence->setLength(4.0);
        }
        imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/posx.png"));
        imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/negx.png"));
        imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/posy.png"));
        imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/negy.png"));
        imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/posz.png"));
        imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/negz.png"));
    }

    // start the image sequence playing
    imageSequence->play();

#if 1
    osg::Texture2D* texture = new osg::Texture2D;
    texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
    texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
    texture->setWrap(osg::Texture::WRAP_R,osg::Texture::REPEAT);
    texture->setResizeNonPowerOfTwoHint(false);
    texture->setImage(imageSequence.get());
    //texture->setTextureSize(512,512);
#else
    osg::TextureRectangle* texture = new osg::TextureRectangle;
    texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
    texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
    texture->setWrap(osg::Texture::WRAP_R,osg::Texture::REPEAT);
    texture->setImage(imageSequence.get());
    //texture->setTextureSize(512,512);
#endif

    // create the StateSet to store the texture data
    osg::StateSet* stateset = new osg::StateSet;

    stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);

    return stateset;
}

osg::Node* createModel(osg::ArgumentParser& arguments)
{

    // create the geometry of the model, just a simple 2d quad right now.
    osg::Geode* geode = new osg::Geode;
    geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(0.0f,0.0f,0.0), osg::Vec3(1.0f,0.0f,0.0), osg::Vec3(0.0f,0.0f,1.0f)));

    geode->setStateSet(createState(arguments));

    return geode;

}

osg::ImageStream* s_imageStream = 0;
class MovieEventHandler : public osgGA::GUIEventHandler
{
public:

    MovieEventHandler():_playToggle(true),_trackMouse(false) {}

    void setMouseTracking(bool track) { _trackMouse = track; }
    bool getMouseTracking() const { return _trackMouse; }

    void set(osg::Node* node);

    void setTrackMouse(bool tm)
    {
        if (tm==_trackMouse) return;

        _trackMouse = tm;

        std::cout << "tracking mouse: " << (_trackMouse ? "ON" : "OFF") << std::endl;

        for(ImageStreamList::iterator itr=_imageStreamList.begin();
            itr!=_imageStreamList.end();
            ++itr)
        {
            if ((*itr)->getStatus()==osg::ImageStream::PLAYING)
            {
                (*itr)->pause();
            }
            else
            {
                (*itr)->play();
            }
        }

    }

    bool getTrackMouse() const { return _trackMouse; }

    virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor* nv);

    virtual void getUsage(osg::ApplicationUsage& usage) const;

    typedef std::vector< osg::observer_ptr<osg::ImageStream> > ImageStreamList;

    struct ImageStreamPlaybackSpeedData {
        double fps;
        unsigned char* lastData;
        double timeStamp, lastOutput;

        ImageStreamPlaybackSpeedData() : fps(0), lastData(NULL), timeStamp(0), lastOutput(0) {}

    };

    typedef std::vector< ImageStreamPlaybackSpeedData > ImageStreamPlayBackSpeedList;

protected:

    virtual ~MovieEventHandler() {}

    class FindImageStreamsVisitor : public osg::NodeVisitor
    {
    public:
        FindImageStreamsVisitor(ImageStreamList& imageStreamList):
            _imageStreamList(imageStreamList) {}

        virtual void apply(osg::Geode& geode)
        {
            apply(geode.getStateSet());

            for(unsigned int i=0;i<geode.getNumDrawables();++i)
            {
                apply(geode.getDrawable(i)->getStateSet());
            }

            traverse(geode);
        }

        virtual void apply(osg::Node& node)
        {
            apply(node.getStateSet());
            traverse(node);
        }

        inline void apply(osg::StateSet* stateset)
        {
            if (!stateset) return;

            osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
            if (attr)
            {
                osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);
                if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));

                osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);
                if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));
            }
        }

        inline void apply(osg::ImageStream* imagestream)
        {
            if (imagestream)
            {
                _imageStreamList.push_back(imagestream);
                s_imageStream = imagestream;
            }
        }

        ImageStreamList& _imageStreamList;

    protected:

        FindImageStreamsVisitor& operator = (const FindImageStreamsVisitor&) { return *this; }
    };

    bool            _playToggle;
    bool            _trackMouse;
    ImageStreamList _imageStreamList;
    ImageStreamPlayBackSpeedList _imageStreamPlayBackSpeedList;

};

void MovieEventHandler::set(osg::Node* node)
{
    _imageStreamList.clear();
    if (node)
    {
        FindImageStreamsVisitor fisv(_imageStreamList);
        node->accept(fisv);
    }
    _imageStreamPlayBackSpeedList.resize(_imageStreamList.size());
}

bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor* nv)
{
    switch(ea.getEventType())
    {
        case(osgGA::GUIEventAdapter::FRAME):
            {
                double t = ea.getTime();
                bool printed(false);

                ImageStreamPlayBackSpeedList::iterator fps_itr = _imageStreamPlayBackSpeedList.begin();
                for(ImageStreamList::iterator itr=_imageStreamList.begin();
                    itr!=_imageStreamList.end();
                    ++itr, ++fps_itr)
                {
                    if (((*itr)->getStatus()==osg::ImageStream::PLAYING) && ((*itr)->data() != (*fps_itr).lastData))
                    {
                        ImageStreamPlaybackSpeedData& data(*fps_itr);
                        double dt = (data.timeStamp > 0) ? t - data.timeStamp : 1/60.0;
                        data.lastData = (*itr)->data();
                        data.fps = (*fps_itr).fps * 0.8 + 0.2 * (1/dt);
                        data.timeStamp = t;

                        if (t-data.lastOutput > 1)
                        {
                            std::cout << data.fps << " ";
                            data.lastOutput = t;
                            printed = true;
                        }

                    }
                }
                if (printed)
                    std::cout << std::endl;
            }
            break;
        case(osgGA::GUIEventAdapter::MOVE):
            {
                if (_trackMouse)
                {
                    for(ImageStreamList::iterator itr=_imageStreamList.begin();
                        itr!=_imageStreamList.end();
                        ++itr)
                    {
                        double dt = (*itr)->getLength() * ((1.0+ea.getXnormalized()) / 2.0);
                        (*itr)->seek(dt);
                        std::cout << "seeking to " << dt << " length: " <<(*itr)->getLength() << std::endl;
                    }
                }
                return false;
            }

        case(osgGA::GUIEventAdapter::KEYDOWN):
        {
            if (ea.getKey()=='p')
            {
                for(ImageStreamList::iterator itr=_imageStreamList.begin();
                    itr!=_imageStreamList.end();
                    ++itr)
                {
                    if ((*itr)->getStatus()==osg::ImageStream::PLAYING)
                    {
                        // playing, so pause
                        std::cout<<"Pause"<<std::endl;
                        (*itr)->pause();
                    }
                    else
                    {
                        // playing, so pause
                        std::cout<<"Play"<<std::endl;
                        (*itr)->play();
                    }
                }
                return true;
            }
            else if (ea.getKey()=='r')
            {
                for(ImageStreamList::iterator itr=_imageStreamList.begin();
                    itr!=_imageStreamList.end();
                    ++itr)
                {
                    std::cout<<"Restart"<<std::endl;
                    (*itr)->rewind();
                }
                return true;
            }
            else if (ea.getKey()=='L')
            {
                for(ImageStreamList::iterator itr=_imageStreamList.begin();
                    itr!=_imageStreamList.end();
                    ++itr)
                {
                    if ( (*itr)->getLoopingMode() == osg::ImageStream::LOOPING)
                    {
                        std::cout<<"Toggle Looping Off"<<std::endl;
                        (*itr)->setLoopingMode( osg::ImageStream::NO_LOOPING );
                    }
                    else
                    {
                        std::cout<<"Toggle Looping On"<<std::endl;
                        (*itr)->setLoopingMode( osg::ImageStream::LOOPING );
                    }
                }
                return true;
            }
            else if (ea.getKey() == 'i')
            {
                setTrackMouse(!_trackMouse);

            }
            return false;
        }

        default:
            return false;
    }

    return false;
}

void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
{
    usage.addKeyboardMouseBinding("i","toggle interactive mode, scrub via mouse-move");
    usage.addKeyboardMouseBinding("p","Play/Pause movie");
    usage.addKeyboardMouseBinding("r","Restart movie");
    usage.addKeyboardMouseBinding("l","Toggle looping of movie");
}

int main(int argc, char **argv)
{
    osg::ArgumentParser arguments(&argc,argv);

    // construct the viewer.
    osgViewer::Viewer viewer(arguments);

    std::string filename;
    arguments.read("-o",filename);

    // create a model from the images and pass it to the viewer.
    viewer.setSceneData(createModel(arguments));

    // pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
    MovieEventHandler* meh = new MovieEventHandler();
    meh->set( viewer.getSceneData() );

    if (arguments.read("--track-mouse")) meh->setTrackMouse(true);

    viewer.addEventHandler( meh );

    viewer.addEventHandler( new osgViewer::StatsHandler());

    if (!filename.empty())
    {
        osgDB::writeNodeFile(*viewer.getSceneData(),filename);
    }

    return viewer.run();
}
<commit_msg>Fixed unused parameter warning.<commit_after>/* OpenSceneGraph example, osgtexture3D.
*
*  Permission is hereby granted, free of charge, to any person obtaining a copy
*  of this software and associated documentation files (the "Software"), to deal
*  in the Software without restriction, including without limitation the rights
*  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
*  copies of the Software, and to permit persons to whom the Software is
*  furnished to do so, subject to the following conditions:
*
*  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
*  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
*  THE SOFTWARE.
*/

#include <osg/Node>
#include <osg/Geometry>
#include <osg/Notify>
#include <osg/Texture1D>
#include <osg/Texture2D>
#include <osg/Texture3D>
#include <osg/TextureRectangle>
#include <osg/ImageSequence>
#include <osg/Geode>

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

#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>

#include <iostream>

static osgDB::DirectoryContents getSuitableFiles(osg::ArgumentParser& arguments)
{
    osgDB::DirectoryContents files;
    for(int i=1; i<arguments.argc(); ++i)
    {
        if (osgDB::fileType(arguments[i]) == osgDB::DIRECTORY)
        {
            const std::string& directory = arguments[i];
            osgDB::DirectoryContents dc = osgDB::getSortedDirectoryContents(directory);

            for(osgDB::DirectoryContents::iterator itr = dc.begin(); itr != dc.end(); ++itr)
            {
                std::string full_file_name = directory + "/" + (*itr);
                std::string ext = osgDB::getLowerCaseFileExtension(full_file_name);
                if ((ext == "jpg") || (ext == "png") || (ext == "gif") ||  (ext == "rgb") || (ext == "dds") )
                {
                    files.push_back(full_file_name);
                }
            }
        }
        else {
            files.push_back(arguments[i]);
        }
    }
    return files;
}

//
// A simple demo demonstrating how to set on an animated texture using an osg::ImageSequence
//

osg::StateSet* createState(osg::ArgumentParser& arguments)
{
    osg::ref_ptr<osg::ImageSequence> imageSequence = new osg::ImageSequence;

    bool preLoad = true;

    while (arguments.read("--page-and-discard"))
    {
        imageSequence->setMode(osg::ImageSequence::PAGE_AND_DISCARD_USED_IMAGES);
        preLoad = false;
    }

    while (arguments.read("--page-and-retain"))
    {
        imageSequence->setMode(osg::ImageSequence::PAGE_AND_RETAIN_IMAGES);
        preLoad = false;
    }

    while (arguments.read("--preload"))
    {
        imageSequence->setMode(osg::ImageSequence::PRE_LOAD_ALL_IMAGES);
        preLoad = true;
    }

    double length = -1.0;
    while (arguments.read("--length",length)) {}

    double fps = 30.0;
    while (arguments.read("--fps",fps)) {}

    osgDB::DirectoryContents files = getSuitableFiles(arguments);
    if (!files.empty())
    {
        for(osgDB::DirectoryContents::iterator itr = files.begin();
            itr != files.end();
            ++itr)
        {
            const std::string& filename = *itr;
            if (preLoad)
            {
                osg::ref_ptr<osg::Image> image = osgDB::readRefImageFile(filename);
                if (image.valid())
                {
                    imageSequence->addImage(image.get());
                }
            }
            else
            {
                imageSequence->addImageFile(filename);
            }

        }

        if (length>0.0)
        {
            imageSequence->setLength(length);
        }
        else
        {
            unsigned int maxNum = imageSequence->getNumImageData();
            imageSequence->setLength(double(maxNum)*(1.0/fps));
        }
    }
    else
    {
        if (length>0.0)
        {
            imageSequence->setLength(length);
        }
        else
        {
            imageSequence->setLength(4.0);
        }
        imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/posx.png"));
        imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/negx.png"));
        imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/posy.png"));
        imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/negy.png"));
        imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/posz.png"));
        imageSequence->addImage(osgDB::readRefImageFile("Cubemap_axis/negz.png"));
    }

    // start the image sequence playing
    imageSequence->play();

#if 1
    osg::Texture2D* texture = new osg::Texture2D;
    texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
    texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
    texture->setWrap(osg::Texture::WRAP_R,osg::Texture::REPEAT);
    texture->setResizeNonPowerOfTwoHint(false);
    texture->setImage(imageSequence.get());
    //texture->setTextureSize(512,512);
#else
    osg::TextureRectangle* texture = new osg::TextureRectangle;
    texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
    texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
    texture->setWrap(osg::Texture::WRAP_R,osg::Texture::REPEAT);
    texture->setImage(imageSequence.get());
    //texture->setTextureSize(512,512);
#endif

    // create the StateSet to store the texture data
    osg::StateSet* stateset = new osg::StateSet;

    stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);

    return stateset;
}

osg::Node* createModel(osg::ArgumentParser& arguments)
{

    // create the geometry of the model, just a simple 2d quad right now.
    osg::Geode* geode = new osg::Geode;
    geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(0.0f,0.0f,0.0), osg::Vec3(1.0f,0.0f,0.0), osg::Vec3(0.0f,0.0f,1.0f)));

    geode->setStateSet(createState(arguments));

    return geode;

}

osg::ImageStream* s_imageStream = 0;
class MovieEventHandler : public osgGA::GUIEventHandler
{
public:

    MovieEventHandler():_playToggle(true),_trackMouse(false) {}

    void setMouseTracking(bool track) { _trackMouse = track; }
    bool getMouseTracking() const { return _trackMouse; }

    void set(osg::Node* node);

    void setTrackMouse(bool tm)
    {
        if (tm==_trackMouse) return;

        _trackMouse = tm;

        std::cout << "tracking mouse: " << (_trackMouse ? "ON" : "OFF") << std::endl;

        for(ImageStreamList::iterator itr=_imageStreamList.begin();
            itr!=_imageStreamList.end();
            ++itr)
        {
            if ((*itr)->getStatus()==osg::ImageStream::PLAYING)
            {
                (*itr)->pause();
            }
            else
            {
                (*itr)->play();
            }
        }

    }

    bool getTrackMouse() const { return _trackMouse; }

    virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor* nv);

    virtual void getUsage(osg::ApplicationUsage& usage) const;

    typedef std::vector< osg::observer_ptr<osg::ImageStream> > ImageStreamList;

    struct ImageStreamPlaybackSpeedData {
        double fps;
        unsigned char* lastData;
        double timeStamp, lastOutput;

        ImageStreamPlaybackSpeedData() : fps(0), lastData(NULL), timeStamp(0), lastOutput(0) {}

    };

    typedef std::vector< ImageStreamPlaybackSpeedData > ImageStreamPlayBackSpeedList;

protected:

    virtual ~MovieEventHandler() {}

    class FindImageStreamsVisitor : public osg::NodeVisitor
    {
    public:
        FindImageStreamsVisitor(ImageStreamList& imageStreamList):
            _imageStreamList(imageStreamList) {}

        virtual void apply(osg::Geode& geode)
        {
            apply(geode.getStateSet());

            for(unsigned int i=0;i<geode.getNumDrawables();++i)
            {
                apply(geode.getDrawable(i)->getStateSet());
            }

            traverse(geode);
        }

        virtual void apply(osg::Node& node)
        {
            apply(node.getStateSet());
            traverse(node);
        }

        inline void apply(osg::StateSet* stateset)
        {
            if (!stateset) return;

            osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
            if (attr)
            {
                osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);
                if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));

                osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);
                if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));
            }
        }

        inline void apply(osg::ImageStream* imagestream)
        {
            if (imagestream)
            {
                _imageStreamList.push_back(imagestream);
                s_imageStream = imagestream;
            }
        }

        ImageStreamList& _imageStreamList;

    protected:

        FindImageStreamsVisitor& operator = (const FindImageStreamsVisitor&) { return *this; }
    };

    bool            _playToggle;
    bool            _trackMouse;
    ImageStreamList _imageStreamList;
    ImageStreamPlayBackSpeedList _imageStreamPlayBackSpeedList;

};

void MovieEventHandler::set(osg::Node* node)
{
    _imageStreamList.clear();
    if (node)
    {
        FindImageStreamsVisitor fisv(_imageStreamList);
        node->accept(fisv);
    }
    _imageStreamPlayBackSpeedList.resize(_imageStreamList.size());
}

bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter&, osg::Object*, osg::NodeVisitor*)
{
    switch(ea.getEventType())
    {
        case(osgGA::GUIEventAdapter::FRAME):
            {
                double t = ea.getTime();
                bool printed(false);

                ImageStreamPlayBackSpeedList::iterator fps_itr = _imageStreamPlayBackSpeedList.begin();
                for(ImageStreamList::iterator itr=_imageStreamList.begin();
                    itr!=_imageStreamList.end();
                    ++itr, ++fps_itr)
                {
                    if (((*itr)->getStatus()==osg::ImageStream::PLAYING) && ((*itr)->data() != (*fps_itr).lastData))
                    {
                        ImageStreamPlaybackSpeedData& data(*fps_itr);
                        double dt = (data.timeStamp > 0) ? t - data.timeStamp : 1/60.0;
                        data.lastData = (*itr)->data();
                        data.fps = (*fps_itr).fps * 0.8 + 0.2 * (1/dt);
                        data.timeStamp = t;

                        if (t-data.lastOutput > 1)
                        {
                            std::cout << data.fps << " ";
                            data.lastOutput = t;
                            printed = true;
                        }

                    }
                }
                if (printed)
                    std::cout << std::endl;
            }
            break;
        case(osgGA::GUIEventAdapter::MOVE):
            {
                if (_trackMouse)
                {
                    for(ImageStreamList::iterator itr=_imageStreamList.begin();
                        itr!=_imageStreamList.end();
                        ++itr)
                    {
                        double dt = (*itr)->getLength() * ((1.0+ea.getXnormalized()) / 2.0);
                        (*itr)->seek(dt);
                        std::cout << "seeking to " << dt << " length: " <<(*itr)->getLength() << std::endl;
                    }
                }
                return false;
            }

        case(osgGA::GUIEventAdapter::KEYDOWN):
        {
            if (ea.getKey()=='p')
            {
                for(ImageStreamList::iterator itr=_imageStreamList.begin();
                    itr!=_imageStreamList.end();
                    ++itr)
                {
                    if ((*itr)->getStatus()==osg::ImageStream::PLAYING)
                    {
                        // playing, so pause
                        std::cout<<"Pause"<<std::endl;
                        (*itr)->pause();
                    }
                    else
                    {
                        // playing, so pause
                        std::cout<<"Play"<<std::endl;
                        (*itr)->play();
                    }
                }
                return true;
            }
            else if (ea.getKey()=='r')
            {
                for(ImageStreamList::iterator itr=_imageStreamList.begin();
                    itr!=_imageStreamList.end();
                    ++itr)
                {
                    std::cout<<"Restart"<<std::endl;
                    (*itr)->rewind();
                }
                return true;
            }
            else if (ea.getKey()=='L')
            {
                for(ImageStreamList::iterator itr=_imageStreamList.begin();
                    itr!=_imageStreamList.end();
                    ++itr)
                {
                    if ( (*itr)->getLoopingMode() == osg::ImageStream::LOOPING)
                    {
                        std::cout<<"Toggle Looping Off"<<std::endl;
                        (*itr)->setLoopingMode( osg::ImageStream::NO_LOOPING );
                    }
                    else
                    {
                        std::cout<<"Toggle Looping On"<<std::endl;
                        (*itr)->setLoopingMode( osg::ImageStream::LOOPING );
                    }
                }
                return true;
            }
            else if (ea.getKey() == 'i')
            {
                setTrackMouse(!_trackMouse);

            }
            return false;
        }

        default:
            return false;
    }

    return false;
}

void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
{
    usage.addKeyboardMouseBinding("i","toggle interactive mode, scrub via mouse-move");
    usage.addKeyboardMouseBinding("p","Play/Pause movie");
    usage.addKeyboardMouseBinding("r","Restart movie");
    usage.addKeyboardMouseBinding("l","Toggle looping of movie");
}

int main(int argc, char **argv)
{
    osg::ArgumentParser arguments(&argc,argv);

    // construct the viewer.
    osgViewer::Viewer viewer(arguments);

    std::string filename;
    arguments.read("-o",filename);

    // create a model from the images and pass it to the viewer.
    viewer.setSceneData(createModel(arguments));

    // pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
    MovieEventHandler* meh = new MovieEventHandler();
    meh->set( viewer.getSceneData() );

    if (arguments.read("--track-mouse")) meh->setTrackMouse(true);

    viewer.addEventHandler( meh );

    viewer.addEventHandler( new osgViewer::StatsHandler());

    if (!filename.empty())
    {
        osgDB::writeNodeFile(*viewer.getSceneData(),filename);
    }

    return viewer.run();
}
<|endoftext|>


<commit_before><commit_msg>Alphabetized file format lists<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>

using namespace pcl;

int
main (int argc, char** argv)
{
  PointCloud<PointXYZ>::Ptr cloud (new PointCloud<PointXYZ>);

  if (io::loadPCDFile<PointXYZ> ("test_pcd.pcd", *cloud) == -1) //* load the file
  {
    PCL_ERROR ("Couldn't read file test_pcd.pcd \n");
    return (-1);
  }
  std::cerr << "Loaded "
            << cloud->width * cloud->height
            << " data points from test_pcd.pcd with the following fields: "
            << std::endl;
  for (size_t i = 0; i < cloud->points.size (); ++i)
    std::cerr << "    " << cloud->points[i].x
              << " "    << cloud->points[i].y
              << " "    << cloud->points[i].z << std::endl;

  return (0);
}<commit_msg>removed using namespace pcl from code<commit_after>#include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/point_types.h>

//using namespace pcl;

int
main (int argc, char** argv)
{
  pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);

  if (pcl::io::loadPCDFile<pcl::PointXYZ> ("test_pcd.pcd", *cloud) == -1) //* load the file
  {
    PCL_ERROR ("Couldn't read file test_pcd.pcd \n");
    return (-1);
  }
  std::cerr << "Loaded "
            << cloud->width * cloud->height
            << " data points from test_pcd.pcd with the following fields: "
            << std::endl;
  for (size_t i = 0; i < cloud->points.size (); ++i)
    std::cerr << "    " << cloud->points[i].x
              << " "    << cloud->points[i].y
              << " "    << cloud->points[i].z << std::endl;

  return (0);
}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

// Class header file...
#include "XalanDOMStringHashTable.hpp"

#include <algorithm>

#include "DOMStringHelper.hpp"

XalanDOMStringHashTable::XalanDOMStringHashTable(
			unsigned int	theBucketCount,
			unsigned int	theBucketSize) :

	m_bucketCount(theBucketCount),
	m_bucketSize(theBucketSize),
	m_buckets(new BucketType[theBucketCount]),
	m_count(0),
	m_collisions(0)
{
}

void
XalanDOMStringHashTable::clear()
{
	for(unsigned int i = 0; i < m_bucketCount; ++i)
	{
		m_buckets[i].clear();
	}

#if !defined(NDEBUG)
	m_collisions = 0;
#endif
	m_count = 0;
}

void
XalanDOMStringHashTable::getBucketCounts(BucketCountsType&	theVector) const
{
	for(unsigned int i = 0; i < m_bucketCount; ++i)
	{
		theVector.push_back(m_buckets[i].size());
	}
}

struct
equalsXalanDOMString
{
	equalsXalanDOMString(
			const XalanDOMChar*		theString,
			unsigned int			theLength) :
		m_string(theString),
		m_length(theLength)
	{
	}

	bool
	operator()(const XalanDOMString*	theString) const
	{
		if (m_length != length(*theString))
		{
			return false;
		}
		else
		{
			return equals(m_string, c_wstr(*theString), m_length);
		}
	}

private:

	const XalanDOMChar* const	m_string;

	const unsigned int			m_length;
};

const XalanDOMString*
XalanDOMStringHashTable::find(
			const XalanDOMString&	theString,
			unsigned int*			theBucketIndex) const
{
	return find(c_wstr(theString), length(theString), theBucketIndex);
}

inline unsigned int
hash(
			const XalanDOMChar*		theString,
			unsigned int			theLength)
{
	assert(theString != 0);

    unsigned int				theResult = 0;

	const XalanDOMChar* const	theEnd = theString + theLength;

	while (theString != theEnd)
    {
        theResult += (theResult * 37) + (theResult >> 24) + unsigned(*theString);

        ++theString;
    }

	return theResult;
}

const XalanDOMString*
XalanDOMStringHashTable::find(
			const XalanDOMChar*		theString,
			unsigned int			theLength,
			unsigned int*			theBucketIndex) const
{
	assert(theString != 0);

	const unsigned int	theActualLength =
		theLength == unsigned(-1) ? length(theString) : theLength;

	const unsigned int	theHash = hash(theString, theActualLength);

	const unsigned int	theLocalBucketIndex = theHash % m_bucketCount;

	assert(theLocalBucketIndex < m_bucketCount);

	const BucketType&	theBucket = m_buckets[theLocalBucketIndex];

	if (theBucketIndex != 0)
	{
		*theBucketIndex = theLocalBucketIndex;
	}

#if !defined(XALAN_NO_NAMESPACES)
	using std::find_if;
#endif

	const BucketType::const_iterator	i =
		find_if(
				theBucket.begin(),
				theBucket.end(),
				equalsXalanDOMString(theString, theActualLength));

	if (i == theBucket.end())
	{
		return 0;
	}
	else
	{
		return *i;
	}
}

void
XalanDOMStringHashTable::insert(const XalanDOMString&	theString)
{
	const unsigned int	theHash = hash(c_wstr(theString), length(theString));

	const unsigned int	theBucketIndex = theHash % m_bucketCount;

	assert(theBucketIndex < m_bucketCount);

	BucketType&	theBucket = m_buckets[theBucketIndex];

#if !defined(NDEBUG)
	if (theBucket.size() > 0)
	{
		++m_collisions;
	}
#endif

	theBucket.reserve(m_bucketSize);

	theBucket.push_back(&theString);

	++m_count;
}

void
XalanDOMStringHashTable::insert(
			const XalanDOMString&	theString,
			unsigned int			theBucketIndex)
{
	assert(theBucketIndex == hash(c_wstr(theString), length(theString)) % m_bucketCount);
	assert(theBucketIndex < m_bucketCount);

	BucketType&	theBucket = m_buckets[theBucketIndex];

#if !defined(NDEBUG)
	if (theBucket.size() > 0)
	{
		++m_collisions;
	}
#endif

	theBucket.reserve(m_bucketSize);

	theBucket.push_back(&theString);

	++m_count;
}
<commit_msg>Changed hash to hashString since Solaris seems to have a conflicting hash() function.  The evils of global functions...<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2001 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

// Class header file...
#include "XalanDOMStringHashTable.hpp"

#include <algorithm>

#include "DOMStringHelper.hpp"

XalanDOMStringHashTable::XalanDOMStringHashTable(
			unsigned int	theBucketCount,
			unsigned int	theBucketSize) :

	m_bucketCount(theBucketCount),
	m_bucketSize(theBucketSize),
	m_buckets(new BucketType[theBucketCount]),
	m_count(0),
	m_collisions(0)
{
}

void
XalanDOMStringHashTable::clear()
{
	for(unsigned int i = 0; i < m_bucketCount; ++i)
	{
		m_buckets[i].clear();
	}

#if !defined(NDEBUG)
	m_collisions = 0;
#endif
	m_count = 0;
}

void
XalanDOMStringHashTable::getBucketCounts(BucketCountsType&	theVector) const
{
	for(unsigned int i = 0; i < m_bucketCount; ++i)
	{
		theVector.push_back(m_buckets[i].size());
	}
}

struct
equalsXalanDOMString
{
	equalsXalanDOMString(
			const XalanDOMChar*		theString,
			unsigned int			theLength) :
		m_string(theString),
		m_length(theLength)
	{
	}

	bool
	operator()(const XalanDOMString*	theString) const
	{
		if (m_length != length(*theString))
		{
			return false;
		}
		else
		{
			return equals(m_string, c_wstr(*theString), m_length);
		}
	}

private:

	const XalanDOMChar* const	m_string;

	const unsigned int			m_length;
};

const XalanDOMString*
XalanDOMStringHashTable::find(
			const XalanDOMString&	theString,
			unsigned int*			theBucketIndex) const
{
	return find(c_wstr(theString), length(theString), theBucketIndex);
}

inline unsigned int
hashString(
			const XalanDOMChar*		theString,
			unsigned int			theLength)
{
	assert(theString != 0);

    unsigned int				theResult = 0;

	const XalanDOMChar* const	theEnd = theString + theLength;

	while (theString != theEnd)
    {
        theResult += (theResult * 37) + (theResult >> 24) + unsigned(*theString);

        ++theString;
    }

	return theResult;
}

const XalanDOMString*
XalanDOMStringHashTable::find(
			const XalanDOMChar*		theString,
			unsigned int			theLength,
			unsigned int*			theBucketIndex) const
{
	assert(theString != 0);

	const unsigned int	theActualLength =
		theLength == unsigned(-1) ? length(theString) : theLength;

	const unsigned int	theHash = hashString(theString, theActualLength);

	const unsigned int	theLocalBucketIndex = theHash % m_bucketCount;

	assert(theLocalBucketIndex < m_bucketCount);

	const BucketType&	theBucket = m_buckets[theLocalBucketIndex];

	if (theBucketIndex != 0)
	{
		*theBucketIndex = theLocalBucketIndex;
	}

#if !defined(XALAN_NO_NAMESPACES)
	using std::find_if;
#endif

	const BucketType::const_iterator	i =
		find_if(
				theBucket.begin(),
				theBucket.end(),
				equalsXalanDOMString(theString, theActualLength));

	if (i == theBucket.end())
	{
		return 0;
	}
	else
	{
		return *i;
	}
}

void
XalanDOMStringHashTable::insert(const XalanDOMString&	theString)
{
	const unsigned int	theHash = hashString(c_wstr(theString), length(theString));

	const unsigned int	theBucketIndex = theHash % m_bucketCount;

	assert(theBucketIndex < m_bucketCount);

	BucketType&	theBucket = m_buckets[theBucketIndex];

#if !defined(NDEBUG)
	if (theBucket.size() > 0)
	{
		++m_collisions;
	}
#endif

	theBucket.reserve(m_bucketSize);

	theBucket.push_back(&theString);

	++m_count;
}

void
XalanDOMStringHashTable::insert(
			const XalanDOMString&	theString,
			unsigned int			theBucketIndex)
{
	assert(theBucketIndex == hashString(c_wstr(theString), length(theString)) % m_bucketCount);
	assert(theBucketIndex < m_bucketCount);

	BucketType&	theBucket = m_buckets[theBucketIndex];

#if !defined(NDEBUG)
	if (theBucket.size() > 0)
	{
		++m_collisions;
	}
#endif

	theBucket.reserve(m_bucketSize);

	theBucket.push_back(&theString);

	++m_count;
}
<|endoftext|>


<commit_before>
/*
 * Copyright (C) 2010, Victor Semionov
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 */

#include <climits>

#include <string>
#include <vector>
#include <set>
#include <ostream>
#include <iostream>

#include "Poco/Util/ServerApplication.h"
#include "Poco/URI.h"
#include "Poco/File.h"
#include "Poco/DirectoryIterator.h"
#include "Poco/NumberFormatter.h"

#include "IndigoRequestHandler.h"
#include "IndigoConfiguration.h"

using namespace std;

using namespace Poco;
using namespace Poco::Util;
using namespace Poco::Net;

POCO_DECLARE_EXCEPTION(, ShareNotFoundException, ApplicationException)
POCO_IMPLEMENT_EXCEPTION(ShareNotFoundException, ApplicationException, "ShareNotFoundException")

IndigoRequestHandler::IndigoRequestHandler()
{
}

void IndigoRequestHandler::handleRequest(HTTPServerRequest &request, HTTPServerResponse &response)
{
	logRequest(request);

	const string &method = request.getMethod();

	if (method != HTTPRequest::HTTP_GET)
	{
		sendMethodNotAllowed(response);
		return;
	}

	URI uri;
	try
	{
		uri = request.getURI();
	}
	catch (SyntaxException &se)
	{
		sendBadRequest(response);
		return;
	}

	Path uriPath(uri.getPath(), Path::PATH_UNIX);

	if (!uriPath.isAbsolute())
	{
		sendBadRequest(response);
		return;
	}

	const IndigoConfiguration &configuration = IndigoConfiguration::get();

	try
	{
		if (uriPath.isDirectory() && uriPath.depth() == 0)
		{
			if (configuration.virtualRoot())
			{
				sendVirtualIndex(response);
				return;
			}
		}

		const Path &fsPath = resolveFSPath(uriPath);
		const string &target = fsPath.toString();

		File f(target);
		if (f.isDirectory())
		{
			if (uriPath.isDirectory())
			{
				sendDirectoryIndex(response, target, uriPath.toString(Path::PATH_UNIX));
			}
			else
			{
				Path uriDirPath = uriPath;
				uriDirPath.makeDirectory();
				redirectToDirectory(response, uriDirPath.toString(Path::PATH_UNIX), false);
			}
		}
		else
		{
			sendFile(response, target);
		}
	}
	catch (ShareNotFoundException &snfe)
	{
		sendNotFound(response);
	}
	catch (FileNotFoundException &fnfe)
	{
		sendNotFound(response);
	}
	catch (FileAccessDeniedException &fade)
	{
		sendForbidden(response);
	}
	catch (FileException &fe)
	{
		sendInternalServerError(response);
	}
	catch (PathSyntaxException &pse)
	{
		sendNotImplemented(response);
	}
	catch (...)
	{
		sendInternalServerError(response);
	}
}

Path IndigoRequestHandler::resolveFSPath(const Path &uriPath)
{
	const IndigoConfiguration &configuration = IndigoConfiguration::get();

	const string &shareName = uriPath[0];
	string base = configuration.getSharePath(shareName);
	bool share = true;

	if (base.empty())
	{
		base = configuration.getRoot();
		if (base.empty())
			throw ShareNotFoundException();

		share = false;
	}

	Path fsPath(base);

	if (share)
	{
		fsPath.makeDirectory();

		const int d = uriPath.depth();
		for (int i = 1; i <= d; i++)
			fsPath.pushDirectory(uriPath[i]);
	}
	else
	{
		fsPath.append(uriPath);
	}

	fsPath.makeFile();
	return fsPath;
}

void IndigoRequestHandler::sendFile(HTTPServerResponse &response, const string &path)
{
	const string &ext = Path(path).getExtension();
	const string &mediaType = IndigoConfiguration::get().getMimeType(ext);
	response.sendFile(path, mediaType);
}

void IndigoRequestHandler::sendDirectoryListing(HTTPServerResponse &response, const string &dirURI, const vector<string> &entries)
{
	bool root = (dirURI == "/");

	response.setContentType("text/html");
	response.setContentLength(HTTPResponse::UNKNOWN_CONTENT_LENGTH);
	response.setChunkedTransferEncoding(true);

	ostream &out = response.send();

	out << "" << endl;
	out << "" << endl;
	out << "<title>";
	out << "Index of " << dirURI;
	out << "</title>" << endl;
	out << "" << endl;
	out << "" << endl;
	out << "
";
	out << "Index of " << dirURI;
	out << "
" << endl;

	if (!root)
	{
		out << "<Parent Directory>
" << endl;
	}

	const int l = entries.size();
	for (int i = 0; i < l; i++)
	{
		out << "<a href=\"" << entries[i] << "\">" << entries[i] << "" << "
" << endl;
	}

	out << "" << endl;
	out << "" << endl;
}

string IndigoRequestHandler::findVirtualIndex()
{
	const IndigoConfiguration &configuration = IndigoConfiguration::get();

	const set<string> indexes = configuration.getIndexes();

	set<string>::const_iterator it;
	set<string>::const_iterator end = indexes.end();
	for (it = indexes.begin(); it != end; ++it)
	{
		try
		{
			const Path &index = resolveFSPath(Path("/" + *it, Path::PATH_UNIX));
			File f(index);
			if (!f.isDirectory())
			{
				return index.toString();
			}
		}
		catch (ShareNotFoundException &snfe)
		{
		}
		catch (FileException &fe)
		{
		}
		catch (PathSyntaxException &pse)
		{
		}
	}

	return "";
}

void IndigoRequestHandler::sendVirtualIndex(HTTPServerResponse &response)
{
	const IndigoConfiguration &configuration = IndigoConfiguration::get();

	const string &index = findVirtualIndex();
	if (!index.empty())
	{
		sendFile(response, index);
		return;
	}

	if (!configuration.getAutoIndex())
		throw ShareNotFoundException();

	const set<string> &shares = configuration.getShares();
	vector<string> entries;

	set<string>::const_iterator it;
	const set<string>::const_iterator &end = shares.end();
	for (it = shares.begin(); it != end; ++it)
	{
		const string &shareName = *it;
		try
		{
			const Path &fsPath = resolveFSPath(Path("/" + shareName, Path::PATH_UNIX));
			File f(fsPath);

			if (!f.isHidden())
			{
				string entry = shareName;
				if (f.isDirectory())
					entry += '/';

				entries.push_back(entry);
			}
		}
		catch (ShareNotFoundException &snfe)
		{
		}
		catch (FileException &fe)
		{
		}
		catch (PathSyntaxException &pse)
		{
		}
	}

	sendDirectoryListing(response, "/", entries);
}

string IndigoRequestHandler::findDirectoryIndex(const string &base)
{
	const IndigoConfiguration &configuration = IndigoConfiguration::get();

	const set<string> indexes = configuration.getIndexes(true);

	set<string>::const_iterator it;
	set<string>::const_iterator end = indexes.end();
	for (it = indexes.begin(); it != end; ++it)
	{
		try
		{
			string index = base;
			if (index[index.length() - 1] != Path::separator())
				index += Path::separator();
			index += *it;

			File f(index);
			if (!f.isDirectory())
			{
				return index;
			}
		}
		catch (FileException &fe)
		{
		}
		catch (PathSyntaxException &pse)
		{
		}
	}

	return "";
}

void IndigoRequestHandler::sendDirectoryIndex(HTTPServerResponse &response, const string &path, const string &dirURI)
{
	const IndigoConfiguration &configuration = IndigoConfiguration::get();

	const string &index = findDirectoryIndex(path);
	if (!index.empty())
	{
		sendFile(response, index);
		return;
	}

	if (!configuration.getAutoIndex())
		throw FileNotFoundException();

	vector<string> entries;

	DirectoryIterator it(path);
	DirectoryIterator end;
	while (it != end)
	{
		try
		{
			if (!it->isHidden())
			{
				string entry = it.name();
				if (it->isDirectory())
					entry += '/';

				entries.push_back(entry);
			}
		}
		catch (FileException &fe)
		{
		}
		catch (PathSyntaxException &pse)
		{
		}

		++it;
	}

	sendDirectoryListing(response, dirURI, entries);
}

void IndigoRequestHandler::redirectToDirectory(HTTPServerResponse &response, const string &dirURI, bool permanent)
{
	if (!permanent)
	{
		response.redirect(dirURI);
	}
	else
	{
		response.setStatusAndReason(HTTPResponse::HTTP_MOVED_PERMANENTLY);
		response.setContentLength(0);
		response.setChunkedTransferEncoding(false);
		response.set("Location", dirURI);
		response.send();
	}
}

void IndigoRequestHandler::logRequest(const HTTPServerRequest &request)
{
	const ServerApplication &app = dynamic_cast<ServerApplication &>(Application::instance());
	if (app.isInteractive())
	{
		const string &method = request.getMethod();
		const string &uri = request.getURI();
		const string &host = request.clientAddress().host().toString();

		string logString = host + " - " + method + " " + uri;

		app.logger().information(logString);
	}
}

void IndigoRequestHandler::sendError(HTTPServerResponse &response, int code)
{
	if (response.sent())
		return;

	response.setStatusAndReason(HTTPResponse::HTTPStatus(code));
	response.setChunkedTransferEncoding(true);
	response.setContentType("text/html");

	const string &reason = response.getReason();

	ostream &out = response.send();
	out << "";
	out << "<title>" + NumberFormatter::format(code) + " " + reason + "</title>";
	out << "
" + reason + "
";
	out << "";
}

void IndigoRequestHandler::sendMethodNotAllowed(HTTPServerResponse &response)
{
	sendError(response, HTTPResponse::HTTP_METHOD_NOT_ALLOWED);
}

void IndigoRequestHandler::sendRequestURITooLong(HTTPServerResponse &response)
{
	sendError(response, HTTPResponse::HTTP_REQUESTURITOOLONG);
}

void IndigoRequestHandler::sendBadRequest(HTTPServerResponse &response)
{
	sendError(response, HTTPResponse::HTTP_BAD_REQUEST);
}

void IndigoRequestHandler::sendNotImplemented(HTTPServerResponse &response)
{
	sendError(response, HTTPResponse::HTTP_NOT_IMPLEMENTED);
}

void IndigoRequestHandler::sendNotFound(HTTPServerResponse &response)
{
	sendError(response, HTTPResponse::HTTP_NOT_FOUND);
}

void IndigoRequestHandler::sendForbidden(HTTPServerResponse &response)
{
	sendError(response, HTTPResponse::HTTP_FORBIDDEN);
}

void IndigoRequestHandler::sendInternalServerError(HTTPServerResponse &response)
{
	sendError(response, HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
}
<commit_msg>Check if the file is a regular file before treating it as a directory index.<commit_after>
/*
 * Copyright (C) 2010, Victor Semionov
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 */

#include <climits>

#include <string>
#include <vector>
#include <set>
#include <ostream>
#include <iostream>

#include "Poco/Util/ServerApplication.h"
#include "Poco/URI.h"
#include "Poco/File.h"
#include "Poco/DirectoryIterator.h"
#include "Poco/NumberFormatter.h"

#include "IndigoRequestHandler.h"
#include "IndigoConfiguration.h"

using namespace std;

using namespace Poco;
using namespace Poco::Util;
using namespace Poco::Net;

POCO_DECLARE_EXCEPTION(, ShareNotFoundException, ApplicationException)
POCO_IMPLEMENT_EXCEPTION(ShareNotFoundException, ApplicationException, "ShareNotFoundException")

IndigoRequestHandler::IndigoRequestHandler()
{
}

void IndigoRequestHandler::handleRequest(HTTPServerRequest &request, HTTPServerResponse &response)
{
	logRequest(request);

	const string &method = request.getMethod();

	if (method != HTTPRequest::HTTP_GET)
	{
		sendMethodNotAllowed(response);
		return;
	}

	URI uri;
	try
	{
		uri = request.getURI();
	}
	catch (SyntaxException &se)
	{
		sendBadRequest(response);
		return;
	}

	Path uriPath(uri.getPath(), Path::PATH_UNIX);

	if (!uriPath.isAbsolute())
	{
		sendBadRequest(response);
		return;
	}

	const IndigoConfiguration &configuration = IndigoConfiguration::get();

	try
	{
		if (uriPath.isDirectory() && uriPath.depth() == 0)
		{
			if (configuration.virtualRoot())
			{
				sendVirtualIndex(response);
				return;
			}
		}

		const Path &fsPath = resolveFSPath(uriPath);
		const string &target = fsPath.toString();

		File f(target);
		if (f.isDirectory())
		{
			if (uriPath.isDirectory())
			{
				sendDirectoryIndex(response, target, uriPath.toString(Path::PATH_UNIX));
			}
			else
			{
				Path uriDirPath = uriPath;
				uriDirPath.makeDirectory();
				redirectToDirectory(response, uriDirPath.toString(Path::PATH_UNIX), false);
			}
		}
		else
		{
			sendFile(response, target);
		}
	}
	catch (ShareNotFoundException &snfe)
	{
		sendNotFound(response);
	}
	catch (FileNotFoundException &fnfe)
	{
		sendNotFound(response);
	}
	catch (FileAccessDeniedException &fade)
	{
		sendForbidden(response);
	}
	catch (FileException &fe)
	{
		sendInternalServerError(response);
	}
	catch (PathSyntaxException &pse)
	{
		sendNotImplemented(response);
	}
	catch (...)
	{
		sendInternalServerError(response);
	}
}

Path IndigoRequestHandler::resolveFSPath(const Path &uriPath)
{
	const IndigoConfiguration &configuration = IndigoConfiguration::get();

	const string &shareName = uriPath[0];
	string base = configuration.getSharePath(shareName);
	bool share = true;

	if (base.empty())
	{
		base = configuration.getRoot();
		if (base.empty())
			throw ShareNotFoundException();

		share = false;
	}

	Path fsPath(base);

	if (share)
	{
		fsPath.makeDirectory();

		const int d = uriPath.depth();
		for (int i = 1; i <= d; i++)
			fsPath.pushDirectory(uriPath[i]);
	}
	else
	{
		fsPath.append(uriPath);
	}

	fsPath.makeFile();
	return fsPath;
}

void IndigoRequestHandler::sendFile(HTTPServerResponse &response, const string &path)
{
	const string &ext = Path(path).getExtension();
	const string &mediaType = IndigoConfiguration::get().getMimeType(ext);
	response.sendFile(path, mediaType);
}

void IndigoRequestHandler::sendDirectoryListing(HTTPServerResponse &response, const string &dirURI, const vector<string> &entries)
{
	bool root = (dirURI == "/");

	response.setContentType("text/html");
	response.setContentLength(HTTPResponse::UNKNOWN_CONTENT_LENGTH);
	response.setChunkedTransferEncoding(true);

	ostream &out = response.send();

	out << "" << endl;
	out << "" << endl;
	out << "<title>";
	out << "Index of " << dirURI;
	out << "</title>" << endl;
	out << "" << endl;
	out << "" << endl;
	out << "
";
	out << "Index of " << dirURI;
	out << "
" << endl;

	if (!root)
	{
		out << "<Parent Directory>
" << endl;
	}

	const int l = entries.size();
	for (int i = 0; i < l; i++)
	{
		out << "<a href=\"" << entries[i] << "\">" << entries[i] << "" << "
" << endl;
	}

	out << "" << endl;
	out << "" << endl;
}

string IndigoRequestHandler::findVirtualIndex()
{
	const IndigoConfiguration &configuration = IndigoConfiguration::get();

	const set<string> indexes = configuration.getIndexes();

	set<string>::const_iterator it;
	set<string>::const_iterator end = indexes.end();
	for (it = indexes.begin(); it != end; ++it)
	{
		try
		{
			const Path &index = resolveFSPath(Path("/" + *it, Path::PATH_UNIX));
			File f(index);
			if (f.isFile())
			{
				return index.toString();
			}
		}
		catch (ShareNotFoundException &snfe)
		{
		}
		catch (FileException &fe)
		{
		}
		catch (PathSyntaxException &pse)
		{
		}
	}

	return "";
}

void IndigoRequestHandler::sendVirtualIndex(HTTPServerResponse &response)
{
	const IndigoConfiguration &configuration = IndigoConfiguration::get();

	const string &index = findVirtualIndex();
	if (!index.empty())
	{
		sendFile(response, index);
		return;
	}

	if (!configuration.getAutoIndex())
		throw ShareNotFoundException();

	const set<string> &shares = configuration.getShares();
	vector<string> entries;

	set<string>::const_iterator it;
	const set<string>::const_iterator &end = shares.end();
	for (it = shares.begin(); it != end; ++it)
	{
		const string &shareName = *it;
		try
		{
			const Path &fsPath = resolveFSPath(Path("/" + shareName, Path::PATH_UNIX));
			File f(fsPath);

			if (!f.isHidden())
			{
				string entry = shareName;
				if (f.isDirectory())
					entry += '/';

				entries.push_back(entry);
			}
		}
		catch (ShareNotFoundException &snfe)
		{
		}
		catch (FileException &fe)
		{
		}
		catch (PathSyntaxException &pse)
		{
		}
	}

	sendDirectoryListing(response, "/", entries);
}

string IndigoRequestHandler::findDirectoryIndex(const string &base)
{
	const IndigoConfiguration &configuration = IndigoConfiguration::get();

	const set<string> indexes = configuration.getIndexes(true);

	set<string>::const_iterator it;
	set<string>::const_iterator end = indexes.end();
	for (it = indexes.begin(); it != end; ++it)
	{
		try
		{
			string index = base;
			if (index[index.length() - 1] != Path::separator())
				index += Path::separator();
			index += *it;

			File f(index);
			if (f.isFile())
			{
				return index;
			}
		}
		catch (FileException &fe)
		{
		}
		catch (PathSyntaxException &pse)
		{
		}
	}

	return "";
}

void IndigoRequestHandler::sendDirectoryIndex(HTTPServerResponse &response, const string &path, const string &dirURI)
{
	const IndigoConfiguration &configuration = IndigoConfiguration::get();

	const string &index = findDirectoryIndex(path);
	if (!index.empty())
	{
		sendFile(response, index);
		return;
	}

	if (!configuration.getAutoIndex())
		throw FileNotFoundException();

	vector<string> entries;

	DirectoryIterator it(path);
	DirectoryIterator end;
	while (it != end)
	{
		try
		{
			if (!it->isHidden())
			{
				string entry = it.name();
				if (it->isDirectory())
					entry += '/';

				entries.push_back(entry);
			}
		}
		catch (FileException &fe)
		{
		}
		catch (PathSyntaxException &pse)
		{
		}

		++it;
	}

	sendDirectoryListing(response, dirURI, entries);
}

void IndigoRequestHandler::redirectToDirectory(HTTPServerResponse &response, const string &dirURI, bool permanent)
{
	if (!permanent)
	{
		response.redirect(dirURI);
	}
	else
	{
		response.setStatusAndReason(HTTPResponse::HTTP_MOVED_PERMANENTLY);
		response.setContentLength(0);
		response.setChunkedTransferEncoding(false);
		response.set("Location", dirURI);
		response.send();
	}
}

void IndigoRequestHandler::logRequest(const HTTPServerRequest &request)
{
	const ServerApplication &app = dynamic_cast<ServerApplication &>(Application::instance());
	if (app.isInteractive())
	{
		const string &method = request.getMethod();
		const string &uri = request.getURI();
		const string &host = request.clientAddress().host().toString();

		string logString = host + " - " + method + " " + uri;

		app.logger().information(logString);
	}
}

void IndigoRequestHandler::sendError(HTTPServerResponse &response, int code)
{
	if (response.sent())
		return;

	response.setStatusAndReason(HTTPResponse::HTTPStatus(code));
	response.setChunkedTransferEncoding(true);
	response.setContentType("text/html");

	const string &reason = response.getReason();

	ostream &out = response.send();
	out << "";
	out << "<title>" + NumberFormatter::format(code) + " " + reason + "</title>";
	out << "
" + reason + "
";
	out << "";
}

void IndigoRequestHandler::sendMethodNotAllowed(HTTPServerResponse &response)
{
	sendError(response, HTTPResponse::HTTP_METHOD_NOT_ALLOWED);
}

void IndigoRequestHandler::sendRequestURITooLong(HTTPServerResponse &response)
{
	sendError(response, HTTPResponse::HTTP_REQUESTURITOOLONG);
}

void IndigoRequestHandler::sendBadRequest(HTTPServerResponse &response)
{
	sendError(response, HTTPResponse::HTTP_BAD_REQUEST);
}

void IndigoRequestHandler::sendNotImplemented(HTTPServerResponse &response)
{
	sendError(response, HTTPResponse::HTTP_NOT_IMPLEMENTED);
}

void IndigoRequestHandler::sendNotFound(HTTPServerResponse &response)
{
	sendError(response, HTTPResponse::HTTP_NOT_FOUND);
}

void IndigoRequestHandler::sendForbidden(HTTPServerResponse &response)
{
	sendError(response, HTTPResponse::HTTP_FORBIDDEN);
}

void IndigoRequestHandler::sendInternalServerError(HTTPServerResponse &response)
{
	sendError(response, HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <mpi.h>

#define MASTER 0
#define TAG 0
#define MAX 25
const long long MSGSIZE = 99999999;

int main(int argc, char *argv[]) {
  int my_rank, source, num_nodes;
  char *message = new char[MSGSIZE];

  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
  MPI_Comm_size(MPI_COMM_WORLD, &num_nodes);
  double program_start = MPI_Wtime();
  if (my_rank != MASTER) {
    double message_sent = MPI_Wtime();
    for (long long i = 0; i < MSGSIZE; i++) {
      message[i] = 'a' + std::rand() % 26;
    }
    MPI_Send(&message, MSGSIZE, MPI_CHAR, MASTER, TAG, MPI_COMM_WORLD);

  } else {
    printf("Num_nodes: %d\n", num_nodes);
    printf("Hello from Master (process %d)!\n", my_rank);
    MPI_Status status;
    for (source = 1; source < num_nodes; source++) {
      MPI_Recv(&message, MSGSIZE, MPI_CHAR, source, TAG, MPI_COMM_WORLD,
               &status);
    }

    double program_end = MPI_Wtime();
    double program_elapsed = program_end - program_start;
    printf("Nodes, Message Size, Program Execution Time, %d,%lld,%f\n",
           num_nodes, MSGSIZE, program_elapsed);
  }

  MPI_Finalize();

  return 0;
}
<commit_msg>try lowering message size<commit_after>#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <mpi.h>

#define MASTER 0
#define TAG 0
#define MAX 25
const long long MSGSIZE = 9999999;

int main(int argc, char *argv[]) {
  int my_rank, source, num_nodes;
  char *message = new char[MSGSIZE];

  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
  MPI_Comm_size(MPI_COMM_WORLD, &num_nodes);
  double program_start = MPI_Wtime();
  if (my_rank != MASTER) {
    double message_sent = MPI_Wtime();
    for (long long i = 0; i < MSGSIZE; i++) {
      message[i] = 'a' + std::rand() % 26;
    }
    MPI_Send(&message, MSGSIZE, MPI_CHAR, MASTER, TAG, MPI_COMM_WORLD);

  } else {
    printf("Num_nodes: %d\n", num_nodes);
    printf("Hello from Master (process %d)!\n", my_rank);
    MPI_Status status;
    for (source = 1; source < num_nodes; source++) {
      MPI_Recv(&message, MSGSIZE, MPI_CHAR, source, TAG, MPI_COMM_WORLD,
               &status);
    }

    double program_end = MPI_Wtime();
    double program_elapsed = program_end - program_start;
    printf("Nodes, Message Size, Program Execution Time, %d,%lld,%f\n",
           num_nodes, MSGSIZE, program_elapsed);
  }

  MPI_Finalize();

  return 0;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <mpi.h>

#define MASTER 0
#define TAG 0
#define MAX 25
const long long MSGSIZE = 999999;

int main(int argc, char *argv[]) {
  int my_rank, source, num_nodes;
  char message[MSGSIZE];

  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
  MPI_Comm_size(MPI_COMM_WORLD, &num_nodes);
  double program_start = MPI_Wtime();
  if (my_rank != MASTER) {
    double message_sent = MPI_Wtime();
    for (long long i = 0; i < MSGSIZE; i++) {
      message[i] = 'a' + rand() % 26;
    }
    MPI_Send(&message, MSGSIZE, MPI_CHAR, MASTER, TAG, MPI_COMM_WORLD);

  } else {

    printf("Num_nodes: %d\n", num_nodes);
    printf("Hello from Master (process %d)!\n", my_rank);
    char message[MSGSIZE];
    MPI_Status status;
    for (source = 1; source < num_nodes; source++) {
      MPI_Recv(&message, MSGSIZE, MPI_CHAR, source, TAG, MPI_COMM_WORLD,
               &status);
    }

    double program_end = MPI_Wtime();
    double program_elapsed = program_end - program_start;
    printf("Nodes, Message Size, Program Execution Time, %d,%lld,%f\n",
           num_nodes, MSGSIZE, program_elapsed);
  }

  MPI_Finalize();

  return 0;
}
<commit_msg>increase message size<commit_after>#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <mpi.h>

#define MASTER 0
#define TAG 0
#define MAX 25
const long long MSGSIZE = 999999999;

int main(int argc, char *argv[]) {
  int my_rank, source, num_nodes;
  char message[MSGSIZE];

  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
  MPI_Comm_size(MPI_COMM_WORLD, &num_nodes);
  double program_start = MPI_Wtime();
  if (my_rank != MASTER) {
    double message_sent = MPI_Wtime();
    for (long long i = 0; i < MSGSIZE; i++) {
      message[i] = 'a' + rand() % 26;
    }
    MPI_Send(&message, MSGSIZE, MPI_CHAR, MASTER, TAG, MPI_COMM_WORLD);

  } else {

    printf("Num_nodes: %d\n", num_nodes);
    printf("Hello from Master (process %d)!\n", my_rank);
    char message[MSGSIZE];
    MPI_Status status;
    for (source = 1; source < num_nodes; source++) {
      MPI_Recv(&message, MSGSIZE, MPI_CHAR, source, TAG, MPI_COMM_WORLD,
               &status);
    }

    double program_end = MPI_Wtime();
    double program_elapsed = program_end - program_start;
    printf("Nodes, Message Size, Program Execution Time, %d,%lld,%f\n",
           num_nodes, MSGSIZE, program_elapsed);
  }

  MPI_Finalize();

  return 0;
}
<|endoftext|>