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

/*
 * $Id$
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/validators/datatype/Base64BinaryDatatypeValidator.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeFacetException.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeValueException.hpp>
#include <xercesc/util/Base64.hpp>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  Constructors and Destructor
// ---------------------------------------------------------------------------
Base64BinaryDatatypeValidator::Base64BinaryDatatypeValidator(MemoryManager* const manager)
:AbstractStringValidator(0, 0, 0, DatatypeValidator::Base64Binary, manager)
{}

Base64BinaryDatatypeValidator::~Base64BinaryDatatypeValidator()
{}

Base64BinaryDatatypeValidator::Base64BinaryDatatypeValidator(
                          DatatypeValidator*            const baseValidator
                        , RefHashTableOf<KVStringPair>* const facets
                        , RefArrayVectorOf<XMLCh>*      const enums
                        , const int                           finalSet
                        , MemoryManager* const                manager)
:AbstractStringValidator(baseValidator, facets, finalSet, DatatypeValidator::Base64Binary, manager)
{
    init(enums, manager);
}

DatatypeValidator* Base64BinaryDatatypeValidator::newInstance
(
      RefHashTableOf<KVStringPair>* const facets
    , RefArrayVectorOf<XMLCh>* const      enums
    , const int                           finalSet
    , MemoryManager* const                manager
)
{
    return (DatatypeValidator*) new (manager) Base64BinaryDatatypeValidator(this, facets, enums, finalSet, manager);
}

// ---------------------------------------------------------------------------
//  Utilities
// ---------------------------------------------------------------------------

void Base64BinaryDatatypeValidator::checkValueSpace(const XMLCh* const content
                                                    , MemoryManager* const manager)
{
    if (getLength(content, manager) < 0)
    {
        ThrowXMLwithMemMgr1(InvalidDatatypeValueException
                , XMLExcepts::VALUE_Not_Base64
                , content
                , manager);
    }
}

int Base64BinaryDatatypeValidator::getLength(const XMLCh* const content
                                         , MemoryManager* const manager) const
{
    return Base64::getDataLength(content, manager, Base64::Conf_Schema);
}

void Base64BinaryDatatypeValidator::normalizeEnumeration(MemoryManager* const manager)
{

    int enumLength = getEnumeration()->size();
    for ( int i=0; i < enumLength; i++)
    {
        XMLString::removeWS(getEnumeration()->elementAt(i), manager);
    }

}

void Base64BinaryDatatypeValidator::normalizeContent(XMLCh* const content
                                                     , MemoryManager* const manager) const
{
    XMLString::removeWS(content, manager);
}

/***
 * Support for Serialization/De-serialization
 ***/

IMPL_XSERIALIZABLE_TOCREATE(Base64BinaryDatatypeValidator)

void Base64BinaryDatatypeValidator::serialize(XSerializeEngine& serEng)
{
    AbstractStringValidator::serialize(serEng);
}

XERCES_CPP_NAMESPACE_END

/**
  * End of file Base64BinaryDatatypeValidator.cpp
  */
<commit_msg>Empty content for Base64Binary should be allowed.<commit_after>/*
 * Copyright 2001-2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * $Id$
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/validators/datatype/Base64BinaryDatatypeValidator.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeFacetException.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeValueException.hpp>
#include <xercesc/util/Base64.hpp>

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  Constructors and Destructor
// ---------------------------------------------------------------------------
Base64BinaryDatatypeValidator::Base64BinaryDatatypeValidator(MemoryManager* const manager)
:AbstractStringValidator(0, 0, 0, DatatypeValidator::Base64Binary, manager)
{}

Base64BinaryDatatypeValidator::~Base64BinaryDatatypeValidator()
{}

Base64BinaryDatatypeValidator::Base64BinaryDatatypeValidator(
                          DatatypeValidator*            const baseValidator
                        , RefHashTableOf<KVStringPair>* const facets
                        , RefArrayVectorOf<XMLCh>*      const enums
                        , const int                           finalSet
                        , MemoryManager* const                manager)
:AbstractStringValidator(baseValidator, facets, finalSet, DatatypeValidator::Base64Binary, manager)
{
    init(enums, manager);
}

DatatypeValidator* Base64BinaryDatatypeValidator::newInstance
(
      RefHashTableOf<KVStringPair>* const facets
    , RefArrayVectorOf<XMLCh>* const      enums
    , const int                           finalSet
    , MemoryManager* const                manager
)
{
    return (DatatypeValidator*) new (manager) Base64BinaryDatatypeValidator(this, facets, enums, finalSet, manager);
}

// ---------------------------------------------------------------------------
//  Utilities
// ---------------------------------------------------------------------------

void Base64BinaryDatatypeValidator::checkValueSpace(const XMLCh* const content
                                                    , MemoryManager* const manager)
{
    if (!content || !*content)
        return;
    if (getLength(content, manager) < 0)
    {
        ThrowXMLwithMemMgr1(InvalidDatatypeValueException
                , XMLExcepts::VALUE_Not_Base64
                , content
                , manager);
    }
}

int Base64BinaryDatatypeValidator::getLength(const XMLCh* const content
                                         , MemoryManager* const manager) const
{
    if (!content || !*content)
        return 0;
    return Base64::getDataLength(content, manager, Base64::Conf_Schema);
}

void Base64BinaryDatatypeValidator::normalizeEnumeration(MemoryManager* const manager)
{

    int enumLength = getEnumeration()->size();
    for ( int i=0; i < enumLength; i++)
    {
        XMLString::removeWS(getEnumeration()->elementAt(i), manager);
    }

}

void Base64BinaryDatatypeValidator::normalizeContent(XMLCh* const content
                                                     , MemoryManager* const manager) const
{
    XMLString::removeWS(content, manager);
}

/***
 * Support for Serialization/De-serialization
 ***/

IMPL_XSERIALIZABLE_TOCREATE(Base64BinaryDatatypeValidator)

void Base64BinaryDatatypeValidator::serialize(XSerializeEngine& serEng)
{
    AbstractStringValidator::serialize(serEng);
}

XERCES_CPP_NAMESPACE_END

/**
  * End of file Base64BinaryDatatypeValidator.cpp
  */
<|endoftext|>


<commit_before>#include "autocompletebasictest.h"
#include <QUrl>
#include <QFileInfo>
#include <QStringList>
#include "integrationtestbase.h"
#include "signalwaiter.h"
#include "../../xpiks-qt/Commands/commandmanager.h"
#include "../../xpiks-qt/Models/artitemsmodel.h"
#include "../../xpiks-qt/MetadataIO/metadataiocoordinator.h"
#include "../../xpiks-qt/Models/artworkmetadata.h"
#include "../../xpiks-qt/Models/settingsmodel.h"
#include "../../xpiks-qt/AutoComplete/autocompleteservice.h"
#include "../../xpiks-qt/AutoComplete/autocompletemodel.h"

QString AutoCompleteBasicTest::testName() {
    return QLatin1String("AutoCompleteBasicTest");
}

void AutoCompleteBasicTest::setup() {
    Models::SettingsModel *settingsModel = m_CommandManager->getSettingsModel();
    settingsModel->setUseAutoComplete(true);
}

int AutoCompleteBasicTest::doTest() {
    Models::ArtItemsModel *artItemsModel = m_CommandManager->getArtItemsModel();
    QList<QUrl> files;
    files << QUrl::fromLocalFile(QFileInfo("images-for-tests/vector/026.jpg").absoluteFilePath());

    int addedCount = artItemsModel->addLocalArtworks(files);

    VERIFY(addedCount == files.length(), "Failed to add file");

    MetadataIO::MetadataIOCoordinator *ioCoordinator = m_CommandManager->getMetadataIOCoordinator();
    SignalWaiter waiter;
    QObject::connect(ioCoordinator, SIGNAL(metadataReadingFinished()), &waiter, SIGNAL(finished()));

    ioCoordinator->continueReading(true);

    if (!waiter.wait(20)) {
        VERIFY(false, "Timeout exceeded for reading metadata.");
    }

    VERIFY(!ioCoordinator->getHasErrors(), "Errors in IO Coordinator while reading");

    Models::ArtworkMetadata *metadata = artItemsModel->getArtwork(0);

    SignalWaiter completionWaiter;
    QObject::connect(metadata, SIGNAL(completionsAvailable()), &completionWaiter, SIGNAL(finished()));

    AutoComplete::AutoCompleteService *acService = m_CommandManager->getAutoCompleteService();
    AutoComplete::AutoCompleteModel *acModel = acService->getAutoCompleteModel();

    VERIFY(acModel->getCount() == 0, "AC model was not empty");

    m_CommandManager->autoCompleteKeyword("tes", metadata);

    if (!completionWaiter.wait(10)) {
        VERIFY(false, "Timeout while waiting for the completion");
    }

    VERIFY(acModel->getCount() > 0, "AC model didn't receive the completions");
    VERIFY(acModel->containsWord("test"), "AC model has irrelevant results");

    return 0;
}
<commit_msg>Fixes for connections of signals<commit_after>#include "autocompletebasictest.h"
#include <QUrl>
#include <QFileInfo>
#include <QStringList>
#include "integrationtestbase.h"
#include "signalwaiter.h"
#include "../../xpiks-qt/Commands/commandmanager.h"
#include "../../xpiks-qt/Models/artitemsmodel.h"
#include "../../xpiks-qt/MetadataIO/metadataiocoordinator.h"
#include "../../xpiks-qt/Models/artworkmetadata.h"
#include "../../xpiks-qt/Models/settingsmodel.h"
#include "../../xpiks-qt/AutoComplete/autocompleteservice.h"
#include "../../xpiks-qt/AutoComplete/autocompletemodel.h"

QString AutoCompleteBasicTest::testName() {
    return QLatin1String("AutoCompleteBasicTest");
}

void AutoCompleteBasicTest::setup() {
    Models::SettingsModel *settingsModel = m_CommandManager->getSettingsModel();
    settingsModel->setUseAutoComplete(true);
}

