<commit_before>#ifndef ITER_FILTER_H_
#define ITER_FILTER_H_

#include "iterbase.hpp"

#include <utility>
#include <iterator>
#include <initializer_list>

namespace iter {

  // Forward declarations of Filter and filter
  template <typename FilterFunc, typename Container>
  class Filter;

  template <typename FilterFunc, typename Container>
  Filter<FilterFunc, Container> filter(FilterFunc, Container&&);

  template <typename FilterFunc, typename T>
  Filter<FilterFunc, std::initializer_list<T>> filter(
      FilterFunc, std::initializer_list<T>);

  template <typename FilterFunc, typename Container>
  class Filter {
   private:
    Container container;
    FilterFunc filter_func;

    // The filter function is the only thing allowed to create a Filter
    friend Filter filter<FilterFunc, Container>(FilterFunc, Container&&);

    template <typename FF, typename T>
    friend Filter<FF, std::initializer_list<T>> filter(
        FF, std::initializer_list<T>);

    // Value constructor for use only in the filter function
    Filter(FilterFunc in_filter_func, Container&& in_container)
        : container(std::forward<Container>(in_container)),
          filter_func(in_filter_func) {}

   public:
    class Iterator : public std::iterator<std::input_iterator_tag,
                         iterator_traits_deref<Container>> {
     protected:
      using Holder = DerefHolder<iterator_deref<Container>>;
      iterator_type<Container> sub_iter;
      iterator_type<Container> sub_end;
      Holder item;
      FilterFunc* filter_func;

      void inc_sub_iter() {
        ++this->sub_iter;
        if (this->sub_iter != this->sub_end) {
          this->item.reset(*this->sub_iter);
        }
      }

      // increment until the iterator points to is true on the
      // predicate.  Called by constructor and operator++
      void skip_failures() {
        while (this->sub_iter != this->sub_end
               && !(*this->filter_func)(this->item.get())) {
          this->inc_sub_iter();
        }
      }

     public:
      Iterator(iterator_type<Container> iter, iterator_type<Container> end,
          FilterFunc& in_filter_func)
          : sub_iter{iter}, sub_end{end}, filter_func(&in_filter_func) {
        if (this->sub_iter != this->sub_end) {
          this->item.reset(*this->sub_iter);
        }
        this->skip_failures();
      }

      typename Holder::reference operator*() {
        return this->item.get();
      }

      typename Holder::pointer operator->() {
        return this->item.get_ptr();
      }

      Iterator& operator++() {
        this->inc_sub_iter();
        this->skip_failures();
        return *this;
      }

      Iterator operator++(int) {
        auto ret = *this;
        ++*this;
        return ret;
      }

      bool operator!=(const Iterator& other) const {
        return this->sub_iter != other.sub_iter;
      }

      bool operator==(const Iterator& other) const {
        return !(*this != other);
      }
    };

    Iterator begin() {
      return {std::begin(this->container), std::end(this->container),
          this->filter_func};
    }

    Iterator end() {
      return {std::end(this->container), std::end(this->container),
          this->filter_func};
    }
  };

  // Helper function to instantiate a Filter
  template <typename FilterFunc, typename Container>
  Filter<FilterFunc, Container> filter(
      FilterFunc filter_func, Container&& container) {
    return {filter_func, std::forward<Container>(container)};
  }

  template <typename FilterFunc, typename T>
  Filter<FilterFunc, std::initializer_list<T>> filter(
      FilterFunc filter_func, std::initializer_list<T> il) {
    return {filter_func, std::move(il)};
  }

  namespace detail {

    template <typename T>
    bool boolean_cast(const T& t) {
      return bool(t);
    }

    template <typename Container>
    class BoolTester {
     public:
      bool operator()(const iterator_deref<Container> item) const {
        return bool(item);
      }
    };
  }

  template <typename Container>
  auto filter(Container&& container) -> decltype(filter(
      detail::BoolTester<Container>(), std::forward<Container>(container))) {
    return filter(
        detail::BoolTester<Container>(), std::forward<Container>(container));
  }

  template <typename T>
  auto filter(std::initializer_list<T> il) -> decltype(
      filter(detail::BoolTester<std::initializer_list<T>>(), std::move(il))) {
    return filter(
        detail::BoolTester<std::initializer_list<T>>(), std::move(il));
  }
}

#endif
<commit_msg>moves Filtered into impl { }<commit_after>#ifndef ITER_FILTER_H_
#define ITER_FILTER_H_

#include "iterbase.hpp"

#include <utility>
#include <iterator>
#include <initializer_list>

namespace iter {
  namespace impl {
    template <typename FilterFunc, typename Container>
    class Filtered;
  }

  template <typename FilterFunc, typename Container>
  impl::Filtered<FilterFunc, Container> filter(FilterFunc, Container&&);

  template <typename FilterFunc, typename T>
  impl::Filtered<FilterFunc, std::initializer_list<T>> filter(
      FilterFunc, std::initializer_list<T>);
}

template <typename FilterFunc, typename Container>
class iter::impl::Filtered {
 private:
  Container container;
  FilterFunc filter_func;

  // The filter function is the only thing allowed to create a Filtered
  friend Filtered iter::filter<FilterFunc, Container>(FilterFunc, Container&&);

  template <typename FF, typename T>
  friend Filtered<FF, std::initializer_list<T>> iter::filter(
      FF, std::initializer_list<T>);

  // Value constructor for use only in the filter function
  Filtered(FilterFunc in_filter_func, Container&& in_container)
      : container(std::forward<Container>(in_container)),
        filter_func(in_filter_func) {}

 public:
  class Iterator : public std::iterator<std::input_iterator_tag,
                       iterator_traits_deref<Container>> {
   protected:
    using Holder = DerefHolder<iterator_deref<Container>>;
    iterator_type<Container> sub_iter;
    iterator_type<Container> sub_end;
    Holder item;
    FilterFunc* filter_func;

    void inc_sub_iter() {
      ++this->sub_iter;
      if (this->sub_iter != this->sub_end) {
        this->item.reset(*this->sub_iter);
      }
    }

    // increment until the iterator points to is true on the
    // predicate.  Called by constructor and operator++
    void skip_failures() {
      while (this->sub_iter != this->sub_end
             && !(*this->filter_func)(this->item.get())) {
        this->inc_sub_iter();
      }
    }

   public:
    Iterator(iterator_type<Container> iter, iterator_type<Container> end,
        FilterFunc& in_filter_func)
        : sub_iter{iter}, sub_end{end}, filter_func(&in_filter_func) {
      if (this->sub_iter != this->sub_end) {
        this->item.reset(*this->sub_iter);
      }
      this->skip_failures();
    }

    typename Holder::reference operator*() {
      return this->item.get();
    }

    typename Holder::pointer operator->() {
      return this->item.get_ptr();
    }

    Iterator& operator++() {
      this->inc_sub_iter();
      this->skip_failures();
      return *this;
    }

    Iterator operator++(int) {
      auto ret = *this;
      ++*this;
      return ret;
    }

    bool operator!=(const Iterator& other) const {
      return this->sub_iter != other.sub_iter;
    }

    bool operator==(const Iterator& other) const {
      return !(*this != other);
    }
  };

  Iterator begin() {
    return {std::begin(this->container), std::end(this->container),
        this->filter_func};
  }

  Iterator end() {
    return {std::end(this->container), std::end(this->container),
        this->filter_func};
  }
};

template <typename FilterFunc, typename Container>
iter::impl::Filtered<FilterFunc, Container> iter::filter(
    FilterFunc filter_func, Container&& container) {
  return {filter_func, std::forward<Container>(container)};
}

template <typename FilterFunc, typename T>
iter::impl::Filtered<FilterFunc, std::initializer_list<T>> iter::filter(
    FilterFunc filter_func, std::initializer_list<T> il) {
  return {filter_func, std::move(il)};
}

namespace iter {
  namespace detail {

    template <typename T>
    bool boolean_cast(const T& t) {
      return bool(t);
    }

    template <typename Container>
    class BoolTester {
     public:
      bool operator()(const iterator_deref<Container> item) const {
        return bool(item);
      }
    };
  }

  template <typename Container>
  auto filter(Container&& container) -> decltype(filter(
      detail::BoolTester<Container>(), std::forward<Container>(container))) {
    return filter(
        detail::BoolTester<Container>(), std::forward<Container>(container));
  }

  template <typename T>
  auto filter(std::initializer_list<T> il) -> decltype(
      filter(detail::BoolTester<std::initializer_list<T>>(), std::move(il))) {
    return filter(
        detail::BoolTester<std::initializer_list<T>>(), std::move(il));
  }
}

#endif
<|endoftext|>


<commit_before>/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Data Differential YATL (i.e. libtest)  library
 *
 *  Copyright (C) 2012 Data Differential, http://datadifferential.com/
 *
 *  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.
 *
 *      * The names of its contributors may not be used to endorse or
 *  promote products derived from this software without specific prior
 *  written permission.
 *
 *  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
 *  OWNER 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 <config.h>
#include <libtest/common.h>

#include <cstdlib>
#include <unistd.h>

namespace libtest {

bool has_libmemcached(void)
{
  if (HAVE_LIBMEMCACHED)
  {
    return true;
  }

  return false;
}

bool has_libdrizzle(void)
{
  if (HAVE_LIBDRIZZLE)
  {
    return true;
  }

  return false;
}

bool has_postgres_support(void)
{
  if (getenv("POSTGES_IS_RUNNING_AND_SETUP"))
  {
    if (HAVE_LIBPQ)
    {
      return true;
    }
  }

  return false;
}

bool has_gearmand()
{
  if (HAVE_GEARMAND_BINARY)
  {
    std::stringstream arg_buffer;

    if (getenv("PWD"))
    {
      arg_buffer << getenv("PWD");
      arg_buffer << "/";
    }
    arg_buffer << GEARMAND_BINARY;

    if (access(arg_buffer.str().c_str(), X_OK) == 0)
    {
      return true;
    }
  }

  return false;
}

bool has_drizzled()
{
  if (HAVE_DRIZZLED_BINARY)
  {
    if (access(DRIZZLED_BINARY, X_OK) == 0)
    {
      return true;
    }
  }

  return false;
}

bool has_memcached()
{
  if (HAVE_MEMCACHED_BINARY)
  {
    std::stringstream arg_buffer;

    if (getenv("PWD") and strcmp(MEMCACHED_BINARY, "memcached/memcached") == 0)
    {
      arg_buffer << getenv("PWD");
      arg_buffer << "/";
    }
    arg_buffer << MEMCACHED_BINARY;

    if (access(arg_buffer.str().c_str(), X_OK) == 0)
    {
      return true;
    }
  }

  return false;
}

bool has_memcached_sasl()
{
  if (HAVE_MEMCACHED_SASL_BINARY)
  {
    if (access(MEMCACHED_SASL_BINARY, X_OK) == 0)
    {
      return true;
    }
  }

  return false;
}

} // namespace libtest
<commit_msg>Make sure that gearman, is libtool'ized correctly.<commit_after>/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Data Differential YATL (i.e. libtest)  library
 *
 *  Copyright (C) 2012 Data Differential, http://datadifferential.com/
 *
 *  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.
 *
 *      * The names of its contributors may not be used to endorse or
 *  promote products derived from this software without specific prior
 *  written permission.
 *
 *  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
 *  OWNER 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 <config.h>
