<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkPluginActivator.h"

#include "mitkLog.h"

#include <QString>
#include <QFileInfo>

#include "internal/mitkDataStorageService.h"

#include <mitkModuleRegistry.h>
#include <mitkModule.h>
#include <mitkModuleContext.h>

namespace mitk
{

class ITKLightObjectToQObjectAdapter : public QObject
{

public:

  ITKLightObjectToQObjectAdapter(const QStringList& clazzes, itk::LightObject* service)
    : interfaceNames(clazzes), mitkService(service)
  {}

  // This method is called by the Qt meta object system. It is usually
  // generated by the moc, but we create it manually to be able to return
  // a MITK micro service object (derived from itk::LightObject). It basically
  // works as if the micro service class had used the Q_INTERFACES macro in
  // its declaration. Now we can successfully do a
  // qobject_cast<mitk::SomeMicroServiceInterface>(lightObjectToQObjectAdapter)
  void* qt_metacast(const char *_clname)
  {
    if (!_clname) return 0;
    if (!strcmp(_clname, "ITKLightObjectToQObjectAdapter"))
      return static_cast<void*>(const_cast<ITKLightObjectToQObjectAdapter*>(this));
    if (interfaceNames.contains(QString(_clname)))
      return static_cast<void*>(mitkService);
    return QObject::qt_metacast(_clname);
  }

private:

  QStringList interfaceNames;
  itk::LightObject* mitkService;
};

const std::string org_mitk_core_services_Activator::PLUGIN_ID = "org.mitk.core.services";

void org_mitk_core_services_Activator::start(ctkPluginContext* context)
{
  pluginContext = context;

  //initialize logging
  mitk::LoggingBackend::Register();
  QString filename = "mitk.log";
  QFileInfo path = context->getDataFile(filename);
  mitk::LoggingBackend::SetLogFile(path.absoluteFilePath().toStdString().c_str());
  MITK_INFO << "Logfile: " << path.absoluteFilePath().toStdString().c_str();

  //initialize data storage service
  DataStorageService* service = new DataStorageService();
  dataStorageService = IDataStorageService::Pointer(service);
  context->registerService<mitk::IDataStorageService>(service);

  // Get the MitkCore Module Context
  mitkContext = mitk::ModuleRegistry::GetModule(1)->GetModuleContext();

  // Process all already registered services
  std::list<mitk::ServiceReference> refs = mitkContext->GetServiceReferences("");
  for (std::list<mitk::ServiceReference>::const_iterator i = refs.begin();
       i != refs.end(); ++i)
  {
    this->AddMitkService(*i);
  }

  mitkContext->AddServiceListener(this, &org_mitk_core_services_Activator::MitkServiceChanged);
}

void org_mitk_core_services_Activator::stop(ctkPluginContext* /*context*/)
{
  mitkContext->RemoveServiceListener(this, &org_mitk_core_services_Activator::MitkServiceChanged);

  foreach(ctkServiceRegistration reg, mapMitkIdToRegistration.values())
  {
    reg.unregister();
  }
  mapMitkIdToRegistration.clear();

  qDeleteAll(mapMitkIdToAdapter);
  mapMitkIdToAdapter.clear();

  //clean up logging
  mitk::LoggingBackend::Unregister();

  dataStorageService = 0;
  mitkContext = 0;
  pluginContext = 0;
}

void org_mitk_core_services_Activator::MitkServiceChanged(const mitk::ServiceEvent event)
{
  switch (event.GetType())
  {
  case mitk::ServiceEvent::REGISTERED:
  {
    this->AddMitkService(event.GetServiceReference());
    break;
  }
  case mitk::ServiceEvent::UNREGISTERING:
  {
    long mitkServiceId = mitk::any_cast<long>(event.GetServiceReference().GetProperty(mitk::ServiceConstants::SERVICE_ID()));
    ctkServiceRegistration reg = mapMitkIdToRegistration.take(mitkServiceId);
    if (reg)
    {
      reg.unregister();
    }
    delete mapMitkIdToAdapter.take(mitkServiceId);
    break;
  }
  case mitk::ServiceEvent::MODIFIED:
  {
    long mitkServiceId = mitk::any_cast<long>(event.GetServiceReference().GetProperty(mitk::ServiceConstants::SERVICE_ID()));
    ctkDictionary newProps = CreateServiceProperties(event.GetServiceReference());
    mapMitkIdToRegistration[mitkServiceId].setProperties(newProps);
    break;
  }
  default:
    break; // do nothing
  }
}

void org_mitk_core_services_Activator::AddMitkService(const mitk::ServiceReference& ref)
{
  // Get the MITK micro service object
  itk::LightObject* mitkService = mitkContext->GetService(ref);
  if (mitkService == 0) return;

  // Get the interface names against which the service was registered
  std::list<std::string> clazzes =
      mitk::any_cast<std::list<std::string> >(ref.GetProperty(mitk::ServiceConstants::OBJECTCLASS()));

  QStringList qclazzes;
  for(std::list<std::string>::const_iterator clazz = clazzes.begin();
      clazz != clazzes.end(); ++clazz)
  {
    qclazzes << QString::fromStdString(*clazz);
  }

  long mitkServiceId = mitk::any_cast<long>(ref.GetProperty(mitk::ServiceConstants::SERVICE_ID()));

  QObject* adapter = new ITKLightObjectToQObjectAdapter(qclazzes, mitkService);
  mapMitkIdToAdapter[mitkServiceId] = adapter;

  ctkDictionary props = CreateServiceProperties(ref);
  mapMitkIdToRegistration[mitkServiceId] = pluginContext->registerService(qclazzes, adapter, props);
}

ctkDictionary org_mitk_core_services_Activator::CreateServiceProperties(const ServiceReference &ref)
{
  ctkDictionary props;

  long mitkServiceId = mitk::any_cast<long>(ref.GetProperty(mitk::ServiceConstants::SERVICE_ID()));
  props.insert("mitk.serviceid", QVariant::fromValue(mitkServiceId));

  // Add all other properties from the MITK micro service
  std::vector<std::string> keys;
  ref.GetPropertyKeys(keys);
  for (std::vector<std::string>::const_iterator it = keys.begin(); it != keys.end(); ++it)
  {
    QString key = QString::fromStdString(*it);
    mitk::Any value = ref.GetProperty(*it);
    // We cannot add any mitk::Any object, we need to query the type
    const std::type_info& objType = value.Type();
    if (objType == typeid(std::string))
    {
      props.insert(key, QString::fromStdString(ref_any_cast<std::string>(value)));
    }
    else if (objType == typeid(std::vector<std::string>))
    {
      const std::vector<std::string>& list = ref_any_cast<std::vector<std::string> >(value);
      QStringList qlist;
      for (std::vector<std::string>::const_iterator str = list.begin();
           str != list.end(); ++str)
      {
         qlist << QString::fromStdString(*str);
      }
      props.insert(key, qlist);
    }
    else if (objType == typeid(std::list<std::string>))
    {
      const std::list<std::string>& list = ref_any_cast<std::list<std::string> >(value);
      QStringList qlist;
      for (std::list<std::string>::const_iterator str = list.begin();
           str != list.end(); ++str)
      {
         qlist << QString::fromStdString(*str);
      }
      props.insert(key, qlist);
    }
    else if (objType == typeid(char))
    {
      props.insert(key, QChar(ref_any_cast<char>(value)));
    }
    else if (objType == typeid(unsigned char))
    {
      props.insert(key, QChar(ref_any_cast<unsigned char>(value)));
    }
    else if (objType == typeid(bool))
    {
      props.insert(key, any_cast<bool>(value));
    }
    else if (objType == typeid(short))
    {
      props.insert(key, any_cast<short>(value));
    }
    else if (objType == typeid(unsigned short))
    {
      props.insert(key, any_cast<unsigned short>(value));
    }
    else if (objType == typeid(int))
    {
      props.insert(key, any_cast<int>(value));
    }
    else if (objType == typeid(unsigned int))
    {
      props.insert(key, any_cast<unsigned int>(value));
    }
    else if (objType == typeid(float))
    {
      props.insert(key, any_cast<float>(value));
    }
    else if (objType == typeid(double))
    {
      props.insert(key, any_cast<double>(value));
    }
    else if (objType == typeid(long long int))
    {
      props.insert(key, any_cast<long long int>(value));
    }
    else if (objType == typeid(unsigned long long int))
    {
      props.insert(key, any_cast<unsigned long long int>(value));
    }
  }

  return props;
}

org_mitk_core_services_Activator::org_mitk_core_services_Activator()
  : mitkContext(0), pluginContext(0)
{
}

}

Q_EXPORT_PLUGIN2(org_mitk_core_services, mitk::org_mitk_core_services_Activator)
<commit_msg>removed logging message when opening logging file which is now logged in the logging backend itself<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

#include "mitkPluginActivator.h"

#include "mitkLog.h"

#include <QString>
#include <QFileInfo>

#include "internal/mitkDataStorageService.h"

#include <mitkModuleRegistry.h>
#include <mitkModule.h>
#include <mitkModuleContext.h>

namespace mitk
{

class ITKLightObjectToQObjectAdapter : public QObject
{

public:

  ITKLightObjectToQObjectAdapter(const QStringList& clazzes, itk::LightObject* service)
    : interfaceNames(clazzes), mitkService(service)
  {}

  // This method is called by the Qt meta object system. It is usually
  // generated by the moc, but we create it manually to be able to return
  // a MITK micro service object (derived from itk::LightObject). It basically
  // works as if the micro service class had used the Q_INTERFACES macro in
  // its declaration. Now we can successfully do a
  // qobject_cast<mitk::SomeMicroServiceInterface>(lightObjectToQObjectAdapter)
  void* qt_metacast(const char *_clname)
  {
    if (!_clname) return 0;
    if (!strcmp(_clname, "ITKLightObjectToQObjectAdapter"))
      return static_cast<void*>(const_cast<ITKLightObjectToQObjectAdapter*>(this));
    if (interfaceNames.contains(QString(_clname)))
      return static_cast<void*>(mitkService);
    return QObject::qt_metacast(_clname);
  }

private:

  QStringList interfaceNames;
  itk::LightObject* mitkService;
};

const std::string org_mitk_core_services_Activator::PLUGIN_ID = "org.mitk.core.services";

void org_mitk_core_services_Activator::start(ctkPluginContext* context)
{
  pluginContext = context;

  //initialize logging
  mitk::LoggingBackend::Register();
  QString filename = "mitk.log";
  QFileInfo path = context->getDataFile(filename);
  mitk::LoggingBackend::SetLogFile(path.absoluteFilePath().toStdString().c_str());

  //initialize data storage service
  DataStorageService* service = new DataStorageService();
  dataStorageService = IDataStorageService::Pointer(service);
  context->registerService<mitk::IDataStorageService>(service);

  // Get the MitkCore Module Context
  mitkContext = mitk::ModuleRegistry::GetModule(1)->GetModuleContext();

  // Process all already registered services
  std::list<mitk::ServiceReference> refs = mitkContext->GetServiceReferences("");
  for (std::list<mitk::ServiceReference>::const_iterator i = refs.begin();
       i != refs.end(); ++i)
  {
    this->AddMitkService(*i);
  }

  mitkContext->AddServiceListener(this, &org_mitk_core_services_Activator::MitkServiceChanged);
}

void org_mitk_core_services_Activator::stop(ctkPluginContext* /*context*/)
{
  mitkContext->RemoveServiceListener(this, &org_mitk_core_services_Activator::MitkServiceChanged);

  foreach(ctkServiceRegistration reg, mapMitkIdToRegistration.values())
  {
    reg.unregister();
  }
  mapMitkIdToRegistration.clear();

  qDeleteAll(mapMitkIdToAdapter);
  mapMitkIdToAdapter.clear();

  //clean up logging
  mitk::LoggingBackend::Unregister();

  dataStorageService = 0;
  mitkContext = 0;
  pluginContext = 0;
}

void org_mitk_core_services_Activator::MitkServiceChanged(const mitk::ServiceEvent event)
{
  switch (event.GetType())
  {
  case mitk::ServiceEvent::REGISTERED:
  {
    this->AddMitkService(event.GetServiceReference());
    break;
  }
  case mitk::ServiceEvent::UNREGISTERING:
  {
    long mitkServiceId = mitk::any_cast<long>(event.GetServiceReference().GetProperty(mitk::ServiceConstants::SERVICE_ID()));
    ctkServiceRegistration reg = mapMitkIdToRegistration.take(mitkServiceId);
    if (reg)
    {
      reg.unregister();
    }
    delete mapMitkIdToAdapter.take(mitkServiceId);
    break;
  }
  case mitk::ServiceEvent::MODIFIED:
  {
    long mitkServiceId = mitk::any_cast<long>(event.GetServiceReference().GetProperty(mitk::ServiceConstants::SERVICE_ID()));
    ctkDictionary newProps = CreateServiceProperties(event.GetServiceReference());
    mapMitkIdToRegistration[mitkServiceId].setProperties(newProps);
    break;
  }
  default:
    break; // do nothing
  }
}

void org_mitk_core_services_Activator::AddMitkService(const mitk::ServiceReference& ref)
{
  // Get the MITK micro service object
  itk::LightObject* mitkService = mitkContext->GetService(ref);
  if (mitkService == 0) return;

  // Get the interface names against which the service was registered
  std::list<std::string> clazzes =
      mitk::any_cast<std::list<std::string> >(ref.GetProperty(mitk::ServiceConstants::OBJECTCLASS()));

  QStringList qclazzes;
  for(std::list<std::string>::const_iterator clazz = clazzes.begin();
      clazz != clazzes.end(); ++clazz)
  {
    qclazzes << QString::fromStdString(*clazz);
  }

  long mitkServiceId = mitk::any_cast<long>(ref.GetProperty(mitk::ServiceConstants::SERVICE_ID()));

  QObject* adapter = new ITKLightObjectToQObjectAdapter(qclazzes, mitkService);
  mapMitkIdToAdapter[mitkServiceId] = adapter;

  ctkDictionary props = CreateServiceProperties(ref);
  mapMitkIdToRegistration[mitkServiceId] = pluginContext->registerService(qclazzes, adapter, props);
}

ctkDictionary org_mitk_core_services_Activator::CreateServiceProperties(const ServiceReference &ref)
{
  ctkDictionary props;

  long mitkServiceId = mitk::any_cast<long>(ref.GetProperty(mitk::ServiceConstants::SERVICE_ID()));
  props.insert("mitk.serviceid", QVariant::fromValue(mitkServiceId));

  // Add all other properties from the MITK micro service
  std::vector<std::string> keys;
  ref.GetPropertyKeys(keys);
  for (std::vector<std::string>::const_iterator it = keys.begin(); it != keys.end(); ++it)
  {
    QString key = QString::fromStdString(*it);
    mitk::Any value = ref.GetProperty(*it);
    // We cannot add any mitk::Any object, we need to query the type
    const std::type_info& objType = value.Type();
    if (objType == typeid(std::string))
    {
      props.insert(key, QString::fromStdString(ref_any_cast<std::string>(value)));
    }
    else if (objType == typeid(std::vector<std::string>))
    {
      const std::vector<std::string>& list = ref_any_cast<std::vector<std::string> >(value);
      QStringList qlist;
      for (std::vector<std::string>::const_iterator str = list.begin();
           str != list.end(); ++str)
      {
         qlist << QString::fromStdString(*str);
      }
      props.insert(key, qlist);
    }
    else if (objType == typeid(std::list<std::string>))
    {
      const std::list<std::string>& list = ref_any_cast<std::list<std::string> >(value);
      QStringList qlist;
      for (std::list<std::string>::const_iterator str = list.begin();
           str != list.end(); ++str)
      {
         qlist << QString::fromStdString(*str);
      }
      props.insert(key, qlist);
    }
    else if (objType == typeid(char))
    {
      props.insert(key, QChar(ref_any_cast<char>(value)));
    }
    else if (objType == typeid(unsigned char))
    {
      props.insert(key, QChar(ref_any_cast<unsigned char>(value)));
    }
    else if (objType == typeid(bool))
    {
      props.insert(key, any_cast<bool>(value));
    }
    else if (objType == typeid(short))
    {
      props.insert(key, any_cast<short>(value));
    }
    else if (objType == typeid(unsigned short))
    {
      props.insert(key, any_cast<unsigned short>(value));
    }
    else if (objType == typeid(int))
    {
      props.insert(key, any_cast<int>(value));
    }
    else if (objType == typeid(unsigned int))
    {
      props.insert(key, any_cast<unsigned int>(value));
    }
    else if (objType == typeid(float))
    {
      props.insert(key, any_cast<float>(value));
    }
    else if (objType == typeid(double))
    {
      props.insert(key, any_cast<double>(value));
    }
    else if (objType == typeid(long long int))
    {
      props.insert(key, any_cast<long long int>(value));
    }
    else if (objType == typeid(unsigned long long int))
    {
      props.insert(key, any_cast<unsigned long long int>(value));
    }
  }

  return props;
}

org_mitk_core_services_Activator::org_mitk_core_services_Activator()
  : mitkContext(0), pluginContext(0)
{
}

}

Q_EXPORT_PLUGIN2(org_mitk_core_services, mitk::org_mitk_core_services_Activator)
<|endoftext|>


<commit_before><commit_msg>Bump the interpreter stack size for the main thread.<commit_after><|endoftext|>