int AutoCompleteBasicTest::doTest() {
    Models::ArtItemsModel *artItemsModel = m_CommandManager->getArtItemsModel();
    QList<QUrl> files;
    files << QUrl::fromLocalFile(QFileInfo("images-for-tests/vector/026.jpg").absoluteFilePath());

    int addedCount = artItemsModel->addLocalArtworks(files);

    VERIFY(addedCount == files.length(), "Failed to add file");

    MetadataIO::MetadataIOCoordinator *ioCoordinator = m_CommandManager->getMetadataIOCoordinator();
    SignalWaiter waiter;
    QObject::connect(ioCoordinator, SIGNAL(metadataReadingFinished()), &waiter, SIGNAL(finished()));

    ioCoordinator->continueReading(true);

    if (!waiter.wait(20)) {
        VERIFY(false, "Timeout exceeded for reading metadata.");
    }

    VERIFY(!ioCoordinator->getHasErrors(), "Errors in IO Coordinator while reading");

    Models::ArtworkMetadata *metadata = artItemsModel->getArtwork(0);

    SignalWaiter completionWaiter;
    QObject::connect(metadata->getKeywordsModel(), SIGNAL(completionsAvailable()), &completionWaiter, SIGNAL(finished()));

    AutoComplete::AutoCompleteService *acService = m_CommandManager->getAutoCompleteService();
    AutoComplete::AutoCompleteModel *acModel = acService->getAutoCompleteModel();

    VERIFY(acModel->getCount() == 0, "AC model was not empty");

    m_CommandManager->autoCompleteKeyword("tes", metadata);

    if (!completionWaiter.wait(10)) {
        VERIFY(false, "Timeout while waiting for the completion");
    }

    VERIFY(acModel->getCount() > 0, "AC model didn't receive the completions");
    VERIFY(acModel->containsWord("test"), "AC model has irrelevant results");

    return 0;
}
<|endoftext|>


<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "generic_state_handler.h"
#include <vespa/vespalib/data/slime/slime.h>

namespace vespalib {

namespace {

vespalib::string url_escape(const vespalib::string &item) {
    return item;
}

class Url {
private:
    vespalib::string _url;
    void append(const vespalib::string &item) {
        if (*_url.rbegin() != '/') {
            _url.append('/');
        }
        _url.append(url_escape(item));
    }
public:
    Url(const vespalib::string &host, const std::vector<vespalib::string> &items)
        : _url("http://")
    {
        _url.append(host);
        _url.append('/');
        for (const auto &item: items) {
            append(item);
        }
    }
    Url(const Url &parent, const vespalib::string &item)
        : _url(parent._url)
    {
        append(item);
    }
    const vespalib::string &get() const { return _url; }
};

std::vector<vespalib::string> split_path(const vespalib::string &path) {
    vespalib::string tmp;
    std::vector<vespalib::string> items;
    for (size_t i = 0; (i < path.size()) && (path[i] != '?'); ++i) {
        if (path[i] == '/') {
            if (!tmp.empty()) {
                items.push_back(tmp);
                tmp.clear();
            }
        } else {
            tmp.push_back(path[i]);
        }
    }
    if (!tmp.empty()) {
        items.push_back(tmp);
    }
    return items;
}

bool is_prefix(const std::vector<vespalib::string> &root, const std::vector<vespalib::string> &full) {
    if (root.size() > full.size()) {
        return false;
    }
    for (size_t i = 0; i < root.size(); ++i) {
        if (root[i] != full[i]) {
            return false;
        }
    }
    return true;
}

void inject_children(const StateExplorer &state, const Url &url, slime::Cursor &self);

Slime child_state(const StateExplorer &state, const Url &url) {
    Slime child_state;
    state.get_state(slime::SlimeInserter(child_state), false);
    if (child_state.get().type().getId() == slime::NIX::ID) {
        inject_children(state, url, child_state.setObject());
    } else {
        child_state.get().setString("url", url.get());
    }
    return child_state;
}

void inject_children(const StateExplorer &state, const Url &url, slime::Cursor &self) {
    std::vector<vespalib::string> children_names = state.get_children_names();
    for (const vespalib::string &child_name: children_names) {
        std::unique_ptr<StateExplorer> child = state.get_child(child_name);
        if (child) {
            Slime fragment = child_state(*child, Url(url, child_name));
            slime::inject(fragment.get(), slime::ObjectInserter(self, child_name));
        }
    }
}

vespalib::string render(const StateExplorer &state, const Url &url) {
    Slime top;
    state.get_state(slime::SlimeInserter(top), true);
    if (top.get().type().getId() == slime::NIX::ID) {
        top.setObject();
    }
    inject_children(state, url, top.get());
    slime::SimpleBuffer buf;
    slime::JsonFormat::encode(top, buf, true);
    return buf.get().make_string();
}

vespalib::string explore(const StateExplorer &state, const vespalib::string &host,
                         const std::vector<vespalib::string> &items, size_t pos) {
    if (pos == items.size()) {
        return render(state, Url(host, items));
    }
    std::unique_ptr<StateExplorer> child = state.get_child(items[pos]);
    if (!child) {
        return "";
    }
    return explore(*child, host, items, pos + 1);
}

} // namespace vespalib::<unnamed>

GenericStateHandler::GenericStateHandler(const vespalib::string &root_path, const StateExplorer &state)
    : _root(split_path(root_path)),
      _state(state)
{
}

vespalib::string
GenericStateHandler::get(const vespalib::string &host,
                         const vespalib::string &path,
                         const std::map<vespalib::string,vespalib::string> &) const
{
    std::vector<vespalib::string> items = split_path(path);
    if (!is_prefix(_root, items)) {
        return "";
    }
    return explore(_state, host, items, _root.size());
}

} // namespace vespalib
<commit_msg>actually escape URL components<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "generic_state_handler.h"
#include <vespa/vespalib/data/slime/slime.h>

namespace vespalib {

namespace {

// escape a path component in the URL
// (needed to avoid java.net.URI throwing an exception)

vespalib::string url_escape(const vespalib::string &item) {
    static const char hexdigits[] = "0123456789ABCDEF";
    vespalib::string r;
    r.reserve(item.size());
    for (const char c : item) {
        if (   ('a' <= c && c <= 'z')
            || ('0' <= c && c <= '9')
            || ('A' <= c && c <= 'Z')
            || (c == '_')
            || (c == '-'))
        {
            r.append(c);
        } else {
            r.append('%');
            r.append(hexdigits[0xF & (c >> 4)]);
            r.append(hexdigits[0xF & c]);
        }
    }
    return r;
}

class Url {
private:
    vespalib::string _url;
    void append(const vespalib::string &item) {
        if (*_url.rbegin() != '/') {
            _url.append('/');
        }
        _url.append(url_escape(item));
    }
public:
    Url(const vespalib::string &host, const std::vector<vespalib::string> &items)
        : _url("http://")
    {
        _url.append(host);
        _url.append('/');
        for (const auto &item: items) {
            append(item);
        }
    }
    Url(const Url &parent, const vespalib::string &item)
        : _url(parent._url)
    {
        append(item);
    }
    const vespalib::string &get() const { return _url; }
};

std::vector<vespalib::string> split_path(const vespalib::string &path) {
    vespalib::string tmp;
    std::vector<vespalib::string> items;
    for (size_t i = 0; (i < path.size()) && (path[i] != '?'); ++i) {
        if (path[i] == '/') {
            if (!tmp.empty()) {
                items.push_back(tmp);
                tmp.clear();
            }
        } else {
            tmp.push_back(path[i]);
        }
    }
    if (!tmp.empty()) {
        items.push_back(tmp);
    }
    return items;
}

bool is_prefix(const std::vector<vespalib::string> &root, const std::vector<vespalib::string> &full) {
    if (root.size() > full.size()) {
        return false;
    }
    for (size_t i = 0; i < root.size(); ++i) {
        if (root[i] != full[i]) {
            return false;
        }
    }
    return true;
}

void inject_children(const StateExplorer &state, const Url &url, slime::Cursor &self);

Slime child_state(const StateExplorer &state, const Url &url) {
    Slime child_state;
    state.get_state(slime::SlimeInserter(child_state), false);
    if (child_state.get().type().getId() == slime::NIX::ID) {
        inject_children(state, url, child_state.setObject());
    } else {
        child_state.get().setString("url", url.get());
    }
    return child_state;
}

void inject_children(const StateExplorer &state, const Url &url, slime::Cursor &self) {
    std::vector<vespalib::string> children_names = state.get_children_names();
    for (const vespalib::string &child_name: children_names) {
        std::unique_ptr<StateExplorer> child = state.get_child(child_name);
        if (child) {
            Slime fragment = child_state(*child, Url(url, child_name));
            slime::inject(fragment.get(), slime::ObjectInserter(self, child_name));
        }
    }
}

vespalib::string render(const StateExplorer &state, const Url &url) {
    Slime top;
    state.get_state(slime::SlimeInserter(top), true);
    if (top.get().type().getId() == slime::NIX::ID) {
        top.setObject();
    }
    inject_children(state, url, top.get());
    slime::SimpleBuffer buf;
    slime::JsonFormat::encode(top, buf, true);
    return buf.get().make_string();
}

vespalib::string explore(const StateExplorer &state, const vespalib::string &host,
                         const std::vector<vespalib::string> &items, size_t pos) {
    if (pos == items.size()) {
        return render(state, Url(host, items));
    }
    std::unique_ptr<StateExplorer> child = state.get_child(items[pos]);
    if (!child) {
        return "";
    }
    return explore(*child, host, items, pos + 1);
}

} // namespace vespalib::<unnamed>

GenericStateHandler::GenericStateHandler(const vespalib::string &root_path, const StateExplorer &state)
    : _root(split_path(root_path)),
      _state(state)
{
}

vespalib::string
GenericStateHandler::get(const vespalib::string &host,
                         const vespalib::string &path,
                         const std::map<vespalib::string,vespalib::string> &) const
{
    std::vector<vespalib::string> items = split_path(path);
    if (!is_prefix(_root, items)) {
        return "";
    }
    return explore(_state, host, items, _root.size());
}

} // namespace vespalib
<|endoftext|>