#include <libtest/common.h>

#include <cstdlib>
#include <unistd.h>

namespace libtest {

bool has_libmemcached(void)
{
  if (HAVE_LIBMEMCACHED)
  {
    return true;
  }

  return false;
}

bool has_libdrizzle(void)
{
  if (HAVE_LIBDRIZZLE)
  {
    return true;
  }

  return false;
}

bool has_postgres_support(void)
{
  if (getenv("POSTGES_IS_RUNNING_AND_SETUP"))
  {
    if (HAVE_LIBPQ)
    {
      return true;
    }
  }

  return false;
}

bool has_gearmand()
{
  if (HAVE_GEARMAND_BINARY)
  {
    std::stringstream arg_buffer;

    if (getenv("PWD") and strcmp(MEMCACHED_BINARY, "gearmand/gearmand") == 0)
    {
      arg_buffer << getenv("PWD");
      arg_buffer << "/";
    }
    arg_buffer << GEARMAND_BINARY;

    if (access(arg_buffer.str().c_str(), X_OK) == 0)
    {
      return true;
    }
  }

  return false;
}

bool has_drizzled()
{
  if (HAVE_DRIZZLED_BINARY)
  {
    if (access(DRIZZLED_BINARY, X_OK) == 0)
    {
      return true;
    }
  }

  return false;
}

bool has_memcached()
{
  if (HAVE_MEMCACHED_BINARY)
  {
    std::stringstream arg_buffer;

    if (getenv("PWD") and strcmp(MEMCACHED_BINARY, "memcached/memcached") == 0)
    {
      arg_buffer << getenv("PWD");
      arg_buffer << "/";
    }
    arg_buffer << MEMCACHED_BINARY;

    if (access(arg_buffer.str().c_str(), X_OK) == 0)
    {
      return true;
    }
  }

  return false;
}

bool has_memcached_sasl()
{
  if (HAVE_MEMCACHED_SASL_BINARY)
  {
    if (access(MEMCACHED_SASL_BINARY, X_OK) == 0)
    {
      return true;
    }
  }

  return false;
}

} // namespace libtest
<|endoftext|>


<commit_before>#include "parse.hpp"

#include "sexpr.hpp"
#include "syntax.hpp"

namespace lisp {

  parse::any<sexpr> parser() {

    using namespace parse;

    const auto alpha = debug("alpha") >>= chr<std::isalpha>();
    const auto alnum = debug("alnum") >>= chr<std::isalnum>();
    const auto space = debug("space") >>= chr<std::isspace>();

    const auto dquote = chr('"');

    // const auto endl = chr('\n');
    // const auto comment = (chr(';'), kleene(!endl), endl);

    const auto as_sexpr = cast<sexpr>();

    const auto real = debug("real") >>=
      lit<lisp::real>() >> as_sexpr;

    const auto integer = debug("integer") >>=
      lit<lisp::integer>() >> as_sexpr;

    const auto symbol = debug("symbol") >>=
      no_skip(alpha >> [alnum](char first) {
          return *alnum >> [first](std::deque<char>&& chars) {
            chars.emplace_front(first);
            const lisp::string str(chars.begin(), chars.end());
            return pure<sexpr>( lisp::symbol(str) );
          };
        });

    const auto string = debug("string") >>=
      no_skip( (dquote, *!dquote) >> [dquote](std::deque<char>&& chars) {
          ref<lisp::string> str = make_ref<lisp::string>(chars.begin(), chars.end());
          return dquote, pure<sexpr>(str);
        });

    const auto atom = debug("atom") >>=
      string | symbol | integer | real;

    struct expr_tag;
    rec<sexpr, expr_tag> expr;

    const auto list = debug("list") >>=
      no_skip( (chr('('), *space, expr % +space) >> [space](std::deque<sexpr>&& terms) {
          return *space, chr(')'), pure<sexpr>(lisp::make_list<sexpr>(terms.begin(), terms.end()));
        });

    const auto quote = chr('\'');
    const auto quoted_expr = no_skip(quote >> then(expr) >> [](sexpr&& e) {
        return pure<sexpr>( lisp::symbol(kw::quote) >>= e >>= sexpr::list() );
      });

    expr = debug("expr") >>=
      atom | list | quoted_expr;

    return expr;
  }

}
<commit_msg>fixed grammar for reals<commit_after>#include "parse.hpp"

#include "sexpr.hpp"
#include "syntax.hpp"

namespace lisp {

  parse::any<sexpr> parser() {

    using namespace parse;

    const auto alpha = debug("alpha") >>= chr<std::isalpha>();
    const auto alnum = debug("alnum") >>= chr<std::isalnum>();
    const auto space = debug("space") >>= chr<std::isspace>();

    const auto dquote = chr('"');

    // const auto endl = chr('\n');
    // const auto comment = (chr(';'), kleene(!endl), endl);

    const auto as_sexpr = cast<sexpr>();

    const auto real = debug("real") >>=
      lit<lisp::real>() >> as_sexpr;

    const auto integer = debug("integer") >>=
      lit<lisp::integer>() >> as_sexpr;

    const auto symbol = debug("symbol") >>=
      no_skip(alpha >> [alnum](char first) {
          return *alnum >> [first](std::deque<char>&& chars) {
            chars.emplace_front(first);
            const lisp::string str(chars.begin(), chars.end());
            return pure<sexpr>( lisp::symbol(str) );
          };
        });

    const auto string = debug("string") >>=
      no_skip( (dquote, *!dquote) >> [dquote](std::deque<char>&& chars) {
          ref<lisp::string> str = make_ref<lisp::string>(chars.begin(), chars.end());
          return dquote, pure<sexpr>(str);
        });

    const auto atom = debug("atom") >>=
      string | symbol | real | integer;

    struct expr_tag;
    rec<sexpr, expr_tag> expr;

    const auto list = debug("list") >>=
      no_skip( (chr('('), *space, expr % +space) >> [space](std::deque<sexpr>&& terms) {
          return *space, chr(')'), pure<sexpr>(lisp::make_list<sexpr>(terms.begin(), terms.end()));
        });

    const auto quote = chr('\'');
    const auto quoted_expr = no_skip(quote >> then(expr) >> [](sexpr&& e) {
        return pure<sexpr>( lisp::symbol(kw::quote) >>= e >>= sexpr::list() );
      });

    expr = debug("expr") >>=
      atom | list | quoted_expr;

    return expr;
  }

}
<|endoftext|>


<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use these files 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 "pch.h"

#include "CanvasAnimatedControl.h"
#include "CanvasGameLoop.h"

using namespace ::ABI::Microsoft::Graphics::Canvas;
using namespace ::ABI::Microsoft::Graphics::Canvas::UI;
using namespace ::ABI::Microsoft::Graphics::Canvas::UI::Xaml;
using namespace ::Microsoft::WRL::Wrappers;