<commit_before>/*
  Copyright (C) 2008-2014 The Communi Project

  You may use this file under the terms of BSD license as follows:

  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.
    * Neither the name of the copyright holder nor the names of its
      contributors may 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 HOLDERS 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 "zncmanager.h"
#include "ignoremanager.h"
#include <ircbuffermodel.h>
#include <ircconnection.h>
#include <irccommand.h>
#include <ircmessage.h>
#include <ircbuffer.h>

IRC_USE_NAMESPACE

ZncManager::ZncManager(QObject* parent) : QObject(parent)
{
    d.model = 0;
    d.buffer = 0;
    d.timestamp = QDateTime::fromTime_t(0);
    setModel(qobject_cast<IrcBufferModel*>(parent));
}

ZncManager::~ZncManager()
{
}

IrcBufferModel* ZncManager::model() const
{
    return d.model;
}

void ZncManager::setModel(IrcBufferModel* model)
{
    if (d.model != model) {
        if (d.model && d.model->connection()) {
            IrcConnection* connection = d.model->connection();
            disconnect(connection, SIGNAL(connected()), this, SLOT(requestPlayback()));
            disconnect(connection->network(), SIGNAL(requestingCapabilities()), this, SLOT(requestCapabilities()));
            connection->removeMessageFilter(this);
            disconnect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*)));
        }
        d.model = model;
        if (d.model && d.model->connection()) {
            IrcConnection* connection = d.model->connection();
            connect(connection, SIGNAL(connected()), this, SLOT(requestPlayback()));
            connect(connection->network(), SIGNAL(requestingCapabilities()), this, SLOT(requestCapabilities()));
            connection->installMessageFilter(this);
            connect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*)));
        }
        emit modelChanged(model);
    }
}

bool ZncManager::messageFilter(IrcMessage* message)
{
    bool playback = false;
    if (message->tags().contains("time")) {
        QDateTime timestamp = message->tags().value("time").toDateTime();
        if (timestamp.isValid()) {
            message->setTimeStamp(timestamp.toTimeSpec(Qt::LocalTime));
            playback = timestamp < d.timestamp;
            d.timestamp = qMax(timestamp, d.timestamp);
        }
    }

    if (!playback && d.buffer) {
        emit playbackEnd(d.buffer);
        d.buffer = 0;
    }

    if (message->type() == IrcMessage::Private) {
        IrcPrivateMessage* msg = static_cast<IrcPrivateMessage*>(message);
        IrcBuffer* buffer = d.model->find(msg->target());
        if (buffer) {
            if (d.buffer != buffer) {
                if (d.buffer) {
                    emit playbackEnd(d.buffer);
                    d.buffer = 0;
                }
                if (playback) {
                    emit playbackBegin(buffer);
                    d.buffer = buffer;
                }
            }
            return processMessage(buffer, msg);
        }
    }
    return IgnoreManager::instance()->messageFilter(message);
}

bool ZncManager::processMessage(IrcBuffer* buffer, IrcPrivateMessage* message)
{
    if (message->nick() == "*buffextras") {
        const QString msg = message->content();
        const int idx = msg.indexOf(" ");
        const QString prefix = msg.left(idx);
        const QString content = msg.mid(idx + 1);

        IrcMessage* tmp = 0;
        if (content.startsWith("joined")) {
            tmp = IrcMessage::fromParameters(prefix, "JOIN", QStringList() << message->target(), message->connection());
        } else if (content.startsWith("parted")) {
            QString reason = content.mid(content.indexOf("[") + 1);
            reason.chop(1);
            tmp = IrcMessage::fromParameters(prefix, "PART", QStringList() << message->target() << reason , message->connection());
        } else if (content.startsWith("quit")) {
            QString reason = content.mid(content.indexOf("[") + 1);
            reason.chop(1);
            tmp = IrcMessage::fromParameters(prefix, "QUIT", QStringList() << reason , message->connection());
        } else if (content.startsWith("is")) {
            const QStringList tokens = content.split(" ", QString::SkipEmptyParts);
            tmp = IrcMessage::fromParameters(prefix, "NICK", QStringList() << tokens.last() , message->connection());
        } else if (content.startsWith("set")) {
            QStringList tokens = content.split(" ", QString::SkipEmptyParts);
            const QString user = tokens.takeLast();
            const QString mode = tokens.takeLast();
            tmp = IrcMessage::fromParameters(prefix, "MODE", QStringList() << message->target() << mode << user, message->connection());
        } else if (content.startsWith("changed")) {
            const QString topic = content.mid(content.indexOf(":") + 2);
            tmp = IrcMessage::fromParameters(prefix, "TOPIC", QStringList() << message->target() << topic, message->connection());
        } else if (content.startsWith("kicked")) {
            QString reason = content.mid(content.indexOf("[") + 1);
            reason.chop(1);
            QStringList tokens = content.split(" ", QString::SkipEmptyParts);
            tmp = IrcMessage::fromParameters(prefix, "KICK", QStringList() << message->target() << tokens.value(1) << reason, message->connection());
        }
        if (tmp) {
            tmp->setTags(message->tags());
            tmp->setTimeStamp(message->timeStamp());
            buffer->receiveMessage(tmp);
            tmp->deleteLater();
            return true;
        }
    }
    return IgnoreManager::instance()->messageFilter(message);
}

void ZncManager::requestPlayback()
{
    if (d.model->network()->isCapable("znc.in/playback")) {
        IrcConnection* connection = d.model->connection();
        connection->sendCommand(IrcCommand::createMessage("*playback", QString("PLAY * %1").arg(d.timestamp.isValid() ? d.timestamp.toTime_t() : 0)));
    }
}

void ZncManager::requestCapabilities()
{
    QStringList request;
    QStringList available = d.model->network()->availableCapabilities();

    if (available.contains("znc.in/self-message"))
        request << "znc.in/self-message";

    if (available.contains("znc.in/playback"))
        request << "znc.in/playback";

    if (available.contains("server-time"))
        request << "server-time";
    else if (available.contains("znc.in/server-time-iso"))
        request << "znc.in/server-time-iso";
    else if (available.contains("znc.in/server-time"))
        request << "znc.in/server-time";

    if (!request.isEmpty())
        d.model->network()->requestCapabilities(request);
}

void ZncManager::clearBuffer(IrcBuffer* buffer)
{
    if (d.model->network()->isCapable("znc.in/playback") && !buffer->title().contains("*"))
        buffer->sendCommand(IrcCommand::createMessage("*playback", QString("CLEAR %1").arg(buffer->title())));
}
<commit_msg>Request znc.in/echo-message capability<commit_after>/*
  Copyright (C) 2008-2014 The Communi Project

  You may use this file under the terms of BSD license as follows:

  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.
    * Neither the name of the copyright holder nor the names of its
      contributors may 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 HOLDERS 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 "zncmanager.h"
#include "ignoremanager.h"
#include <ircbuffermodel.h>
#include <ircconnection.h>
#include <irccommand.h>
#include <ircmessage.h>
#include <ircbuffer.h>

IRC_USE_NAMESPACE

ZncManager::ZncManager(QObject* parent) : QObject(parent)
{
    d.model = 0;
    d.buffer = 0;
    d.timestamp = QDateTime::fromTime_t(0);
    setModel(qobject_cast<IrcBufferModel*>(parent));
}

ZncManager::~ZncManager()
{
}

IrcBufferModel* ZncManager::model() const
{
    return d.model;
}

void ZncManager::setModel(IrcBufferModel* model)
{
    if (d.model != model) {
        if (d.model && d.model->connection()) {
            IrcConnection* connection = d.model->connection();
            disconnect(connection, SIGNAL(connected()), this, SLOT(requestPlayback()));
            disconnect(connection->network(), SIGNAL(requestingCapabilities()), this, SLOT(requestCapabilities()));
            connection->removeMessageFilter(this);
            disconnect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*)));
        }
        d.model = model;
        if (d.model && d.model->connection()) {
            IrcConnection* connection = d.model->connection();
            connect(connection, SIGNAL(connected()), this, SLOT(requestPlayback()));
            connect(connection->network(), SIGNAL(requestingCapabilities()), this, SLOT(requestCapabilities()));
            connection->installMessageFilter(this);
            connect(model, SIGNAL(removed(IrcBuffer*)), this, SLOT(clearBuffer(IrcBuffer*)));
        }
        emit modelChanged(model);
    }
}

bool ZncManager::messageFilter(IrcMessage* message)
{
    bool playback = false;
    if (message->tags().contains("time")) {
        QDateTime timestamp = message->tags().value("time").toDateTime();
        if (timestamp.isValid()) {
            message->setTimeStamp(timestamp.toTimeSpec(Qt::LocalTime));
            playback = timestamp < d.timestamp;
            d.timestamp = qMax(timestamp, d.timestamp);
        }
    }

    if (!playback && d.buffer) {
        emit playbackEnd(d.buffer);
        d.buffer = 0;
    }

    if (message->type() == IrcMessage::Private) {
        IrcPrivateMessage* msg = static_cast<IrcPrivateMessage*>(message);
        IrcBuffer* buffer = d.model->find(msg->target());
        if (buffer) {
            if (d.buffer != buffer) {
                if (d.buffer) {
                    emit playbackEnd(d.buffer);
                    d.buffer = 0;
                }
                if (playback) {
                    emit playbackBegin(buffer);
                    d.buffer = buffer;
                }
            }
            return processMessage(buffer, msg);
        }
    }
    return IgnoreManager::instance()->messageFilter(message);
}

bool ZncManager::processMessage(IrcBuffer* buffer, IrcPrivateMessage* message)
{
    if (message->nick() == "*buffextras") {
        const QString msg = message->content();
        const int idx = msg.indexOf(" ");
        const QString prefix = msg.left(idx);
        const QString content = msg.mid(idx + 1);

        IrcMessage* tmp = 0;
        if (content.startsWith("joined")) {
            tmp = IrcMessage::fromParameters(prefix, "JOIN", QStringList() << message->target(), message->connection());
        } else if (content.startsWith("parted")) {
            QString reason = content.mid(content.indexOf("[") + 1);
            reason.chop(1);
            tmp = IrcMessage::fromParameters(prefix, "PART", QStringList() << message->target() << reason , message->connection());
        } else if (content.startsWith("quit")) {
            QString reason = content.mid(content.indexOf("[") + 1);
            reason.chop(1);
            tmp = IrcMessage::fromParameters(prefix, "QUIT", QStringList() << reason , message->connection());
        } else if (content.startsWith("is")) {
            const QStringList tokens = content.split(" ", QString::SkipEmptyParts);
            tmp = IrcMessage::fromParameters(prefix, "NICK", QStringList() << tokens.last() , message->connection());
        } else if (content.startsWith("set")) {
            QStringList tokens = content.split(" ", QString::SkipEmptyParts);
            const QString user = tokens.takeLast();
            const QString mode = tokens.takeLast();
            tmp = IrcMessage::fromParameters(prefix, "MODE", QStringList() << message->target() << mode << user, message->connection());
        } else if (content.startsWith("changed")) {
            const QString topic = content.mid(content.indexOf(":") + 2);
            tmp = IrcMessage::fromParameters(prefix, "TOPIC", QStringList() << message->target() << topic, message->connection());
        } else if (content.startsWith("kicked")) {
            QString reason = content.mid(content.indexOf("[") + 1);
            reason.chop(1);
            QStringList tokens = content.split(" ", QString::SkipEmptyParts);
            tmp = IrcMessage::fromParameters(prefix, "KICK", QStringList() << message->target() << tokens.value(1) << reason, message->connection());
        }
        if (tmp) {
            tmp->setTags(message->tags());
            tmp->setTimeStamp(message->timeStamp());
            buffer->receiveMessage(tmp);
            tmp->deleteLater();
            return true;
        }
    }
    return IgnoreManager::instance()->messageFilter(message);
}

void ZncManager::requestPlayback()
{
    if (d.model->network()->isCapable("znc.in/playback")) {
        IrcConnection* connection = d.model->connection();
        connection->sendCommand(IrcCommand::createMessage("*playback", QString("PLAY * %1").arg(d.timestamp.isValid() ? d.timestamp.toTime_t() : 0)));
    }
}

void ZncManager::requestCapabilities()
{
    QStringList request;
    QStringList available = d.model->network()->availableCapabilities();

    if (available.contains("znc.in/self-message"))
        request << "znc.in/self-message";

    if (available.contains("znc.in/echo-message"))
        request << "znc.in/echo-message";

    if (available.contains("znc.in/playback"))
        request << "znc.in/playback";

    if (available.contains("server-time"))
        request << "server-time";
    else if (available.contains("znc.in/server-time-iso"))
        request << "znc.in/server-time-iso";
    else if (available.contains("znc.in/server-time"))
        request << "znc.in/server-time";

    if (!request.isEmpty())
        d.model->network()->requestCapabilities(request);
}

void ZncManager::clearBuffer(IrcBuffer* buffer)
{
    if (d.model->network()->isCapable("znc.in/playback") && !buffer->title().contains("*"))
        buffer->sendCommand(IrcCommand::createMessage("*playback", QString("CLEAR %1").arg(buffer->title())));
}
<|endoftext|>


<commit_before>#include <iostream>
#include "PGMReader.hpp"
#include "matrix/Matrix.hpp"

int main(int argc, char** argv)
{
    const std::string filename = "test.pgm";
    PGMReader reader{filename};
    auto mat = reader.read();
    std::cout << mat({0, 0}) << std::endl;
}
<commit_msg>mostly working test program, need to debug further<commit_after>#include <iostream>
#include "io/PGMReader.hpp"
#include "matrix/Matrix.hpp"

using namespace sipl;

int main(int argc, char** argv)
{
    if (argc < 2) {
        std::cout << "Usage:" << std::endl;
        std::cout << "    " << argv[0] << " file.pgm" << std::endl;
        std::exit(1);
    }

    const std::string filename{argv[1]};
    PGMReader reader{filename};
    auto mat = reader.read8();
    std::cout << mat({0, 0}) << std::endl;
}
<|endoftext|>


<commit_before>// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#ifndef MFEM_LIBCEED_COEFF
#define MFEM_LIBCEED_COEFF

#include "../../config/config.hpp"
#ifdef MFEM_USE_CEED
#include "util.hpp"
#include "../../linalg/vector.hpp"
#include "../../linalg/dtensor.hpp"
#include "../../mesh/mesh.hpp"
#include "../gridfunc.hpp"
#include "../../linalg/dtensor.hpp"

namespace mfem
{

class Mesh;
class IntegrationRule;
class Coefficient;
class VectorCoefficient;
class GridFunction;

namespace ceed
{

struct Coefficient
{
   const int ncomp;
   Coefficient(int ncomp_) : ncomp(ncomp_) { }
   virtual bool IsConstant() const { return true; }
   virtual ~Coefficient() { }
};

struct VariableCoefficient : Coefficient
{
   CeedVector coeffVector = nullptr;
   const CeedEvalMode emode;
   VariableCoefficient(int ncomp_, CeedEvalMode emode_)
      : Coefficient(ncomp_), emode(emode_) { }
   virtual bool IsConstant() const override { return false; }
   ~VariableCoefficient()
   {
      CeedVectorDestroy(&coeffVector);
   }
};

struct GridCoefficient : VariableCoefficient
{
   const mfem::GridFunction &gf;
   CeedBasis basis;
   CeedElemRestriction restr;
   GridCoefficient(const mfem::GridFunction &gf_)
      : VariableCoefficient(gf_.VectorDim(), CEED_EVAL_INTERP),
        gf(gf_)
   {
      InitVector(gf, coeffVector);
   }
};

struct QuadCoefficient : VariableCoefficient
{
   mfem::Vector coeff;
   CeedElemRestriction restr;
   QuadCoefficient(int ncomp_) : VariableCoefficient(ncomp_, CEED_EVAL_NONE) { }
};

/** @brief Initializes an mfem::ceed::Coefficient @a coeff_ptr from an
    mfem::Coefficient @a Q, an mfem::Mesh @a mesh, and an mfem::IntegrationRule
    @a ir. */
template <typename Context>
void InitCoefficient(mfem::Coefficient *Q, mfem::Mesh &mesh,
                     const mfem::IntegrationRule &ir,
                     Coefficient*& coeff_ptr, Context &ctx)
{
   ConstantCoefficient *coeff;
   if ( Q == nullptr )
   {
      Coefficient *ceedCoeff = new Coefficient(1);
      ctx.coeff = 1.0;
      coeff_ptr = ceedCoeff;
   }
   else if (coeff = dynamic_cast<ConstantCoefficient*>(Q))
   {
      Coefficient *ceedCoeff = new Coefficient(1);
      ctx.coeff = coeff->constant;
      coeff_ptr = ceedCoeff;
   }
   else if (coeff = dynamic_cast<GridFunctionCoefficient*>(Q))
   {
      GridCoefficient *ceedCoeff = new GridCoefficient(*coeff->GetGridFunction());
      coeff_ptr = ceedCoeff;
   }
   else if (QuadratureFunctionCoefficient *cQ =
               dynamic_cast<QuadratureFunctionCoefficient*>(Q))
   {
      QuadCoefficient *ceedCoeff = new QuadCoefficient(1);
      const int ne = mesh.GetNE();
      const int nq = ir.GetNPoints();
      const mfem::QuadratureFunction &qFun = cQ->GetQuadFunction();
      MFEM_VERIFY(qFun.Size() == nq * ne,
                  "Incompatible QuadratureFunction dimension \n");

      MFEM_VERIFY(&ir == &qFun.GetSpace()->GetElementIntRule(0),
                  "IntegrationRule used within integrator and in"
                  " QuadratureFunction appear to be different");
      qFun.Read();
      ceedCoeff->coeff.MakeRef(const_cast<mfem::QuadratureFunction &>(qFun),0);
      InitVector(ceedCoeff->coeff, ceedCoeff->coeffVector);
      coeff_ptr = ceedCoeff;
   }
   else
   {
      QuadCoefficient *ceedCoeff = new QuadCoefficient(1);
      const int ne = mesh.GetNE();
      const int nq = ir.GetNPoints();
      ceedCoeff->coeff.SetSize(nq * ne);
      auto C = Reshape(ceedCoeff->coeff.HostWrite(), nq, ne);
      for (int e = 0; e < ne; ++e)
      {
         mfem::ElementTransformation &T = *mesh.GetElementTransformation(e);
         for (int q = 0; q < nq; ++q)
         {
            C(q,e) = Q->Eval(T, ir.IntPoint(q));
         }
      }
      InitVector(ceedCoeff->coeff, ceedCoeff->coeffVector);
      coeff_ptr = ceedCoeff;
   }
}

/** @brief Initializes an mfem::ceed::Coefficient @a coeff_ptr from an
    mfem::VectorCoefficient @a Q, an mfem::Mesh @a mesh, and an
    mfem::IntegrationRule @a ir. */