<commit_before>/* $Id$
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to you under the Apache License, Version
 * 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "support/EtchQueuedPool.h"

#include "capu/os/Thread.h"
#include "capu/util/ThreadPool.h"
#include "capu/os/Memory.h"
#include "capu/util/Runnable.h"

class EtchQueuedPoolRunnable : public capu::Runnable {
public:

  /**
   * Create a new instance of EtchFreePoolRunnable class.
   */
  EtchQueuedPoolRunnable(EtchQueuedPool* pool, capu::SmartPointer<EtchPoolRunnable> runnable)
    : mPool(pool), mRunnable(runnable) {
  }

  /**
   * Destructor
   */
  virtual ~EtchQueuedPoolRunnable() {
  }

  /**
   * Runnable
   */
  void run() {
    if(mRunnable.get() != NULL) {
      if(ETCH_OK != mRunnable->run()) {
        //TODO: Log exception
        if(mRunnable->hasException()) {
          capu::SmartPointer<EtchException> exception;
          mRunnable->getException(&exception);
          mRunnable->exception(exception);
        }
      }
    }
  }

private:
  EtchQueuedPool* mPool;
  capu::SmartPointer<EtchPoolRunnable> mRunnable;
};

const EtchObjectType* EtchQueuedPool::TYPE() {
  const static EtchObjectType TYPE(EOTID_QUEUEDPOOL, NULL);
  return &TYPE;
}

EtchQueuedPool::EtchQueuedPool(capu::int32_t size)
: mSizeMax(size), mIsOpen(true) {
  addObjectType(TYPE());
  mPool = new capu::ThreadPool(1);
}

EtchQueuedPool::~EtchQueuedPool() {
  delete mPool;
}

status_t EtchQueuedPool::close() {
  mIsOpen = false;
  return ETCH_OK;
}

status_t EtchQueuedPool::join() {
  mPool->join();
  return ETCH_OK;
}

status_t EtchQueuedPool::add(capu::SmartPointer<EtchPoolRunnable> runnable) {
  if(!mIsOpen) {
    return ETCH_EINVAL;
  }

  EtchQueuedPoolRunnable* pr = new EtchQueuedPoolRunnable(this, runnable);
  //TODO: check max Size before adding a new Runnable
  capu::status_t status = mPool->add(pr);
  if(status != capu::CAPU_OK) {
    return ETCH_ERROR;
  }
  return ETCH_OK;
}
<commit_msg>ETCH-244 Fixing QueuedPool todo<commit_after>/* $Id$
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to you under the Apache License, Version
 * 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "support/EtchQueuedPool.h"

#include "capu/os/Thread.h"
#include "capu/util/ThreadPool.h"
#include "capu/os/Memory.h"
#include "capu/util/Runnable.h"

class EtchQueuedPoolRunnable : public capu::Runnable {
public:

  /**
   * Create a new instance of EtchFreePoolRunnable class.
   */
  EtchQueuedPoolRunnable(EtchQueuedPool* pool, capu::SmartPointer<EtchPoolRunnable> runnable)
    : mPool(pool), mRunnable(runnable) {
  }

  /**
   * Destructor
   */
  virtual ~EtchQueuedPoolRunnable() {
  }

  /**
   * Runnable
   */
  void run() {
    if(mRunnable.get() != NULL) {
      if(ETCH_OK != mRunnable->run()) {
        //TODO: Log exception
        if(mRunnable->hasException()) {
          capu::SmartPointer<EtchException> exception;
          mRunnable->getException(&exception);
          mRunnable->exception(exception);
        }
      }
    }
  }

private:
  EtchQueuedPool* mPool;
  capu::SmartPointer<EtchPoolRunnable> mRunnable;
};

const EtchObjectType* EtchQueuedPool::TYPE() {
  const static EtchObjectType TYPE(EOTID_QUEUEDPOOL, NULL);
  return &TYPE;
}

EtchQueuedPool::EtchQueuedPool(capu::int32_t size)
: mSizeMax(size), mIsOpen(true) {
  addObjectType(TYPE());
  mPool = new capu::ThreadPool(1);
}

EtchQueuedPool::~EtchQueuedPool() {
  delete mPool;
}

status_t EtchQueuedPool::close() {
  mIsOpen = false;
  return ETCH_OK;
}

status_t EtchQueuedPool::join() {
  mPool->join();
  return ETCH_OK;
}

status_t EtchQueuedPool::add(capu::SmartPointer<EtchPoolRunnable> runnable) {
  if(!mIsOpen) {
    return ETCH_EINVAL;
  }
  if(mPool->getSize() + 1 > mSizeMax)
    return ETCH_ENOT_SUPPORTED;

  EtchQueuedPoolRunnable* pr = new EtchQueuedPoolRunnable(this, runnable);
  capu::status_t status = mPool->add(pr);
  if(status != capu::CAPU_OK) {
    return ETCH_ERROR;
  }
  return ETCH_OK;
}
<|endoftext|>


<commit_before>#pragma once

#include <map>
#include <typeinfo>
#include "../Scene/Scene.hpp"

namespace Component {
    class SuperComponent;
}

/// %Entity containing various components.
class Entity {
    public:
        /// Create new entity.
        /**
         * @param scene The scene in which the entity is contained.
         */
        Entity(Scene* scene);

        /// Destructor.
        ~Entity();

        /// Adds component with type T.
        /**
         * @return The created component.
         */
        template<typename T> T* AddComponent();

    private:
        Scene* scene;

        std::map<const std::type_info*, Component::SuperComponent*> components;
};

template <typename T> T* Entity::AddComponent() {
    const std::type_info* componentType = &typeid(T*);
    if (components.find(componentType) != components.end())
        return nullptr;
    T* component = new T(this);
    components[componentType] = component;
    scene->AddComponent(component, componentType);
    return component;
}
<commit_msg>Method to get an entity's component.<commit_after>#pragma once

#include <map>
#include <typeinfo>
#include "../Scene/Scene.hpp"

namespace Component {
    class SuperComponent;
}

/// %Entity containing various components.
class Entity {
    public:
        /// Create new entity.
        /**
         * @param scene The scene in which the entity is contained.
         */
        Entity(Scene* scene);

        /// Destructor.
        ~Entity();

        /// Adds component with type T.
        /**
         * @return The created component.
         */
        template<typename T> T* AddComponent();

        /// Gets component with type T.
        /**
         * @return The requested component (or nullptr).
         */
        template<typename T> T* GetComponent();

    private:
        Scene* scene;

        std::map<const std::type_info*, Component::SuperComponent*> components;
};

template<typename T> T* Entity::AddComponent() {
    const std::type_info* componentType = &typeid(T*);
    if (components.find(componentType) != components.end())
        return nullptr;
    T* component = new T(this);
    components[componentType] = component;
    scene->AddComponent(component, componentType);
    return component;
}