class CanvasAnimatedControlAdapter : public BaseControlAdapter<CanvasAnimatedControlTraits>,
    public std::enable_shared_from_this<CanvasAnimatedControlAdapter>
{
    ComPtr<IThreadPoolStatics> m_threadPoolStatics;
    ComPtr<ICanvasSwapChainFactory> m_canvasSwapChainFactory;
    std::shared_ptr<CanvasSwapChainPanelAdapter> m_canvasSwapChainPanelAdapter;
    ComPtr<IActivationFactory> m_canvasSwapChainPanelActivationFactory;

public:
    CanvasAnimatedControlAdapter(IThreadPoolStatics* threadPoolStatics)
        : m_threadPoolStatics(threadPoolStatics)
        , m_canvasSwapChainPanelAdapter(std::make_shared<CanvasSwapChainPanelAdapter>())
    {
        auto& module = Module<InProc>::GetModule();

        ComPtr<IActivationFactory> swapChainActivationFactory;

        ThrowIfFailed(module.GetActivationFactory(
            HStringReference(RuntimeClass_Microsoft_Graphics_Canvas_CanvasSwapChain).Get(),
            &swapChainActivationFactory));

        m_canvasSwapChainFactory = As<ICanvasSwapChainFactory>(swapChainActivationFactory);

        ThrowIfFailed(module.GetActivationFactory(
            HStringReference(RuntimeClass_Microsoft_Graphics_Canvas_UI_Xaml_CanvasSwapChainPanel).Get(),
            &m_canvasSwapChainPanelActivationFactory));
    }

    virtual ComPtr<CanvasSwapChainPanel> CreateCanvasSwapChainPanel() override
    {
        ComPtr<IInspectable> canvasSwapChainPanelInspectable;
        ThrowIfFailed(m_canvasSwapChainPanelActivationFactory->ActivateInstance(&canvasSwapChainPanelInspectable));

        auto canvasSwapChainPanel = As<ICanvasSwapChainPanel>(canvasSwapChainPanelInspectable);

        return static_cast<CanvasSwapChainPanel*>(canvasSwapChainPanel.Get());
    }

    virtual ComPtr<CanvasSwapChain> CreateCanvasSwapChain(
        ICanvasDevice* device,
        float width,
        float height,
        float dpi,
        CanvasAlphaMode alphaMode) override
    {
        ComPtr<ICanvasSwapChain> swapChain;

        ThrowIfFailed(m_canvasSwapChainFactory->CreateWithAllOptions(
            As<ICanvasResourceCreator>(device).Get(),
            width,
            height,
            dpi,
            PIXEL_FORMAT(B8G8R8A8UIntNormalized),
            2,
            alphaMode,
            &swapChain));

        return static_cast<CanvasSwapChain*>(swapChain.Get());
    }

    virtual std::shared_ptr<CanvasGameLoop> CreateAndStartGameLoop(ComPtr<ISwapChainPanel> swapChainPanel, ComPtr<AnimatedControlInput> input) override
    {
        //
        // This needs to start a new thread and, while executing code on that
        // thread, then get a CoreDispatcher set up on that thread, and then, on
        // the original thread, create a CanvasGameLoop that has access to that
        // dispatcher.
        //

        class GameLoopStartup
        {
            // This mutex & condition variable are used to block the incoming
            // thread while waiting for the game loop thread to start up and set
            // the dispatcher.
            std::mutex m_mutex;
            std::condition_variable m_conditionVariable;

            ComPtr<ICoreDispatcher> m_dispatcher;

        public:
            void SetDispatcher(ICoreDispatcher* dispatcher)
            {
                Lock lock(m_mutex);
                m_dispatcher = dispatcher;
                lock.unlock();
                m_conditionVariable.notify_one();
            }

            void NotifyOne()
            {
                m_conditionVariable.notify_one();
            }

            ComPtr<ICoreDispatcher> WaitAndGetDispatcher(IAsyncAction* action)
            {
                auto info = As<IAsyncInfo>(action);

                Lock lock(m_mutex);
                m_conditionVariable.wait(lock,
                    [&]
                    {
                        if (m_dispatcher)
                        {
                            // The dispatcher has been sent to us; we're done
                            return true;
                        }

                        AsyncStatus status;
                        ThrowIfFailed(info->get_Status(&status));

                        switch (status)
                        {
                        case AsyncStatus::Started:
                            // We're still waiting to find out
                            return false;

                        case AsyncStatus::Error:
                        {
                            HRESULT hr = S_OK;
                            ThrowIfFailed(info->get_ErrorCode(&hr));
                            ThrowHR(hr);
                        }

                        case AsyncStatus::Completed:
                            return true;

                        default:
                            ThrowHR(E_UNEXPECTED);
                        }
                    });

                // We should only get here if the dispatcher was actually set.
                // All other cases should have resulted in an exception.
                assert(m_dispatcher);
                return m_dispatcher;
            }
        };

        auto gameLoopStartup = std::make_shared<GameLoopStartup>();

        auto startThreadHandler = Callback<AddFtmBase<IWorkItemHandler>::Type>(
            [=](IAsyncAction*) mutable
            {
                return ExceptionBoundary(
                    [&]
                    {
                        auto notifyWarden = MakeScopeWarden([&] { gameLoopStartup->NotifyOne(); });

                        auto dispatcher = CreateCoreDispatcher(swapChainPanel.Get());

                        // Now notify the original thread that we've got the
                        // dispatcher
                        gameLoopStartup->SetDispatcher(dispatcher.Get());
                        notifyWarden.Dismiss();
                        gameLoopStartup.reset();

                        // At this point the original thread is likely to go
                        // about its business - so we cannot access anything we
                        // captured by reference from it.
                        //
                        // Which is ok, because all we want to do here is to
                        // start processing events.

                        ThrowIfFailed(dispatcher->ProcessEvents(CoreProcessEventsOption_ProcessUntilQuit));
                    });
            });
        CheckMakeResult(startThreadHandler);

        auto action = StartThread(std::move(startThreadHandler));
        auto dispatcher = gameLoopStartup->WaitAndGetDispatcher(action.Get());

        return std::make_shared<CanvasGameLoop>(std::move(action), std::move(dispatcher), input);
    }

    static ComPtr<ICoreDispatcher> CreateCoreDispatcher(ISwapChainPanel* swapChainPanel)
    {
        // We do a little dance here to create the dispatcher.
        // We first create a core independent input source,
        // which will create a dispatcher.  We then discard the
        // input source we created.
        ComPtr<ICoreInputSourceBase> inputSource;
        ThrowIfFailed(swapChainPanel->CreateCoreIndependentInputSource(
            CoreInputDeviceTypes_Touch | CoreInputDeviceTypes_Pen | CoreInputDeviceTypes_Mouse,
            &inputSource));

        ComPtr<ICoreDispatcher> dispatcher;
        ThrowIfFailed(inputSource->get_Dispatcher(&dispatcher));

        ThrowIfFailed(swapChainPanel->CreateCoreIndependentInputSource(
            CoreInputDeviceTypes_None,
            &inputSource));

        return dispatcher;
    }

    ComPtr<IAsyncAction> StartThread(ComPtr<IWorkItemHandler>&& handler)
    {
        ComPtr<IAsyncAction> action;
        ThrowIfFailed(m_threadPoolStatics->RunWithPriorityAndOptionsAsync(
            handler.Get(),
            WorkItemPriority_Normal,
            WorkItemOptions_TimeSliced,
            &action));

        return action;
    }

    virtual ComPtr<IInspectable> CreateSwapChainPanel(IInspectable* canvasSwapChainPanel) override
    {
        return m_canvasSwapChainPanelAdapter->CreateSwapChainPanel(canvasSwapChainPanel);
    }

    virtual void Sleep(DWORD timeInMs) override
    {
        ::Sleep(timeInMs);
    }

    virtual LARGE_INTEGER GetPerformanceCounter() override
    {
        LARGE_INTEGER counter;
        if (QueryPerformanceCounter(&counter) == 0)
        {
            ThrowHR(E_FAIL);
        }
        return counter;
    }

    virtual LARGE_INTEGER GetPerformanceFrequency() override
    {
        LARGE_INTEGER frequency;
        if (QueryPerformanceFrequency(&frequency) == 0)
        {
            ThrowHR(E_FAIL);
        }
        return frequency;
    }
};

namespace ABI { namespace Microsoft { namespace Graphics { namespace Canvas { namespace UI { namespace Xaml
{

    std::shared_ptr<ICanvasAnimatedControlAdapter> CreateCanvasAnimatedControlAdapter()
    {
        ComPtr<IThreadPoolStatics> threadPoolStatics;
        ThrowIfFailed(GetActivationFactory(
            HStringReference(RuntimeClass_Windows_System_Threading_ThreadPool).Get(),
            &threadPoolStatics));

        return std::make_shared<CanvasAnimatedControlAdapter>(threadPoolStatics.Get());
    }

} } } } } }<commit_msg>Pull GameLoopStartup out of CanvasAnimatedControlAdapter::CreateAndStartGameLoop<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use these files 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 "pch.h"

#include "CanvasAnimatedControl.h"
#include "CanvasGameLoop.h"

using namespace ::ABI::Microsoft::Graphics::Canvas;
using namespace ::ABI::Microsoft::Graphics::Canvas::UI;
using namespace ::ABI::Microsoft::Graphics::Canvas::UI::Xaml;
using namespace ::Microsoft::WRL::Wrappers;

//
// Helper for CreateAndStartGameLoop, tracks state shared between the UI thread
// and the newly created game loop thread.  The game loop thread needs to
// communicate back the ICoreDispatcher.
//
class GameLoopStartup
{
    // This mutex & condition variable are used to block the incoming
    // thread while waiting for the game loop thread to start up and set
    // the dispatcher.
    std::mutex m_mutex;
    std::condition_variable m_conditionVariable;

    ComPtr<ICoreDispatcher> m_dispatcher;

public:
    void SetDispatcher(ICoreDispatcher* dispatcher)
    {
        Lock lock(m_mutex);
        m_dispatcher = dispatcher;
        lock.unlock();
        m_conditionVariable.notify_one();
    }

    void NotifyOne()
    {
        m_conditionVariable.notify_one();
    }

    ComPtr<ICoreDispatcher> WaitAndGetDispatcher(IAsyncAction* action)
    {
        auto info = As<IAsyncInfo>(action);

        Lock lock(m_mutex);
        m_conditionVariable.wait(lock,
            [&]
            {
                if (m_dispatcher)
                {
                    // The dispatcher has been sent to us; we're done
                    return true;
                }

                AsyncStatus status;
                ThrowIfFailed(info->get_Status(&status));

                switch (status)
                {
                case AsyncStatus::Started:
                    // We're still waiting to find out
                    return false;

                case AsyncStatus::Error:
                {
                    HRESULT hr = S_OK;
                    ThrowIfFailed(info->get_ErrorCode(&hr));
                    ThrowHR(hr);
                }

                case AsyncStatus::Completed:
                    return true;

                default:
                    ThrowHR(E_UNEXPECTED);
                }
            });

        // We should only get here if the dispatcher was actually set.
        // All other cases should have resulted in an exception.
        assert(m_dispatcher);
        return m_dispatcher;
    }
};

//
// Creates a CoreDispatcher for the current thread.
//
// We do a little dance here to create the dispatcher.  We first create a core
// independent input source (via the swapChainPanel), which will create a
// dispatcher.  We then discard the input source we created.
//
static ComPtr<ICoreDispatcher> CreateCoreDispatcher(ISwapChainPanel* swapChainPanel)
{
    ComPtr<ICoreInputSourceBase> inputSource;
    ThrowIfFailed(swapChainPanel->CreateCoreIndependentInputSource(
        CoreInputDeviceTypes_Touch | CoreInputDeviceTypes_Pen | CoreInputDeviceTypes_Mouse,
        &inputSource));

    ComPtr<ICoreDispatcher> dispatcher;
    ThrowIfFailed(inputSource->get_Dispatcher(&dispatcher));

    ThrowIfFailed(swapChainPanel->CreateCoreIndependentInputSource(
        CoreInputDeviceTypes_None,
        &inputSource));

    return dispatcher;
}

//
// CanvasAnimatedControlAdapter
//