template <typename Context>
void InitCoefficient(mfem::VectorCoefficient *VQ, mfem::Mesh &mesh,
                     const mfem::IntegrationRule &ir,
                     Coefficient *&coeff_ptr, Context &ctx)
{
   VectorConstantCoefficient *coeff;
   if (coeff = dynamic_cast<VectorConstantCoefficient*>(VQ))
   {
      const int vdim = coeff->GetVDim();
      const mfem::Vector &val = coeff->GetVec();
      Coefficient *ceedCoeff = new Coefficient(vdim);
      for (int i = 0; i < vdim; i++)
      {
         ctx.coeff[i] = val[i];
      }
      coeff_ptr = ceedCoeff;
   }
   else if (coeff = dynamic_cast<VectorGridFunctionCoefficient*>(VQ))
   {
      GridCoefficient *ceedCoeff = new GridCoefficient(*coeff->GetGridFunction());
      coeff_ptr = ceedCoeff;
   }
   else if (VectorQuadratureFunctionCoefficient *cQ =
               dynamic_cast<VectorQuadratureFunctionCoefficient*>(VQ))
   {
      QuadCoefficient *ceedCoeff = new QuadCoefficient(cQ->GetVDim());
      const int dim = mesh.Dimension();
      const int ne = mesh.GetNE();
      const int nq = ir.GetNPoints();
      const mfem::QuadratureFunction &qFun = cQ->GetQuadFunction();
      MFEM_VERIFY(qFun.Size() == dim * nq * ne,
                  "Incompatible QuadratureFunction dimension \n");

      MFEM_VERIFY(&ir == &qFun.GetSpace()->GetElementIntRule(0),
                  "IntegrationRule used within integrator and in"
                  " QuadratureFunction appear to be different");
      qFun.Read();
      ceedCoeff->coeff.MakeRef(const_cast<mfem::QuadratureFunction &>(qFun),0);
      InitVector(ceedCoeff->coeff, ceedCoeff->coeffVector);
      coeff_ptr = ceedCoeff;
   }
   else
   {
      const int dim = mesh.Dimension();
      QuadCoefficient *ceedCoeff = new QuadCoefficient(dim);
      const int ne = mesh.GetNE();
      const int nq = ir.GetNPoints();
      ceedCoeff->coeff.SetSize(dim * nq * ne);
      auto C = Reshape(ceedCoeff->coeff.HostWrite(), dim, nq, ne);
      mfem::DenseMatrix Q_ir;
      for (int e = 0; e < ne; ++e)
      {
         mfem::ElementTransformation &T = *mesh.GetElementTransformation(e);
         VQ->Eval(Q_ir, T, ir);
         for (int q = 0; q < nq; ++q)
         {
            for (int i = 0; i < dim; ++i)
            {
               C(i,q,e) = Q_ir(i,q);
            }
         }
      }
      InitVector(ceedCoeff->coeff, ceedCoeff->coeffVector);
      coeff_ptr = ceedCoeff;
   }
}

} // namespace ceed

} // namespace mfem

#endif

#endif // MFEM_LIBCEED_COEFF
<commit_msg>Fixed a bug introduced in 7eb93bfb2114b<commit_after>// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#ifndef MFEM_LIBCEED_COEFF
#define MFEM_LIBCEED_COEFF

#include "../../config/config.hpp"
#ifdef MFEM_USE_CEED
#include "util.hpp"
#include "../../linalg/vector.hpp"
#include "../../linalg/dtensor.hpp"
#include "../../mesh/mesh.hpp"
#include "../gridfunc.hpp"
#include "../../linalg/dtensor.hpp"

namespace mfem
{

class Mesh;
class IntegrationRule;
class Coefficient;
class VectorCoefficient;
class GridFunction;

namespace ceed
{

struct Coefficient
{
   const int ncomp;
   Coefficient(int ncomp_) : ncomp(ncomp_) { }
   virtual bool IsConstant() const { return true; }
   virtual ~Coefficient() { }
};

struct VariableCoefficient : Coefficient
{
   CeedVector coeffVector = nullptr;
   const CeedEvalMode emode;
   VariableCoefficient(int ncomp_, CeedEvalMode emode_)
      : Coefficient(ncomp_), emode(emode_) { }
   virtual bool IsConstant() const override { return false; }
   ~VariableCoefficient()
   {
      CeedVectorDestroy(&coeffVector);
   }
};

struct GridCoefficient : VariableCoefficient
{
   const mfem::GridFunction &gf;
   CeedBasis basis;
   CeedElemRestriction restr;
   GridCoefficient(const mfem::GridFunction &gf_)
      : VariableCoefficient(gf_.VectorDim(), CEED_EVAL_INTERP),
        gf(gf_)
   {
      InitVector(gf, coeffVector);
   }
};

struct QuadCoefficient : VariableCoefficient
{
   mfem::Vector coeff;
   CeedElemRestriction restr;
   QuadCoefficient(int ncomp_) : VariableCoefficient(ncomp_, CEED_EVAL_NONE) { }
};

/** @brief Initializes an mfem::ceed::Coefficient @a coeff_ptr from an
    mfem::Coefficient @a Q, an mfem::Mesh @a mesh, and an mfem::IntegrationRule
    @a ir. */
template <typename Context>
void InitCoefficient(mfem::Coefficient *Q, mfem::Mesh &mesh,
                     const mfem::IntegrationRule &ir,
                     Coefficient*& coeff_ptr, Context &ctx)
{
   if ( Q == nullptr )
   {
      Coefficient *ceedCoeff = new Coefficient(1);
      ctx.coeff = 1.0;
      coeff_ptr = ceedCoeff;
   }
   else if (ConstantCoefficient *const_coeff =
               dynamic_cast<ConstantCoefficient*>(Q))
   {
      Coefficient *ceedCoeff = new Coefficient(1);
      ctx.coeff = const_coeff->constant;
      coeff_ptr = ceedCoeff;
   }
   else if (GridFunctionCoefficient* gf_coeff =
               dynamic_cast<GridFunctionCoefficient*>(Q))
   {
      GridCoefficient *ceedCoeff =
         new GridCoefficient(*gf_coeff->GetGridFunction());
      coeff_ptr = ceedCoeff;
   }
   else if (QuadratureFunctionCoefficient *cQ =
               dynamic_cast<QuadratureFunctionCoefficient*>(Q))
   {
      QuadCoefficient *ceedCoeff = new QuadCoefficient(1);
      const int ne = mesh.GetNE();
      const int nq = ir.GetNPoints();
      const mfem::QuadratureFunction &qFun = cQ->GetQuadFunction();
      MFEM_VERIFY(qFun.Size() == nq * ne,
                  "Incompatible QuadratureFunction dimension \n");

      MFEM_VERIFY(&ir == &qFun.GetSpace()->GetElementIntRule(0),
                  "IntegrationRule used within integrator and in"
                  " QuadratureFunction appear to be different");
      qFun.Read();
      ceedCoeff->coeff.MakeRef(const_cast<mfem::QuadratureFunction &>(qFun),0);
      InitVector(ceedCoeff->coeff, ceedCoeff->coeffVector);
      coeff_ptr = ceedCoeff;
   }
   else
   {
      QuadCoefficient *ceedCoeff = new QuadCoefficient(1);
      const int ne = mesh.GetNE();
      const int nq = ir.GetNPoints();
      ceedCoeff->coeff.SetSize(nq * ne);
      auto C = Reshape(ceedCoeff->coeff.HostWrite(), nq, ne);
      for (int e = 0; e < ne; ++e)
      {
         mfem::ElementTransformation &T = *mesh.GetElementTransformation(e);
         for (int q = 0; q < nq; ++q)
         {
            C(q,e) = Q->Eval(T, ir.IntPoint(q));
         }
      }
      InitVector(ceedCoeff->coeff, ceedCoeff->coeffVector);
      coeff_ptr = ceedCoeff;
   }
}

/** @brief Initializes an mfem::ceed::Coefficient @a coeff_ptr from an
    mfem::VectorCoefficient @a Q, an mfem::Mesh @a mesh, and an
    mfem::IntegrationRule @a ir. */
template <typename Context>
void InitCoefficient(mfem::VectorCoefficient *VQ, mfem::Mesh &mesh,
                     const mfem::IntegrationRule &ir,
                     Coefficient *&coeff_ptr, Context &ctx)
{
   if (VectorConstantCoefficient *const_coeff =
          dynamic_cast<VectorConstantCoefficient*>(VQ))
   {
      const int vdim = const_coeff->GetVDim();
      const mfem::Vector &val = const_coeff->GetVec();
      Coefficient *ceedCoeff = new Coefficient(vdim);
      for (int i = 0; i < vdim; i++)
      {
         ctx.coeff[i] = val[i];
      }
      coeff_ptr = ceedCoeff;
   }
   else if (VectorGridFunctionCoefficient* gf_coeff
            dynamic_cast<VectorGridFunctionCoefficient*>(VQ))
   {
      GridCoefficient *ceedCoeff =
         new GridCoefficient(*gf_coeff->GetGridFunction());
      coeff_ptr = ceedCoeff;
   }
   else if (VectorQuadratureFunctionCoefficient *cQ =
               dynamic_cast<VectorQuadratureFunctionCoefficient*>(VQ))
   {
      QuadCoefficient *ceedCoeff = new QuadCoefficient(cQ->GetVDim());
      const int dim = mesh.Dimension();
      const int ne = mesh.GetNE();
      const int nq = ir.GetNPoints();
      const mfem::QuadratureFunction &qFun = cQ->GetQuadFunction();
      MFEM_VERIFY(qFun.Size() == dim * nq * ne,
                  "Incompatible QuadratureFunction dimension \n");

      MFEM_VERIFY(&ir == &qFun.GetSpace()->GetElementIntRule(0),
                  "IntegrationRule used within integrator and in"
                  " QuadratureFunction appear to be different");
      qFun.Read();
      ceedCoeff->coeff.MakeRef(const_cast<mfem::QuadratureFunction &>(qFun),0);
      InitVector(ceedCoeff->coeff, ceedCoeff->coeffVector);
      coeff_ptr = ceedCoeff;
   }
   else
   {
      const int dim = mesh.Dimension();
      QuadCoefficient *ceedCoeff = new QuadCoefficient(dim);
      const int ne = mesh.GetNE();
      const int nq = ir.GetNPoints();
      ceedCoeff->coeff.SetSize(dim * nq * ne);
      auto C = Reshape(ceedCoeff->coeff.HostWrite(), dim, nq, ne);
      mfem::DenseMatrix Q_ir;
      for (int e = 0; e < ne; ++e)
      {
         mfem::ElementTransformation &T = *mesh.GetElementTransformation(e);
         VQ->Eval(Q_ir, T, ir);
         for (int q = 0; q < nq; ++q)
         {
            for (int i = 0; i < dim; ++i)
            {
               C(i,q,e) = Q_ir(i,q);
            }
         }
      }
      InitVector(ceedCoeff->coeff, ceedCoeff->coeffVector);
      coeff_ptr = ceedCoeff;
   }
}

} // namespace ceed

} // namespace mfem

#endif

#endif // MFEM_LIBCEED_COEFF
<|endoftext|>


<commit_before>// ffmpeg player output (portaudio)
// part of MusicPlayer, https://github.com/albertz/music-player
// Copyright (c) 2012, Albert Zeyer, www.az2000.de
// All rights reserved.
// This code is under the 2-clause BSD license, see License.txt in the root directory of this project.

#include "ffmpeg.h"

#include <portaudio.h>

#ifdef __APPLE__
// PortAudio specific Mac stuff
#include "pa_mac_core.h"
#endif

// For setting the thread priority to realtime on MacOSX.
#ifdef __APPLE__
#include <mach/mach_init.h>
#include <mach/thread_policy.h>
#include <mach/thread_act.h> // the doc says mach/sched.h but that seems outdated...
#include <pthread.h>
#include <mach/mach_error.h>
#include <mach/mach_time.h>
#endif
static void setRealtime();

#define AUDIO_BUFFER_SIZE	(2048 * 5 * OUTSAMPLEBYTELEN) // soundcard buffer

int initPlayerOutput() {
	PaError ret = Pa_Initialize();
	if(ret != paNoError)
		Py_FatalError("PortAudio init failed");
	return 0;
}

template<typename T> struct OutPaSampleFormat{};
template<> struct OutPaSampleFormat<int16_t> {
	static const PaSampleFormat format = paInt16;
};
template<> struct OutPaSampleFormat<float32_t> {
	static const PaSampleFormat format = paFloat32;
};

struct PlayerObject::OutStream {
	PlayerObject* const player;
	PaStream* stream;
	bool needRealtimeReset; // PortAudio callback thread must set itself to realtime

	OutStream(PlayerObject* p) : player(p), stream(NULL), needRealtimeReset(false) {}
	~OutStream() { close(); }

	static int paStreamCallback(
		const void *input, void *output,
		unsigned long frameCount,
		const PaStreamCallbackTimeInfo* timeInfo,
		PaStreamCallbackFlags statusFlags,
		void *userData )
	{
		OutStream* outStream = (OutStream*) userData;

		// We must not hold the PyGIL here!
		PyScopedLock lock(outStream->player->lock);

		if(outStream->needRealtimeReset) {
			outStream->needRealtimeReset = false;
			setRealtime();
		}

		outStream->player->readOutStream((OUTSAMPLE_t*) output, frameCount * outStream->player->outNumChannels, NULL);
		return paContinue;
	}