template<typename T> T* Entity::GetComponent() {
    if (components.count(&typeid(T*)) != 0) {
        return static_cast<T*>(components[&typeid(T*)]);
    } else {
        return nullptr;
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: UriSchemeParser_vndDOTsunDOTstarDOTscript.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 17:38:50 $
 *
 *  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_stoc.hxx"

#include "UriSchemeParser_vndDOTsunDOTstarDOTscript.hxx"

#include "UriReference.hxx"
#include "supportsService.hxx"

#include "com/sun/star/lang/XServiceInfo.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/uno/XInterface.hpp"
#include "com/sun/star/uri/XUriReference.hpp"
#include "com/sun/star/uri/XUriSchemeParser.hpp"
#include "com/sun/star/uri/XVndSunStarScriptUrlReference.hpp"
#include "cppuhelper/implbase1.hxx"
#include "cppuhelper/implbase2.hxx"
#include "cppuhelper/weak.hxx"
#include "osl/mutex.hxx"
#include "rtl/ustrbuf.hxx"
#include "rtl/ustring.hxx"
#include "sal/types.h"

#include <new>

namespace css = com::sun::star;

namespace {

int getHexWeight(sal_Unicode c) {
    return c >= '0' && c <= '9' ? static_cast< int >(c - '0')
        : c >= 'A' && c <= 'F' ? static_cast< int >(c - 'A' + 10)
        : c >= 'a' && c <= 'f' ? static_cast< int >(c - 'a' + 10)
        : -1;
}

int parseEscaped(rtl::OUString const & part, sal_Int32 * index) {
    if (part.getLength() - *index < 3 || part[*index] != '%') {
        return -1;
    }
    int n1 = getHexWeight(part[*index + 1]);
    int n2 = getHexWeight(part[*index + 2]);
    if (n1 < 0 || n2 < 0) {
        return -1;
    }
    *index += 3;
    return (n1 << 4) | n2;
}

rtl::OUString parsePart(
    rtl::OUString const & part, bool namePart, sal_Int32 * index)
{
    rtl::OUStringBuffer buf;
    while (*index < part.getLength()) {
        sal_Unicode c = part[*index];
        if (namePart ? c == '?' : c == '&' || c == '=') {
            break;
        } else if (c == '%') {
            sal_Int32 i = *index;
            int n = parseEscaped(part, &i);
            if (n >= 0 && n <= 0x7F) {
                buf.append(static_cast< sal_Unicode >(n));
            } else if (n >= 0xC0 && n <= 0xFC) {
                sal_Int32 encoded;
                int shift;
                sal_Int32 min;
                if (n <= 0xDF) {
                    encoded = (n & 0x1F) << 6;
                    shift = 0;
                    min = 0x80;
                } else if (n <= 0xEF) {
                    encoded = (n & 0x0F) << 12;
                    shift = 6;
                    min = 0x800;
                } else if (n <= 0xF7) {
                    encoded = (n & 0x07) << 18;
                    shift = 12;
                    min = 0x10000;
                } else if (n <= 0xFB) {
                    encoded = (n & 0x03) << 24;
                    shift = 18;
                    min = 0x200000;
                } else {
                    encoded = 0;
                    shift = 24;
                    min = 0x4000000;
                }
                bool utf8 = true;
                for (; shift >= 0; shift -= 6) {
                    n = parseEscaped(part, &i);
                    if (n < 0x80 || n > 0xBF) {
                        utf8 = false;
                        break;
                    }
                    encoded |= (n & 0x3F) << shift;
                }
                if (!utf8 || encoded < min
                    || encoded >= 0xD800 && encoded <= 0xDFFF
                    || encoded > 0x10FFFF)
                {
                    break;
                }
                if (encoded <= 0xFFFF) {
                    buf.append(static_cast< sal_Unicode >(encoded));
                } else {
                    buf.append(static_cast< sal_Unicode >(
                        (encoded >> 10) | 0xD800));
                    buf.append(static_cast< sal_Unicode >(
                        (encoded & 0x3FF) | 0xDC00));
                }
            } else {
                break;
            }
            *index = i;
        } else {
            buf.append(c);
            ++*index;
        }
    }
    return buf.makeStringAndClear();
}

bool parseSchemeSpecificPart(rtl::OUString const & part) {
    sal_Int32 len = part.getLength();
    sal_Int32 i = 0;
    if (parsePart(part, true, &i).getLength() == 0 || part[0] == '/') {
        return false;
    }
    if (i == len) {
        return true;
    }
    for (;;) {
        ++i; // skip '?' or '&'
        if (parsePart(part, false, &i).getLength() == 0 || i == len
            || part[i] != '=')
        {
            return false;
        }
        ++i;
        parsePart(part, false, &i);
        if (i == len) {
            return true;
        }
        if (part[i] != '&') {
            return false;
        }
    }
}

class UrlReference:
    public cppu::WeakImplHelper1< css::uri::XVndSunStarScriptUrlReference >
{
public:
    UrlReference(rtl::OUString const & scheme, rtl::OUString const & path):
        m_base(
            scheme, false, false, rtl::OUString(), path, false, rtl::OUString())
    {}

    virtual rtl::OUString SAL_CALL getUriReference()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.getUriReference(); }

    virtual sal_Bool SAL_CALL isAbsolute()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.isAbsolute(); }

    virtual rtl::OUString SAL_CALL getScheme()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.getScheme(); }

    virtual rtl::OUString SAL_CALL getSchemeSpecificPart()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.getSchemeSpecificPart(); }

    virtual sal_Bool SAL_CALL isHierarchical()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.isHierarchical(); }

    virtual sal_Bool SAL_CALL hasAuthority()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.hasAuthority(); }

    virtual rtl::OUString SAL_CALL getAuthority()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.getAuthority(); }

    virtual rtl::OUString SAL_CALL getPath()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.getPath(); }

    virtual sal_Bool SAL_CALL hasRelativePath()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.hasRelativePath(); }

    virtual sal_Int32 SAL_CALL getPathSegmentCount()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.getPathSegmentCount(); }

    virtual rtl::OUString SAL_CALL getPathSegment(sal_Int32 index)
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.getPathSegment(index); }

    virtual sal_Bool SAL_CALL hasQuery()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.hasQuery(); }

    virtual rtl::OUString SAL_CALL getQuery()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.getQuery(); }

    virtual sal_Bool SAL_CALL hasFragment()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.hasFragment(); }

    virtual rtl::OUString SAL_CALL getFragment()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.getFragment(); }

    virtual void SAL_CALL setFragment(rtl::OUString const & fragment)
        throw (com::sun::star::uno::RuntimeException)
    { m_base.setFragment(fragment); }

    virtual void SAL_CALL clearFragment()
        throw (com::sun::star::uno::RuntimeException)
    { m_base.clearFragment(); }

    virtual rtl::OUString SAL_CALL getName() throw (css::uno::RuntimeException);

    virtual sal_Bool SAL_CALL hasParameter(rtl::OUString const & key)
        throw (css::uno::RuntimeException);

    virtual rtl::OUString SAL_CALL getParameter(rtl::OUString const & key)
        throw (css::uno::RuntimeException);

private:
    UrlReference(UrlReference &); // not implemented
    void operator =(UrlReference); // not implemented

    virtual ~UrlReference() {}

    sal_Int32 findParameter(rtl::OUString const & key);

    stoc::uriproc::UriReference m_base;
};

rtl::OUString UrlReference::getName() throw (css::uno::RuntimeException) {
    osl::MutexGuard g(m_base.m_mutex);
    sal_Int32 i = 0;
    return parsePart(m_base.m_path, true, &i);
}

sal_Bool UrlReference::hasParameter(rtl::OUString const & key)
    throw (css::uno::RuntimeException)
{
    osl::MutexGuard g(m_base.m_mutex);
    return findParameter(key) >= 0;
}

rtl::OUString UrlReference::getParameter(rtl::OUString const & key)
    throw (css::uno::RuntimeException)
{
    osl::MutexGuard g(m_base.m_mutex);
    sal_Int32 i = findParameter(key);
    return i >= 0 ? parsePart(m_base.m_path, false, &i) : rtl::OUString();
}

sal_Int32 UrlReference::findParameter(rtl::OUString const & key) {
    sal_Int32 i = 0;
    parsePart(m_base.m_path, true, &i); // skip name
    for (;;) {
        if (i == m_base.m_path.getLength()) {
            return -1;
        }
        ++i; // skip '?' or '&'
        rtl::OUString k = parsePart(m_base.m_path, false, &i);
        ++i; // skip '='
        if (k == key) {
            return i;
        }
        parsePart(m_base.m_path, false, &i); // skip value
    }
}

class Parser: public cppu::WeakImplHelper2<
    css::lang::XServiceInfo, css::uri::XUriSchemeParser >
{
public:
    Parser() {}

    virtual rtl::OUString SAL_CALL getImplementationName()
        throw (css::uno::RuntimeException);

    virtual sal_Bool SAL_CALL supportsService(rtl::OUString const & serviceName)
        throw (css::uno::RuntimeException);

    virtual css::uno::Sequence< rtl::OUString > SAL_CALL
    getSupportedServiceNames() throw (css::uno::RuntimeException);

    virtual css::uno::Reference< css::uri::XUriReference > SAL_CALL
    parse(
        rtl::OUString const & scheme, rtl::OUString const & schemeSpecificPart)
        throw (css::uno::RuntimeException);

private:
    Parser(Parser &); // not implemented
    void operator =(Parser); // not implemented

    virtual ~Parser() {}
};

rtl::OUString Parser::getImplementationName()
    throw (css::uno::RuntimeException)
{
    return stoc::uriproc::UriSchemeParser_vndDOTsunDOTstarDOTscript::
        getImplementationName();
}

sal_Bool Parser::supportsService(rtl::OUString const & serviceName)
    throw (css::uno::RuntimeException)
{
    return stoc::uriproc::supportsService(
        getSupportedServiceNames(), serviceName);
}

css::uno::Sequence< rtl::OUString > Parser::getSupportedServiceNames()
    throw (css::uno::RuntimeException)
{
    return stoc::uriproc::UriSchemeParser_vndDOTsunDOTstarDOTscript::
        getSupportedServiceNames();
}

css::uno::Reference< css::uri::XUriReference >
Parser::parse(
    rtl::OUString const & scheme, rtl::OUString const & schemeSpecificPart)
    throw (css::uno::RuntimeException)
{
    if (!parseSchemeSpecificPart(schemeSpecificPart)) {
        return 0;
    }
    try {
        return new UrlReference(scheme, schemeSpecificPart);
    } catch (std::bad_alloc &) {
        throw css::uno::RuntimeException(
            rtl::OUString::createFromAscii("std::bad_alloc"), 0);
    }
}

}

namespace stoc { namespace uriproc {
namespace UriSchemeParser_vndDOTsunDOTstarDOTscript {

css::uno::Reference< css::uno::XInterface > create(
    css::uno::Reference< css::uno::XComponentContext > const &)
    SAL_THROW((css::uno::Exception))
{
    //TODO: single instance
    try {
        return static_cast< cppu::OWeakObject * >(new Parser);
    } catch (std::bad_alloc &) {
        throw css::uno::RuntimeException(
            rtl::OUString::createFromAscii("std::bad_alloc"), 0);
    }
}

rtl::OUString getImplementationName() {
    return rtl::OUString::createFromAscii(
        "com.sun.star.comp.uri.UriSchemeParser_vndDOTsunDOTstarDOTscript");
}

css::uno::Sequence< rtl::OUString > getSupportedServiceNames() {
    css::uno::Sequence< rtl::OUString > s(1);
    s[0] = rtl::OUString::createFromAscii(
        "com.sun.star.uri.UriSchemeParser_vndDOTsunDOTstarDOTscript");
    return s;
}

} } }
<commit_msg>INTEGRATION: CWS sb76 (1.5.46); FILE MERGED 2007/08/31 11:01:56 sb 1.5.46.1: #i77885# Consolidate stoc libraries; patch by jnavrati.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: UriSchemeParser_vndDOTsunDOTstarDOTscript.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 13:06:44 $
 *
 *  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_stoc.hxx"

#include "stocservices.hxx"

#include "UriReference.hxx"
#include "supportsService.hxx"

#include "com/sun/star/lang/XServiceInfo.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/RuntimeException.hpp"
#include "com/sun/star/uno/Sequence.hxx"
#include "com/sun/star/uno/XInterface.hpp"
#include "com/sun/star/uri/XUriReference.hpp"
#include "com/sun/star/uri/XUriSchemeParser.hpp"
#include "com/sun/star/uri/XVndSunStarScriptUrlReference.hpp"
#include "cppuhelper/implbase1.hxx"
#include "cppuhelper/implbase2.hxx"
#include "cppuhelper/weak.hxx"
#include "osl/mutex.hxx"
#include "rtl/ustrbuf.hxx"
#include "rtl/ustring.hxx"
#include "sal/types.h"

#include <new>

namespace css = com::sun::star;