class CanvasAnimatedControlAdapter : public BaseControlAdapter<CanvasAnimatedControlTraits>,
    public std::enable_shared_from_this<CanvasAnimatedControlAdapter>
{
    ComPtr<IThreadPoolStatics> m_threadPoolStatics;
    ComPtr<ICanvasSwapChainFactory> m_canvasSwapChainFactory;
    std::shared_ptr<CanvasSwapChainPanelAdapter> m_canvasSwapChainPanelAdapter;
    ComPtr<IActivationFactory> m_canvasSwapChainPanelActivationFactory;

public:
    CanvasAnimatedControlAdapter(IThreadPoolStatics* threadPoolStatics)
        : m_threadPoolStatics(threadPoolStatics)
        , m_canvasSwapChainPanelAdapter(std::make_shared<CanvasSwapChainPanelAdapter>())
    {
        auto& module = Module<InProc>::GetModule();

        ComPtr<IActivationFactory> swapChainActivationFactory;

        ThrowIfFailed(module.GetActivationFactory(
            HStringReference(RuntimeClass_Microsoft_Graphics_Canvas_CanvasSwapChain).Get(),
            &swapChainActivationFactory));

        m_canvasSwapChainFactory = As<ICanvasSwapChainFactory>(swapChainActivationFactory);

        ThrowIfFailed(module.GetActivationFactory(
            HStringReference(RuntimeClass_Microsoft_Graphics_Canvas_UI_Xaml_CanvasSwapChainPanel).Get(),
            &m_canvasSwapChainPanelActivationFactory));
    }

    virtual ComPtr<CanvasSwapChainPanel> CreateCanvasSwapChainPanel() override
    {
        ComPtr<IInspectable> canvasSwapChainPanelInspectable;
        ThrowIfFailed(m_canvasSwapChainPanelActivationFactory->ActivateInstance(&canvasSwapChainPanelInspectable));

        auto canvasSwapChainPanel = As<ICanvasSwapChainPanel>(canvasSwapChainPanelInspectable);

        return static_cast<CanvasSwapChainPanel*>(canvasSwapChainPanel.Get());
    }

    virtual ComPtr<CanvasSwapChain> CreateCanvasSwapChain(
        ICanvasDevice* device,
        float width,
        float height,
        float dpi,
        CanvasAlphaMode alphaMode) override
    {
        ComPtr<ICanvasSwapChain> swapChain;

        ThrowIfFailed(m_canvasSwapChainFactory->CreateWithAllOptions(
            As<ICanvasResourceCreator>(device).Get(),
            width,
            height,
            dpi,
            PIXEL_FORMAT(B8G8R8A8UIntNormalized),
            2,
            alphaMode,
            &swapChain));

        return static_cast<CanvasSwapChain*>(swapChain.Get());
    }

    virtual std::shared_ptr<CanvasGameLoop> CreateAndStartGameLoop(ComPtr<ISwapChainPanel> swapChainPanel, ComPtr<AnimatedControlInput> input) override
    {
        //
        // This needs to start a new thread and, while executing code on that
        // thread, then get a CoreDispatcher set up on that thread, and then, on
        // the original thread, create a CanvasGameLoop that has access to that
        // dispatcher.
        //

        auto gameLoopStartup = std::make_shared<GameLoopStartup>();

        auto startThreadHandler = Callback<AddFtmBase<IWorkItemHandler>::Type>(
            [=](IAsyncAction*) mutable
            {
                return ExceptionBoundary(
                    [&]
                    {
                        auto notifyWarden = MakeScopeWarden([&] { gameLoopStartup->NotifyOne(); });

                        auto dispatcher = CreateCoreDispatcher(swapChainPanel.Get());

                        // Now notify the original thread that we've got the
                        // dispatcher
                        gameLoopStartup->SetDispatcher(dispatcher.Get());
                        notifyWarden.Dismiss();
                        gameLoopStartup.reset();

                        // At this point the original thread is likely to go
                        // about its business - so we cannot access anything we
                        // captured by reference from it.
                        //
                        // Which is ok, because all we want to do here is to
                        // start processing events.

                        ThrowIfFailed(dispatcher->ProcessEvents(CoreProcessEventsOption_ProcessUntilQuit));
                    });
            });
        CheckMakeResult(startThreadHandler);

        auto action = StartThread(std::move(startThreadHandler));
        auto dispatcher = gameLoopStartup->WaitAndGetDispatcher(action.Get());

        return std::make_shared<CanvasGameLoop>(std::move(action), std::move(dispatcher), input);
    }

    virtual ComPtr<IInspectable> CreateSwapChainPanel(IInspectable* canvasSwapChainPanel) override
    {
        return m_canvasSwapChainPanelAdapter->CreateSwapChainPanel(canvasSwapChainPanel);
    }

    virtual void Sleep(DWORD timeInMs) override
    {
        ::Sleep(timeInMs);
    }

    virtual LARGE_INTEGER GetPerformanceCounter() override
    {
        LARGE_INTEGER counter;
        if (QueryPerformanceCounter(&counter) == 0)
        {
            ThrowHR(E_FAIL);
        }
        return counter;
    }

    virtual LARGE_INTEGER GetPerformanceFrequency() override
    {
        LARGE_INTEGER frequency;
        if (QueryPerformanceFrequency(&frequency) == 0)
        {
            ThrowHR(E_FAIL);
        }
        return frequency;
    }

private:
    ComPtr<IAsyncAction> StartThread(ComPtr<IWorkItemHandler>&& handler)
    {
        ComPtr<IAsyncAction> action;
        ThrowIfFailed(m_threadPoolStatics->RunWithPriorityAndOptionsAsync(
            handler.Get(),
            WorkItemPriority_Normal,
            WorkItemOptions_TimeSliced,
            &action));

        return action;
    }
};

namespace ABI { namespace Microsoft { namespace Graphics { namespace Canvas { namespace UI { namespace Xaml
{

    std::shared_ptr<ICanvasAnimatedControlAdapter> CreateCanvasAnimatedControlAdapter()
    {
        ComPtr<IThreadPoolStatics> threadPoolStatics;
        ThrowIfFailed(GetActivationFactory(
            HStringReference(RuntimeClass_Windows_System_Threading_ThreadPool).Get(),
            &threadPoolStatics));

        return std::make_shared<CanvasAnimatedControlAdapter>(threadPoolStatics.Get());
    }

} } } } } }<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: PageHeaderFooterContext.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: dvo $ $Date: 2001-06-29 21:07:17 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "filt_pch.hxx"
#endif

#pragma hdrstop

// INCLUDE ---------------------------------------------------------------

#ifndef _XMLOFF_PAGEPHEADERFOOTERCONTEXT_HXX
#include "PageHeaderFooterContext.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_PAGEPROPERTYSETCONTEXT_HXX
#include "PagePropertySetContext.hxx"
#endif

using namespace com::sun::star;
using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_PROPERTIES;

//------------------------------------------------------------------

PageHeaderFooterContext::PageHeaderFooterContext( SvXMLImport& rImport,
                                      USHORT nPrfx,
                                      const rtl::OUString& rLName,
                                      const ::com::sun::star::uno::Reference<
                                      ::com::sun::star::xml::sax::XAttributeList>& xAttrList,
                                      ::std::vector< XMLPropertyState > & rTempProperties,
                                      const UniReference < SvXMLImportPropertyMapper > &rTempMap,
                                      sal_Int32 nStart, sal_Int32 nEnd,
                                      const sal_Bool bTempHeader ) :
    SvXMLImportContext( rImport, nPrfx, rLName ),
    rProperties(rTempProperties),
    rMap(rTempMap),
    nStartIndex(nStart),
    nEndIndex(nEnd)
{
    bHeader = bTempHeader;
}

PageHeaderFooterContext::~PageHeaderFooterContext()
{
}

SvXMLImportContext *PageHeaderFooterContext::CreateChildContext( USHORT nPrefix,
                                            const rtl::OUString& rLName,
                                            const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
    SvXMLImportContext *pContext = 0;

    if( XML_NAMESPACE_STYLE == nPrefix && IsXMLToken( rLName, XML_PROPERTIES ) )
    {
        PageContextType aType = Header;
        if (!bHeader)
            aType = Footer;
        pContext = new PagePropertySetContext( GetImport(), nPrefix,
                                                rLName, xAttrList,
                                                rProperties,
                                                rMap,  nStartIndex, nEndIndex, aType);
    }

    if( !pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );

    return pContext;
}

void PageHeaderFooterContext::EndElement()
{
}