	bool open() {
		if(stream) close();
		assert(stream == NULL);

		PaStreamParameters outputParameters;

#if defined(__APPLE__)
		PaMacCoreStreamInfo macInfo;
		PaMacCore_SetupStreamInfo( &macInfo,
			paMacCorePlayNice | paMacCorePro );
		outputParameters.hostApiSpecificStreamInfo = &macInfo;
#elif defined(__LINUX__)
		// TODO: if we have PaAlsa_EnableRealtimeScheduling in portaudio,
		// we can call that to enable RT priority with ALSA.
		// We could check dynamically via dsym.
		outputParameters.hostApiSpecificStreamInfo = NULL;
#else
		outputParameters.hostApiSpecificStreamInfo = NULL;
#endif

		outputParameters.device = Pa_GetDefaultOutputDevice();
		if (outputParameters.device == paNoDevice) {
			PyErr_SetString(PyExc_RuntimeError, "Pa_GetDefaultOutputDevice didn't returned a device");
			return false;
		}
		outputParameters.channelCount = player->outNumChannels;
		outputParameters.sampleFormat = OutPaSampleFormat<OUTSAMPLE_t>::format;
		outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency;

		PaError ret = Pa_OpenStream(
			&stream,
			NULL, // no input
			&outputParameters,
			player->outSamplerate, // sampleRate
			AUDIO_BUFFER_SIZE / OUTSAMPLEBYTELEN, // framesPerBuffer,
			paClipOff | paDitherOff,
			&paStreamCallback,
			this //void *userData
			);

		if(ret != paNoError) {
			PyErr_Format(PyExc_RuntimeError, "Pa_OpenStream failed: (err %i) %s", ret, Pa_GetErrorText(ret));
			if(stream)
				close();
			return false;
		}
		return true;
	}

	void close() {
		if(this->stream == NULL) return;
		// we expect that we have the player lock here.
		// we must release the lock so that any thread-join can be done.
		PaStream* stream = NULL;
		std::swap(stream, this->stream);
		PyScopedUnlock unlock(player->lock);
		Pa_CloseStream(stream);
	}

	void start() {
		assert(stream != NULL);
		needRealtimeReset = true;
		Pa_StartStream(stream);
	}

	void stop() {
		if(this->stream == NULL) return;
		// we expect that we have the lock here.
		// we must release the lock so that any thread-join can be done.
		PaStream* stream = this->stream; // buffer for unlock-scope
		PyScopedUnlock unlock(player->lock);
		Pa_StopStream(stream);
	}
};

int PlayerObject::setPlaying(bool playing) {
	PlayerObject* player = this;
	bool oldplayingstate = false;
	PyScopedGIL gil;
	{
		PyScopedGIUnlock gunlock;

		player->workerThread.start(); // if not running yet, start
		if(!player->outStream.get())
			player->outStream.reset(new OutStream(this));
		assert(player->outStream.get() != NULL);

		if(soundcardOutputEnabled) {
			if(playing && !player->outStream->stream) {
				if(!player->outStream->open())
					playing = false;
			}
			if(playing)
				player->outStream->start();
			else
				player->outStream->stop();
		}

		oldplayingstate = player->playing;
		player->playing = playing;
	}

	if(!PyErr_Occurred() && player->dict) {
		Py_INCREF(player->dict);
		PyObject* onPlayingStateChange = PyDict_GetItemString(player->dict, "onPlayingStateChange");
		if(onPlayingStateChange && onPlayingStateChange != Py_None) {
			Py_INCREF(onPlayingStateChange);

			PyObject* kwargs = PyDict_New();
			assert(kwargs);
			PyDict_SetItemString_retain(kwargs, "oldState", PyBool_FromLong(oldplayingstate));
			PyDict_SetItemString_retain(kwargs, "newState", PyBool_FromLong(playing));

			PyObject* retObj = PyEval_CallObjectWithKeywords(onPlayingStateChange, NULL, kwargs);
			Py_XDECREF(retObj);

			// errors are not fatal from the callback, so handle it now and go on
			if(PyErr_Occurred())
				PyErr_Print();

			Py_DECREF(kwargs);
			Py_DECREF(onPlayingStateChange);
		}
		Py_DECREF(player->dict);
	}

	return PyErr_Occurred() ? -1 : 0;
}

#ifdef __APPLE__
// https://developer.apple.com/library/mac/#documentation/Darwin/Conceptual/KernelProgramming/scheduler/scheduler.html
// Also, from Google Native Client, osx/nacl_thread_nice.c has some related code.
// Or, from Google Chrome, platform_thread_mac.mm.
void setRealtime() {
	kern_return_t ret;
	thread_port_t threadport = pthread_mach_thread_np(pthread_self());

	thread_extended_policy_data_t policy;
	policy.timeshare = 0;
	ret = thread_policy_set(threadport,
							THREAD_EXTENDED_POLICY,
							(thread_policy_t)&policy,
							THREAD_EXTENDED_POLICY_COUNT);
	if(ret != KERN_SUCCESS) {
		fprintf(stderr, "setRealtime() THREAD_EXTENDED_POLICY failed: %d, %s\n", ret, mach_error_string(ret));
		return;
	}

	thread_precedence_policy_data_t precedence;
	precedence.importance = 63;
	ret = thread_policy_set(threadport,
							THREAD_PRECEDENCE_POLICY,
							(thread_policy_t)&precedence,
							THREAD_PRECEDENCE_POLICY_COUNT);
	if(ret != KERN_SUCCESS) {
		fprintf(stderr, "setRealtime() THREAD_PRECEDENCE_POLICY failed: %d, %s\n", ret, mach_error_string(ret));
		return;
	}

	mach_timebase_info_data_t tb_info;
	mach_timebase_info(&tb_info);
	double timeFact = ((double)tb_info.denom / (double)tb_info.numer) * 1000000;

	thread_time_constraint_policy_data_t ttcpolicy;
	ttcpolicy.period = 2.9 * timeFact; // about 128 frames @44.1KHz
	ttcpolicy.computation = 0.75 * 2.9 * timeFact;
	ttcpolicy.constraint = 0.85 * 2.9 * timeFact;
	ttcpolicy.preemptible = 1;

	ret = thread_policy_set(threadport,
							THREAD_TIME_CONSTRAINT_POLICY,
							(thread_policy_t)&ttcpolicy,
							THREAD_TIME_CONSTRAINT_POLICY_COUNT);
	if(ret != KERN_SUCCESS) {
		fprintf(stderr, "setRealtime() THREAD_TIME_CONSTRAINT_POLICY failed: %d, %s\n", ret, mach_error_string(ret));
		return;
	}
}
#else
void setRealtime() {} // not implemented yet
#endif

<commit_msg>ffmpeg: portaudio: use paFramesPerBufferUnspecified<commit_after>// ffmpeg player output (portaudio)
// part of MusicPlayer, https://github.com/albertz/music-player
// Copyright (c) 2012, Albert Zeyer, www.az2000.de
// All rights reserved.
// This code is under the 2-clause BSD license, see License.txt in the root directory of this project.

#include "ffmpeg.h"

#include <portaudio.h>

#ifdef __APPLE__
// PortAudio specific Mac stuff
#include "pa_mac_core.h"
#endif

// For setting the thread priority to realtime on MacOSX.
#ifdef __APPLE__
#include <mach/mach_init.h>
#include <mach/thread_policy.h>
#include <mach/thread_act.h> // the doc says mach/sched.h but that seems outdated...
#include <pthread.h>
#include <mach/mach_error.h>
#include <mach/mach_time.h>
#endif
static void setRealtime();

int initPlayerOutput() {
	PaError ret = Pa_Initialize();
	if(ret != paNoError)
		Py_FatalError("PortAudio init failed");
	return 0;
}

template<typename T> struct OutPaSampleFormat{};
template<> struct OutPaSampleFormat<int16_t> {
	static const PaSampleFormat format = paInt16;
};
template<> struct OutPaSampleFormat<float32_t> {
	static const PaSampleFormat format = paFloat32;
};

struct PlayerObject::OutStream {
	PlayerObject* const player;
	PaStream* stream;
	bool needRealtimeReset; // PortAudio callback thread must set itself to realtime

	OutStream(PlayerObject* p) : player(p), stream(NULL), needRealtimeReset(false) {}
	~OutStream() { close(); }

	static int paStreamCallback(
		const void *input, void *output,
		unsigned long frameCount,
		const PaStreamCallbackTimeInfo* timeInfo,
		PaStreamCallbackFlags statusFlags,
		void *userData )
	{
		OutStream* outStream = (OutStream*) userData;

		// We must not hold the PyGIL here!
		PyScopedLock lock(outStream->player->lock);

		if(outStream->needRealtimeReset) {
			outStream->needRealtimeReset = false;
			setRealtime();
		}

		outStream->player->readOutStream((OUTSAMPLE_t*) output, frameCount * outStream->player->outNumChannels, NULL);
		return paContinue;
	}

	bool open() {
		if(stream) close();
		assert(stream == NULL);

		PaStreamParameters outputParameters;

#if defined(__APPLE__)
		PaMacCoreStreamInfo macInfo;
		PaMacCore_SetupStreamInfo( &macInfo,
			paMacCorePlayNice | paMacCorePro );
		outputParameters.hostApiSpecificStreamInfo = &macInfo;
#elif defined(__LINUX__)
		// TODO: if we have PaAlsa_EnableRealtimeScheduling in portaudio,
		// we can call that to enable RT priority with ALSA.
		// We could check dynamically via dsym.
		outputParameters.hostApiSpecificStreamInfo = NULL;
#else
		outputParameters.hostApiSpecificStreamInfo = NULL;
#endif

		outputParameters.device = Pa_GetDefaultOutputDevice();
		if (outputParameters.device == paNoDevice) {
			PyErr_SetString(PyExc_RuntimeError, "Pa_GetDefaultOutputDevice didn't returned a device");
			return false;
		}
		outputParameters.channelCount = player->outNumChannels;
		outputParameters.sampleFormat = OutPaSampleFormat<OUTSAMPLE_t>::format;
		outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency;

		// Note about framesPerBuffer:
		// Earlier, we used (2048 * 5 * OUTSAMPLEBYTELEN) which caused
		// some random more or less rare cracking noises.
		// See here: https://github.com/albertz/music-player/issues/35
		// This doesn't seem to happen with paFramesPerBufferUnspecified.

		PaError ret = Pa_OpenStream(
			&stream,
			NULL, // no input
			&outputParameters,
			player->outSamplerate, // sampleRate
			paFramesPerBufferUnspecified, // framesPerBuffer,
			paClipOff | paDitherOff,
			&paStreamCallback,
			this //void *userData
			);

		if(ret != paNoError) {
			PyErr_Format(PyExc_RuntimeError, "Pa_OpenStream failed: (err %i) %s", ret, Pa_GetErrorText(ret));
			if(stream)
				close();
			return false;
		}
		return true;
	}

	void close() {
		if(this->stream == NULL) return;
		// we expect that we have the player lock here.
		// we must release the lock so that any thread-join can be done.
		PaStream* stream = NULL;
		std::swap(stream, this->stream);
		PyScopedUnlock unlock(player->lock);
		Pa_CloseStream(stream);
	}

	void start() {
		assert(stream != NULL);
		needRealtimeReset = true;
		Pa_StartStream(stream);
	}

	void stop() {
		if(this->stream == NULL) return;
		// we expect that we have the lock here.
		// we must release the lock so that any thread-join can be done.
		PaStream* stream = this->stream; // buffer for unlock-scope
		PyScopedUnlock unlock(player->lock);
		Pa_StopStream(stream);
	}
};

int PlayerObject::setPlaying(bool playing) {
	PlayerObject* player = this;
	bool oldplayingstate = false;
	PyScopedGIL gil;
	{
		PyScopedGIUnlock gunlock;

		player->workerThread.start(); // if not running yet, start
		if(!player->outStream.get())
			player->outStream.reset(new OutStream(this));
		assert(player->outStream.get() != NULL);

		if(soundcardOutputEnabled) {
			if(playing && !player->outStream->stream) {
				if(!player->outStream->open())
					playing = false;
			}
			if(playing)
				player->outStream->start();
			else
				player->outStream->stop();
		}

		oldplayingstate = player->playing;
		player->playing = playing;
	}

	if(!PyErr_Occurred() && player->dict) {
		Py_INCREF(player->dict);
		PyObject* onPlayingStateChange = PyDict_GetItemString(player->dict, "onPlayingStateChange");
		if(onPlayingStateChange && onPlayingStateChange != Py_None) {
			Py_INCREF(onPlayingStateChange);

			PyObject* kwargs = PyDict_New();
			assert(kwargs);
			PyDict_SetItemString_retain(kwargs, "oldState", PyBool_FromLong(oldplayingstate));
			PyDict_SetItemString_retain(kwargs, "newState", PyBool_FromLong(playing));

			PyObject* retObj = PyEval_CallObjectWithKeywords(onPlayingStateChange, NULL, kwargs);
			Py_XDECREF(retObj);

			// errors are not fatal from the callback, so handle it now and go on
			if(PyErr_Occurred())
				PyErr_Print();

			Py_DECREF(kwargs);
			Py_DECREF(onPlayingStateChange);
		}
		Py_DECREF(player->dict);
	}

	return PyErr_Occurred() ? -1 : 0;
}