namespace {

int getHexWeight(sal_Unicode c) {
    return c >= '0' && c <= '9' ? static_cast< int >(c - '0')
        : c >= 'A' && c <= 'F' ? static_cast< int >(c - 'A' + 10)
        : c >= 'a' && c <= 'f' ? static_cast< int >(c - 'a' + 10)
        : -1;
}

int parseEscaped(rtl::OUString const & part, sal_Int32 * index) {
    if (part.getLength() - *index < 3 || part[*index] != '%') {
        return -1;
    }
    int n1 = getHexWeight(part[*index + 1]);
    int n2 = getHexWeight(part[*index + 2]);
    if (n1 < 0 || n2 < 0) {
        return -1;
    }
    *index += 3;
    return (n1 << 4) | n2;
}

rtl::OUString parsePart(
    rtl::OUString const & part, bool namePart, sal_Int32 * index)
{
    rtl::OUStringBuffer buf;
    while (*index < part.getLength()) {
        sal_Unicode c = part[*index];
        if (namePart ? c == '?' : c == '&' || c == '=') {
            break;
        } else if (c == '%') {
            sal_Int32 i = *index;
            int n = parseEscaped(part, &i);
            if (n >= 0 && n <= 0x7F) {
                buf.append(static_cast< sal_Unicode >(n));
            } else if (n >= 0xC0 && n <= 0xFC) {
                sal_Int32 encoded;
                int shift;
                sal_Int32 min;
                if (n <= 0xDF) {
                    encoded = (n & 0x1F) << 6;
                    shift = 0;
                    min = 0x80;
                } else if (n <= 0xEF) {
                    encoded = (n & 0x0F) << 12;
                    shift = 6;
                    min = 0x800;
                } else if (n <= 0xF7) {
                    encoded = (n & 0x07) << 18;
                    shift = 12;
                    min = 0x10000;
                } else if (n <= 0xFB) {
                    encoded = (n & 0x03) << 24;
                    shift = 18;
                    min = 0x200000;
                } else {
                    encoded = 0;
                    shift = 24;
                    min = 0x4000000;
                }
                bool utf8 = true;
                for (; shift >= 0; shift -= 6) {
                    n = parseEscaped(part, &i);
                    if (n < 0x80 || n > 0xBF) {
                        utf8 = false;
                        break;
                    }
                    encoded |= (n & 0x3F) << shift;
                }
                if (!utf8 || encoded < min
                    || encoded >= 0xD800 && encoded <= 0xDFFF
                    || encoded > 0x10FFFF)
                {
                    break;
                }
                if (encoded <= 0xFFFF) {
                    buf.append(static_cast< sal_Unicode >(encoded));
                } else {
                    buf.append(static_cast< sal_Unicode >(
                        (encoded >> 10) | 0xD800));
                    buf.append(static_cast< sal_Unicode >(
                        (encoded & 0x3FF) | 0xDC00));
                }
            } else {
                break;
            }
            *index = i;
        } else {
            buf.append(c);
            ++*index;
        }
    }
    return buf.makeStringAndClear();
}

bool parseSchemeSpecificPart(rtl::OUString const & part) {
    sal_Int32 len = part.getLength();
    sal_Int32 i = 0;
    if (parsePart(part, true, &i).getLength() == 0 || part[0] == '/') {
        return false;
    }
    if (i == len) {
        return true;
    }
    for (;;) {
        ++i; // skip '?' or '&'
        if (parsePart(part, false, &i).getLength() == 0 || i == len
            || part[i] != '=')
        {
            return false;
        }
        ++i;
        parsePart(part, false, &i);
        if (i == len) {
            return true;
        }
        if (part[i] != '&') {
            return false;
        }
    }
}

class UrlReference:
    public cppu::WeakImplHelper1< css::uri::XVndSunStarScriptUrlReference >
{
public:
    UrlReference(rtl::OUString const & scheme, rtl::OUString const & path):
        m_base(
            scheme, false, false, rtl::OUString(), path, false, rtl::OUString())
    {}

    virtual rtl::OUString SAL_CALL getUriReference()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.getUriReference(); }

    virtual sal_Bool SAL_CALL isAbsolute()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.isAbsolute(); }

    virtual rtl::OUString SAL_CALL getScheme()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.getScheme(); }

    virtual rtl::OUString SAL_CALL getSchemeSpecificPart()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.getSchemeSpecificPart(); }

    virtual sal_Bool SAL_CALL isHierarchical()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.isHierarchical(); }

    virtual sal_Bool SAL_CALL hasAuthority()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.hasAuthority(); }

    virtual rtl::OUString SAL_CALL getAuthority()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.getAuthority(); }

    virtual rtl::OUString SAL_CALL getPath()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.getPath(); }

    virtual sal_Bool SAL_CALL hasRelativePath()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.hasRelativePath(); }

    virtual sal_Int32 SAL_CALL getPathSegmentCount()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.getPathSegmentCount(); }

    virtual rtl::OUString SAL_CALL getPathSegment(sal_Int32 index)
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.getPathSegment(index); }

    virtual sal_Bool SAL_CALL hasQuery()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.hasQuery(); }

    virtual rtl::OUString SAL_CALL getQuery()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.getQuery(); }

    virtual sal_Bool SAL_CALL hasFragment()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.hasFragment(); }

    virtual rtl::OUString SAL_CALL getFragment()
        throw (com::sun::star::uno::RuntimeException)
    { return m_base.getFragment(); }

    virtual void SAL_CALL setFragment(rtl::OUString const & fragment)
        throw (com::sun::star::uno::RuntimeException)
    { m_base.setFragment(fragment); }

    virtual void SAL_CALL clearFragment()
        throw (com::sun::star::uno::RuntimeException)
    { m_base.clearFragment(); }

    virtual rtl::OUString SAL_CALL getName() throw (css::uno::RuntimeException);

    virtual sal_Bool SAL_CALL hasParameter(rtl::OUString const & key)
        throw (css::uno::RuntimeException);

    virtual rtl::OUString SAL_CALL getParameter(rtl::OUString const & key)
        throw (css::uno::RuntimeException);

private:
    UrlReference(UrlReference &); // not implemented
    void operator =(UrlReference); // not implemented

    virtual ~UrlReference() {}

    sal_Int32 findParameter(rtl::OUString const & key);

    stoc::uriproc::UriReference m_base;
};

rtl::OUString UrlReference::getName() throw (css::uno::RuntimeException) {
    osl::MutexGuard g(m_base.m_mutex);
    sal_Int32 i = 0;
    return parsePart(m_base.m_path, true, &i);
}

sal_Bool UrlReference::hasParameter(rtl::OUString const & key)
    throw (css::uno::RuntimeException)
{
    osl::MutexGuard g(m_base.m_mutex);
    return findParameter(key) >= 0;
}

rtl::OUString UrlReference::getParameter(rtl::OUString const & key)
    throw (css::uno::RuntimeException)
{
    osl::MutexGuard g(m_base.m_mutex);
    sal_Int32 i = findParameter(key);
    return i >= 0 ? parsePart(m_base.m_path, false, &i) : rtl::OUString();
}

sal_Int32 UrlReference::findParameter(rtl::OUString const & key) {
    sal_Int32 i = 0;
    parsePart(m_base.m_path, true, &i); // skip name
    for (;;) {
        if (i == m_base.m_path.getLength()) {
            return -1;
        }
        ++i; // skip '?' or '&'
        rtl::OUString k = parsePart(m_base.m_path, false, &i);
        ++i; // skip '='
        if (k == key) {
            return i;
        }
        parsePart(m_base.m_path, false, &i); // skip value
    }
}

class Parser: public cppu::WeakImplHelper2<
    css::lang::XServiceInfo, css::uri::XUriSchemeParser >
{
public:
    Parser() {}

    virtual rtl::OUString SAL_CALL getImplementationName()
        throw (css::uno::RuntimeException);

    virtual sal_Bool SAL_CALL supportsService(rtl::OUString const & serviceName)
        throw (css::uno::RuntimeException);

    virtual css::uno::Sequence< rtl::OUString > SAL_CALL
    getSupportedServiceNames() throw (css::uno::RuntimeException);

    virtual css::uno::Reference< css::uri::XUriReference > SAL_CALL
    parse(
        rtl::OUString const & scheme, rtl::OUString const & schemeSpecificPart)
        throw (css::uno::RuntimeException);

private:
    Parser(Parser &); // not implemented
    void operator =(Parser); // not implemented

    virtual ~Parser() {}
};

rtl::OUString Parser::getImplementationName()
    throw (css::uno::RuntimeException)
{
    return stoc_services::UriSchemeParser_vndDOTsunDOTstarDOTscript::
        getImplementationName();
}

sal_Bool Parser::supportsService(rtl::OUString const & serviceName)
    throw (css::uno::RuntimeException)
{
    return stoc::uriproc::supportsService(
        getSupportedServiceNames(), serviceName);
}

css::uno::Sequence< rtl::OUString > Parser::getSupportedServiceNames()
    throw (css::uno::RuntimeException)
{
    return stoc_services::UriSchemeParser_vndDOTsunDOTstarDOTscript::
        getSupportedServiceNames();
}

css::uno::Reference< css::uri::XUriReference >
Parser::parse(
    rtl::OUString const & scheme, rtl::OUString const & schemeSpecificPart)
    throw (css::uno::RuntimeException)
{
    if (!parseSchemeSpecificPart(schemeSpecificPart)) {
        return 0;
    }
    try {
        return new UrlReference(scheme, schemeSpecificPart);
    } catch (std::bad_alloc &) {
        throw css::uno::RuntimeException(
            rtl::OUString::createFromAscii("std::bad_alloc"), 0);
    }
}

}

namespace stoc_services {
namespace UriSchemeParser_vndDOTsunDOTstarDOTscript {

css::uno::Reference< css::uno::XInterface > create(
    css::uno::Reference< css::uno::XComponentContext > const &)
    SAL_THROW((css::uno::Exception))
{
    //TODO: single instance
    try {
        return static_cast< cppu::OWeakObject * >(new Parser);
    } catch (std::bad_alloc &) {
        throw css::uno::RuntimeException(
            rtl::OUString::createFromAscii("std::bad_alloc"), 0);
    }
}

rtl::OUString getImplementationName() {
    return rtl::OUString::createFromAscii(
        "com.sun.star.comp.uri.UriSchemeParser_vndDOTsunDOTstarDOTscript");
}

css::uno::Sequence< rtl::OUString > getSupportedServiceNames() {
    css::uno::Sequence< rtl::OUString > s(1);
    s[0] = rtl::OUString::createFromAscii(
        "com.sun.star.uri.UriSchemeParser_vndDOTsunDOTstarDOTscript");
    return s;
}

} }
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include "qsysteminfo.h"