<commit_msg>INTEGRATION: CWS oasis (1.4.276); FILE MERGED 2004/04/21 07:27:22 mib 1.4.276.2: - separated attribute lists for <*-properties> elements on import (#i20153#) - replaced "style:text-backgroubnd-color" with "fo:background-color" 2004/04/07 11:49:55 mib 1.4.276.1: splitted <properties><commit_after>/*************************************************************************
 *
 *  $RCSfile: PageHeaderFooterContext.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-13 08:19:53 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PCH
#include "filt_pch.hxx"
#endif

#pragma hdrstop

// INCLUDE ---------------------------------------------------------------

#ifndef _XMLOFF_PAGEPHEADERFOOTERCONTEXT_HXX
#include "PageHeaderFooterContext.hxx"
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
#ifndef _XMLOFF_PAGEPROPERTYSETCONTEXT_HXX
#include "PagePropertySetContext.hxx"
#endif

using namespace com::sun::star;
using ::xmloff::token::IsXMLToken;
using ::xmloff::token::XML_HEADER_FOOTER_PROPERTIES;

//------------------------------------------------------------------

PageHeaderFooterContext::PageHeaderFooterContext( SvXMLImport& rImport,
                                      USHORT nPrfx,
                                      const rtl::OUString& rLName,
                                      const ::com::sun::star::uno::Reference<
                                      ::com::sun::star::xml::sax::XAttributeList>& xAttrList,
                                      ::std::vector< XMLPropertyState > & rTempProperties,
                                      const UniReference < SvXMLImportPropertyMapper > &rTempMap,
                                      sal_Int32 nStart, sal_Int32 nEnd,
                                      const sal_Bool bTempHeader ) :
    SvXMLImportContext( rImport, nPrfx, rLName ),
    rProperties(rTempProperties),
    rMap(rTempMap),
    nStartIndex(nStart),
    nEndIndex(nEnd)
{
    bHeader = bTempHeader;
}

PageHeaderFooterContext::~PageHeaderFooterContext()
{
}

SvXMLImportContext *PageHeaderFooterContext::CreateChildContext( USHORT nPrefix,
                                            const rtl::OUString& rLName,
                                            const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
    SvXMLImportContext *pContext = 0;

    if( XML_NAMESPACE_STYLE == nPrefix && IsXMLToken( rLName, XML_HEADER_FOOTER_PROPERTIES ) )
    {
        PageContextType aType = Header;
        if (!bHeader)
            aType = Footer;
        pContext = new PagePropertySetContext( GetImport(), nPrefix,
                                                rLName, xAttrList,
                                                XML_TYPE_PROP_HEADER_FOOTER,
                                                rProperties,
                                                rMap,  nStartIndex, nEndIndex, aType);
    }

    if( !pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLName );

    return pContext;
}

void PageHeaderFooterContext::EndElement()
{
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLTextListAutoStylePool.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 18:46:13 $
 *
 *  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 _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _CNTRSRT_HXX
#include <svtools/cntnrsrt.hxx>
#endif

#ifndef _COM_SUN_STAR_UCB_XANYCOMPAREFACTORY_HPP_
#include <com/sun/star/ucb/XAnyCompareFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_
#include <com/sun/star/container/XNamed.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_
#include <com/sun/star/container/XIndexReplace.hpp>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _XMLOFF_XMLNUME_HXX
#include "xmlnume.hxx"
#endif
#ifndef _XMLOFF_XMLTEXTLISTAUTOSTYLEPOOL_HXX
#include "XMLTextListAutoStylePool.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::style;

int XMLTextListAutoStylePoolNameCmp_Impl( const OUString& r1,
                                           const OUString& r2 )
{
    return (int)r1.compareTo( r2 );
}

DECLARE_CONTAINER_SORT_DEL( XMLTextListAutoStylePoolNames_Impl,
                            OUString )
IMPL_CONTAINER_SORT( XMLTextListAutoStylePoolNames_Impl,
                     OUString,
                     XMLTextListAutoStylePoolNameCmp_Impl )

class XMLTextListAutoStylePoolEntry_Impl
{
    OUString    sName;
    OUString    sInternalName;
    Reference < XIndexReplace > xNumRules;
    sal_uInt32  nPos;
    sal_Bool    bIsNamed;

public:

    XMLTextListAutoStylePoolEntry_Impl(
            sal_uInt32 nPos,
            const Reference < XIndexReplace > & rNumRules,
            XMLTextListAutoStylePoolNames_Impl& rNames,
            const OUString& rPrefix,
            sal_uInt32& rName );

    XMLTextListAutoStylePoolEntry_Impl(
            const Reference < XIndexReplace > & rNumRules ) :
        xNumRules( rNumRules ),
        nPos( 0 ),
        bIsNamed( sal_False )
    {
        Reference < XNamed > xNamed( xNumRules, UNO_QUERY );
        if( xNamed.is() )
        {
            sInternalName = xNamed->getName();
            bIsNamed = sal_True;
        }
    }

    XMLTextListAutoStylePoolEntry_Impl(
            const OUString& rInternalName ) :
        sInternalName( rInternalName ),
        nPos( 0 ),
        bIsNamed( sal_True )
    {
    }

    const OUString& GetName() const { return sName; }
    const OUString& GetInternalName() const { return sInternalName; }
    const Reference < XIndexReplace > & GetNumRules() const { return xNumRules; }
    sal_uInt32 GetPos() const { return nPos; }
    sal_Bool IsNamed() const { return bIsNamed; }
};

XMLTextListAutoStylePoolEntry_Impl::XMLTextListAutoStylePoolEntry_Impl(
        sal_uInt32 nP,
        const Reference < XIndexReplace > & rNumRules,
        XMLTextListAutoStylePoolNames_Impl& rNames,
        const OUString& rPrefix,
        sal_uInt32& rName ) :
    xNumRules( rNumRules ),
    nPos( nP ),
    bIsNamed( sal_False )
{
    Reference < XNamed > xNamed( xNumRules, UNO_QUERY );
    if( xNamed.is() )
    {
        sInternalName = xNamed->getName();
        bIsNamed = sal_True;
    }

    // create a name that hasn't been used before. The created name has not
    // to be added to the array, because it will never tried again
    OUStringBuffer sBuffer( 7 );
    do
    {
        rName++;
        sBuffer.append( rPrefix );
        sBuffer.append( (sal_Int32)rName );
        sName = sBuffer.makeStringAndClear();
    }
    while( rNames.Seek_Entry( &sName, 0 ) );
}

int XMLTextListAutoStylePoolEntryCmp_Impl(
        const XMLTextListAutoStylePoolEntry_Impl& r1,
        const XMLTextListAutoStylePoolEntry_Impl& r2 )
{
    int nRet;
    if( r1.IsNamed() )
    {
        if( r2.IsNamed() )
             nRet = (int)r1.GetInternalName().compareTo( r2.GetInternalName());
        else
            nRet = -1;
    }
    else
    {
        if( r2.IsNamed() )
            nRet = 1;
        else
             nRet = (int)(r1.GetNumRules().get() - r2.GetNumRules().get());
    }

    return nRet;
}

typedef XMLTextListAutoStylePoolEntry_Impl *XMLTextListAutoStylePoolEntryPtr;
DECLARE_CONTAINER_SORT( XMLTextListAutoStylePool_Impl,
                        XMLTextListAutoStylePoolEntry_Impl )
IMPL_CONTAINER_SORT( XMLTextListAutoStylePool_Impl,
                     XMLTextListAutoStylePoolEntry_Impl,
                     XMLTextListAutoStylePoolEntryCmp_Impl )

XMLTextListAutoStylePool::XMLTextListAutoStylePool( SvXMLExport& rExp ) :
    rExport( rExp ),
    sPrefix( RTL_CONSTASCII_USTRINGPARAM("L") ),
    pPool( new XMLTextListAutoStylePool_Impl( 5, 5 ) ),
    pNames( new XMLTextListAutoStylePoolNames_Impl( 5, 5 ) ),
    nName( 0 )
{
    Reference<ucb::XAnyCompareFactory> xCompareFac( rExp.GetModel(), uno::UNO_QUERY );
    if( xCompareFac.is() )
        mxNumRuleCompare = xCompareFac->createAnyCompareByName( OUString( RTL_CONSTASCII_USTRINGPARAM( "NumberingRules" ) ) );
}

XMLTextListAutoStylePool::~XMLTextListAutoStylePool()
{
    delete pPool;
    delete pNames;
}

void XMLTextListAutoStylePool::RegisterName( const OUString& rName )
{
    OUString *pName = new OUString( rName );
    if( !pNames->Insert( pName ) )
        delete pName;
}

sal_Bool XMLTextListAutoStylePool::HasName( const OUString& rName ) const
{
    return pNames->Seek_Entry( &rName, 0 );
}

sal_uInt32 XMLTextListAutoStylePool::Find( XMLTextListAutoStylePoolEntry_Impl* pEntry ) const
{
    ULONG nPos;
    if( !pEntry->IsNamed() && mxNumRuleCompare.is() )
    {
        const sal_uInt32 nCount = pPool->Count();

        uno::Any aAny1, aAny2;
        aAny1 <<= pEntry->GetNumRules();

        for( nPos = 0; nPos < nCount; nPos++ )
        {
            aAny2 <<= pPool->GetObject(nPos)->GetNumRules();

            if( mxNumRuleCompare->compare( aAny1, aAny2 ) == 0 )
                return nPos;
        }
    }
    else if( pPool->Seek_Entry( pEntry, &nPos ) )
    {
        return nPos;
    }

    return (sal_uInt32)-1;
}

OUString XMLTextListAutoStylePool::Add(
            const Reference < XIndexReplace > & rNumRules )
{
    OUString sName;
    XMLTextListAutoStylePoolEntry_Impl aTmp( rNumRules );

    sal_uInt32 nPos = Find( &aTmp );
    if( nPos != (sal_uInt32)-1 )
    {
        sName = pPool->GetObject( nPos )->GetName();
    }
    else
    {
        XMLTextListAutoStylePoolEntry_Impl *pEntry =
            new XMLTextListAutoStylePoolEntry_Impl( pPool->Count(),
                                               rNumRules, *pNames, sPrefix,
                                               nName );
        pPool->Insert( pEntry );
        sName = pEntry->GetName();
    }

    return sName;
}

::rtl::OUString XMLTextListAutoStylePool::Find(
            const Reference < XIndexReplace > & rNumRules ) const
{
    OUString sName;
    XMLTextListAutoStylePoolEntry_Impl aTmp( rNumRules );

    sal_uInt32 nPos = Find( &aTmp );
    if( nPos != (sal_uInt32)-1 )
        sName = pPool->GetObject( nPos )->GetName();

    return sName;
}

::rtl::OUString XMLTextListAutoStylePool::Find(
            const OUString& rInternalName ) const
{
    OUString sName;
    XMLTextListAutoStylePoolEntry_Impl aTmp( rInternalName );
    sal_uInt32 nPos = Find( &aTmp );
    if( nPos != (sal_uInt32)-1 )
        sName = pPool->GetObject( nPos )->GetName();

    return sName;
}

void XMLTextListAutoStylePool::exportXML() const
{
    sal_uInt32 nCount = pPool->Count();
    if( !nCount )
        return;

    XMLTextListAutoStylePoolEntry_Impl **aExpEntries =
        new XMLTextListAutoStylePoolEntryPtr[nCount];

    sal_uInt32 i;
    for( i=0; i < nCount; i++ )
    {
        aExpEntries[i] = 0;
    }
    for( i=0; i < nCount; i++ )
    {
        XMLTextListAutoStylePoolEntry_Impl *pEntry = pPool->GetObject(i);
        DBG_ASSERT( pEntry->GetPos() < nCount, "Illegal pos" );
        aExpEntries[pEntry->GetPos()] = pEntry;
    }

    SvxXMLNumRuleExport aNumRuleExp( rExport );

    for( i=0; i < nCount; i++ )
    {
        XMLTextListAutoStylePoolEntry_Impl *pEntry = aExpEntries[i];
        aNumRuleExp.exportNumberingRule( pEntry->GetName(),
                                         pEntry->GetNumRules() );
    }
    delete [] aExpEntries;
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.7.34); FILE MERGED 2006/09/01 18:00:07 kaib 1.7.34.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: XMLTextListAutoStylePool.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 11:13:40 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_xmloff.hxx"

#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _CNTRSRT_HXX
#include <svtools/cntnrsrt.hxx>
#endif

#ifndef _COM_SUN_STAR_UCB_XANYCOMPAREFACTORY_HPP_
#include <com/sun/star/ucb/XAnyCompareFactory.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMED_HPP_
#include <com/sun/star/container/XNamed.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XINDEXREPLACE_HPP_
#include <com/sun/star/container/XIndexReplace.hpp>
#endif

#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif

#ifndef _XMLOFF_XMLNUME_HXX
#include "xmlnume.hxx"
#endif
#ifndef _XMLOFF_XMLTEXTLISTAUTOSTYLEPOOL_HXX
#include "XMLTextListAutoStylePool.hxx"
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::style;

int XMLTextListAutoStylePoolNameCmp_Impl( const OUString& r1,
                                           const OUString& r2 )
{
    return (int)r1.compareTo( r2 );
}

DECLARE_CONTAINER_SORT_DEL( XMLTextListAutoStylePoolNames_Impl,
                            OUString )
IMPL_CONTAINER_SORT( XMLTextListAutoStylePoolNames_Impl,
                     OUString,
                     XMLTextListAutoStylePoolNameCmp_Impl )

class XMLTextListAutoStylePoolEntry_Impl
{
    OUString    sName;
    OUString    sInternalName;
    Reference < XIndexReplace > xNumRules;
    sal_uInt32  nPos;
    sal_Bool    bIsNamed;

public:

    XMLTextListAutoStylePoolEntry_Impl(
            sal_uInt32 nPos,
            const Reference < XIndexReplace > & rNumRules,
            XMLTextListAutoStylePoolNames_Impl& rNames,
            const OUString& rPrefix,
            sal_uInt32& rName );

    XMLTextListAutoStylePoolEntry_Impl(
            const Reference < XIndexReplace > & rNumRules ) :
        xNumRules( rNumRules ),
        nPos( 0 ),
        bIsNamed( sal_False )
    {
        Reference < XNamed > xNamed( xNumRules, UNO_QUERY );
        if( xNamed.is() )
        {
            sInternalName = xNamed->getName();
            bIsNamed = sal_True;
        }
    }

    XMLTextListAutoStylePoolEntry_Impl(
            const OUString& rInternalName ) :
        sInternalName( rInternalName ),
        nPos( 0 ),
        bIsNamed( sal_True )
    {
    }

    const OUString& GetName() const { return sName; }
    const OUString& GetInternalName() const { return sInternalName; }
    const Reference < XIndexReplace > & GetNumRules() const { return xNumRules; }
    sal_uInt32 GetPos() const { return nPos; }
    sal_Bool IsNamed() const { return bIsNamed; }
};

XMLTextListAutoStylePoolEntry_Impl::XMLTextListAutoStylePoolEntry_Impl(
        sal_uInt32 nP,
        const Reference < XIndexReplace > & rNumRules,
        XMLTextListAutoStylePoolNames_Impl& rNames,
        const OUString& rPrefix,
        sal_uInt32& rName ) :
    xNumRules( rNumRules ),
    nPos( nP ),
    bIsNamed( sal_False )
{
    Reference < XNamed > xNamed( xNumRules, UNO_QUERY );
    if( xNamed.is() )
    {
        sInternalName = xNamed->getName();
        bIsNamed = sal_True;
    }

    // create a name that hasn't been used before. The created name has not
    // to be added to the array, because it will never tried again
    OUStringBuffer sBuffer( 7 );
    do
    {
        rName++;
        sBuffer.append( rPrefix );
        sBuffer.append( (sal_Int32)rName );
        sName = sBuffer.makeStringAndClear();
    }
    while( rNames.Seek_Entry( &sName, 0 ) );
}

int XMLTextListAutoStylePoolEntryCmp_Impl(
        const XMLTextListAutoStylePoolEntry_Impl& r1,
        const XMLTextListAutoStylePoolEntry_Impl& r2 )
{
    int nRet;
    if( r1.IsNamed() )
    {
        if( r2.IsNamed() )
             nRet = (int)r1.GetInternalName().compareTo( r2.GetInternalName());
        else
            nRet = -1;
    }
    else
    {
        if( r2.IsNamed() )
            nRet = 1;
        else
             nRet = (int)(r1.GetNumRules().get() - r2.GetNumRules().get());
    }

    return nRet;
}

typedef XMLTextListAutoStylePoolEntry_Impl *XMLTextListAutoStylePoolEntryPtr;
DECLARE_CONTAINER_SORT( XMLTextListAutoStylePool_Impl,
                        XMLTextListAutoStylePoolEntry_Impl )
IMPL_CONTAINER_SORT( XMLTextListAutoStylePool_Impl,
                     XMLTextListAutoStylePoolEntry_Impl,
                     XMLTextListAutoStylePoolEntryCmp_Impl )

XMLTextListAutoStylePool::XMLTextListAutoStylePool( SvXMLExport& rExp ) :
    rExport( rExp ),
    sPrefix( RTL_CONSTASCII_USTRINGPARAM("L") ),
    pPool( new XMLTextListAutoStylePool_Impl( 5, 5 ) ),
    pNames( new XMLTextListAutoStylePoolNames_Impl( 5, 5 ) ),
    nName( 0 )
{
    Reference<ucb::XAnyCompareFactory> xCompareFac( rExp.GetModel(), uno::UNO_QUERY );
    if( xCompareFac.is() )
        mxNumRuleCompare = xCompareFac->createAnyCompareByName( OUString( RTL_CONSTASCII_USTRINGPARAM( "NumberingRules" ) ) );
}

XMLTextListAutoStylePool::~XMLTextListAutoStylePool()
{
    delete pPool;
    delete pNames;
}

void XMLTextListAutoStylePool::RegisterName( const OUString& rName )
{
    OUString *pName = new OUString( rName );
    if( !pNames->Insert( pName ) )
        delete pName;
}

sal_Bool XMLTextListAutoStylePool::HasName( const OUString& rName ) const
{
    return pNames->Seek_Entry( &rName, 0 );
}

sal_uInt32 XMLTextListAutoStylePool::Find( XMLTextListAutoStylePoolEntry_Impl* pEntry ) const
{
    ULONG nPos;
    if( !pEntry->IsNamed() && mxNumRuleCompare.is() )
    {
        const sal_uInt32 nCount = pPool->Count();

        uno::Any aAny1, aAny2;
        aAny1 <<= pEntry->GetNumRules();

        for( nPos = 0; nPos < nCount; nPos++ )
        {
            aAny2 <<= pPool->GetObject(nPos)->GetNumRules();

            if( mxNumRuleCompare->compare( aAny1, aAny2 ) == 0 )
                return nPos;
        }
    }
    else if( pPool->Seek_Entry( pEntry, &nPos ) )
    {
        return nPos;
    }

    return (sal_uInt32)-1;
}

OUString XMLTextListAutoStylePool::Add(
            const Reference < XIndexReplace > & rNumRules )
{
    OUString sName;
    XMLTextListAutoStylePoolEntry_Impl aTmp( rNumRules );

    sal_uInt32 nPos = Find( &aTmp );
    if( nPos != (sal_uInt32)-1 )
    {
        sName = pPool->GetObject( nPos )->GetName();
    }
    else
    {
        XMLTextListAutoStylePoolEntry_Impl *pEntry =
            new XMLTextListAutoStylePoolEntry_Impl( pPool->Count(),
                                               rNumRules, *pNames, sPrefix,
                                               nName );
        pPool->Insert( pEntry );
        sName = pEntry->GetName();
    }

    return sName;
}

::rtl::OUString XMLTextListAutoStylePool::Find(
            const Reference < XIndexReplace > & rNumRules ) const
{
    OUString sName;
    XMLTextListAutoStylePoolEntry_Impl aTmp( rNumRules );

    sal_uInt32 nPos = Find( &aTmp );
    if( nPos != (sal_uInt32)-1 )
        sName = pPool->GetObject( nPos )->GetName();

    return sName;
}

::rtl::OUString XMLTextListAutoStylePool::Find(
            const OUString& rInternalName ) const
{
    OUString sName;
    XMLTextListAutoStylePoolEntry_Impl aTmp( rInternalName );
    sal_uInt32 nPos = Find( &aTmp );
    if( nPos != (sal_uInt32)-1 )
        sName = pPool->GetObject( nPos )->GetName();

    return sName;
}

void XMLTextListAutoStylePool::exportXML() const
{
    sal_uInt32 nCount = pPool->Count();
    if( !nCount )
        return;

    XMLTextListAutoStylePoolEntry_Impl **aExpEntries =
        new XMLTextListAutoStylePoolEntryPtr[nCount];

    sal_uInt32 i;
    for( i=0; i < nCount; i++ )
    {
        aExpEntries[i] = 0;
    }
    for( i=0; i < nCount; i++ )
    {
        XMLTextListAutoStylePoolEntry_Impl *pEntry = pPool->GetObject(i);
        DBG_ASSERT( pEntry->GetPos() < nCount, "Illegal pos" );
        aExpEntries[pEntry->GetPos()] = pEntry;
    }

    SvxXMLNumRuleExport aNumRuleExp( rExport );

    for( i=0; i < nCount; i++ )
    {
        XMLTextListAutoStylePoolEntry_Impl *pEntry = aExpEntries[i];
        aNumRuleExp.exportNumberingRule( pEntry->GetName(),
                                         pEntry->GetNumRules() );
    }
    delete [] aExpEntries;
}

<|endoftext|>


<commit_before>
#include "common_headers.h"

#include "tests/common.h"
#include "branch.h"
#include "operations.h"
#include "term.h"
#include "term_list.h"
#include "term_namespace.h"
#include "term_set.h"
#include "value_map.h"

namespace circa {
namespace container_tests {

void test_set()
{
    TermSet set;

    Term* term1 = new Term();

    test_assert(!set.contains(term1));
    test_assert(set.count() == 0);

    set.add(term1);

    test_assert(set.contains(term1));
    test_assert(set.count() == 1);

    set.add(term1);

    test_assert(set.contains(term1));
    test_assert(set.count() == 1);

    Term* term2 = new Term();
    set.add(term2);

    test_assert(set.contains(term2));
    test_assert(set.count() == 2);

    set.remove(term1);

    test_assert(!set.contains(term1));
    test_assert(set.count() == 1);

    set.remove(term2);

    test_assert(!set.contains(term2));
    test_assert(set.count() == 0);

    set.add(term1);
    test_assert(set.contains(term1));
    test_assert(set.count() == 1);

    /*TermMap remap;
    remap[term1] = term2;
    set.remapPointers(remap);
    test_assert(set.contains(term2));
    test_assert(set.count() == 1);*/
}

void test_namespace()
{
    TermNamespace nspace;
    Term *term = new Term();

    nspace.bind(term, "a");
    test_assert(nspace.contains("a"));
    test_assert(nspace["a"] == term);

    Term *term2 = new Term();
    TermMap remap;
    remap[term] = term2;
    nspace.remapPointers(remap);
    test_assert(nspace["a"] == term2);

    test_assert(nspace.contains("a"));
    remap[term2] = NULL;
    nspace.remapPointers(remap);
    test_assert(!nspace.contains("a"));
}

void test_list()
{
    TermList list;
    Term* term = new Term();
    Term* term2 = new Term();

    test_assert(list.count() == 0);

    list.append(term);
    list.append(term2);
    test_assert(list.count() == 2);
    test_assert(list[0] == term);
    test_assert(list[1] == term2);

    Term* term3 = new Term();
    TermMap remap;
    remap[term] = term3;
    list.remapPointers(remap);
    test_assert(list.count() == 2);
    test_assert(list[0] == term3);
    test_assert(list[1] == term2);

    list.clear();

    test_assert(list.count() == 0);
}

void value_map()
{
    Branch branch;
    ValueMap map;

    Term* two = constant_int(&branch, 2);
    Term* hi = constant_string(&branch, "hi");

    map.set(two, hi);

}

} // namespace container_tests

void register_container_tests()
{
    REGISTER_TEST_CASE(container_tests::test_set);
    REGISTER_TEST_CASE(container_tests::test_namespace);
    REGISTER_TEST_CASE(container_tests::test_list);
    REGISTER_TEST_CASE(container_tests::value_map);
}

} // namespace circa
<commit_msg>Added container_tests::value_map<commit_after>
#include "common_headers.h"

#include "tests/common.h"
#include "branch.h"
#include "builtins.h"
#include "operations.h"
#include "term.h"
#include "term_list.h"
#include "term_namespace.h"
#include "term_set.h"
#include "value_map.h"

namespace circa {
namespace container_tests {

void test_set()
{
    TermSet set;

    Term* term1 = new Term();

    test_assert(!set.contains(term1));
    test_assert(set.count() == 0);

    set.add(term1);

    test_assert(set.contains(term1));
    test_assert(set.count() == 1);

    set.add(term1);

    test_assert(set.contains(term1));
    test_assert(set.count() == 1);

    Term* term2 = new Term();
    set.add(term2);

    test_assert(set.contains(term2));
    test_assert(set.count() == 2);

    set.remove(term1);

    test_assert(!set.contains(term1));
    test_assert(set.count() == 1);

    set.remove(term2);

    test_assert(!set.contains(term2));
    test_assert(set.count() == 0);

    set.add(term1);
    test_assert(set.contains(term1));
    test_assert(set.count() == 1);

    /*TermMap remap;
    remap[term1] = term2;
    set.remapPointers(remap);
    test_assert(set.contains(term2));
    test_assert(set.count() == 1);*/
}

void test_namespace()
{
    TermNamespace nspace;
    Term *term = new Term();

    nspace.bind(term, "a");
    test_assert(nspace.contains("a"));
    test_assert(nspace["a"] == term);

    Term *term2 = new Term();
    TermMap remap;
    remap[term] = term2;
    nspace.remapPointers(remap);
    test_assert(nspace["a"] == term2);

    test_assert(nspace.contains("a"));
    remap[term2] = NULL;
    nspace.remapPointers(remap);
    test_assert(!nspace.contains("a"));
}

void test_list()
{
    TermList list;
    Term* term = new Term();
    Term* term2 = new Term();

    test_assert(list.count() == 0);

    list.append(term);
    list.append(term2);
    test_assert(list.count() == 2);
    test_assert(list[0] == term);
    test_assert(list[1] == term2);

    Term* term3 = new Term();
    TermMap remap;
    remap[term] = term3;
    list.remapPointers(remap);
    test_assert(list.count() == 2);
    test_assert(list[0] == term3);
    test_assert(list[1] == term2);

    list.clear();

    test_assert(list.count() == 0);
}

void value_map()
{
    Branch branch;
    ValueMap map;

    Term* two = constant_int(&branch, 2);
    Term* another_two = constant_int(&branch, 2);
    Term* hi = constant_string(&branch, "hi");

    map.set(two, hi);

    // Change our version of hi to verify that ValueMap has made a duplicate
    as_string(hi) = "hello";

    test_assert(as_string(map.findValueForKey(another_two)) == "hi");
}

} // namespace container_tests

void register_container_tests()
{
    REGISTER_TEST_CASE(container_tests::test_set);
    REGISTER_TEST_CASE(container_tests::test_namespace);
    REGISTER_TEST_CASE(container_tests::test_list);
    REGISTER_TEST_CASE(container_tests::value_map);
}

} // namespace circa
<|endoftext|>


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

#include "config.h"

#include <ctime>

#include <boost/foreach.hpp>
#include <boost/random.hpp>

#include <curl/curl.h>

#ifndef foreach
#define foreach BOOST_FOREACH
#endif

#include "cclive/application.h"
#include "cclive/get.h"
#include "cclive/error.h"
#include "cclive/log.h"
#include "cclive/wait.h"
#include "cclive/background.h"

namespace cclive {

static boost::mt19937 _rng;

static void
rand_decor () {

    boost::uniform_int<> r(2,5);

    boost::variate_generator<boost::mt19937&, boost::uniform_int<> > v(_rng,r);

    const int n = v();

    for (int i=0; i<n; ++i) cclive::log << ".";
}

static void
handle_fetch (const quvi_word type, void*) {
    rand_decor();
    if (type == QUVISTATUSTYPE_DONE)
        cclive::log << " ";
}

static void
handle_verify (const quvi_word type) {
    rand_decor();
    if (type == QUVISTATUSTYPE_DONE)
        cclive::log << "done.\n";
}

static int
status_callback (long param, void *ptr) {

    const quvi_word status = quvi_loword(param);
    const quvi_word type   = quvi_hiword(param);

    switch (status) {
    case QUVISTATUS_FETCH : handle_fetch (type,ptr); break;
    case QUVISTATUS_VERIFY: handle_verify(type); break;
    }

    cclive::log << std::flush;

    return QUVI_OK;
}

template<class Iterator>
static Iterator
make_unique (Iterator first, Iterator last) {
    while (first != last) {
        Iterator next (first);
        last  = std::remove (++next, last, *first);
        first = next;
    }
    return last;
}

static void
print_quvi_error (const quvicpp::error& e)
    { std::clog << "libquvi: error: " << e.what() << std::endl; }

static void
print_error (const std::exception& e)
    { std::clog << "error: " << e.what() << std::endl; }

extern char LICENSE[]; // cclive/license.cpp

int
application::exec (int argc, char **argv) {

    try   { _opts.exec(argc,argv); }

    catch (const std::exception& e) {
        print_error (e);
        return invalid_option;
    }

    const boost::program_options::variables_map map = _opts.map();

    // Dump and terminate options.

    if (map.count("help")) {
        std::clog << _opts;
        return ok;
    }

    if (map.count("version")) {
        std::clog
            << "cclive version "
            << VERSION_LONG
            << "\n"
            << "libquvi version "
            << quvi_version (QUVI_VERSION_LONG)
            << std::endl;
        return ok;
    }

    if (map.count("license")) {
        std::clog << LICENSE << std::endl;
        return ok;
    }

    // Set up quvicpp.

    quvicpp::query query; // Throws quvicpp::error caught in main.cpp .

    if (map.count("support")) {
        std::clog << quvicpp::support_to_s (query.support ()) << std::flush;
        return ok;
    }

    // Parse input.

    std::vector<std::string> input;

    if (map.count("url"))
        input = map["url"].as< std::vector<std::string> >();
    else
        _read_stdin (input);

    // Remove duplicates.

    input.erase (make_unique (input.begin(), input.end()), input.end());

    // Turn on libcurl verbose output.

    if (map.count("verbose-libcurl"))
        curl_easy_setopt (query.curlHandle(), CURLOPT_VERBOSE, 1L);

    // Set up quvicpp.

    _tweak_curl_opts(query,map);

    quvicpp::options qopts;
    qopts.statusfunc (status_callback);
    qopts.format     (map["format"].as<std::string>());

    // Seed random generator.

    _rng.seed ( static_cast<unsigned int>(std::time(0)) );

    // Omit flag.

    bool omit = map.count ("quiet");

    // Go to background.

    if (map.count ("background")) {

        // Throws std::runtime_error if fails.

        cclive::go_background (map["log-file"].as<std::string>(), omit);
    }

    // Omit std output. Note that --background flips this above.

    cclive::log.push (cclive::omit_sink (omit));

    // For each input URL.

    const size_t n = input.size();
    size_t i = 0;

    const int max_retries  = map["max-retries"].as<int>();
    const int retry_wait   = map["retry-wait"].as<int>();

    foreach(std::string url, input) {

        ++i;

        try {

            int retry = 0;

            while (retry <= max_retries) {

                if (retry > 0) {

                    std::clog
                        << "Retrying "
                        << retry
                        << " of "
                        << max_retries
                        << " ... "
                        << std::flush;

                    cclive::wait (retry_wait);
                }

                ++retry;

                if (n > 1)
                    cclive::log << "(" << i << " of " << n << ") ";

                cclive::log << "Checking ";

                quvicpp::video v;

                try { v = query.parse (url, qopts); }

                catch (const quvicpp::error& e) {

                    const long resp_code = e.response_code ();

                    if (resp_code >= 400 && resp_code <= 500)
                        throw e;

                    else {

                        print_quvi_error (e);

                        continue; // Retry.
                    }

                }

                cclive::get (query, v, _opts);

                break; // Stop retrying.
            }

        }

        catch (const quvicpp::error& e)
            { print_quvi_error (e); }

        catch (const std::runtime_error& e)
            { print_error (e); }

    }

    return ok;
}

void
application::_read_stdin (std::vector<std::string>& dst) {

    std::string s;
    char ch = 0;

    while (std::cin.get(ch))
        s += ch;

    std::istringstream iss(s);
    std::copy(
        std::istream_iterator<std::string >(iss),
        std::istream_iterator<std::string >(),
        std::back_inserter<std::vector<std::string> >(dst)
    );
}

void
application::_tweak_curl_opts (
    const quvicpp::query& query,
    const boost::program_options::variables_map& map)
{
    CURL *curl = query.curlHandle();

    curl_easy_setopt(curl, CURLOPT_USERAGENT,
        map["agent"].as<std::string>().c_str());

    if (map.count("verbose-curl"))
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

    if (map.count("proxy")) {
        curl_easy_setopt(curl, CURLOPT_PROXY,
            map["proxy"].as<std::string>().c_str());
    }

    if (map.count("no-proxy"))
        curl_easy_setopt(curl, CURLOPT_PROXY, "");

    if (map.count("throttle")) {
        curl_off_t limit = map["throttle"].as<int>()*1024;
        curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, limit);
    }

    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT,
        map["connect-timeout"].as<int>());
}

} // End namespace.