#ifdef __APPLE__
// https://developer.apple.com/library/mac/#documentation/Darwin/Conceptual/KernelProgramming/scheduler/scheduler.html
// Also, from Google Native Client, osx/nacl_thread_nice.c has some related code.
// Or, from Google Chrome, platform_thread_mac.mm.
void setRealtime() {
	kern_return_t ret;
	thread_port_t threadport = pthread_mach_thread_np(pthread_self());

	thread_extended_policy_data_t policy;
	policy.timeshare = 0;
	ret = thread_policy_set(threadport,
							THREAD_EXTENDED_POLICY,
							(thread_policy_t)&policy,
							THREAD_EXTENDED_POLICY_COUNT);
	if(ret != KERN_SUCCESS) {
		fprintf(stderr, "setRealtime() THREAD_EXTENDED_POLICY failed: %d, %s\n", ret, mach_error_string(ret));
		return;
	}

	thread_precedence_policy_data_t precedence;
	precedence.importance = 63;
	ret = thread_policy_set(threadport,
							THREAD_PRECEDENCE_POLICY,
							(thread_policy_t)&precedence,
							THREAD_PRECEDENCE_POLICY_COUNT);
	if(ret != KERN_SUCCESS) {
		fprintf(stderr, "setRealtime() THREAD_PRECEDENCE_POLICY failed: %d, %s\n", ret, mach_error_string(ret));
		return;
	}

	mach_timebase_info_data_t tb_info;
	mach_timebase_info(&tb_info);
	double timeFact = ((double)tb_info.denom / (double)tb_info.numer) * 1000000;

	thread_time_constraint_policy_data_t ttcpolicy;
	ttcpolicy.period = 2.9 * timeFact; // about 128 frames @44.1KHz
	ttcpolicy.computation = 0.75 * 2.9 * timeFact;
	ttcpolicy.constraint = 0.85 * 2.9 * timeFact;
	ttcpolicy.preemptible = 1;

	ret = thread_policy_set(threadport,
							THREAD_TIME_CONSTRAINT_POLICY,
							(thread_policy_t)&ttcpolicy,
							THREAD_TIME_CONSTRAINT_POLICY_COUNT);
	if(ret != KERN_SUCCESS) {
		fprintf(stderr, "setRealtime() THREAD_TIME_CONSTRAINT_POLICY failed: %d, %s\n", ret, mach_error_string(ret));
		return;
	}
}
#else
void setRealtime() {} // not implemented yet
#endif

<|endoftext|>


<commit_before><commit_msg>Removed implicit usage of boost::python from num_util.cc<commit_after><|endoftext|>


<commit_before><commit_msg>fix maxsegmentindex being off by one<commit_after><|endoftext|>


<commit_before><commit_msg>Base: Updated display name of VolumeSequenceElementSelector to allowed characters<commit_after><|endoftext|>


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

#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/offline/offline_load_page.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "content/browser/tab_contents/interstitial_page.h"
#include "content/browser/tab_contents/test_tab_contents.h"
#include "content/test/test_browser_thread.h"

using content::BrowserThread;

static const char* kURL1 = "http://www.google.com/";
static const char* kURL2 = "http://www.gmail.com/";

namespace chromeos {

class OfflineLoadPageTest;

// An OfflineLoadPage class that does not create windows.
class TestOfflineLoadPage :  public chromeos::OfflineLoadPage {
 public:
  TestOfflineLoadPage(TabContents* tab_contents,
                      const GURL& url,
                      OfflineLoadPageTest* test_page)
    : chromeos::OfflineLoadPage(tab_contents, url, CompletionCallback()),
      test_page_(test_page) {
    interstitial_page_->DontCreateViewForTesting();
  }

  // chromeos::OfflineLoadPage override.
  virtual void NotifyBlockingPageComplete(bool proceed) OVERRIDE;

 private:
  OfflineLoadPageTest* test_page_;

  DISALLOW_COPY_AND_ASSIGN(TestOfflineLoadPage);
};

class OfflineLoadPageTest : public ChromeRenderViewHostTestHarness {
 public:
  // The decision the user made.
  enum UserResponse {
    PENDING,
    OK,
    CANCEL
  };

  OfflineLoadPageTest()
      : ui_thread_(BrowserThread::UI, MessageLoop::current()),
        io_thread_(BrowserThread::IO, MessageLoop::current()) {
  }

  virtual void SetUp() {
    ChromeRenderViewHostTestHarness::SetUp();
    user_response_ = PENDING;
  }

  void OnBlockingPageComplete(bool proceed) {
    if (proceed)
      user_response_ = OK;
    else
      user_response_ = CANCEL;
  }

  void Navigate(const char* url, int page_id) {
    contents()->TestDidNavigate(
        contents()->GetRenderViewHost(), page_id, GURL(url),
        content::PAGE_TRANSITION_TYPED);
  }

  void ShowInterstitial(const char* url) {
    new TestOfflineLoadPage(contents(), GURL(url), this);
  }

  // Returns the OfflineLoadPage currently showing or NULL if none is
  // showing.
  InterstitialPage* GetOfflineLoadPage() {
    return InterstitialPage::GetInterstitialPage(contents());
  }

  UserResponse user_response() const { return user_response_; }

 private:
  UserResponse user_response_;
  content::TestBrowserThread ui_thread_;
  content::TestBrowserThread io_thread_;

  // Initializes / shuts down a stub CrosLibrary.
  chromeos::ScopedStubCrosEnabler stub_cros_enabler_;

  DISALLOW_COPY_AND_ASSIGN(OfflineLoadPageTest);
};

void TestOfflineLoadPage::NotifyBlockingPageComplete(bool proceed) {
  test_page_->OnBlockingPageComplete(proceed);
}

TEST_F(OfflineLoadPageTest, OfflinePageProceed) {
  // Start a load.
  Navigate(kURL1, 1);
  // Load next page.
  controller().LoadURL(GURL(kURL2), content::Referrer(),
                       content::PAGE_TRANSITION_TYPED, std::string());

  // Simulate the load causing an offline browsing interstitial page
  // to be shown.
  ShowInterstitial(kURL2);
  InterstitialPage* interstitial = GetOfflineLoadPage();
  ASSERT_TRUE(interstitial);
  MessageLoop::current()->RunAllPending();

  // Simulate the user clicking "proceed".
  interstitial->Proceed();
  MessageLoop::current()->RunAllPending();

  EXPECT_EQ(OK, user_response());

  // The URL remains to be URL2.
  EXPECT_EQ(kURL2, contents()->GetURL().spec());

  // Commit navigation and the interstitial page is gone.
  Navigate(kURL2, 2);
  EXPECT_FALSE(GetOfflineLoadPage());
}

// Tests showing an offline page and not proceeding.
TEST_F(OfflineLoadPageTest, OfflinePageDontProceed) {
  // Start a load.
  Navigate(kURL1, 1);
  controller().LoadURL(GURL(kURL2), content::Referrer(),
                       content::PAGE_TRANSITION_TYPED, std::string());

  // Simulate the load causing an offline interstitial page to be shown.
  ShowInterstitial(kURL2);
  InterstitialPage* interstitial = GetOfflineLoadPage();
  ASSERT_TRUE(interstitial);
  MessageLoop::current()->RunAllPending();

  // Simulate the user clicking "don't proceed".
  interstitial->DontProceed();

  // The interstitial should be gone.
  EXPECT_EQ(CANCEL, user_response());
  EXPECT_FALSE(GetOfflineLoadPage());
  // We did not proceed, the pending entry should be gone.
  EXPECT_FALSE(controller().GetPendingEntry());
  // the URL is set back to kURL1.
  EXPECT_EQ(kURL1, contents()->GetURL().spec());
}

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

#include "chrome/browser/chromeos/cros/cros_library.h"
#include "chrome/browser/chromeos/offline/offline_load_page.h"
#include "chrome/test/base/chrome_render_view_host_test_harness.h"
#include "content/browser/tab_contents/interstitial_page.h"
#include "content/browser/tab_contents/test_tab_contents.h"
#include "content/test/test_browser_thread.h"

using content::BrowserThread;

static const char* kURL1 = "http://www.google.com/";
static const char* kURL2 = "http://www.gmail.com/";

namespace chromeos {

class OfflineLoadPageTest;

// An OfflineLoadPage class that does not create windows.
class TestOfflineLoadPage :  public chromeos::OfflineLoadPage {
 public:
  TestOfflineLoadPage(TabContents* tab_contents,
                      const GURL& url,
                      OfflineLoadPageTest* test_page)
    : chromeos::OfflineLoadPage(tab_contents, url, CompletionCallback()),
      test_page_(test_page) {
    interstitial_page_->DontCreateViewForTesting();
  }

  // chromeos::OfflineLoadPage override.
  virtual void NotifyBlockingPageComplete(bool proceed) OVERRIDE;

 private:
  OfflineLoadPageTest* test_page_;

  DISALLOW_COPY_AND_ASSIGN(TestOfflineLoadPage);
};

class OfflineLoadPageTest : public ChromeRenderViewHostTestHarness {
 public:
  // The decision the user made.
  enum UserResponse {
    PENDING,
    OK,
    CANCEL
  };

  OfflineLoadPageTest()
      : ui_thread_(BrowserThread::UI, MessageLoop::current()),
        io_thread_(BrowserThread::IO, MessageLoop::current()) {
  }

  virtual void SetUp() {
    ChromeRenderViewHostTestHarness::SetUp();
    user_response_ = PENDING;
  }

  void OnBlockingPageComplete(bool proceed) {
    if (proceed)
      user_response_ = OK;
    else
      user_response_ = CANCEL;
  }

  void Navigate(const char* url, int page_id) {
    contents()->TestDidNavigate(
        contents()->GetRenderViewHost(), page_id, GURL(url),
        content::PAGE_TRANSITION_TYPED);
  }

  void ShowInterstitial(const char* url) {
    new TestOfflineLoadPage(contents(), GURL(url), this);
  }

  // Returns the OfflineLoadPage currently showing or NULL if none is
  // showing.
  InterstitialPage* GetOfflineLoadPage() {
    return InterstitialPage::GetInterstitialPage(contents());
  }

  UserResponse user_response() const { return user_response_; }

 private:
  UserResponse user_response_;
  content::TestBrowserThread ui_thread_;
  content::TestBrowserThread io_thread_;

  // Initializes / shuts down a stub CrosLibrary.
  chromeos::ScopedStubCrosEnabler stub_cros_enabler_;

  DISALLOW_COPY_AND_ASSIGN(OfflineLoadPageTest);
};

void TestOfflineLoadPage::NotifyBlockingPageComplete(bool proceed) {
  test_page_->OnBlockingPageComplete(proceed);
}

// Tests are disabled due to crash. see crbug.com/113219.
TEST_F(OfflineLoadPageTest, DISABLED_OfflinePageProceed) {
  // Start a load.
  Navigate(kURL1, 1);
  // Load next page.
  controller().LoadURL(GURL(kURL2), content::Referrer(),
                       content::PAGE_TRANSITION_TYPED, std::string());

  // Simulate the load causing an offline browsing interstitial page
  // to be shown.
  ShowInterstitial(kURL2);
  InterstitialPage* interstitial = GetOfflineLoadPage();
  ASSERT_TRUE(interstitial);
  MessageLoop::current()->RunAllPending();

  // Simulate the user clicking "proceed".
  interstitial->Proceed();
  MessageLoop::current()->RunAllPending();

  EXPECT_EQ(OK, user_response());

  // The URL remains to be URL2.
  EXPECT_EQ(kURL2, contents()->GetURL().spec());

  // Commit navigation and the interstitial page is gone.
  Navigate(kURL2, 2);
  EXPECT_FALSE(GetOfflineLoadPage());
}

// Tests showing an offline page and not proceeding.
TEST_F(OfflineLoadPageTest, DISABLED_OfflinePageDontProceed) {
  // Start a load.
  Navigate(kURL1, 1);
  controller().LoadURL(GURL(kURL2), content::Referrer(),
                       content::PAGE_TRANSITION_TYPED, std::string());

  // Simulate the load causing an offline interstitial page to be shown.
  ShowInterstitial(kURL2);
  InterstitialPage* interstitial = GetOfflineLoadPage();
  ASSERT_TRUE(interstitial);
  MessageLoop::current()->RunAllPending();

  // Simulate the user clicking "don't proceed".
  interstitial->DontProceed();

  // The interstitial should be gone.
  EXPECT_EQ(CANCEL, user_response());
  EXPECT_FALSE(GetOfflineLoadPage());
  // We did not proceed, the pending entry should be gone.
  EXPECT_FALSE(controller().GetPendingEntry());
  // the URL is set back to kURL1.
  EXPECT_EQ(kURL1, contents()->GetURL().spec());
}

}  // namespace chromeos
<|endoftext|>


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

#include "chrome/browser/search_engines/template_url_model_test_util.h"

#include "base/file_util.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_model.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

// A Task used to coordinate when the database has finished processing
// requests. See note in BlockTillServiceProcessesRequests for details.
//
// When Run() schedules a QuitTask on the message loop it was created with.
class QuitTask2 : public Task {
 public:
  QuitTask2() : main_loop_(MessageLoop::current()) {}