Q_DECLARE_METATYPE(QSystemNetworkInfo::NetworkStatus);
Q_DECLARE_METATYPE(QSystemNetworkInfo::NetworkMode);

class tst_QSystemNetworkInfo : public QObject
{
    Q_OBJECT

private slots:

    void initTestCase();
    void tst_networkStatus();

    void tst_networkSignalStrength_data();
    void tst_networkSignalStrength();
    void tst_cellId();
    void tst_locationAreaCode();

    void tst_currentMobileCountryCode(); // Mobile Country Code
    void tst_currentMobileNetworkCode(); // Mobile Network Code

    void tst_homeMobileCountryCode();
    void tst_homeMobileNetworkCode();

    void tst_networkName();

    void tst_macAddress_data();
    void tst_macAddress();
};
//signal todo:
//    void networkStatusChanged(QSystemNetworkInfo::NetworkMode netmode, QSystemNetworkInfo::CellNetworkStatus netStatus);

void tst_QSystemNetworkInfo::initTestCase()
{
    qRegisterMetaType<QSystemNetworkInfo::NetworkStatus>("QSystemNetworkInfo::NetworkStatus");
    qRegisterMetaType<QSystemNetworkInfo::NetworkMode>("QSystemNetworkInfo::NetworkMode");
}

void tst_QSystemNetworkInfo::tst_networkStatus()
{
    QSystemNetworkInfo ni;
    QList<QSystemNetworkInfo::NetworkMode> modeList;
    modeList << QSystemNetworkInfo::GsmMode;
    modeList << QSystemNetworkInfo::CdmaMode;
    modeList << QSystemNetworkInfo::WcdmaMode;
    modeList << QSystemNetworkInfo::WlanMode;
    modeList << QSystemNetworkInfo::EthernetMode;
    modeList << QSystemNetworkInfo::BluetoothMode;
    modeList << QSystemNetworkInfo::WimaxMode;

    foreach(QSystemNetworkInfo::NetworkMode mode, modeList) {
        QSystemNetworkInfo::NetworkStatus status = ni.networkStatus(mode);

        QVERIFY( status == QSystemNetworkInfo::UndefinedStatus
                 || status == QSystemNetworkInfo::NoNetworkAvailable
                 || status == QSystemNetworkInfo::EmergencyOnly
                 || status == QSystemNetworkInfo::Searching
                 || status == QSystemNetworkInfo::Busy
                 || status == QSystemNetworkInfo::Connected
                 || status == QSystemNetworkInfo::HomeNetwork
                 || status == QSystemNetworkInfo::Denied
                 || status == QSystemNetworkInfo::Roaming);
    }

}

void tst_QSystemNetworkInfo::tst_networkSignalStrength_data()
{
    QTest::addColumn<QSystemNetworkInfo::NetworkMode>("mode");

    QTest::newRow("GsmMode") << QSystemNetworkInfo::GsmMode;
    QTest::newRow("CdmaMode") << QSystemNetworkInfo::CdmaMode;
    QTest::newRow("WcdmaMode") << QSystemNetworkInfo::WcdmaMode;
    QTest::newRow("WlanMode") << QSystemNetworkInfo::WlanMode;
    QTest::newRow("EthernetMode") << QSystemNetworkInfo::EthernetMode;
    QTest::newRow("BluetoothMode") << QSystemNetworkInfo::BluetoothMode;
    QTest::newRow("WimaxMode") << QSystemNetworkInfo::WimaxMode;
}

void tst_QSystemNetworkInfo::tst_networkSignalStrength()
{
    {
        QFETCH(QSystemNetworkInfo::NetworkMode, mode);
        QSystemNetworkInfo ni;
        qint32 strength = ni.networkSignalStrength(mode);
        QVERIFY( strength > -2
                && strength < 101);
    }
}

void  tst_QSystemNetworkInfo::tst_cellId()
{
    QSystemNetworkInfo ni;
    qint32 id = ni.cellId();
    QVERIFY(id > -2);
}

void  tst_QSystemNetworkInfo::tst_locationAreaCode()
{
    QSystemNetworkInfo ni;
    qint32 lac = ni.locationAreaCode();
    QVERIFY(lac > -2);
}

void  tst_QSystemNetworkInfo::tst_currentMobileCountryCode()
{
    QSystemNetworkInfo ni;
    QVERIFY(!ni.currentMobileCountryCode().isEmpty());
}

void  tst_QSystemNetworkInfo::tst_currentMobileNetworkCode()
{
    QSystemNetworkInfo ni;
    QVERIFY(!ni.currentMobileNetworkCode().isEmpty());
}

void  tst_QSystemNetworkInfo::tst_homeMobileCountryCode()
{
    QSystemNetworkInfo ni;
    QVERIFY(!ni.homeMobileCountryCode().isEmpty());
}

void  tst_QSystemNetworkInfo::tst_homeMobileNetworkCode()
{
    QSystemNetworkInfo ni;
    QVERIFY(!ni.homeMobileNetworkCode().isEmpty());
}

void  tst_QSystemNetworkInfo::tst_networkName()
{
    QSystemNetworkInfo ni;
    QList<QSystemNetworkInfo::NetworkMode> modeList;
    modeList << QSystemNetworkInfo::GsmMode;
    modeList << QSystemNetworkInfo::CdmaMode;
    modeList << QSystemNetworkInfo::WcdmaMode;
    modeList << QSystemNetworkInfo::WlanMode;
    modeList << QSystemNetworkInfo::EthernetMode;
    modeList << QSystemNetworkInfo::BluetoothMode;
    modeList << QSystemNetworkInfo::WimaxMode;

    foreach(QSystemNetworkInfo::NetworkMode mode, modeList) {
        QVERIFY(!ni.networkName(mode).isEmpty());
    }
}

void tst_QSystemNetworkInfo::tst_macAddress_data()
{
   tst_networkSignalStrength_data();
}

void tst_QSystemNetworkInfo::tst_macAddress()
{
   QFETCH(QSystemNetworkInfo::NetworkMode, mode);
   QSystemNetworkInfo ni;
   QString mac = ni.macAddress(mode);
   if (!mac.isEmpty()) {
      QVERIFY(mac.length() == 17);
      QVERIFY(mac.contains(":"));
   }
}

QTEST_MAIN(tst_QSystemNetworkInfo)
#include "tst_qsystemnetworkinfo.moc"
<commit_msg>add interfaceForMode<commit_after>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include "qsysteminfo.h"

Q_DECLARE_METATYPE(QSystemNetworkInfo::NetworkStatus);
Q_DECLARE_METATYPE(QSystemNetworkInfo::NetworkMode);

class tst_QSystemNetworkInfo : public QObject
{
    Q_OBJECT

private slots:

    void initTestCase();
    void tst_networkStatus();

    void tst_networkSignalStrength_data();
    void tst_networkSignalStrength();
    void tst_cellId();
    void tst_locationAreaCode();

    void tst_currentMobileCountryCode(); // Mobile Country Code
    void tst_currentMobileNetworkCode(); // Mobile Network Code

    void tst_homeMobileCountryCode();
    void tst_homeMobileNetworkCode();

    void tst_networkName();

    void tst_macAddress_data();
    void tst_macAddress();

    void tst_interfaceForMode();
};
//signal todo:
//    void networkStatusChanged(QSystemNetworkInfo::NetworkMode netmode, QSystemNetworkInfo::CellNetworkStatus netStatus);

void tst_QSystemNetworkInfo::initTestCase()
{
    qRegisterMetaType<QSystemNetworkInfo::NetworkStatus>("QSystemNetworkInfo::NetworkStatus");
    qRegisterMetaType<QSystemNetworkInfo::NetworkMode>("QSystemNetworkInfo::NetworkMode");
}

void tst_QSystemNetworkInfo::tst_networkStatus()
{
    QSystemNetworkInfo ni;
    QList<QSystemNetworkInfo::NetworkMode> modeList;
    modeList << QSystemNetworkInfo::GsmMode;
    modeList << QSystemNetworkInfo::CdmaMode;
    modeList << QSystemNetworkInfo::WcdmaMode;
    modeList << QSystemNetworkInfo::WlanMode;
    modeList << QSystemNetworkInfo::EthernetMode;
    modeList << QSystemNetworkInfo::BluetoothMode;
    modeList << QSystemNetworkInfo::WimaxMode;

    foreach(QSystemNetworkInfo::NetworkMode mode, modeList) {
        QSystemNetworkInfo::NetworkStatus status = ni.networkStatus(mode);

        QVERIFY( status == QSystemNetworkInfo::UndefinedStatus
                 || status == QSystemNetworkInfo::NoNetworkAvailable
                 || status == QSystemNetworkInfo::EmergencyOnly
                 || status == QSystemNetworkInfo::Searching
                 || status == QSystemNetworkInfo::Busy
                 || status == QSystemNetworkInfo::Connected
                 || status == QSystemNetworkInfo::HomeNetwork
                 || status == QSystemNetworkInfo::Denied
                 || status == QSystemNetworkInfo::Roaming);
    }

}

void tst_QSystemNetworkInfo::tst_networkSignalStrength_data()
{
    QTest::addColumn<QSystemNetworkInfo::NetworkMode>("mode");

    QTest::newRow("GsmMode") << QSystemNetworkInfo::GsmMode;
    QTest::newRow("CdmaMode") << QSystemNetworkInfo::CdmaMode;
    QTest::newRow("WcdmaMode") << QSystemNetworkInfo::WcdmaMode;
    QTest::newRow("WlanMode") << QSystemNetworkInfo::WlanMode;
    QTest::newRow("EthernetMode") << QSystemNetworkInfo::EthernetMode;
    QTest::newRow("BluetoothMode") << QSystemNetworkInfo::BluetoothMode;
    QTest::newRow("WimaxMode") << QSystemNetworkInfo::WimaxMode;
}

void tst_QSystemNetworkInfo::tst_networkSignalStrength()
{
    {
        QFETCH(QSystemNetworkInfo::NetworkMode, mode);
        QSystemNetworkInfo ni;
        qint32 strength = ni.networkSignalStrength(mode);
        QVERIFY( strength > -2
                && strength < 101);
    }
}