<commit_msg>check for quvi_code, put into wrapper functions.<commit_after>/*
* Copyright (C) 2010 Toni Gundogdu.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "config.h"

#include <ctime>

#include <boost/foreach.hpp>
#include <boost/random.hpp>

#include <curl/curl.h>

#ifndef foreach
#define foreach BOOST_FOREACH
#endif

#include "cclive/application.h"
#include "cclive/get.h"
#include "cclive/error.h"
#include "cclive/log.h"
#include "cclive/wait.h"
#include "cclive/background.h"

namespace cclive {

static boost::mt19937 _rng;

static void
rand_decor () {

    boost::uniform_int<> r(2,5);

    boost::variate_generator<boost::mt19937&, boost::uniform_int<> > v(_rng,r);

    const int n = v();

    for (int i=0; i<n; ++i) cclive::log << ".";
}

static void
handle_fetch (const quvi_word type, void*) {
    rand_decor();
    if (type == QUVISTATUSTYPE_DONE)
        cclive::log << " ";
}

static void
handle_verify (const quvi_word type) {
    rand_decor();
    if (type == QUVISTATUSTYPE_DONE)
        cclive::log << "done.\n";
}

static int
status_callback (long param, void *ptr) {

    const quvi_word status = quvi_loword(param);
    const quvi_word type   = quvi_hiword(param);

    switch (status) {
    case QUVISTATUS_FETCH : handle_fetch (type,ptr); break;
    case QUVISTATUS_VERIFY: handle_verify(type); break;
    }

    cclive::log << std::flush;

    return QUVI_OK;
}

template<class Iterator>
static Iterator
make_unique (Iterator first, Iterator last) {
    while (first != last) {
        Iterator next (first);
        last  = std::remove (++next, last, *first);
        first = next;
    }
    return last;
}

static void
print_retrying (
    const int retry,
    const int max_retries,
    const int retry_wait)
{
    if (retry > 0) {

        std::clog
            << "Retrying "
            << retry
            << " of "
            << max_retries
            << " ... "
            << std::flush;

        cclive::wait (retry_wait);
    }
}

static void
print_checking (const int i, const int n) {

    if (n > 1)
        cclive::log << "(" << i << " of " << n << ") ";

    cclive::log << "Checking ";
}

static void
print_quvi_error (const quvicpp::error& e)
    { std::clog << "libquvi: error: " << e.what() << std::endl; }

static void
print_error (const std::exception& e)
    { std::clog << "error: " << e.what() << std::endl; }

static void
check_quvi_error (const quvicpp::error& e) {

    const long resp_code = e.response_code ();

    if (resp_code >= 400 && resp_code <= 500)
        throw e;

    else {

        switch (e.quvi_code ()) {

        case QUVI_CURL:
            print_quvi_error (e);
            break; // Retry.

        default:
            throw e;
        }

    }

}

extern char LICENSE[]; // cclive/license.cpp

int
application::exec (int argc, char **argv) {

    try   { _opts.exec(argc,argv); }

    catch (const std::exception& e) {
        print_error (e);
        return invalid_option;
    }

    const boost::program_options::variables_map map = _opts.map();

    // Dump and terminate options.

    if (map.count("help")) {
        std::clog << _opts;
        return ok;
    }

    if (map.count("version")) {
        std::clog
            << "cclive version "
            << VERSION_LONG
            << "\n"
            << "libquvi version "
            << quvi_version (QUVI_VERSION_LONG)
            << std::endl;
        return ok;
    }

    if (map.count("license")) {
        std::clog << LICENSE << std::endl;
        return ok;
    }

    // Set up quvicpp.

    quvicpp::query query; // Throws quvicpp::error caught in main.cpp .

    if (map.count("support")) {
        std::clog << quvicpp::support_to_s (query.support ()) << std::flush;
        return ok;
    }

    // Parse input.

    std::vector<std::string> input;

    if (map.count("url"))
        input = map["url"].as< std::vector<std::string> >();
    else
        _read_stdin (input);

    // Remove duplicates.

    input.erase (make_unique (input.begin(), input.end()), input.end());

    // Turn on libcurl verbose output.

    if (map.count("verbose-libcurl"))
        curl_easy_setopt (query.curlHandle(), CURLOPT_VERBOSE, 1L);

    // Set up quvicpp.

    _tweak_curl_opts(query,map);

    quvicpp::options qopts;
    qopts.statusfunc (status_callback);
    qopts.format     (map["format"].as<std::string>());

    // Seed random generator.

    _rng.seed ( static_cast<unsigned int>(std::time(0)) );

    // Omit flag.

    bool omit = map.count ("quiet");

    // Go to background.

    if (map.count ("background")) {

        // Throws std::runtime_error if fails.

        cclive::go_background (map["log-file"].as<std::string>(), omit);
    }

    // Omit std output. Note that --background flips this above.

    cclive::log.push (cclive::omit_sink (omit));

    // For each input URL.

    const size_t n = input.size();
    size_t i = 0;

    const int max_retries  = map["max-retries"].as<int>();
    const int retry_wait   = map["retry-wait"].as<int>();

    foreach(std::string url, input) {

        ++i;

        try {

            int retry = 0;

            while (retry <= max_retries) {

                print_retrying (retry, max_retries, retry_wait);

                ++retry;

                print_checking (i, n);

                quvicpp::video v;

                try
                    { v = query.parse (url, qopts); }

                catch (const quvicpp::error& e)
                    { check_quvi_error (e); }

                cclive::get (query, v, _opts);

                break; // Stop retrying.
            }
        }

        catch (const quvicpp::error& e)
            { print_quvi_error (e); }

        catch (const std::runtime_error& e)
            { print_error (e); }
    }

    return ok;
}

void
application::_read_stdin (std::vector<std::string>& dst) {

    std::string s;
    char ch = 0;

    while (std::cin.get(ch))
        s += ch;

    std::istringstream iss(s);
    std::copy(
        std::istream_iterator<std::string >(iss),
        std::istream_iterator<std::string >(),
        std::back_inserter<std::vector<std::string> >(dst)
    );
}

void
application::_tweak_curl_opts (
    const quvicpp::query& query,
    const boost::program_options::variables_map& map)
{
    CURL *curl = query.curlHandle();

    curl_easy_setopt(curl, CURLOPT_USERAGENT,
        map["agent"].as<std::string>().c_str());

    if (map.count("verbose-curl"))
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

    if (map.count("proxy")) {
        curl_easy_setopt(curl, CURLOPT_PROXY,
            map["proxy"].as<std::string>().c_str());
    }

    if (map.count("no-proxy"))
        curl_easy_setopt(curl, CURLOPT_PROXY, "");

    if (map.count("throttle")) {
        curl_off_t limit = map["throttle"].as<int>()*1024;
        curl_easy_setopt(curl, CURLOPT_MAX_RECV_SPEED_LARGE, limit);
    }

    curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT,
        map["connect-timeout"].as<int>());
}

} // End namespace.

<|endoftext|>


<commit_before>/**
 * @file Spectrogram.cpp
 *
 * Spectrogram calculation.
 *
 * This file is part of the Aquila DSP library.
 * Aquila is free software, licensed under the MIT/X11 License. A copy of
 * the license is provided with the library in the LICENSE file.
 *
 * @package Aquila
 * @version 3.0.0-dev
 * @author Zbigniew Siciarz
 * @date 2007-2010
 * @license http://www.opensource.org/licenses/mit-license.php MIT
 * @since 3.0.0
 */