  virtual void Run() {
    main_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask());
  }

 private:
  MessageLoop* main_loop_;
};

// Blocks the caller until thread has finished servicing all pending
// requests.
static void WaitForThreadToProcessRequests(ChromeThread::ID identifier) {
  // Schedule a task on the thread that is processed after all
  // pending requests on the thread.
  ChromeThread::PostTask(identifier, FROM_HERE, new QuitTask2());
  // Run the current message loop. QuitTask2, when run, invokes Quit,
  // which unblocks this.
  MessageLoop::current()->Run();
}

}  // namespace

// Subclass the TestingProfile so that it can return a WebDataService.
class TemplateURLModelTestingProfile : public TestingProfile {
 public:
  TemplateURLModelTestingProfile() : TestingProfile() {}

  void SetUp();
  void TearDown();

  virtual WebDataService* GetWebDataService(ServiceAccessType access) {
    return service_.get();
  }

 private:
  scoped_refptr<WebDataService> service_;
  FilePath test_dir_;
  scoped_ptr<ChromeThread> db_thread_;
};

// Trivial subclass of TemplateURLModel that records the last invocation of
// SetKeywordSearchTermsForURL.
class TestingTemplateURLModel : public TemplateURLModel {
 public:
  explicit TestingTemplateURLModel(Profile* profile)
      : TemplateURLModel(profile) {
  }

  std::wstring GetAndClearSearchTerm() {
    std::wstring search_term;
    search_term.swap(search_term_);
    return search_term;
  }

 protected:
  virtual void SetKeywordSearchTermsForURL(const TemplateURL* t_url,
                                           const GURL& url,
                                           const std::wstring& term) {
    search_term_ = term;
  }

 private:
  std::wstring search_term_;

  DISALLOW_COPY_AND_ASSIGN(TestingTemplateURLModel);
};

void TemplateURLModelTestingProfile::SetUp() {
  db_thread_.reset(new ChromeThread(ChromeThread::DB));
  db_thread_->Start();

  // Name a subdirectory of the temp directory.
  ASSERT_TRUE(PathService::Get(base::DIR_TEMP, &test_dir_));
  test_dir_ = test_dir_.AppendASCII("TemplateURLModelTest");

  // Create a fresh, empty copy of this directory.
  file_util::Delete(test_dir_, true);
  file_util::CreateDirectory(test_dir_);

  FilePath path = test_dir_.AppendASCII("TestDataService.db");
  service_ = new WebDataService;
  EXPECT_TRUE(service_->InitWithPath(path));
}

void TemplateURLModelTestingProfile::TearDown() {
  // Clean up the test directory.
  service_->Shutdown();
  // Note that we must ensure the DB thread is stopped after WDS
  // shutdown (so it can commit pending transactions) but before
  // deleting the test profile directory, otherwise we may not be
  // able to delete it due to an open transaction.
  db_thread_->Stop();

  ASSERT_TRUE(file_util::Delete(test_dir_, true));
  ASSERT_FALSE(file_util::PathExists(test_dir_));
}

TemplateURLModelTestUtil::TemplateURLModelTestUtil()
    : ui_thread_(ChromeThread::UI, &message_loop_),
      changed_count_(0) {
}

TemplateURLModelTestUtil::~TemplateURLModelTestUtil() {
}

void TemplateURLModelTestUtil::SetUp() {
  profile_.reset(new TemplateURLModelTestingProfile());
  profile_->SetUp();
  model_.reset(new TestingTemplateURLModel(profile_.get()));
  model_->AddObserver(this);
}

void TemplateURLModelTestUtil::TearDown() {
  profile_->TearDown();
  TemplateURLRef::SetGoogleBaseURL(NULL);

  // Flush the message loop to make Purify happy.
  message_loop_.RunAllPending();
}

void TemplateURLModelTestUtil::OnTemplateURLModelChanged() {
  changed_count_++;
}

void TemplateURLModelTestUtil::VerifyObserverCount(int expected_changed_count) {
  ASSERT_EQ(expected_changed_count, changed_count_);
  changed_count_ = 0;
}

void TemplateURLModelTestUtil::ResetObserverCount() {
  changed_count_ = 0;
}

void TemplateURLModelTestUtil::BlockTillServiceProcessesRequests() {
  WaitForThreadToProcessRequests(ChromeThread::DB);
}

void TemplateURLModelTestUtil::BlockTillIOThreadProcessesRequests() {
  WaitForThreadToProcessRequests(ChromeThread::IO);
}

void TemplateURLModelTestUtil::VerifyLoad() {
  ASSERT_FALSE(model_->loaded());
  model_->Load();
  BlockTillServiceProcessesRequests();
  VerifyObserverCount(1);
}

void TemplateURLModelTestUtil::ChangeModelToLoadState() {
  model_->ChangeToLoadedState();
  // Initialize the web data service so that the database gets updated with
  // any changes made.
  model_->service_ = profile_->GetWebDataService(Profile::EXPLICIT_ACCESS);
}

void TemplateURLModelTestUtil::ClearModel() {
  model_.reset(NULL);
}

void TemplateURLModelTestUtil::ResetModel(bool verify_load) {
  model_.reset(new TestingTemplateURLModel(profile_.get()));
  model_->AddObserver(this);
  changed_count_ = 0;
  if (verify_load)
    VerifyLoad();
}

std::wstring TemplateURLModelTestUtil::GetAndClearSearchTerm() {
  return model_->GetAndClearSearchTerm();
}

void TemplateURLModelTestUtil::SetGoogleBaseURL(
    const std::string& base_url) const {
  TemplateURLRef::SetGoogleBaseURL(new std::string(base_url));
}

WebDataService* TemplateURLModelTestUtil::GetWebDataService() {
  return profile_->GetWebDataService(Profile::EXPLICIT_ACCESS);
}

TemplateURLModel* TemplateURLModelTestUtil::model() const {
  return model_.get();
}

TestingProfile* TemplateURLModelTestUtil::profile() const {
  return profile_.get();
}
<commit_msg>Remove the code that shall not be used in tests: PathService::Get(base::DIR_TEMP<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/search_engines/template_url_model_test_util.h"

#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/scoped_temp_dir.h"
#include "chrome/browser/search_engines/template_url.h"
#include "chrome/browser/search_engines/template_url_model.h"
#include "chrome/test/testing_profile.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

// A Task used to coordinate when the database has finished processing
// requests. See note in BlockTillServiceProcessesRequests for details.
//
// When Run() schedules a QuitTask on the message loop it was created with.
class QuitTask2 : public Task {
 public:
  QuitTask2() : main_loop_(MessageLoop::current()) {}

  virtual void Run() {
    main_loop_->PostTask(FROM_HERE, new MessageLoop::QuitTask());
  }

 private:
  MessageLoop* main_loop_;
};

// Blocks the caller until thread has finished servicing all pending
// requests.
static void WaitForThreadToProcessRequests(ChromeThread::ID identifier) {
  // Schedule a task on the thread that is processed after all
  // pending requests on the thread.
  ChromeThread::PostTask(identifier, FROM_HERE, new QuitTask2());
  // Run the current message loop. QuitTask2, when run, invokes Quit,
  // which unblocks this.
  MessageLoop::current()->Run();
}

}  // namespace

// Subclass the TestingProfile so that it can return a WebDataService.
class TemplateURLModelTestingProfile : public TestingProfile {
 public:
  TemplateURLModelTestingProfile() : TestingProfile() {}

  void SetUp();
  void TearDown();

  virtual WebDataService* GetWebDataService(ServiceAccessType access) {
    return service_.get();
  }

 private:
  scoped_refptr<WebDataService> service_;
  ScopedTempDir temp_dir_;
  scoped_ptr<ChromeThread> db_thread_;
};

// Trivial subclass of TemplateURLModel that records the last invocation of
// SetKeywordSearchTermsForURL.
class TestingTemplateURLModel : public TemplateURLModel {
 public:
  explicit TestingTemplateURLModel(Profile* profile)
      : TemplateURLModel(profile) {
  }

  std::wstring GetAndClearSearchTerm() {
    std::wstring search_term;
    search_term.swap(search_term_);
    return search_term;
  }

 protected:
  virtual void SetKeywordSearchTermsForURL(const TemplateURL* t_url,
                                           const GURL& url,
                                           const std::wstring& term) {
    search_term_ = term;
  }

 private:
  std::wstring search_term_;

  DISALLOW_COPY_AND_ASSIGN(TestingTemplateURLModel);
};

void TemplateURLModelTestingProfile::SetUp() {
  db_thread_.reset(new ChromeThread(ChromeThread::DB));
  db_thread_->Start();

  // Make unique temp directory.
  ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());

  FilePath path = temp_dir_.path().AppendASCII("TestDataService.db");
  service_ = new WebDataService;
  EXPECT_TRUE(service_->InitWithPath(path));
}

void TemplateURLModelTestingProfile::TearDown() {
  // Clean up the test directory.
  service_->Shutdown();
  // Note that we must ensure the DB thread is stopped after WDS
  // shutdown (so it can commit pending transactions) but before
  // deleting the test profile directory, otherwise we may not be
  // able to delete it due to an open transaction.
  db_thread_->Stop();
}

TemplateURLModelTestUtil::TemplateURLModelTestUtil()
    : ui_thread_(ChromeThread::UI, &message_loop_),
      changed_count_(0) {
}

TemplateURLModelTestUtil::~TemplateURLModelTestUtil() {
}

void TemplateURLModelTestUtil::SetUp() {
  profile_.reset(new TemplateURLModelTestingProfile());
  profile_->SetUp();
  model_.reset(new TestingTemplateURLModel(profile_.get()));
  model_->AddObserver(this);
}

void TemplateURLModelTestUtil::TearDown() {
  profile_->TearDown();
  TemplateURLRef::SetGoogleBaseURL(NULL);

  // Flush the message loop to make Purify happy.
  message_loop_.RunAllPending();
}

void TemplateURLModelTestUtil::OnTemplateURLModelChanged() {
  changed_count_++;
}

void TemplateURLModelTestUtil::VerifyObserverCount(int expected_changed_count) {
  ASSERT_EQ(expected_changed_count, changed_count_);
  changed_count_ = 0;
}

void TemplateURLModelTestUtil::ResetObserverCount() {
  changed_count_ = 0;
}

void TemplateURLModelTestUtil::BlockTillServiceProcessesRequests() {
  WaitForThreadToProcessRequests(ChromeThread::DB);
}

void TemplateURLModelTestUtil::BlockTillIOThreadProcessesRequests() {
  WaitForThreadToProcessRequests(ChromeThread::IO);
}

void TemplateURLModelTestUtil::VerifyLoad() {
  ASSERT_FALSE(model_->loaded());
  model_->Load();
  BlockTillServiceProcessesRequests();
  VerifyObserverCount(1);
}

void TemplateURLModelTestUtil::ChangeModelToLoadState() {
  model_->ChangeToLoadedState();
  // Initialize the web data service so that the database gets updated with
  // any changes made.
  model_->service_ = profile_->GetWebDataService(Profile::EXPLICIT_ACCESS);
}

void TemplateURLModelTestUtil::ClearModel() {
  model_.reset(NULL);
}

void TemplateURLModelTestUtil::ResetModel(bool verify_load) {
  model_.reset(new TestingTemplateURLModel(profile_.get()));
  model_->AddObserver(this);
  changed_count_ = 0;
  if (verify_load)
    VerifyLoad();
}

std::wstring TemplateURLModelTestUtil::GetAndClearSearchTerm() {
  return model_->GetAndClearSearchTerm();
}