void  tst_QSystemNetworkInfo::tst_cellId()
{
    QSystemNetworkInfo ni;
    qint32 id = ni.cellId();
    QVERIFY(id > -2);
}

void  tst_QSystemNetworkInfo::tst_locationAreaCode()
{
    QSystemNetworkInfo ni;
    qint32 lac = ni.locationAreaCode();
    QVERIFY(lac > -2);
}

void  tst_QSystemNetworkInfo::tst_currentMobileCountryCode()
{
    QSystemNetworkInfo ni;
    QVERIFY(!ni.currentMobileCountryCode().isEmpty());
}

void  tst_QSystemNetworkInfo::tst_currentMobileNetworkCode()
{
    QSystemNetworkInfo ni;
    QVERIFY(!ni.currentMobileNetworkCode().isEmpty());
}

void  tst_QSystemNetworkInfo::tst_homeMobileCountryCode()
{
    QSystemNetworkInfo ni;
    QVERIFY(!ni.homeMobileCountryCode().isEmpty());
}

void  tst_QSystemNetworkInfo::tst_homeMobileNetworkCode()
{
    QSystemNetworkInfo ni;
    QVERIFY(!ni.homeMobileNetworkCode().isEmpty());
}

void  tst_QSystemNetworkInfo::tst_networkName()
{
    QSystemNetworkInfo ni;
    QList<QSystemNetworkInfo::NetworkMode> modeList;
    modeList << QSystemNetworkInfo::GsmMode;
    modeList << QSystemNetworkInfo::CdmaMode;
    modeList << QSystemNetworkInfo::WcdmaMode;
    modeList << QSystemNetworkInfo::WlanMode;
    modeList << QSystemNetworkInfo::EthernetMode;
    modeList << QSystemNetworkInfo::BluetoothMode;
    modeList << QSystemNetworkInfo::WimaxMode;

    foreach(QSystemNetworkInfo::NetworkMode mode, modeList) {
        QVERIFY(!ni.networkName(mode).isEmpty());
    }
}

void tst_QSystemNetworkInfo::tst_macAddress_data()
{
   tst_networkSignalStrength_data();
}

void tst_QSystemNetworkInfo::tst_macAddress()
{
   QFETCH(QSystemNetworkInfo::NetworkMode, mode);
   QSystemNetworkInfo ni;
   QString mac = ni.macAddress(mode);
   if (!mac.isEmpty()) {
      QVERIFY(mac.length() == 17);
      QVERIFY(mac.contains(":"));
   }
}

void tst_QSystemNetworkInfo::tst_interfaceForMode()
{
    QSystemNetworkInfo ni;
    QList<QSystemNetworkInfo::NetworkMode> modeList;
    modeList << QSystemNetworkInfo::GsmMode;
    modeList << QSystemNetworkInfo::CdmaMode;
    modeList << QSystemNetworkInfo::WcdmaMode;
    modeList << QSystemNetworkInfo::WlanMode;
    modeList << QSystemNetworkInfo::EthernetMode;
    modeList << QSystemNetworkInfo::BluetoothMode;
    modeList << QSystemNetworkInfo::WimaxMode;

    foreach(QSystemNetworkInfo::NetworkMode mode, modeList) {
        QVERIFY(!ni.interfaceForMode(mode).name().isEmpty());
    }

}

QTEST_MAIN(tst_QSystemNetworkInfo)
#include "tst_qsystemnetworkinfo.moc"
<|endoftext|>


<commit_before>
#include "test.h"

#include <GLFW/glfw3.h>
#include <bgfx.h>
#include <common.h>
#include <bgfx_utils.h>
#include <bgfxplatform.h>
#include <bx/string.h>
#include <bx/readerwriter.h>

#include "file.h"
#include "utilities.h"
#include "rendercontext.h"

video_test::video_test( void )
{
    se_type = 0;

}

struct PosColorVertex
{
    float m_x;
    float m_y;
    float m_z;
    uint32_t m_abgr;

    static void init()
    {
        ms_decl
            .begin()
            .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
            .add(bgfx::Attrib::Color0,   4, bgfx::AttribType::Uint8, true)
            .end();
    };

    static bgfx::VertexDecl ms_decl;
};

bgfx::VertexDecl PosColorVertex::ms_decl;

static PosColorVertex s_cubeVertices[8] =
{
    {-1.0f,  1.0f,  1.0f, 0xff000000 },
    { 1.0f,  1.0f,  1.0f, 0xff0000ff },
    {-1.0f, -1.0f,  1.0f, 0xff00ff00 },
    { 1.0f, -1.0f,  1.0f, 0xff00ffff },
    {-1.0f,  1.0f, -1.0f, 0xffff0000 },
    { 1.0f,  1.0f, -1.0f, 0xffff00ff },
    {-1.0f, -1.0f, -1.0f, 0xffffff00 },
    { 1.0f, -1.0f, -1.0f, 0xffffffff },
};

static const uint16_t s_cubeIndices[36] =
{
    0, 1, 2, // 0
    1, 3, 2,
    4, 6, 5, // 2
    5, 6, 7,
    0, 2, 4, // 4
    4, 2, 6,
    1, 5, 3, // 6
    5, 7, 3,
    0, 4, 1, // 8
    4, 5, 1,
    2, 3, 6, // 10
    6, 3, 7,
};

static const bgfx::Memory* loadMem(bx::FileReaderI* _reader, const char* _filePath)
{
    if (0 == bx::open(_reader, _filePath) )
    {
        uint32_t size = (uint32_t)bx::getSize(_reader);
        const bgfx::Memory* mem = bgfx::alloc(size+1);
        bx::read(_reader, mem->data, size);
        bx::close(_reader);
        mem->data[mem->size-1] = '\0';
        return mem;
    }

    return NULL;
}

void video_test::start( void )
{
    uint32_t width = 1280;
        uint32_t height = 720;
        uint32_t debug = BGFX_DEBUG_TEXT;
        uint32_t reset = BGFX_RESET_VSYNC;

        if (!glfwInit())
            exit(EXIT_FAILURE);

        GLFWwindow* window = glfwCreateWindow(1280, 720, "My Title", NULL, NULL);
        glfwMakeContextCurrent(window);

        bgfx::glfwSetWindow( window );

        bgfx::init();
        bgfx::reset(width, height, reset);

        // Enable debug text.
        bgfx::setDebug(debug);

        // Set view 0 clear state.
        bgfx::setViewClear(0
            , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT
            , 0x303030ff
            , 1.0f
            , 0
            );

        // Create vertex stream declaration.
        PosColorVertex::init();

        // Create static vertex buffer.
        bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer(
              // Static data can be passed with bgfx::makeRef
              bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) )
            , PosColorVertex::ms_decl
            );

        crap::VertexDeclaration vb_decl;
        crap::VertexAttribute vb_attr[2];
        crap::setVertexAttribute( vb_attr[0], crap::Attribute::position, 3, crap::AttributeType::flt32 );
        crap::setVertexAttribute( vb_attr[1], crap::Attribute::color0, 4, crap::AttributeType::uint8, true );
        crap::setVertexDeclarationAttributes( vb_decl, vb_attr, 2 );
        crap::RenderHandle vb_buffer = crap::createStaticVertexBuffer( s_cubeVertices, sizeof(s_cubeVertices), &vb_decl );

        crap::file_t* vs_file = crap::openFile( "../../../data/vs_instancing.bin", CRAP_FILE_READBINARY );
        uint32_t vs_size = crap::fileSize("../../../data/vs_instancing.bin");
        char vs_memory[ vs_size ];
        crap::readFromFile( vs_file, vs_memory, vs_size );
        crap::RenderHandle vs_handle = crap::createShader( vs_memory, vs_size );

        crap::file_t* fs_file = crap::openFile( "../../../data/fs_instancing.bin", CRAP_FILE_READBINARY );
        uint32_t fs_size = crap::fileSize("../../../data/fs_instancing.bin");
        char fs_memory[ fs_size ];
        crap::readFromFile( fs_file, fs_memory, fs_size );
        crap::RenderHandle fs_handle = crap::createShader( fs_memory, fs_size );

        crap::RenderHandle pr_handle = crap::createProgram( vs_handle, fs_handle );

        // Create static index buffer.
        bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer(
            // Static data can be passed with bgfx::makeRef
            bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) )
            );

        float at[3] = { 50.0f, 50.0f, 0.0f };
        float eye[3] = { 50.0f, 50.0f, -100.0f };

        int64_t timeOffset = bx::getHPCounter();

        uint32_t key = 0;
        key |= ( 1 << 6 ) | ( 1 << 7 ) | ( 1 << 8 );

        uint32_t keys[100];
        uint32_t levels[100];

        for( uint32_t u=0; u< 100; ++u )
        {
            keys[u] = rand();
            levels[u] = rand() % 9;
        }
        bgfx::setViewSeq(0, true);

        while ( glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS )
        {

            float view[16];
            float proj[16];
            bx::mtxLookAt(view, eye, at);
            bx::mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 1000.0f);

            // Set view and projection matrix for view 0.
            bgfx::setViewTransform(0, view, proj);

            // Set view 0 default viewport.
            bgfx::setViewRect(0, 0, 0, width, height);

            // This dummy draw call is here to make sure that view 0 is cleared
            // if no other draw calls are submitted to view 0.
            bgfx::submit(0);

            int64_t now = bx::getHPCounter();
            static int64_t last = now;
            const int64_t frameTime = now - last;
            last = now;
            const double freq = double(bx::getHPFrequency() );
            const double toMs = 1000.0/freq;

            float time = (float)( (now-timeOffset)/double(bx::getHPFrequency() ) );

            // Use debug font to print information about this example.
            bgfx::dbgTextClear();
            bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/00-helloworld");
            bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Initialization and debug text.");
            bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs);
            bgfx::dbgTextPrintf(0, 4, 0x6f, "Press ESC to close window and exit.");

            const uint16_t instanceStride = 80;
            const bgfx::InstanceDataBuffer* idb = bgfx::allocInstanceDataBuffer(100, instanceStride);

            if( idb != 0 )
            {
                uint8_t* data = idb->data;

                for( uint32_t y=0; y<100; ++y )
                {
                    float* mtx = (float*)data;
                    bx::mtxRotateXY(mtx, 0, 0);
                    keyToCoords( mtx[12], mtx[13], mtx[14], keys[y], levels[y] );

                    bx::mtxScale(mtx, 10, 10, 10);

                    float* color = (float*)&data[64];
                    color[0] = sin(time+float(y)/11.0f)*0.5f+0.5f;
                    color[1] = cos(time+float(y)/11.0f)*0.5f+0.5f;
                    color[2] = sin(time*3.0f)*0.5f+0.5f;
                    color[3] = 1.0f;

                    data += instanceStride;
                }

            }

            // Set vertex and fragment shaders.
            //bgfx::setProgram(program);
            crap::setProgram( pr_handle );

            // Set vertex and index buffer.
            bgfx::setVertexBuffer(vbh);
            //crap::setVertexBuffer( vb_buffer );

            bgfx::setIndexBuffer(ibh);

            // Set instance data buffer.
            bgfx::setInstanceDataBuffer(idb);

            // Set render states.
            bgfx::setState(BGFX_STATE_DEFAULT);

            // Submit primitive for rendering to view 0.
            bgfx::submit(0);

            // Advance to next frame. Rendering thread will be kicked to
            // process submitted rendering primitives.
            bgfx::frame();

            glfwPollEvents();
        }

        // Shutdown bgfx.
        bgfx::shutdown();

        glfwDestroyWindow(window);
        glfwTerminate();
}
<commit_msg>update<commit_after>
#include "test.h"