#include "Spectrogram.h"
#include "OouraFft.h"
#include "../source/Frame.h"

namespace Aquila
{
    Spectrogram::Spectrogram(FramesCollection& frames):
        m_frameCount(frames.count()),
        m_spectrumSize(frames.getSamplesPerFrame()),
        m_fft(new OouraFft(m_spectrumSize)),
        m_data(new SpectrogramDataType(m_frameCount))
    {
        std::size_t i = 0;
        ComplexType* spectrumArray = new ComplexType[m_spectrumSize];
        for (FramesCollection::iterator iFrame = frames.begin(); iFrame != frames.end(); ++iFrame, ++i)
        {
            // a reference to ease typing
            SpectrumType& frameSpectrum = (*m_data)[i];
            m_fft->fft(iFrame->toArray(), spectrumArray);
            frameSpectrum.assign(spectrumArray, spectrumArray + m_spectrumSize);
        }
        delete [] spectrumArray;
    }
}
<commit_msg>Fixed accumulating of spectrum data in the temporary array.<commit_after>/**
 * @file Spectrogram.cpp
 *
 * Spectrogram calculation.
 *
 * This file is part of the Aquila DSP library.
 * Aquila is free software, licensed under the MIT/X11 License. A copy of
 * the license is provided with the library in the LICENSE file.
 *
 * @package Aquila
 * @version 3.0.0-dev
 * @author Zbigniew Siciarz
 * @date 2007-2010
 * @license http://www.opensource.org/licenses/mit-license.php MIT
 * @since 3.0.0
 */

#include "Spectrogram.h"
#include "OouraFft.h"
#include "../source/Frame.h"
#include <cstring> // for memset

namespace Aquila
{
    Spectrogram::Spectrogram(FramesCollection& frames):
        m_frameCount(frames.count()),
        m_spectrumSize(frames.getSamplesPerFrame()),
        m_fft(new OouraFft(m_spectrumSize)),
        m_data(new SpectrogramDataType(m_frameCount))
    {
        std::size_t i = 0;

        ComplexType* spectrumArray = new ComplexType[m_spectrumSize];
        for (FramesCollection::iterator iFrame = frames.begin(); iFrame != frames.end(); ++iFrame, ++i)
        {
            // a reference to ease typing
            SpectrumType& frameSpectrum = (*m_data)[i];
            std::memset(spectrumArray, 0, m_spectrumSize * sizeof(ComplexType));
            m_fft->fft(iFrame->toArray(), spectrumArray);
            frameSpectrum.assign(spectrumArray, spectrumArray + m_spectrumSize);
        }
        delete [] spectrumArray;

    }
}
<|endoftext|>