void TemplateURLModelTestUtil::SetGoogleBaseURL(
    const std::string& base_url) const {
  TemplateURLRef::SetGoogleBaseURL(new std::string(base_url));
}

WebDataService* TemplateURLModelTestUtil::GetWebDataService() {
  return profile_->GetWebDataService(Profile::EXPLICIT_ACCESS);
}

TemplateURLModel* TemplateURLModelTestUtil::model() const {
  return model_.get();
}

TestingProfile* TemplateURLModelTestUtil::profile() const {
  return profile_.get();
}
<|endoftext|>


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

#include "content/renderer/service_worker/embedded_worker_dispatcher.h"

#include "base/memory/scoped_ptr.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "content/child/child_process.h"
#include "content/child/scoped_child_process_reference.h"
#include "content/child/thread_safe_sender.h"
#include "content/common/service_worker/embedded_worker_messages.h"
#include "content/renderer/render_thread_impl.h"
#include "content/renderer/service_worker/embedded_worker_context_client.h"
#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/WebKit/public/platform/WebURL.h"
#include "third_party/WebKit/public/web/WebEmbeddedWorker.h"
#include "third_party/WebKit/public/web/WebEmbeddedWorkerStartData.h"
#include "webkit/child/worker_task_runner.h"
#include "webkit/common/user_agent/user_agent.h"

namespace content {

// A thin wrapper of WebEmbeddedWorker which also adds and releases process
// references automatically.
class EmbeddedWorkerDispatcher::WorkerWrapper {
 public:
  explicit WorkerWrapper(blink::WebEmbeddedWorker* worker) : worker_(worker) {}
  ~WorkerWrapper() {}

  blink::WebEmbeddedWorker* worker() { return worker_.get(); }

 private:
  ScopedChildProcessReference process_ref_;
  scoped_ptr<blink::WebEmbeddedWorker> worker_;
};

EmbeddedWorkerDispatcher::EmbeddedWorkerDispatcher() : weak_factory_(this) {}

EmbeddedWorkerDispatcher::~EmbeddedWorkerDispatcher() {}

bool EmbeddedWorkerDispatcher::OnMessageReceived(
    const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(EmbeddedWorkerDispatcher, message)
    IPC_MESSAGE_HANDLER(EmbeddedWorkerMsg_StartWorker, OnStartWorker)
    IPC_MESSAGE_HANDLER(EmbeddedWorkerMsg_StopWorker, OnStopWorker)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void EmbeddedWorkerDispatcher::WorkerContextDestroyed(
    int embedded_worker_id) {
  RenderThreadImpl::current()->thread_safe_sender()->Send(
      new EmbeddedWorkerHostMsg_WorkerStopped(embedded_worker_id));
  workers_.Remove(embedded_worker_id);
}

void EmbeddedWorkerDispatcher::OnStartWorker(
    int embedded_worker_id,
    int64 service_worker_version_id,
    const GURL& script_url) {
  DCHECK(!workers_.Lookup(embedded_worker_id));
  scoped_ptr<WorkerWrapper> wrapper(new WorkerWrapper(
      blink::WebEmbeddedWorker::create(
          new EmbeddedWorkerContextClient(
              embedded_worker_id,
              service_worker_version_id,
              script_url),
          NULL)));

  blink::WebEmbeddedWorkerStartData start_data;
  start_data.scriptURL = script_url;
  start_data.userAgent =
      base::UTF8ToUTF16(webkit_glue::GetUserAgent(script_url));

  wrapper->worker()->startWorkerContext(start_data);
  workers_.AddWithID(wrapper.release(), embedded_worker_id);
}

void EmbeddedWorkerDispatcher::OnStopWorker(int embedded_worker_id) {
  WorkerWrapper* wrapper = workers_.Lookup(embedded_worker_id);
  if (!wrapper) {
    LOG(WARNING) << "Got OnStopWorker for nonexistent worker";
    return;
  }

  // This should eventually call WorkerContextDestroyed. (We may need to post
  // a delayed task to forcibly abort the worker context if we find it
  // necessary)
  wrapper->worker()->terminateWorkerContext();
}

}  // namespace content
<commit_msg>Initialize WebEmbeddedWorkerStartData before using it<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/renderer/service_worker/embedded_worker_dispatcher.h"

#include "base/memory/scoped_ptr.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "content/child/child_process.h"
#include "content/child/scoped_child_process_reference.h"
#include "content/child/thread_safe_sender.h"
#include "content/common/service_worker/embedded_worker_messages.h"
#include "content/renderer/render_thread_impl.h"
#include "content/renderer/service_worker/embedded_worker_context_client.h"
#include "third_party/WebKit/public/platform/WebString.h"
#include "third_party/WebKit/public/platform/WebURL.h"
#include "third_party/WebKit/public/web/WebEmbeddedWorker.h"
#include "third_party/WebKit/public/web/WebEmbeddedWorkerStartData.h"
#include "webkit/child/worker_task_runner.h"
#include "webkit/common/user_agent/user_agent.h"

namespace content {

// A thin wrapper of WebEmbeddedWorker which also adds and releases process
// references automatically.
class EmbeddedWorkerDispatcher::WorkerWrapper {
 public:
  explicit WorkerWrapper(blink::WebEmbeddedWorker* worker) : worker_(worker) {}
  ~WorkerWrapper() {}

  blink::WebEmbeddedWorker* worker() { return worker_.get(); }

 private:
  ScopedChildProcessReference process_ref_;
  scoped_ptr<blink::WebEmbeddedWorker> worker_;
};

EmbeddedWorkerDispatcher::EmbeddedWorkerDispatcher() : weak_factory_(this) {}

EmbeddedWorkerDispatcher::~EmbeddedWorkerDispatcher() {}

bool EmbeddedWorkerDispatcher::OnMessageReceived(
    const IPC::Message& message) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP(EmbeddedWorkerDispatcher, message)
    IPC_MESSAGE_HANDLER(EmbeddedWorkerMsg_StartWorker, OnStartWorker)
    IPC_MESSAGE_HANDLER(EmbeddedWorkerMsg_StopWorker, OnStopWorker)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP()
  return handled;
}

void EmbeddedWorkerDispatcher::WorkerContextDestroyed(
    int embedded_worker_id) {
  RenderThreadImpl::current()->thread_safe_sender()->Send(
      new EmbeddedWorkerHostMsg_WorkerStopped(embedded_worker_id));
  workers_.Remove(embedded_worker_id);
}

void EmbeddedWorkerDispatcher::OnStartWorker(
    int embedded_worker_id,
    int64 service_worker_version_id,
    const GURL& script_url) {
  DCHECK(!workers_.Lookup(embedded_worker_id));
  scoped_ptr<WorkerWrapper> wrapper(new WorkerWrapper(
      blink::WebEmbeddedWorker::create(
          new EmbeddedWorkerContextClient(
              embedded_worker_id,
              service_worker_version_id,
              script_url),
          NULL)));

  blink::WebEmbeddedWorkerStartData start_data;
  start_data.scriptURL = script_url;
  start_data.userAgent =
      base::UTF8ToUTF16(webkit_glue::GetUserAgent(script_url));
  start_data.startMode = blink::WebEmbeddedWorkerStartModeDontPauseOnStart;

  wrapper->worker()->startWorkerContext(start_data);
  workers_.AddWithID(wrapper.release(), embedded_worker_id);
}

void EmbeddedWorkerDispatcher::OnStopWorker(int embedded_worker_id) {
  WorkerWrapper* wrapper = workers_.Lookup(embedded_worker_id);
  if (!wrapper) {
    LOG(WARNING) << "Got OnStopWorker for nonexistent worker";
    return;
  }

  // This should eventually call WorkerContextDestroyed. (We may need to post
  // a delayed task to forcibly abort the worker context if we find it
  // necessary)
  wrapper->worker()->terminateWorkerContext();
}

}  // namespace content
<|endoftext|>


<commit_before>//---------------------------------------------------------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2006 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//---------------------------------------------------------------------------

// See documentation of CompressedBlockSparsityPattern for documentation of this example

#include <lac/block_sparsity_pattern.h>
#include <grid/tria.h>
#include <grid/tria_accessor.h>
#include <grid/tria_iterator.h>
#include <grid/grid_generator.h>
#include <fe/fe_q.h>
#include <fe/fe_system.h>
#include <dofs/dof_handler.h>
#include <dofs/dof_constraints.h>
#include <dofs/dof_tools.h>

#include <iostream>

int main()
{
  Triangulation<2> tr;
  GridGenerator::subdivided_hyper_cube(tr, 3);
  tr.begin_active()->set_refine_flag();
  tr.execute_coarsening_and_refinement();

  FE_Q<2> fe1(1);
  FE_Q<2> fe2(2);
  FESystem<2> fe(fe1, 2, fe2, 1);

  DoFHandler<2> dof(tr);
  dof.distribute_dofs(fe);
  ConstraintMatrix constraints;
  DoFTools::make_hanging_node_constraints(dof, constraints);
  constraints.close();

  std::vector<unsigned int> dofs_per_block(fe.n_blocks());
  DoFTools::count_dofs_per_block(dof, dofs_per_block);

  CompressedBlockSparsityPattern c_sparsity(fe.n_blocks(), fe.n_blocks());
  for (unsigned int i=0;i<fe.n_blocks();++i)
    for (unsigned int j=0;j<fe.n_blocks();++j)
      c_sparsity.block(i,j).reinit(dofs_per_block[i],dofs_per_block[j]);
  c_sparsity.collect_sizes();

  DoFTools::make_sparsity_pattern(dof, c_sparsity);
  constraints.condense(c_sparsity);

  BlockSparsityPattern sparsity;
  sparsity.copy_from(c_sparsity);

  for (unsigned int i=0;i<fe.n_blocks();++i)
    for (unsigned int j=0;j<fe.n_blocks();++j)
      {
	std::cout << "   Block " << i << ' ' << j << std::endl;
	sparsity.block(i,j).print(std::cout);
      }
}
<commit_msg>Slightly different form of the example program.<commit_after>//---------------------------------------------------------------------------
//    $Id$
//    Version: $Name$
//
//    Copyright (C) 2006 by the deal.II authors
//
//    This file is subject to QPL and may not be  distributed
//    without copyright and license information. Please refer
//    to the file deal.II/doc/license.html for the  text  and
//    further information on this license.
//
//---------------------------------------------------------------------------

// See documentation of CompressedBlockSparsityPattern for documentation of this example

#include <lac/block_sparsity_pattern.h>
#include <grid/tria.h>
#include <grid/tria_accessor.h>
#include <grid/tria_iterator.h>
#include <grid/grid_generator.h>
#include <fe/fe_q.h>
#include <fe/fe_system.h>
#include <dofs/dof_handler.h>
#include <dofs/dof_constraints.h>
#include <dofs/dof_tools.h>

#include <iostream>

int main()
{
  Triangulation<2> tr;
  GridGenerator::subdivided_hyper_cube(tr, 3);
  tr.begin_active()->set_refine_flag();
  tr.execute_coarsening_and_refinement();

  FE_Q<2> fe1(1);
  FE_Q<2> fe2(2);
  FESystem<2> fe(fe1, 2, fe2, 1);

  DoFHandler<2> dof(tr);
  dof.distribute_dofs(fe);
  ConstraintMatrix constraints;
  DoFTools::make_hanging_node_constraints(dof, constraints);
  constraints.close();

  std::vector<unsigned int> dofs_per_block(fe.n_blocks());
  DoFTools::count_dofs_per_block(dof, dofs_per_block);

  CompressedBlockSparsityPattern c_sparsity(fe.n_blocks(), fe.n_blocks());
  for (unsigned int i=0;i<fe.n_blocks();++i)
    for (unsigned int j=0;j<fe.n_blocks();++j)
      c_sparsity.block(i,j).reinit(dofs_per_block[i],dofs_per_block[j]);
  c_sparsity.collect_sizes();

  DoFTools::make_sparsity_pattern(dof, c_sparsity);
  constraints.condense(c_sparsity);

  BlockSparsityPattern sparsity;
  sparsity.copy_from(c_sparsity);

//   for (unsigned int i=0;i<fe.n_blocks();++i)
//     for (unsigned int j=0;j<fe.n_blocks();++j)
//       {
// 	std::cout << "   Block " << i << ' ' << j << std::endl;
// 	sparsity.block(i,j).print(std::cout);
//       }
  for (unsigned int i=0; i<sparsity.n_rows(); ++i)
    for (unsigned int j=0; j<sparsity.n_cols(); ++j)
      if (sparsity.exists(i,j))
	std::cout << i << ' ' << j << std::endl;
}
<|endoftext|>