#include <GLFW/glfw3.h>
#include <bgfx.h>
#include <common.h>
#include <bgfx_utils.h>
#include <bgfxplatform.h>
#include <bx/string.h>
#include <bx/readerwriter.h>

#include "file.h"
#include "utilities.h"
#include "rendercontext.h"

video_test::video_test( void )
{
    se_type = 0;

}

struct PosColorVertex
{
    float m_x;
    float m_y;
    float m_z;
    uint32_t m_abgr;

    static void init()
    {
        ms_decl
            .begin()
            .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
            .add(bgfx::Attrib::Color0,   4, bgfx::AttribType::Uint8, true)
            .end();
    };

    static bgfx::VertexDecl ms_decl;
};

bgfx::VertexDecl PosColorVertex::ms_decl;

static PosColorVertex s_cubeVertices[8] =
{
    {-1.0f,  1.0f,  1.0f, 0xff000000 },
    { 1.0f,  1.0f,  1.0f, 0xff0000ff },
    {-1.0f, -1.0f,  1.0f, 0xff00ff00 },
    { 1.0f, -1.0f,  1.0f, 0xff00ffff },
    {-1.0f,  1.0f, -1.0f, 0xffff0000 },
    { 1.0f,  1.0f, -1.0f, 0xffff00ff },
    {-1.0f, -1.0f, -1.0f, 0xffffff00 },
    { 1.0f, -1.0f, -1.0f, 0xffffffff },
};

static const uint16_t s_cubeIndices[36] =
{
    0, 1, 2, // 0
    1, 3, 2,
    4, 6, 5, // 2
    5, 6, 7,
    0, 2, 4, // 4
    4, 2, 6,
    1, 5, 3, // 6
    5, 7, 3,
    0, 4, 1, // 8
    4, 5, 1,
    2, 3, 6, // 10
    6, 3, 7,
};

static const bgfx::Memory* loadMem(bx::FileReaderI* _reader, const char* _filePath)
{
    if (0 == bx::open(_reader, _filePath) )
    {
        uint32_t size = (uint32_t)bx::getSize(_reader);
        const bgfx::Memory* mem = bgfx::alloc(size+1);
        bx::read(_reader, mem->data, size);
        bx::close(_reader);
        mem->data[mem->size-1] = '\0';
        return mem;
    }

    return NULL;
}

void video_test::start( void )
{
    uint32_t width = 1280;
        uint32_t height = 720;
        uint32_t debug = BGFX_DEBUG_TEXT;
        uint32_t reset = BGFX_RESET_VSYNC;

        if (!glfwInit())
            exit(EXIT_FAILURE);

        GLFWwindow* window = glfwCreateWindow(1280, 720, "My Title", NULL, NULL);
        glfwMakeContextCurrent(window);

        bgfx::glfwSetWindow( window );

        bgfx::init();
        bgfx::reset(width, height, reset);

        // Enable debug text.
        bgfx::setDebug(debug);

        // Set view 0 clear state.
        bgfx::setViewClear(0
            , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT
            , 0x303030ff
            , 1.0f
            , 0
            );

        // Create vertex stream declaration.
        PosColorVertex::init();

        // Create static vertex buffer.
        bgfx::VertexBufferHandle vbh = bgfx::createVertexBuffer(
              // Static data can be passed with bgfx::makeRef
              bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) )
            , PosColorVertex::ms_decl
            );

        crap::VertexDeclaration vb_decl;
        crap::VertexAttribute vb_attr[2];
        crap::setVertexAttribute( vb_attr[0], crap::Attribute::position, 3, crap::AttributeType::flt32 );
        crap::setVertexAttribute( vb_attr[1], crap::Attribute::color0, 4, crap::AttributeType::uint8, true );
        crap::setVertexDeclarationAttributes( vb_decl, vb_attr, 2 );
        crap::RenderHandle vb_buffer = crap::createStaticVertexBuffer( s_cubeVertices, sizeof(s_cubeVertices), &vb_decl );

        crap::file_t* vs_file = crap::openFile( "../../../data/vs_instancing.bin", CRAP_FILE_READBINARY );
        uint32_t vs_size = crap::fileSize("../../../data/vs_instancing.bin");
        char vs_memory[ vs_size ];
        crap::readFromFile( vs_file, vs_memory, vs_size );
        crap::RenderHandle vs_handle = crap::createShader( vs_memory, vs_size );

        crap::file_t* fs_file = crap::openFile( "../../../data/fs_instancing.bin", CRAP_FILE_READBINARY );
        uint32_t fs_size = crap::fileSize("../../../data/fs_instancing.bin");
        char fs_memory[ fs_size ];
        crap::readFromFile( fs_file, fs_memory, fs_size );
        crap::RenderHandle fs_handle = crap::createShader( fs_memory, fs_size );

        crap::RenderHandle pr_handle = crap::createProgram( vs_handle, fs_handle );

        // Create static index buffer.
        bgfx::IndexBufferHandle ibh = bgfx::createIndexBuffer(
            // Static data can be passed with bgfx::makeRef
            bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) )
            );

        float at[3] = { 50.0f, 50.0f, 0.0f };
        float eye[3] = { 50.0f, 50.0f, -100.0f };

        int64_t timeOffset = bx::getHPCounter();

        uint32_t key = 0;
        key |= ( 1 << 6 ) | ( 1 << 7 ) | ( 1 << 8 );

        uint32_t keys[100];
        uint32_t levels[100];

        for( uint32_t u=0; u< 100; ++u )
        {
            keys[u] = rand();
            levels[u] = rand() % 9;
        }
        bgfx::setViewSeq(0, true);

        while ( glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS )
        {

            float view[16];
            float proj[16];
            bx::mtxLookAt(view, eye, at);
            bx::mtxProj(proj, 60.0f, float(width)/float(height), 0.1f, 1000.0f);

            // Set view and projection matrix for view 0.
            bgfx::setViewTransform(0, view, proj);

            // Set view 0 default viewport.
            bgfx::setViewRect(0, 0, 0, width, height);

            // This dummy draw call is here to make sure that view 0 is cleared
            // if no other draw calls are submitted to view 0.
            bgfx::submit(0);

            int64_t now = bx::getHPCounter();
            static int64_t last = now;
            const int64_t frameTime = now - last;
            last = now;
            const double freq = double(bx::getHPFrequency() );
            const double toMs = 1000.0/freq;

            float time = (float)( (now-timeOffset)/double(bx::getHPFrequency() ) );

            // Use debug font to print information about this example.
            bgfx::dbgTextClear();
            bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/00-helloworld");
            bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Initialization and debug text.");
            bgfx::dbgTextPrintf(0, 3, 0x0f, "Frame: % 7.3f[ms]", double(frameTime)*toMs);
            bgfx::dbgTextPrintf(0, 4, 0x6f, "Press ESC to close window and exit.");

            const uint16_t instanceStride = 80;
            const bgfx::InstanceDataBuffer* idb = bgfx::allocInstanceDataBuffer(100, instanceStride);

            if( idb != 0 )
            {
                uint8_t* data = idb->data;

                for( uint32_t y=0; y<100; ++y )
                {
                    float* mtx = (float*)data;
                    bx::mtxRotateXY(mtx, 0, 0);
                    keyToCoords( mtx[12], mtx[13], mtx[14], keys[y], levels[y] );

                    bx::mtxScale(mtx, 10, 10, 10);

                    float* color = (float*)&data[64];
                    color[0] = sin(time+float(y)/11.0f)*0.5f+0.5f;
                    color[1] = cos(time+float(y)/11.0f)*0.5f+0.5f;
                    color[2] = sin(time*3.0f)*0.5f+0.5f;
                    color[3] = 1.0f;

                    data += instanceStride;
                }

            }

            // Set vertex and fragment shaders.
            //bgfx::setProgram(program);
            crap::setProgram( pr_handle );

            // Set vertex and index buffer.
            bgfx::setVertexBuffer(vbh);
            //crap::setVertexBuffer( vb_buffer );

            bgfx::setIndexBuffer(ibh);

            // Set instance data buffer.
            bgfx::setInstanceDataBuffer(idb);

            // Set render states.
            bgfx::setState(BGFX_STATE_DEFAULT);

            // Submit primitive for rendering to view 0.
            bgfx::submit(0);

            // Advance to next frame. Rendering thread will be kicked to
            // process submitted rendering primitives.
            bgfx::frame();

            glfwPollEvents();
        }

        // Shutdown bgfx.
        bgfx::shutdown();

        glfwDestroyWindow(window);
        glfwTerminate();
}
<|endoftext|>