<commit_before>/***************************************************************************
 *   Copyright (C) 2005-2007 by the FIFE Team                              *
 *   fife-public@lists.sourceforge.net                                     *
 *   This file is part of FIFE.                                            *
 *                                                                         *
 *   FIFE is free software; you can redistribute it and/or modify          *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA              *
 ***************************************************************************/

// Standard C++ library includes
#include <algorithm>

// 3rd party library includes
#include <boost/functional.hpp>
#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>

// FIFE includes
// These includes are split up in two parts, separated by one empty line
// First block: files included from the FIFE root src directory
// Second block: files included from the same folder
#include "vfs/raw/rawdata.h"
#include "util/exception.h"
#include "util/logger.h"

#include "vfs.h"
#include "vfssource.h"
#include "vfssourceprovider.h"

namespace FIFE {
	static Logger _log(LM_VFS);

	VFS::VFS() : m_sources() {}

	VFS::~VFS() {
		cleanup();
	}

	void VFS::cleanup() {
		type_sources sources = m_sources;
		type_sources::const_iterator end = sources.end();
		for (type_sources::iterator i = sources.begin(); i != end; ++i)
			delete *i;

		type_providers::const_iterator end2 = m_providers.end();
		for (type_providers::iterator j = m_providers.begin(); j != end2; ++j)
			delete *j;

		m_providers.clear();
	}

	void VFS::addProvider(VFSSourceProvider* provider) {
		m_providers.push_back(provider);
		FL_LOG(_log, LMsg("new provider: ") << provider->getName());
	}

	VFSSource* VFS::createSource(const std::string& path) const {
		if( m_usedfiles.count(path) ) {
			FL_WARN(_log, LMsg(path) << " is already used as VFS source");
			return 0;
		}

		type_providers::const_iterator end = m_providers.end();
		for (type_providers::const_iterator i = m_providers.begin(); i != end; ++i) {
			const VFSSourceProvider* provider = *i;
			if (!provider->isReadable(path))
				continue;

			try {
				VFSSource* source = provider->createSource(path);
				m_usedfiles.insert(path);
				return source;
			} catch(const Exception& ex) {
				FL_WARN(_log, LMsg(provider->getName()) << " thought it could load " << path << " but didn't succeed (" << ex.getMessage() << ")");
				continue;
			} catch(...) {
				FL_WARN(_log, LMsg(provider->getName()) << " thought it could load " << path << " but didn't succeed (unkown exception)");
				continue;
			}
		}

		FL_WARN(_log, LMsg("no provider for ") << path << " found");
		return 0;
	}

	void VFS::addNewSource(const std::string& path) {
		VFSSource* source = createSource(path);
		if (source) {
			addSource(source);
		} else {
			FL_WARN(_log, LMsg("Failed to add new VFS source: ") << path);
		}
	}

	void VFS::addSource(VFSSource* source) {
		m_sources.push_back(source);
	}

	void VFS::removeSource(VFSSource* source) {
		type_sources::iterator i = std::find(m_sources.begin(), m_sources.end(), source);
		if (i != m_sources.end())
			m_sources.erase(i);
	}

	VFSSource* VFS::getSourceForFile(const std::string& file) const {
		std::string lowerpath = lower(file);
		type_sources::const_iterator i = std::find_if(m_sources.begin(), m_sources.end(),
		                                 boost::bind2nd(boost::mem_fun(&VFSSource::fileExists), lowerpath));
		if (i == m_sources.end()) {
			FL_WARN(_log, LMsg("no source for ") << lowerpath << " found");
			return 0;
		}

		return *i;
	}

	bool VFS::exists(const std::string& file) const {
		return getSourceForFile(lower(file));
	}

	bool VFS::isDirectory(const std::string& path) const {
		std::vector<std::string> tokens;
		// Add a slash in case there isn't one in the string
		boost::algorithm::split(tokens, path + "/", boost::algorithm::is_any_of("/"));

		std::string currentpath = "/";
		std::vector<std::string>::const_iterator token=tokens.begin();
		while(token != tokens.end()) {
			if(*token != "") {
				if (VFS::instance()->listDirectories(currentpath, *token).size() == 0) {
					return false;
				}
				else {
					currentpath += *token + "/";
				}
			}
			token++;
		}

		return true;
	}

	RawData* VFS::open(const std::string& path) {
		std::string lowerpath = lower(path);
		FL_DBG(_log, LMsg("Opening: ") << lowerpath);

		VFSSource* source = getSourceForFile(lowerpath);
		if (!source)
			throw NotFound(path);

		return source->open(lowerpath);
	}

	std::string VFS::lower(const std::string& str) const {
		std::string result;
		result.resize(str.size());
		std::transform(str.begin(), str.end(), result.begin(), tolower);
		return result;
	}

	std::vector<std::string> VFS::listFiles(const std::string& pathstr) const {
		std::string lowerpath = lower(pathstr);
		std::vector<std::string> list;
		type_sources::const_iterator end = m_sources.end();
		for (type_sources::const_iterator i = m_sources.begin(); i != end; ++i) {
			std::vector<std::string> sourcelist = (*i)->listFiles(lowerpath);
			list.insert(list.begin(), sourcelist.begin(), sourcelist.end());
		}

		return list;
	}

	std::vector<std::string> VFS::listFiles(const std::string& path, const std::string& filterregex) const {
		std::string lowerpath = lower(path);
		std::vector<std::string> list = listFiles(lowerpath);
		return filterList(list, filterregex);
	}

	std::vector<std::string> VFS::listDirectories(const std::string& pathstr) const {
		std::string lowerpath = lower(pathstr);
		std::vector<std::string> list;
		type_sources::const_iterator end = m_sources.end();
		for (type_sources::const_iterator i = m_sources.begin(); i != end; ++i) {
			std::vector<std::string> sourcelist = (*i)->listDirectories(lowerpath);
			list.insert(list.begin(), sourcelist.begin(), sourcelist.end());
		}

		return list;
	}

	std::vector<std::string> VFS::listDirectories(const std::string& path, const std::string& filterregex) const {
		std::vector<std::string> list = listDirectories(lower(path));
		return filterList(list, filterregex);
	}

	std::vector<std::string> VFS::filterList(const std::vector<std::string>& list, const std::string& fregex) const {
		std::vector<std::string> results;
		boost::regex regex(fregex);
		std::vector<std::string>::const_iterator end = list.end();
		for (std::vector<std::string>::const_iterator i = list.begin(); i != end;) {
			boost::cmatch match;
			if (boost::regex_match((*i).c_str(), match, regex)) {
				results.push_back(*i);
			}
			++i;
		}
		return results;
	}
}
<commit_msg>Makes trunk compile again. Find Wuntvor to know what happened.<commit_after>/***************************************************************************
 *   Copyright (C) 2005-2007 by the FIFE Team                              *
 *   fife-public@lists.sourceforge.net                                     *
 *   This file is part of FIFE.                                            *
 *                                                                         *
 *   FIFE is free software; you can redistribute it and/or modify          *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA              *
 ***************************************************************************/

// Standard C++ library includes
#include <algorithm>

// 3rd party library includes
#include <boost/functional.hpp>
#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>

// FIFE includes
// These includes are split up in two parts, separated by one empty line
// First block: files included from the FIFE root src directory
// Second block: files included from the same folder
#include "vfs/raw/rawdata.h"
#include "util/exception.h"
#include "util/logger.h"

#include "vfs.h"
#include "vfssource.h"
#include "vfssourceprovider.h"

namespace FIFE {
	static Logger _log(LM_VFS);

	VFS::VFS() : m_sources() {}

	VFS::~VFS() {
		cleanup();
	}

	void VFS::cleanup() {
		type_sources sources = m_sources;
		type_sources::const_iterator end = sources.end();
		for (type_sources::iterator i = sources.begin(); i != end; ++i)
			delete *i;

		type_providers::const_iterator end2 = m_providers.end();
		for (type_providers::iterator j = m_providers.begin(); j != end2; ++j)
			delete *j;

		m_providers.clear();
	}

	void VFS::addProvider(VFSSourceProvider* provider) {
		m_providers.push_back(provider);
		FL_LOG(_log, LMsg("new provider: ") << provider->getName());
	}

	VFSSource* VFS::createSource(const std::string& path) const {
		if ( m_usedfiles.count(path) ) {
			FL_WARN(_log, LMsg(path) << " is already used as VFS source");
			return 0;
		}

		type_providers::const_iterator end = m_providers.end();
		for (type_providers::const_iterator i = m_providers.begin(); i != end; ++i) {
			const VFSSourceProvider* provider = *i;
			if (!provider->isReadable(path))
				continue;

			try {
				VFSSource* source = provider->createSource(path);
				m_usedfiles.insert(path);
				return source;
			} catch (const Exception& ex) {
				FL_WARN(_log, LMsg(provider->getName()) << " thought it could load " << path << " but didn't succeed (" << ex.getMessage() << ")");
				continue;
			} catch (...) {
				FL_WARN(_log, LMsg(provider->getName()) << " thought it could load " << path << " but didn't succeed (unkown exception)");
				continue;
			}
		}

		FL_WARN(_log, LMsg("no provider for ") << path << " found");
		return 0;
	}

	void VFS::addNewSource(const std::string& path) {
		VFSSource* source = createSource(path);
		if (source) {
			addSource(source);
		} else {
			FL_WARN(_log, LMsg("Failed to add new VFS source: ") << path);
		}
	}

	void VFS::addSource(VFSSource* source) {
		m_sources.push_back(source);
	}

	void VFS::removeSource(VFSSource* source) {
		type_sources::iterator i = std::find(m_sources.begin(), m_sources.end(), source);
		if (i != m_sources.end())
			m_sources.erase(i);
	}

	VFSSource* VFS::getSourceForFile(const std::string& file) const {
		std::string lowerpath = lower(file);
		type_sources::const_iterator i = std::find_if(m_sources.begin(), m_sources.end(),
										 boost::bind2nd(boost::mem_fun(&VFSSource::fileExists), lowerpath));
		if (i == m_sources.end()) {
			FL_WARN(_log, LMsg("no source for ") << lowerpath << " found");
			return 0;
		}

		return *i;
	}

	bool VFS::exists(const std::string& file) const {
		return getSourceForFile(lower(file));
	}

	bool VFS::isDirectory(const std::string& path) const {
		std::vector<std::string> tokens;
		// Add a slash in case there isn't one in the string
		const std::string newpath = path + "/";
		boost::algorithm::split(tokens, newpath, boost::algorithm::is_any_of("/"));

		std::string currentpath = "/";
		std::vector<std::string>::const_iterator token=tokens.begin();
		while (token != tokens.end()) {
			if (*token != "") {
				if (VFS::instance()->listDirectories(currentpath, *token).size() == 0) {
					return false;
				} else {
					currentpath += *token + "/";
				}
			}
			token++;
		}

		return true;
	}

	RawData* VFS::open(const std::string& path) {
		std::string lowerpath = lower(path);
		FL_DBG(_log, LMsg("Opening: ") << lowerpath);

		VFSSource* source = getSourceForFile(lowerpath);
		if (!source)
			throw NotFound(path);

		return source->open(lowerpath);
	}

	std::string VFS::lower(const std::string& str) const {
		std::string result;
		result.resize(str.size());
		std::transform(str.begin(), str.end(), result.begin(), tolower);
		return result;
	}

	std::vector<std::string> VFS::listFiles(const std::string& pathstr) const {
		std::string lowerpath = lower(pathstr);
		std::vector<std::string> list;
		type_sources::const_iterator end = m_sources.end();
		for (type_sources::const_iterator i = m_sources.begin(); i != end; ++i) {
			std::vector<std::string> sourcelist = (*i)->listFiles(lowerpath);
			list.insert(list.begin(), sourcelist.begin(), sourcelist.end());
		}

		return list;
	}

	std::vector<std::string> VFS::listFiles(const std::string& path, const std::string& filterregex) const {
		std::string lowerpath = lower(path);
		std::vector<std::string> list = listFiles(lowerpath);
		return filterList(list, filterregex);
	}

	std::vector<std::string> VFS::listDirectories(const std::string& pathstr) const {
		std::string lowerpath = lower(pathstr);
		std::vector<std::string> list;
		type_sources::const_iterator end = m_sources.end();
		for (type_sources::const_iterator i = m_sources.begin(); i != end; ++i) {
			std::vector<std::string> sourcelist = (*i)->listDirectories(lowerpath);
			list.insert(list.begin(), sourcelist.begin(), sourcelist.end());
		}

		return list;
	}

	std::vector<std::string> VFS::listDirectories(const std::string& path, const std::string& filterregex) const {
		std::vector<std::string> list = listDirectories(lower(path));
		return filterList(list, filterregex);
	}

	std::vector<std::string> VFS::filterList(const std::vector<std::string>& list, const std::string& fregex) const {
		std::vector<std::string> results;
		boost::regex regex(fregex);
		std::vector<std::string>::const_iterator end = list.end();
		for (std::vector<std::string>::const_iterator i = list.begin(); i != end;) {
			boost::cmatch match;
			if (boost::regex_match((*i).c_str(), match, regex)) {
				results.push_back(*i);
			}
			++i;
		}
		return results;
	}
}
<|endoftext|>


<commit_before>/* This file is part of the KDE project
 * Copyright (C) 2010 Sebastian Sauer <sebsauer@kdab.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */
#include "kaccessiblebridge.h"

#include <QAccessibleInterface>
#include <QWidget>
#include <QFile>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QDBusInterface>
#include <kdebug.h>

Q_EXPORT_PLUGIN(BridgePlugin)

class Bridge::Private
{
    public:
        BridgePlugin *m_plugin;
        const QString m_key;
        QAccessibleInterface *m_root;
        QObject *m_currentPopupMenu;

        Private(BridgePlugin *plugin, const QString& key)
            : m_plugin(plugin)
            , m_key(key)
            , m_root(0)
            , m_currentPopupMenu(0)
        {
        }
};

Bridge::Bridge(BridgePlugin *plugin, const QString& key)
    : QObject(plugin)
    , QAccessibleBridge()
    , d(new Private(plugin, key))
{
}

Bridge::~Bridge()
{
    delete d;
}

QString reasonToString(int reason)
{
    switch(reason) {
        case QAccessible::Focus: return "QAccessible::Focus";
        case QAccessible::MenuCommand: return "QAccessible::MenuCommand";
        case QAccessible::MenuStart: return "QAccessible::MenuStart";
        case QAccessible::MenuEnd: return "QAccessible::MenuEnd";
        case QAccessible::PopupMenuEnd: return "QAccessible::PopupMenuEnd";
        case QAccessible::PopupMenuStart: return "QAccessible::PopupMenuStart";
        case QAccessible::ScrollingEnd: return "QAccessible::ScrollingEnd";
        case QAccessible::ScrollingStart: return "QAccessible::ScrollingStart";
        case QAccessible::Selection: return "QAccessible::Selection";
        case QAccessible::StateChanged: return "QAccessible::StateChanged";
        case QAccessible::ValueChanged: return "QAccessible::ValueChanged";
        case QAccessible::NameChanged: return "QAccessible::NameChanged";
        case QAccessible::ObjectCreated: return "QAccessible::ObjectCreated";
        case QAccessible::ObjectDestroyed: return "QAccessible::ObjectDestroyed";
        //case QAccessible::ObjectHide: return "QAccessible::ObjectHide";
        case QAccessible::ObjectReorder: return "QAccessible::ObjectReorder";
        //case QAccessible::ObjectShow: return "QAccessible::ObjectShow";
        case QAccessible::ParentChanged: return "QAccessible::ParentChanged";
        case QAccessible::Alert: return "QAccessible::Alert";
        case QAccessible::DefaultActionChanged: return "QAccessible::DefaultActionChanged";
        case QAccessible::DialogEnd: return "QAccessible::DialogEnd";
        case QAccessible::DialogStart: return "QAccessible::DialogStart";
        case QAccessible::DragDropEnd: return "QAccessible::DragDropEnd";
        case QAccessible::DragDropStart: return "QAccessible::DragDropStart";
        case QAccessible::ForegroundChanged: return "QAccessible::ForegroundChanged";
        case QAccessible::LocationChanged: return "QAccessible::LocationChanged";
        case QAccessible::SelectionAdd: return "QAccessible::SelectionAdd";
        case QAccessible::SelectionRemove: return "QAccessible::SelectionRemove";
        case QAccessible::SelectionWithin: return "QAccessible::SelectionWithin";
        default: break;
    }
    return QString::number(reason);
}

void Bridge::notifyAccessibilityUpdate(int reason, QAccessibleInterface *interface, int child)
{
    if(!d->m_root) {
        return;
    }

    if(reason == QAccessible::ObjectShow || reason == QAccessible::ObjectHide) {
        return;
    }

    QAccessibleInterface *childInterface = 0;
    if(child > 0) {
        interface->navigate(QAccessible::Child, child, &childInterface);
    }

    kDebug() << "reason=" << reasonToString(reason) << "child=" << child << "childrect=" << interface->rect(child) << "state=" << interface->state(child) << "object=" << (interface->object() ? QString("%1 (%2)").arg(interface->object()->objectName()).arg(interface->object()->metaObject()->className()) : "NULL") << "childInterface=" << (childInterface && childInterface->object() ? QString("%1 (%2)").arg(childInterface->object()->objectName()).arg(childInterface->object()->metaObject()->className()) : "NULL");

    switch(reason) {
        case QAccessible::PopupMenuStart:
            d->m_currentPopupMenu = interface->object();
            break;
        case QAccessible::PopupMenuEnd:
            d->m_currentPopupMenu = 0;
            break;

        //FIX kwrite to send out better events then only StateChanged...
        case QAccessible::StateChanged:
            // fall through...

        case QAccessible::Focus: {
            // abort if the focus would interrupt a popupmenu
            if(d->m_currentPopupMenu && !childInterface)
                return;

            // an optional exact point that has the focus
            QPoint p(-1,-1);
            // the rectangle that has focus
            QRect r = interface->rect(child);

            // here we could add hacks to special case applications/widgets :)
            //
            // QWidget *w = childInterface ? dynamic_cast<QWidget*>(childInterface->object()) : 0;
            // if(!w) w = dynamic_cast<QWidget*>(interface->object());
            // if(w) r = QRect(w->mapToGlobal(QPoint(w->x(), w->y())), w->size());

            QDBusInterface iface("org.kde.kaccessibleapp","/Adaptor");
            iface.asyncCall("setFocusChanged", p.x(), p.y(), r.x(), r.y(), r.width(), r.height());
        } break;
        default:
            break;
    }
}

void Bridge::focusChanged(int px, int py, int rx, int ry, int rwidth, int rheight)
{
    kDebug()<<"KAccessibleBridge: focusChanged px=" << px << "py=" << py << "rx=" << rx << "ry=" << ry << "rwidth=" << rwidth << "rheight=" << rheight;
}

void Bridge::setRootObject(QAccessibleInterface *interface)
{
    d->m_root = interface;

    kDebug()<<"KAccessibleBridge: setRootObject object=" << (interface->object() ? QString("%1 (%2)").arg(interface->object()->objectName()).arg(interface->object()->metaObject()->className()) : "NULL");

    if( ! QDBusConnection::sessionBus().isConnected()) {
        kWarning()<<"KAccessibleBridge: Failed to connect to session bus";
        d->m_root = 0;
        return;
    }

    if( ! QDBusConnection::sessionBus().interface()->isServiceRegistered("org.kde.kaccessibleapp")) {
        kDebug()<<"KAccessibleBridge: Starting kaccessibleapp dbus service";
        QDBusConnection::sessionBus().interface()->startService("org.kde.kaccessibleapp");
        if( ! QDBusConnection::sessionBus().interface()->isServiceRegistered("org.kde.kaccessibleapp")) {
            kWarning()<<"KAccessibleBridge: Failed to start kaccessibleapp dbus service";
            d->m_root = 0;
            return;
        }

        //for testing;
        //QDBusConnection::sessionBus().connect("org.kde.kaccessibleapp", "/Adaptor", "org.kde.kaccessibleapp.Adaptor", "focusChanged", this, SLOT(focusChanged(int,int,int,int,int,int)));
    }
}

BridgePlugin::BridgePlugin(QObject *parent)
    : QAccessibleBridgePlugin(parent)
{
}

BridgePlugin::~BridgePlugin()
{
}

QAccessibleBridge* BridgePlugin::create(const QString &key)
{
    return new Bridge(this, key);
}

QStringList BridgePlugin::keys() const
{
    return QStringList() << "KAccessibleBridge";
}
<commit_msg>don't leak the QAccessibleInterface<commit_after>/* This file is part of the KDE project
 * Copyright (C) 2010 Sebastian Sauer <sebsauer@kdab.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */
#include "kaccessiblebridge.h"

#include <QAccessibleInterface>
#include <QWidget>
#include <QFile>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QDBusInterface>
#include <kdebug.h>

Q_EXPORT_PLUGIN(BridgePlugin)

class Bridge::Private
{
    public:
        BridgePlugin *m_plugin;
        const QString m_key;
        QAccessibleInterface *m_root;
        QObject *m_currentPopupMenu;

        Private(BridgePlugin *plugin, const QString& key)
            : m_plugin(plugin)
            , m_key(key)
            , m_root(0)
            , m_currentPopupMenu(0)
        {
        }
};

Bridge::Bridge(BridgePlugin *plugin, const QString& key)
    : QObject(plugin)
    , QAccessibleBridge()
    , d(new Private(plugin, key))
{
}

Bridge::~Bridge()
{
    delete d;
}

QString reasonToString(int reason)
{
    switch(reason) {
        case QAccessible::Focus: return "QAccessible::Focus";
        case QAccessible::MenuCommand: return "QAccessible::MenuCommand";
        case QAccessible::MenuStart: return "QAccessible::MenuStart";
        case QAccessible::MenuEnd: return "QAccessible::MenuEnd";
        case QAccessible::PopupMenuEnd: return "QAccessible::PopupMenuEnd";
        case QAccessible::PopupMenuStart: return "QAccessible::PopupMenuStart";
        case QAccessible::ScrollingEnd: return "QAccessible::ScrollingEnd";
        case QAccessible::ScrollingStart: return "QAccessible::ScrollingStart";
        case QAccessible::Selection: return "QAccessible::Selection";
        case QAccessible::StateChanged: return "QAccessible::StateChanged";
        case QAccessible::ValueChanged: return "QAccessible::ValueChanged";
        case QAccessible::NameChanged: return "QAccessible::NameChanged";
        case QAccessible::ObjectCreated: return "QAccessible::ObjectCreated";
        case QAccessible::ObjectDestroyed: return "QAccessible::ObjectDestroyed";
        //case QAccessible::ObjectHide: return "QAccessible::ObjectHide";
        case QAccessible::ObjectReorder: return "QAccessible::ObjectReorder";
        //case QAccessible::ObjectShow: return "QAccessible::ObjectShow";
        case QAccessible::ParentChanged: return "QAccessible::ParentChanged";
        case QAccessible::Alert: return "QAccessible::Alert";
        case QAccessible::DefaultActionChanged: return "QAccessible::DefaultActionChanged";
        case QAccessible::DialogEnd: return "QAccessible::DialogEnd";
        case QAccessible::DialogStart: return "QAccessible::DialogStart";
        case QAccessible::DragDropEnd: return "QAccessible::DragDropEnd";
        case QAccessible::DragDropStart: return "QAccessible::DragDropStart";
        case QAccessible::ForegroundChanged: return "QAccessible::ForegroundChanged";
        case QAccessible::LocationChanged: return "QAccessible::LocationChanged";
        case QAccessible::SelectionAdd: return "QAccessible::SelectionAdd";
        case QAccessible::SelectionRemove: return "QAccessible::SelectionRemove";
        case QAccessible::SelectionWithin: return "QAccessible::SelectionWithin";
        default: break;
    }
    return QString::number(reason);
}

void Bridge::notifyAccessibilityUpdate(int reason, QAccessibleInterface *interface, int child)
{
    if(!d->m_root) {
        return;
    }

    if(reason == QAccessible::ObjectShow || reason == QAccessible::ObjectHide) {
        return;
    }

    QAccessibleInterface *childInterface = 0;
    if(child > 0) {
        interface->navigate(QAccessible::Child, child, &childInterface);
    }

    kDebug() << "reason=" << reasonToString(reason) << "child=" << child << "childrect=" << interface->rect(child) << "state=" << interface->state(child) << "object=" << (interface->object() ? QString("%1 (%2)").arg(interface->object()->objectName()).arg(interface->object()->metaObject()->className()) : "NULL") << "childInterface=" << (childInterface && childInterface->object() ? QString("%1 (%2)").arg(childInterface->object()->objectName()).arg(childInterface->object()->metaObject()->className()) : "NULL");

    switch(reason) {
        case QAccessible::PopupMenuStart:
            d->m_currentPopupMenu = interface->object();
            break;
        case QAccessible::PopupMenuEnd:
            d->m_currentPopupMenu = 0;
            break;

        //FIX kwrite to send out better events then only StateChanged...
        case QAccessible::StateChanged:
            // fall through...

        case QAccessible::Focus: {
            // abort if the focus would interrupt a popupmenu
            if(d->m_currentPopupMenu && !childInterface)
                return;

            // an optional exact point that has the focus
            QPoint p(-1,-1);
            // the rectangle that has focus
            QRect r = interface->rect(child);

            // here we could add hacks to special case applications/widgets :)
            //
            // QWidget *w = childInterface ? dynamic_cast<QWidget*>(childInterface->object()) : 0;
            // if(!w) w = dynamic_cast<QWidget*>(interface->object());
            // if(w) r = QRect(w->mapToGlobal(QPoint(w->x(), w->y())), w->size());

            QDBusInterface iface("org.kde.kaccessibleapp","/Adaptor");
            iface.asyncCall("setFocusChanged", p.x(), p.y(), r.x(), r.y(), r.width(), r.height());
        } break;
        default:
            break;
    }

    delete childInterface;
}

void Bridge::focusChanged(int px, int py, int rx, int ry, int rwidth, int rheight)
{
    kDebug()<<"KAccessibleBridge: focusChanged px=" << px << "py=" << py << "rx=" << rx << "ry=" << ry << "rwidth=" << rwidth << "rheight=" << rheight;
}

void Bridge::setRootObject(QAccessibleInterface *interface)
{
    d->m_root = interface;

    kDebug()<<"KAccessibleBridge: setRootObject object=" << (interface->object() ? QString("%1 (%2)").arg(interface->object()->objectName()).arg(interface->object()->metaObject()->className()) : "NULL");

    if( ! QDBusConnection::sessionBus().isConnected()) {
        kWarning()<<"KAccessibleBridge: Failed to connect to session bus";
        d->m_root = 0;
        return;
    }

    if( ! QDBusConnection::sessionBus().interface()->isServiceRegistered("org.kde.kaccessibleapp")) {
        kDebug()<<"KAccessibleBridge: Starting kaccessibleapp dbus service";
        QDBusConnection::sessionBus().interface()->startService("org.kde.kaccessibleapp");
        if( ! QDBusConnection::sessionBus().interface()->isServiceRegistered("org.kde.kaccessibleapp")) {
            kWarning()<<"KAccessibleBridge: Failed to start kaccessibleapp dbus service";
            d->m_root = 0;
            return;
        }

        //for testing;
        //QDBusConnection::sessionBus().connect("org.kde.kaccessibleapp", "/Adaptor", "org.kde.kaccessibleapp.Adaptor", "focusChanged", this, SLOT(focusChanged(int,int,int,int,int,int)));
    }
}

BridgePlugin::BridgePlugin(QObject *parent)
    : QAccessibleBridgePlugin(parent)
{
}

BridgePlugin::~BridgePlugin()
{
}

QAccessibleBridge* BridgePlugin::create(const QString &key)
{
    return new Bridge(this, key);
}

QStringList BridgePlugin::keys() const
{
    return QStringList() << "KAccessibleBridge";
}
<|endoftext|>


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

#include "webkit/extensions/v8/playback_extension.h"

namespace extensions_v8 {

const char* kPlaybackExtensionName = "v8/PlaybackMode";

v8::Extension* PlaybackExtension::Get() {
  v8::Extension* extension = new v8::Extension(
      kPlaybackExtensionName,
      "(function () {"
      "  var orig_date = Date;"
      "  var x = 0;"
      "  var time_seed = 1204251968254;"
      "  Math.random = function() {"
      "    x += .1;"
      "    return (x % 1);"
      "  };"
      "  Date.__proto__.now = function() {"
      "    time_seed += 50;"
      "    return new orig_date(time_seed);"
      "  };"
      "  Date = function() {"
      "    return Date.now();"
      "  };"
      "})()");
    return extension;
}

}  // namespace extensions_v8
<commit_msg>Land patch for WangXianzhu. See http://codereview.chromium.org/1556005/show for the details. BUG=39768 TBR=Wangxianzhu<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/extensions/v8/playback_extension.h"

namespace extensions_v8 {

const char* kPlaybackExtensionName = "v8/PlaybackMode";

v8::Extension* PlaybackExtension::Get() {
  v8::Extension* extension = new v8::Extension(
      kPlaybackExtensionName,
      "(function () {"
      "  var orig_date = Date;"
      "  var x = 0;"
      "  var time_seed = 1204251968254;"
      "  Math.random = function() {"
      "    x += .1;"
      "    return (x % 1);"
      "  };"
      "  Date = function() {"
      "    if (this instanceof Date) {"
      "      switch (arguments.length) {"
      "        case 0: return new orig_date(time_seed += 50);"
      "        case 1: return new orig_date(arguments[0]);"
      "        default: return new orig_date(arguments[0], arguments[1],"
      "            arguments.length >= 3 ? arguments[2] : 1,"
      "            arguments.length >= 4 ? arguments[3] : 0,"
      "            arguments.length >= 5 ? arguments[4] : 0,"
      "            arguments.length >= 6 ? arguments[5] : 0,"
      "            arguments.length >= 7 ? arguments[6] : 0);"
      "      }"
      "    }"
      "    return new Date().toString();"
      "  };"
      "  Date.__proto__ = orig_date;"
      "  Date.prototype.constructor = Date;"
      "  orig_date.now = function() {"
      "    return new Date().getTime();"
      "  };"
      "})()");
    return extension;
}

}  // namespace extensions_v8
<|endoftext|>


<commit_before>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.

#ifndef OUZEL_STORAGE_PATH_HPP
#define OUZEL_STORAGE_PATH_HPP

#include <cstdint>
#include <stdexcept>
#include <string>

#if defined(_WIN32)
#  pragma push_macro("WIN32_LEAN_AND_MEAN")
#  pragma push_macro("NOMINMAX")
#  ifndef WIN32_LEAN_AND_MEAN
#    define WIN32_LEAN_AND_MEAN
#  endif
#  ifndef NOMINMAX
#    define NOMINMAX
#  endif
#  include <Windows.h>
#  pragma pop_macro("WIN32_LEAN_AND_MEAN")
#  pragma pop_macro("NOMINMAX")
#elif defined(__unix__) || defined(__APPLE__)
#  include <sys/stat.h>
#endif

namespace ouzel
{
    namespace storage
    {
        class Path final
        {
        public:
#if defined(_WIN32)
            static constexpr char directorySeparator = '\\';
            using String = std::wstring;
#elif defined(__unix__) || defined(__APPLE__)
            static constexpr char directorySeparator = '/';
            using String = std::string;
#endif

            Path() = default;
            Path(const std::string& p):
#if defined(_WIN32)
                path(toWchar(p))
#elif defined(__unix__) || defined(__APPLE__)
                path(p)
#endif
            {
                // TODO: normalize
            }

            Path(const std::wstring& p):
#if defined(_WIN32)
                path(p)
#elif defined(__unix__) || defined(__APPLE__)
                path(toUtf8(p))
#endif
            {
                // TODO: normalize
            }

            operator std::string() const
            {
#if defined(_WIN32)
                return toUtf8(path);
#elif defined(__unix__) || defined(__APPLE__)
                return path;
#endif
            }

            Path getExtensionPart() const
            {
                const size_t pos = path.find_last_of('.');

                if (pos != std::string::npos)
                    return path.substr(pos + 1);

                return String();
            }

            Path getFilenamePart() const
            {
                const size_t pos = path.find_last_of(directorySeparator);

                if (pos != String::npos)
                    return path.substr(pos + 1);
                else
                    return path;
            }

            Path getDirectoryPart() const
            {
                const size_t pos = path.find_last_of(directorySeparator);

                if (pos != String::npos)
                    return path.substr(0, pos);

                return String();
            }

            bool isDirectory() const
            {
#if defined(_WIN32)
                const DWORD attributes = GetFileAttributesW(path.c_str());
                if (attributes == INVALID_FILE_ATTRIBUTES)
                    return false;

                return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
#elif defined(__unix__) || defined(__APPLE__)
                struct stat buf;
                if (stat(path.c_str(), &buf) == -1)
                    return false;

                return (buf.st_mode & S_IFMT) == S_IFDIR;
#endif
            }

            bool isFile() const
            {
#if defined(_WIN32)
                const DWORD attributes = GetFileAttributesW(path.c_str());
                if (attributes == INVALID_FILE_ATTRIBUTES)
                    return false;

                return (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0;
#elif defined(__unix__) || defined(__APPLE__)
                struct stat buf;
                if (stat(path.c_str(), &buf) == -1)
                    return false;

                return (buf.st_mode & S_IFMT) == S_IFREG;
#endif
            }

            bool isAbsolute() const noexcept
            {
#if defined(_WIN32)
                return path.size() >= 2 &&
                    ((path[0] >= L'a' && path[0] <= L'z') || (path[0] >= L'A' && path[0] <= L'Z')) &&
                    path[1] == L':';
#elif defined(__unix__) || defined(__APPLE__)
                return path.size() >= 1 && path[0] == '/';
#endif
            }

        private:
            static std::string toUtf8(const std::wstring& p)
            {
				std::string s;

				for (wchar_t w : p)
				{
					if (w == L'\\') w = '/';

					if (w <= 0x7F)
						s.push_back(static_cast<char>(w));
					else if (w <= 0x7FF)
					{
						s.push_back(static_cast<char>(0xC0 | ((w >> 6) & 0x1F)));
						s.push_back(static_cast<char>(0x80 | (w & 0x3F)));
					}
					else if (w <= 0xFFFF)
                    {
                        s.push_back(static_cast<char>(0xE0 | ((w >> 12) & 0x0F)));
                        s.push_back(static_cast<char>(0x80 | ((w >> 6) & 0x3F)));
                        s.push_back(static_cast<char>(0x80 | (w & 0x3F)));
                    }
#if WCHAR_MAX > 0xFFFF
                    else
                    {
                        s.push_back(static_cast<char>(0xF0 | ((w >> 18) & 0x07)));
                        s.push_back(static_cast<char>(0x80 | ((w >> 12) & 0x3F)));
                        s.push_back(static_cast<char>(0x80 | ((w >> 6) & 0x3F)));
                        s.push_back(static_cast<char>(0x80 | (w & 0x3F)));
                    }
#endif
				}

                return s;
            }

            static std::wstring toWchar(const std::string& p)
            {
                std::wstring s;

				for (auto i = p.begin(); i != p.end(); ++i)
				{
					char32_t cp = *i & 0xFF;

					if (cp <= 0x7F) // length = 1
					{
						// do nothing
					}
					else if ((cp >> 5) == 0x6) // length = 2
					{
						if (++i == p.end())
							throw std::runtime_error("Invalid UTF-8 string");
						cp = ((cp << 6) & 0x7FF) + (*i & 0x3F);
					}
					else if ((cp >> 4) == 0xE) // length = 3
					{
						if (++i == p.end())
							throw std::runtime_error("Invalid UTF-8 string");
						cp = ((cp << 12) & 0xFFFF) + (((*i & 0xFF) << 6) & 0x0FFF);
						if (++i == p.end())
							throw std::runtime_error("Invalid UTF-8 string");
						cp += *i & 0x3F;
					}
					else if ((cp >> 3) == 0x1E) // length = 4
					{
						if (++i == p.end())
							throw std::runtime_error("Invalid UTF-8 string");
						cp = ((cp << 18) & 0x1FFFFF) + (((*i & 0xFF) << 12) & 0x3FFFF);
						if (++i == p.end())
							throw std::runtime_error("Invalid UTF-8 string");
						cp += ((*i & 0xFF) << 6) & 0x0FFF;
						if (++i == p.end())
							throw std::runtime_error("Invalid UTF-8 string");
						cp += (*i) & 0x3F;
					}

					if (cp > WCHAR_MAX)
						throw std::runtime_error("Unsupported UTF-8 character");

					auto w = static_cast<wchar_t>(cp);
					if (w == L'/') w = L'\\';
					s.push_back(w);
				}

                return s;
            }

            String path;
        };
    } // namespace storage
} // namespace ouzel

#endif
<commit_msg>Add conversion methods to Path<commit_after>// Copyright 2015-2019 Elviss Strazdins. All rights reserved.

#ifndef OUZEL_STORAGE_PATH_HPP
#define OUZEL_STORAGE_PATH_HPP

#include <cstdint>
#include <stdexcept>
#include <string>

#if defined(_WIN32)
#  pragma push_macro("WIN32_LEAN_AND_MEAN")
#  pragma push_macro("NOMINMAX")
#  ifndef WIN32_LEAN_AND_MEAN
#    define WIN32_LEAN_AND_MEAN
#  endif
#  ifndef NOMINMAX
#    define NOMINMAX
#  endif
#  include <Windows.h>
#  pragma pop_macro("WIN32_LEAN_AND_MEAN")
#  pragma pop_macro("NOMINMAX")
#elif defined(__unix__) || defined(__APPLE__)
#  include <sys/stat.h>
#endif

namespace ouzel
{
    namespace storage
    {
        class Path final
        {
        public:
#if defined(_WIN32)
            static constexpr char directorySeparator = '\\';
            using String = std::wstring;
#elif defined(__unix__) || defined(__APPLE__)
            static constexpr char directorySeparator = '/';
            using String = std::string;
#endif

            Path() = default;
            Path(const std::string& p):
#if defined(_WIN32)
                path(convertToNative(toWchar(p)))
#elif defined(__unix__) || defined(__APPLE__)
                path(p)
#endif
            {
                // TODO: normalize
            }

            Path(const std::wstring& p):
#if defined(_WIN32)
                path(convertToNative(p))
#elif defined(__unix__) || defined(__APPLE__)
                path(toUtf8(p))
#endif
            {
                // TODO: normalize
            }

            operator std::string() const
            {
#if defined(_WIN32)
                return toUtf8(convertToUniversal(path));
#elif defined(__unix__) || defined(__APPLE__)
                return path;
#endif
            }

            Path getExtensionPart() const
            {
                const size_t pos = path.find_last_of('.');

                if (pos != std::string::npos)
                    return path.substr(pos + 1);

                return String();
            }

            Path getFilenamePart() const
            {
                const size_t pos = path.find_last_of(directorySeparator);

                if (pos != String::npos)
                    return path.substr(pos + 1);
                else
                    return path;
            }

            Path getDirectoryPart() const
            {
                const size_t pos = path.find_last_of(directorySeparator);

                if (pos != String::npos)
                    return path.substr(0, pos);

                return String();
            }

            bool isDirectory() const
            {
#if defined(_WIN32)
                const DWORD attributes = GetFileAttributesW(path.c_str());
                if (attributes == INVALID_FILE_ATTRIBUTES)
                    return false;

                return (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0;
#elif defined(__unix__) || defined(__APPLE__)
                struct stat buf;
                if (stat(path.c_str(), &buf) == -1)
                    return false;

                return (buf.st_mode & S_IFMT) == S_IFDIR;
#endif
            }

            bool isFile() const
            {
#if defined(_WIN32)
                const DWORD attributes = GetFileAttributesW(path.c_str());
                if (attributes == INVALID_FILE_ATTRIBUTES)
                    return false;

                return (attributes & FILE_ATTRIBUTE_DIRECTORY) == 0;
#elif defined(__unix__) || defined(__APPLE__)
                struct stat buf;
                if (stat(path.c_str(), &buf) == -1)
                    return false;

                return (buf.st_mode & S_IFMT) == S_IFREG;
#endif
            }

            bool isAbsolute() const noexcept
            {
#if defined(_WIN32)
                return path.size() >= 2 &&
                    ((path[0] >= L'a' && path[0] <= L'z') || (path[0] >= L'A' && path[0] <= L'Z')) &&
                    path[1] == L':';
#elif defined(__unix__) || defined(__APPLE__)
                return path.size() >= 1 && path[0] == '/';
#endif
            }

        private:
            static std::string toUtf8(const std::wstring& p)
            {
				std::string s;

				for (wchar_t w : p)
				{
					if (w <= 0x7F)
						s.push_back(static_cast<char>(w));
					else if (w <= 0x7FF)
					{
						s.push_back(static_cast<char>(0xC0 | ((w >> 6) & 0x1F)));
						s.push_back(static_cast<char>(0x80 | (w & 0x3F)));
					}
					else if (w <= 0xFFFF)
                    {
                        s.push_back(static_cast<char>(0xE0 | ((w >> 12) & 0x0F)));
                        s.push_back(static_cast<char>(0x80 | ((w >> 6) & 0x3F)));
                        s.push_back(static_cast<char>(0x80 | (w & 0x3F)));
                    }
#if WCHAR_MAX > 0xFFFF
                    else
                    {
                        s.push_back(static_cast<char>(0xF0 | ((w >> 18) & 0x07)));
                        s.push_back(static_cast<char>(0x80 | ((w >> 12) & 0x3F)));
                        s.push_back(static_cast<char>(0x80 | ((w >> 6) & 0x3F)));
                        s.push_back(static_cast<char>(0x80 | (w & 0x3F)));
                    }
#endif
				}

                return s;
            }

            static std::wstring toWchar(const std::string& p)
            {
                std::wstring s;

				for (auto i = p.begin(); i != p.end(); ++i)
				{
					char32_t cp = *i & 0xFF;

					if (cp <= 0x7F) // length = 1
					{
						// do nothing
					}
					else if ((cp >> 5) == 0x6) // length = 2
					{
						if (++i == p.end())
							throw std::runtime_error("Invalid UTF-8 string");
						cp = ((cp << 6) & 0x7FF) + (*i & 0x3F);
					}
					else if ((cp >> 4) == 0xE) // length = 3
					{
						if (++i == p.end())
							throw std::runtime_error("Invalid UTF-8 string");
						cp = ((cp << 12) & 0xFFFF) + (((*i & 0xFF) << 6) & 0x0FFF);
						if (++i == p.end())
							throw std::runtime_error("Invalid UTF-8 string");
						cp += *i & 0x3F;
					}
					else if ((cp >> 3) == 0x1E) // length = 4
					{
						if (++i == p.end())
							throw std::runtime_error("Invalid UTF-8 string");
						cp = ((cp << 18) & 0x1FFFFF) + (((*i & 0xFF) << 12) & 0x3FFFF);
						if (++i == p.end())
							throw std::runtime_error("Invalid UTF-8 string");
						cp += ((*i & 0xFF) << 6) & 0x0FFF;
						if (++i == p.end())
							throw std::runtime_error("Invalid UTF-8 string");
						cp += (*i) & 0x3F;
					}

					if (cp > WCHAR_MAX)
						throw std::runtime_error("Unsupported UTF-8 character");

					s.push_back(static_cast<wchar_t>(cp));
				}

                return s;
            }

#if defined(_WIN32)
            static std::wstring convertToNative(const std::wstring& p)
            {
                std::wstring result = p;

                for (auto& c : result)
                    if (c == L'/') c = L'\\';

                return result;
            }

            static std::wstring convertToUniversal(const std::wstring& p)
            {
                std::wstring result = p;

                for (auto& c : result)
                    if (c == L'\\') c = L'/';

                return result;
            }
#endif

            String path;
        };
    } // namespace storage
} // namespace ouzel

#endif
<|endoftext|>


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

#include "webkit/glue/multipart_response_delegate.h"

#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "net/base/net_util.h"
#include "net/http/http_util.h"
#include "third_party/WebKit/WebKit/chromium/public/WebHTTPHeaderVisitor.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURL.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURLLoaderClient.h"

using WebKit::WebHTTPHeaderVisitor;
using WebKit::WebString;
using WebKit::WebURLLoader;
using WebKit::WebURLLoaderClient;
using WebKit::WebURLResponse;

namespace webkit_glue {

namespace {

// The list of response headers that we do not copy from the original
// response when generating a WebURLResponse for a MIME payload.
const char* kReplaceHeaders[] = {
  "content-type",
  "content-length",
  "content-disposition",
  "content-range",
  "range",
  "set-cookie"
};

class HeaderCopier : public WebHTTPHeaderVisitor {
 public:
  HeaderCopier(WebURLResponse* response)
      : response_(response) {
  }
  virtual void visitHeader(const WebString& name, const WebString& value) {
    const std::string& name_utf8 = name.utf8();
    for (size_t i = 0; i < arraysize(kReplaceHeaders); ++i) {
      if (LowerCaseEqualsASCII(name_utf8, kReplaceHeaders[i]))
        return;
    }
    response_->setHTTPHeaderField(name, value);
  }
 private:
  WebURLResponse* response_;
};

}  // namespace

MultipartResponseDelegate::MultipartResponseDelegate(
    WebURLLoaderClient* client,
    WebURLLoader* loader,
    const WebURLResponse& response,
    const std::string& boundary)
    : client_(client),
      loader_(loader),
      original_response_(response),
      boundary_("--"),
      first_received_data_(true),
      processing_headers_(false),
      stop_sending_(false),
      has_sent_first_response_(false) {
  // Some servers report a boundary prefixed with "--".  See bug 5786.
  if (StartsWithASCII(boundary, "--", true)) {
    boundary_.assign(boundary);
  } else {
    boundary_.append(boundary);
  }
}

void MultipartResponseDelegate::OnReceivedData(const char* data,
                                               int data_len) {
  // stop_sending_ means that we've already received the final boundary token.
  // The server should stop sending us data at this point, but if it does, we
  // just throw it away.
  if (stop_sending_)
    return;

  data_.append(data, data_len);
  if (first_received_data_) {
    // Some servers don't send a boundary token before the first chunk of
    // data.  We handle this case anyway (Gecko does too).
    first_received_data_ = false;

    // Eat leading \r\n
    int pos = PushOverLine(data_, 0);
    if (pos)
      data_ = data_.substr(pos);

    if (data_.length() < boundary_.length() + 2) {
      // We don't have enough data yet to make a boundary token.  Just wait
      // until the next chunk of data arrives.
      first_received_data_ = true;
      return;
    }

    if (0 != data_.compare(0, boundary_.length(), boundary_)) {
      data_ = boundary_ + "\n" + data_;
    }
  }
  DCHECK(!first_received_data_);

  // Headers
  if (processing_headers_) {
    // Eat leading \r\n
    int pos = PushOverLine(data_, 0);
    if (pos)
      data_ = data_.substr(pos);

    if (ParseHeaders()) {
      // Successfully parsed headers.
      processing_headers_ = false;
    } else {
      // Get more data before trying again.
      return;
    }
  }
  DCHECK(!processing_headers_);

  size_t boundary_pos;
  while ((boundary_pos = FindBoundary()) != std::string::npos) {
    if (client_) {
      // Strip out trailing \n\r characters in the buffer preceding the
      // boundary on the same lines as Firefox.
      size_t data_length = boundary_pos;
      if (boundary_pos > 0 && data_[boundary_pos - 1] == '\n') {
        data_length--;
        if (boundary_pos > 1 && data_[boundary_pos - 2] == '\r') {
          data_length--;
        }
      }
      if (data_length > 0) {
        // Send the last data chunk.
        client_->didReceiveData(loader_,
                                data_.data(),
                                static_cast<int>(data_length));
      }
    }
    size_t boundary_end_pos = boundary_pos + boundary_.length();
    if (boundary_end_pos < data_.length() && '-' == data_[boundary_end_pos]) {
      // This was the last boundary so we can stop processing.
      stop_sending_ = true;
      data_.clear();
      return;
    }

    // We can now throw out data up through the boundary
    int offset = PushOverLine(data_, boundary_end_pos);
    data_ = data_.substr(boundary_end_pos + offset);

    // Ok, back to parsing headers
    if (!ParseHeaders()) {
      processing_headers_ = true;
      break;
    }
  }

  // At this point, we should send over any data we have, but keep enough data
  // buffered to handle a boundary that may have been truncated.
  if (!processing_headers_ && data_.length() > boundary_.length()) {
    // If the last character is a new line character, go ahead and just send
    // everything we have buffered.  This matches an optimization in Gecko.
    int send_length = data_.length() - boundary_.length();
    if (data_[data_.length() - 1] == '\n')
      send_length = data_.length();
    if (client_)
      client_->didReceiveData(loader_, data_.data(), send_length);
    data_ = data_.substr(send_length);
  }
}

void MultipartResponseDelegate::OnCompletedRequest() {
  // If we have any pending data and we're not in a header, go ahead and send
  // it to WebCore.
  if (!processing_headers_ && !data_.empty() && !stop_sending_ && client_) {
    client_->didReceiveData(loader_,
                            data_.data(),
                            static_cast<int>(data_.length()));
  }
}

int MultipartResponseDelegate::PushOverLine(const std::string& data,
                                            size_t pos) {
  int offset = 0;
  if (pos < data.length() && (data[pos] == '\r' || data[pos] == '\n')) {
    ++offset;
    if (pos + 1 < data.length() && data[pos + 1] == '\n')
      ++offset;
  }
  return offset;
}

bool MultipartResponseDelegate::ParseHeaders() {
  int line_feed_increment = 1;

  // Grab the headers being liberal about line endings.
  size_t line_start_pos = 0;
  size_t line_end_pos = data_.find('\n');
  while (line_end_pos != std::string::npos) {
    // Handle CRLF
    if (line_end_pos > line_start_pos && data_[line_end_pos - 1] == '\r') {
      line_feed_increment = 2;
      --line_end_pos;
    } else {
      line_feed_increment = 1;
    }
    if (line_start_pos == line_end_pos) {
      // A blank line, end of headers
      line_end_pos += line_feed_increment;
      break;
    }
    // Find the next header line.
    line_start_pos = line_end_pos + line_feed_increment;
    line_end_pos = data_.find('\n', line_start_pos);
  }
  // Truncated in the middle of a header, stop parsing.
  if (line_end_pos == std::string::npos)
    return false;

  // Eat headers
  std::string headers("\n");
  headers.append(data_, 0, line_end_pos);
  data_ = data_.substr(line_end_pos);

  // Create a WebURLResponse based on the original set of headers + the
  // replacement headers.  We only replace the same few headers that gecko
  // does.  See netwerk/streamconv/converters/nsMultiMixedConv.cpp.
  std::string content_type = net::GetSpecificHeader(headers, "content-type");
  std::string mime_type;
  std::string charset;
  bool has_charset = false;
  net::HttpUtil::ParseContentType(content_type, &mime_type, &charset,
                                  &has_charset);
  WebURLResponse response(original_response_.url());
  response.setMIMEType(WebString::fromUTF8(mime_type));
  response.setTextEncodingName(WebString::fromUTF8(charset));

  HeaderCopier copier(&response);
  original_response_.visitHTTPHeaderFields(&copier);

  for (size_t i = 0; i < arraysize(kReplaceHeaders); ++i) {
    std::string name(kReplaceHeaders[i]);
    std::string value = net::GetSpecificHeader(headers, name);
    if (!value.empty()) {
      response.setHTTPHeaderField(WebString::fromUTF8(name),
                                  WebString::fromUTF8(value));
    }
  }
  // To avoid recording every multipart load as a separate visit in
  // the history database, we want to keep track of whether the response
  // is part of a multipart payload.  We do want to record the first visit,
  // so we only set isMultipartPayload to true after the first visit.
  response.setIsMultipartPayload(has_sent_first_response_);
  has_sent_first_response_ = true;
  // Send the response!
  if (client_)
    client_->didReceiveResponse(loader_, response);

  return true;
}

// Boundaries are supposed to be preceeded with --, but it looks like gecko
// doesn't require the dashes to exist.  See nsMultiMixedConv::FindToken.
size_t MultipartResponseDelegate::FindBoundary() {
  size_t boundary_pos = data_.find(boundary_);
  if (boundary_pos != std::string::npos) {
    // Back up over -- for backwards compat
    // TODO(tc): Don't we only want to do this once?  Gecko code doesn't seem
    // to care.
    if (boundary_pos >= 2) {
      if ('-' == data_[boundary_pos - 1] && '-' == data_[boundary_pos - 2]) {
        boundary_pos -= 2;
        boundary_ = "--" + boundary_;
      }
    }
  }
  return boundary_pos;
}

bool MultipartResponseDelegate::ReadMultipartBoundary(
    const WebURLResponse& response,
    std::string* multipart_boundary) {
  std::string content_type =
      response.httpHeaderField(WebString::fromUTF8("Content-Type")).utf8();

  size_t boundary_start_offset = content_type.find("boundary=");
  if (boundary_start_offset == std::wstring::npos) {
    return false;
  }

  boundary_start_offset += strlen("boundary=");

  size_t boundary_end_offset = content_type.find(';', boundary_start_offset);

  if (boundary_end_offset == std::string::npos)
    boundary_end_offset = content_type.length();

  size_t boundary_length = boundary_end_offset - boundary_start_offset;

  *multipart_boundary =
      content_type.substr(boundary_start_offset, boundary_length);
  // The byte range response can have quoted boundary strings. This is legal
  // as per MIME specifications. Individual data fragements however don't
  // contain quoted boundary strings.
  TrimString(*multipart_boundary, "\"", multipart_boundary);
  return true;
}

bool MultipartResponseDelegate::ReadContentRanges(
    const WebURLResponse& response,
    int* content_range_lower_bound,
    int* content_range_upper_bound,
    int* content_range_instance_size) {

  std::string content_range = response.httpHeaderField("Content-Range").utf8();
  if (content_range.empty()) {
    content_range = response.httpHeaderField("Range").utf8();
  }

  if (content_range.empty()) {
    DLOG(WARNING) << "Failed to read content range from response.";
    return false;
  }

  size_t byte_range_lower_bound_start_offset = content_range.find(" ");
  if (byte_range_lower_bound_start_offset == std::string::npos) {
    return false;
  }

  // Skip over the initial space.
  byte_range_lower_bound_start_offset++;

  // Find the lower bound.
  size_t byte_range_lower_bound_end_offset =
      content_range.find("-", byte_range_lower_bound_start_offset);
  if (byte_range_lower_bound_end_offset == std::string::npos) {
    return false;
  }

  size_t byte_range_lower_bound_characters =
      byte_range_lower_bound_end_offset - byte_range_lower_bound_start_offset;
  std::string byte_range_lower_bound =
      content_range.substr(byte_range_lower_bound_start_offset,
                           byte_range_lower_bound_characters);

  // Find the upper bound.
  size_t byte_range_upper_bound_start_offset =
      byte_range_lower_bound_end_offset + 1;

  size_t byte_range_upper_bound_end_offset =
      content_range.find("/", byte_range_upper_bound_start_offset);
  if (byte_range_upper_bound_end_offset == std::string::npos) {
    return false;
  }

  size_t byte_range_upper_bound_characters =
      byte_range_upper_bound_end_offset - byte_range_upper_bound_start_offset;
  std::string byte_range_upper_bound =
      content_range.substr(byte_range_upper_bound_start_offset,
                           byte_range_upper_bound_characters);

  // Find the instance size.
  size_t byte_range_instance_size_start_offset =
      byte_range_upper_bound_end_offset + 1;

  size_t byte_range_instance_size_end_offset =
      content_range.length();

  size_t byte_range_instance_size_characters =
      byte_range_instance_size_end_offset -
      byte_range_instance_size_start_offset;
  std::string byte_range_instance_size =
      content_range.substr(byte_range_instance_size_start_offset,
                           byte_range_instance_size_characters);

  if (!base::StringToInt(byte_range_lower_bound, content_range_lower_bound))
    return false;
  if (!base::StringToInt(byte_range_upper_bound, content_range_upper_bound))
    return false;
  if (!base::StringToInt(byte_range_instance_size, content_range_instance_size))
    return false;
  return true;
}

}  // namespace webkit_glue
<commit_msg>Fix an incorrect use of wstring::npos.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/glue/multipart_response_delegate.h"

#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "net/base/net_util.h"
#include "net/http/http_util.h"
#include "third_party/WebKit/WebKit/chromium/public/WebHTTPHeaderVisitor.h"
#include "third_party/WebKit/WebKit/chromium/public/WebString.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURL.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURLLoaderClient.h"

using WebKit::WebHTTPHeaderVisitor;
using WebKit::WebString;
using WebKit::WebURLLoader;
using WebKit::WebURLLoaderClient;
using WebKit::WebURLResponse;

namespace webkit_glue {

namespace {

// The list of response headers that we do not copy from the original
// response when generating a WebURLResponse for a MIME payload.
const char* kReplaceHeaders[] = {
  "content-type",
  "content-length",
  "content-disposition",
  "content-range",
  "range",
  "set-cookie"
};

class HeaderCopier : public WebHTTPHeaderVisitor {
 public:
  HeaderCopier(WebURLResponse* response)
      : response_(response) {
  }
  virtual void visitHeader(const WebString& name, const WebString& value) {
    const std::string& name_utf8 = name.utf8();
    for (size_t i = 0; i < arraysize(kReplaceHeaders); ++i) {
      if (LowerCaseEqualsASCII(name_utf8, kReplaceHeaders[i]))
        return;
    }
    response_->setHTTPHeaderField(name, value);
  }
 private:
  WebURLResponse* response_;
};

}  // namespace

MultipartResponseDelegate::MultipartResponseDelegate(
    WebURLLoaderClient* client,
    WebURLLoader* loader,
    const WebURLResponse& response,
    const std::string& boundary)
    : client_(client),
      loader_(loader),
      original_response_(response),
      boundary_("--"),
      first_received_data_(true),
      processing_headers_(false),
      stop_sending_(false),
      has_sent_first_response_(false) {
  // Some servers report a boundary prefixed with "--".  See bug 5786.
  if (StartsWithASCII(boundary, "--", true)) {
    boundary_.assign(boundary);
  } else {
    boundary_.append(boundary);
  }
}

void MultipartResponseDelegate::OnReceivedData(const char* data,
                                               int data_len) {
  // stop_sending_ means that we've already received the final boundary token.
  // The server should stop sending us data at this point, but if it does, we
  // just throw it away.
  if (stop_sending_)
    return;

  data_.append(data, data_len);
  if (first_received_data_) {
    // Some servers don't send a boundary token before the first chunk of
    // data.  We handle this case anyway (Gecko does too).
    first_received_data_ = false;

    // Eat leading \r\n
    int pos = PushOverLine(data_, 0);
    if (pos)
      data_ = data_.substr(pos);

    if (data_.length() < boundary_.length() + 2) {
      // We don't have enough data yet to make a boundary token.  Just wait
      // until the next chunk of data arrives.
      first_received_data_ = true;
      return;
    }

    if (0 != data_.compare(0, boundary_.length(), boundary_)) {
      data_ = boundary_ + "\n" + data_;
    }
  }
  DCHECK(!first_received_data_);

  // Headers
  if (processing_headers_) {
    // Eat leading \r\n
    int pos = PushOverLine(data_, 0);
    if (pos)
      data_ = data_.substr(pos);

    if (ParseHeaders()) {
      // Successfully parsed headers.
      processing_headers_ = false;
    } else {
      // Get more data before trying again.
      return;
    }
  }
  DCHECK(!processing_headers_);

  size_t boundary_pos;
  while ((boundary_pos = FindBoundary()) != std::string::npos) {
    if (client_) {
      // Strip out trailing \n\r characters in the buffer preceding the
      // boundary on the same lines as Firefox.
      size_t data_length = boundary_pos;
      if (boundary_pos > 0 && data_[boundary_pos - 1] == '\n') {
        data_length--;
        if (boundary_pos > 1 && data_[boundary_pos - 2] == '\r') {
          data_length--;
        }
      }
      if (data_length > 0) {
        // Send the last data chunk.
        client_->didReceiveData(loader_,
                                data_.data(),
                                static_cast<int>(data_length));
      }
    }
    size_t boundary_end_pos = boundary_pos + boundary_.length();
    if (boundary_end_pos < data_.length() && '-' == data_[boundary_end_pos]) {
      // This was the last boundary so we can stop processing.
      stop_sending_ = true;
      data_.clear();
      return;
    }

    // We can now throw out data up through the boundary
    int offset = PushOverLine(data_, boundary_end_pos);
    data_ = data_.substr(boundary_end_pos + offset);

    // Ok, back to parsing headers
    if (!ParseHeaders()) {
      processing_headers_ = true;
      break;
    }
  }

  // At this point, we should send over any data we have, but keep enough data
  // buffered to handle a boundary that may have been truncated.
  if (!processing_headers_ && data_.length() > boundary_.length()) {
    // If the last character is a new line character, go ahead and just send
    // everything we have buffered.  This matches an optimization in Gecko.
    int send_length = data_.length() - boundary_.length();
    if (data_[data_.length() - 1] == '\n')
      send_length = data_.length();
    if (client_)
      client_->didReceiveData(loader_, data_.data(), send_length);
    data_ = data_.substr(send_length);
  }
}

void MultipartResponseDelegate::OnCompletedRequest() {
  // If we have any pending data and we're not in a header, go ahead and send
  // it to WebCore.
  if (!processing_headers_ && !data_.empty() && !stop_sending_ && client_) {
    client_->didReceiveData(loader_,
                            data_.data(),
                            static_cast<int>(data_.length()));
  }
}

int MultipartResponseDelegate::PushOverLine(const std::string& data,
                                            size_t pos) {
  int offset = 0;
  if (pos < data.length() && (data[pos] == '\r' || data[pos] == '\n')) {
    ++offset;
    if (pos + 1 < data.length() && data[pos + 1] == '\n')
      ++offset;
  }
  return offset;
}

bool MultipartResponseDelegate::ParseHeaders() {
  int line_feed_increment = 1;

  // Grab the headers being liberal about line endings.
  size_t line_start_pos = 0;
  size_t line_end_pos = data_.find('\n');
  while (line_end_pos != std::string::npos) {
    // Handle CRLF
    if (line_end_pos > line_start_pos && data_[line_end_pos - 1] == '\r') {
      line_feed_increment = 2;
      --line_end_pos;
    } else {
      line_feed_increment = 1;
    }
    if (line_start_pos == line_end_pos) {
      // A blank line, end of headers
      line_end_pos += line_feed_increment;
      break;
    }
    // Find the next header line.
    line_start_pos = line_end_pos + line_feed_increment;
    line_end_pos = data_.find('\n', line_start_pos);
  }
  // Truncated in the middle of a header, stop parsing.
  if (line_end_pos == std::string::npos)
    return false;

  // Eat headers
  std::string headers("\n");
  headers.append(data_, 0, line_end_pos);
  data_ = data_.substr(line_end_pos);

  // Create a WebURLResponse based on the original set of headers + the
  // replacement headers.  We only replace the same few headers that gecko
  // does.  See netwerk/streamconv/converters/nsMultiMixedConv.cpp.
  std::string content_type = net::GetSpecificHeader(headers, "content-type");
  std::string mime_type;
  std::string charset;
  bool has_charset = false;
  net::HttpUtil::ParseContentType(content_type, &mime_type, &charset,
                                  &has_charset);
  WebURLResponse response(original_response_.url());
  response.setMIMEType(WebString::fromUTF8(mime_type));
  response.setTextEncodingName(WebString::fromUTF8(charset));

  HeaderCopier copier(&response);
  original_response_.visitHTTPHeaderFields(&copier);

  for (size_t i = 0; i < arraysize(kReplaceHeaders); ++i) {
    std::string name(kReplaceHeaders[i]);
    std::string value = net::GetSpecificHeader(headers, name);
    if (!value.empty()) {
      response.setHTTPHeaderField(WebString::fromUTF8(name),
                                  WebString::fromUTF8(value));
    }
  }
  // To avoid recording every multipart load as a separate visit in
  // the history database, we want to keep track of whether the response
  // is part of a multipart payload.  We do want to record the first visit,
  // so we only set isMultipartPayload to true after the first visit.
  response.setIsMultipartPayload(has_sent_first_response_);
  has_sent_first_response_ = true;
  // Send the response!
  if (client_)
    client_->didReceiveResponse(loader_, response);

  return true;
}

// Boundaries are supposed to be preceeded with --, but it looks like gecko
// doesn't require the dashes to exist.  See nsMultiMixedConv::FindToken.
size_t MultipartResponseDelegate::FindBoundary() {
  size_t boundary_pos = data_.find(boundary_);
  if (boundary_pos != std::string::npos) {
    // Back up over -- for backwards compat
    // TODO(tc): Don't we only want to do this once?  Gecko code doesn't seem
    // to care.
    if (boundary_pos >= 2) {
      if ('-' == data_[boundary_pos - 1] && '-' == data_[boundary_pos - 2]) {
        boundary_pos -= 2;
        boundary_ = "--" + boundary_;
      }
    }
  }
  return boundary_pos;
}

bool MultipartResponseDelegate::ReadMultipartBoundary(
    const WebURLResponse& response,
    std::string* multipart_boundary) {
  std::string content_type =
      response.httpHeaderField(WebString::fromUTF8("Content-Type")).utf8();

  size_t boundary_start_offset = content_type.find("boundary=");
  if (boundary_start_offset == std::string::npos)
    return false;

  boundary_start_offset += strlen("boundary=");

  size_t boundary_end_offset = content_type.find(';', boundary_start_offset);

  if (boundary_end_offset == std::string::npos)
    boundary_end_offset = content_type.length();

  size_t boundary_length = boundary_end_offset - boundary_start_offset;

  *multipart_boundary =
      content_type.substr(boundary_start_offset, boundary_length);
  // The byte range response can have quoted boundary strings. This is legal
  // as per MIME specifications. Individual data fragements however don't
  // contain quoted boundary strings.
  TrimString(*multipart_boundary, "\"", multipart_boundary);
  return true;
}

bool MultipartResponseDelegate::ReadContentRanges(
    const WebURLResponse& response,
    int* content_range_lower_bound,
    int* content_range_upper_bound,
    int* content_range_instance_size) {

  std::string content_range = response.httpHeaderField("Content-Range").utf8();
  if (content_range.empty()) {
    content_range = response.httpHeaderField("Range").utf8();
  }

  if (content_range.empty()) {
    DLOG(WARNING) << "Failed to read content range from response.";
    return false;
  }

  size_t byte_range_lower_bound_start_offset = content_range.find(" ");
  if (byte_range_lower_bound_start_offset == std::string::npos) {
    return false;
  }

  // Skip over the initial space.
  byte_range_lower_bound_start_offset++;

  // Find the lower bound.
  size_t byte_range_lower_bound_end_offset =
      content_range.find("-", byte_range_lower_bound_start_offset);
  if (byte_range_lower_bound_end_offset == std::string::npos) {
    return false;
  }

  size_t byte_range_lower_bound_characters =
      byte_range_lower_bound_end_offset - byte_range_lower_bound_start_offset;
  std::string byte_range_lower_bound =
      content_range.substr(byte_range_lower_bound_start_offset,
                           byte_range_lower_bound_characters);

  // Find the upper bound.
  size_t byte_range_upper_bound_start_offset =
      byte_range_lower_bound_end_offset + 1;

  size_t byte_range_upper_bound_end_offset =
      content_range.find("/", byte_range_upper_bound_start_offset);
  if (byte_range_upper_bound_end_offset == std::string::npos) {
    return false;
  }

  size_t byte_range_upper_bound_characters =
      byte_range_upper_bound_end_offset - byte_range_upper_bound_start_offset;
  std::string byte_range_upper_bound =
      content_range.substr(byte_range_upper_bound_start_offset,
                           byte_range_upper_bound_characters);

  // Find the instance size.
  size_t byte_range_instance_size_start_offset =
      byte_range_upper_bound_end_offset + 1;

  size_t byte_range_instance_size_end_offset =
      content_range.length();

  size_t byte_range_instance_size_characters =
      byte_range_instance_size_end_offset -
      byte_range_instance_size_start_offset;
  std::string byte_range_instance_size =
      content_range.substr(byte_range_instance_size_start_offset,
                           byte_range_instance_size_characters);

  if (!base::StringToInt(byte_range_lower_bound, content_range_lower_bound))
    return false;
  if (!base::StringToInt(byte_range_upper_bound, content_range_upper_bound))
    return false;
  if (!base::StringToInt(byte_range_instance_size, content_range_instance_size))
    return false;
  return true;
}

}  // namespace webkit_glue
<|endoftext|>


<commit_before>/*
Copyright libCellML Contributors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include "test_resources.h"
#include "test_utils.h"

#include "gtest/gtest.h"

#include <libcellml>

#include <algorithm>
#include <fstream>
#include <sstream>
#include <vector>

TEST(ResolveImports, resolveSineModelFromFile)
{
    libcellml::ParserPtr p = libcellml::Parser::create();
    libcellml::ModelPtr model = p->parseModel(fileContents("sine_approximations.xml"));

    EXPECT_EQ(size_t(0), p->errorCount());
    EXPECT_FALSE(model->hasUnresolvedImports());
}

TEST(ResolveImports, resolveSineImportsModelFromFile)
{
    libcellml::ParserPtr p = libcellml::Parser::create();
    libcellml::ModelPtr model = p->parseModel(fileContents("sine_approximations_import.xml"));
    EXPECT_EQ(size_t(0), p->errorCount());

    EXPECT_TRUE(model->hasUnresolvedImports());
    model->resolveImports(resourcePath());
    EXPECT_FALSE(model->hasUnresolvedImports());
}

TEST(ResolveImports, resolveComplexImportsModelFromFile)
{
    libcellml::ParserPtr p = libcellml::Parser::create();
    libcellml::ModelPtr model = p->parseModel(fileContents("complex_imports.xml"));
    EXPECT_EQ(size_t(0), p->errorCount());

    EXPECT_TRUE(model->hasUnresolvedImports());
    model->resolveImports(resourcePath());
    EXPECT_FALSE(model->hasUnresolvedImports());
}

TEST(ResolveImports, resolveUnitsImportFromFile)
{
    libcellml::ParserPtr p = libcellml::Parser::create();
    libcellml::ModelPtr model = p->parseModel(fileContents("import_units_model.cellml"));

    EXPECT_EQ(size_t(0), p->errorCount());

    EXPECT_TRUE(model->hasUnresolvedImports());
    model->resolveImports(resourcePath());
    EXPECT_FALSE(model->hasUnresolvedImports());
}

TEST(ResolveImports, resolveImportsFromFileLevel0)
{
    libcellml::ParserPtr p = libcellml::Parser::create();
    libcellml::ModelPtr model = p->parseModel(fileContents("level0.xml"));

    EXPECT_EQ(size_t(0), p->errorCount());

    EXPECT_TRUE(model->hasUnresolvedImports());
    model->resolveImports(resourcePath());
    EXPECT_FALSE(model->hasUnresolvedImports());
}

TEST(ResolveImports, resolveImportsFromFileLevel0Unresolvable)
{
    libcellml::ParserPtr p = libcellml::Parser::create();
    libcellml::ModelPtr model = p->parseModel(fileContents("level0-broken-imports.xml"));

    EXPECT_EQ(size_t(0), p->errorCount());

    EXPECT_TRUE(model->hasUnresolvedImports());
    model->resolveImports(resourcePath());
    EXPECT_TRUE(model->hasUnresolvedImports());
}
<commit_msg>Add test for case where an imported component doesn't exist in the imported model.<commit_after>/*
Copyright libCellML Contributors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

#include "test_resources.h"
#include "test_utils.h"

#include "gtest/gtest.h"

#include <libcellml>

#include <algorithm>
#include <fstream>
#include <sstream>
#include <vector>

TEST(ResolveImports, resolveSineModelFromFile)
{
    libcellml::ParserPtr p = libcellml::Parser::create();
    libcellml::ModelPtr model = p->parseModel(fileContents("sine_approximations.xml"));

    EXPECT_EQ(size_t(0), p->errorCount());
    EXPECT_FALSE(model->hasUnresolvedImports());
}

TEST(ResolveImports, resolveSineImportsModelFromFile)
{
    libcellml::ParserPtr p = libcellml::Parser::create();
    libcellml::ModelPtr model = p->parseModel(fileContents("sine_approximations_import.xml"));
    EXPECT_EQ(size_t(0), p->errorCount());

    EXPECT_TRUE(model->hasUnresolvedImports());
    model->resolveImports(resourcePath());
    EXPECT_FALSE(model->hasUnresolvedImports());
}

TEST(ResolveImports, resolveComplexImportsModelFromFile)
{
    libcellml::ParserPtr p = libcellml::Parser::create();
    libcellml::ModelPtr model = p->parseModel(fileContents("complex_imports.xml"));
    EXPECT_EQ(size_t(0), p->errorCount());

    EXPECT_TRUE(model->hasUnresolvedImports());
    model->resolveImports(resourcePath());
    EXPECT_FALSE(model->hasUnresolvedImports());
}

TEST(ResolveImports, resolveUnitsImportFromFile)
{
    libcellml::ParserPtr p = libcellml::Parser::create();
    libcellml::ModelPtr model = p->parseModel(fileContents("import_units_model.cellml"));

    EXPECT_EQ(size_t(0), p->errorCount());

    EXPECT_TRUE(model->hasUnresolvedImports());
    model->resolveImports(resourcePath());
    EXPECT_FALSE(model->hasUnresolvedImports());
}

TEST(ResolveImports, resolveImportsFromFileLevel0)
{
    libcellml::ParserPtr p = libcellml::Parser::create();
    libcellml::ModelPtr model = p->parseModel(fileContents("level0.xml"));

    EXPECT_EQ(size_t(0), p->errorCount());

    EXPECT_TRUE(model->hasUnresolvedImports());
    model->resolveImports(resourcePath());
    EXPECT_FALSE(model->hasUnresolvedImports());
}

TEST(ResolveImports, resolveImportsFromFileLevel0Unresolvable)
{
    libcellml::ParserPtr p = libcellml::Parser::create();
    libcellml::ModelPtr model = p->parseModel(fileContents("level0-broken-imports.xml"));

    EXPECT_EQ(size_t(0), p->errorCount());

    EXPECT_TRUE(model->hasUnresolvedImports());
    model->resolveImports(resourcePath());
    EXPECT_TRUE(model->hasUnresolvedImports());
}

TEST(ResolveImports, componentNotInResolvingModel)
{
    const std::string modelImportingComponent =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
        "<model xmlns=\"http://www.cellml.org/cellml/2.0#\" xmlns:cellml=\"http://www.cellml.org/cellml/2.0#\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" name=\"sin_approximations_import\" id=\"sin_approximations_import\">\n"
        "  <import xlink:href=\"level0.xml\">\n"
        "    <component name=\"real_component\" component_ref=\"this_name_not_a_component_in_level0_model\"/>\n"
        "  </import>\n"
        "  <component name=\"main\" id=\"main\"/>\n"
        "  <encapsulation>\n"
        "    <component_ref component=\"main\">\n"
        "      <component_ref component=\"real_component\"/>\n"
        "    </component_ref>\n"
        "  </encapsulation>\n"
        "</model>\n";

    libcellml::ParserPtr p = libcellml::Parser::create();
    libcellml::ModelPtr model = p->parseModel(modelImportingComponent);

    EXPECT_EQ(size_t(0), p->errorCount());

    EXPECT_TRUE(model->hasUnresolvedImports());
    model->resolveImports(resourcePath());
    EXPECT_TRUE(model->hasUnresolvedImports());
}
<|endoftext|>


<commit_before>#include <QCoreApplication>
#include <QSettings>
#include <QDir>
#include <QDesktopServices>
#include <QJsonDocument>
#include "kernel.h"
#include "ilwisdata.h"
#include "errorobject.h"
#include "abstractfactory.h"
#include "connectorinterface.h"
#include "ilwisobjectconnector.h"
#include "catalogexplorer.h"
#include "catalogconnector.h"
#include "catalog.h"
#include "ilwiscontext.h"
#include "mastercatalog.h"

Ilwis::IlwisContext *Ilwis::IlwisContext::_context = 0;

using namespace Ilwis;

IlwisContext* Ilwis::context() {
    if (Ilwis::IlwisContext::_context == 0) {
        Ilwis::IlwisContext::_context = new Ilwis::IlwisContext();
        Ilwis::IlwisContext::_context->init();

    }
    return Ilwis::IlwisContext::_context;
}

IlwisContext::IlwisContext() : _workingCatalog(0), _memoryLimit(9e8), _memoryLeft(_memoryLimit)
{
    //TODO relocate directories through configuration
    QDir localDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation));
    _cacheLocation = QUrl::fromLocalFile(localDir.absolutePath());
    QString datalocation = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/internalcatalog";
    localDir = QDir(datalocation);
    if (!localDir.exists()){
        localDir.mkpath(datalocation);
    }
    _persistentInternalCatalog = QUrl::fromLocalFile(datalocation);
    QStringList files = localDir.entryList(QStringList() << "*.*", QDir::Files);
    foreach(QString file, files)
        localDir.remove(file);
    _workingCatalog = new Catalog(); // empty catalog>

}

IlwisContext::~IlwisContext()
{
}

void IlwisContext::addSystemLocation(const QUrl &resource)
{
    if ( std::find(_systemlocations.begin(), _systemlocations.end(), resource) == _systemlocations.end() ) {
        _systemlocations.push_back(resource);
    }

}

void IlwisContext::removeSystemLocation(const QUrl &)
{
    //TODO:
}

void IlwisContext::loadIlwisLocationFile(QFileInfo configFile){
    if (configFile.exists()){
        QSettings settings(configFile.filePath(), QSettings::IniFormat);
        this->_ilwisDir = QFileInfo(settings.value("Paths/ilwisDir").toString());
        if (!this->_ilwisDir.isDir()){
            printf("Ilwis directory %s from config file not found\n",this->_ilwisDir.filePath().toStdString().c_str());
            this->_ilwisDir = QFileInfo( qApp->applicationDirPath());
        }
    }else{
        this->_ilwisDir = QFileInfo( qApp->applicationDirPath());
    }
}

QFileInfo IlwisContext::ilwisFolder() const {
    return this->_ilwisDir;
}

void IlwisContext::init()
{

    QFileInfo inf(qApp->applicationDirPath() + "/ilwislocation.config");
    loadIlwisLocationFile(inf)   ;

    QString loc = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);

    QString configfile = loc + "/" + "ilwis.config";
    QFileInfo file;
    file.setFile(configfile);
    if ( !file.exists()){
        if ( _ilwisDir.exists()){
            configfile = _ilwisDir.absoluteFilePath() + "/resources/ilwis.config";
            file.setFile(configfile);
            if (!file.exists()){
                configfile = _ilwisDir.absoluteFilePath() + "/ilwis.config";
                file.setFile(configfile);
            }
        } else{

            configfile = _ilwisDir.absoluteFilePath() + "/resources/ilwis.config";
            file.setFile(configfile);
        }
    }
    mastercatalog()->addContainer(QUrl("ilwis://internalcatalog"));
    mastercatalog()->addContainer(persistentInternalCatalog());

    _systemCatalog.prepare("ilwis://system");

    _configuration.prepare(file.absoluteFilePath());

}

ICatalog IlwisContext::workingCatalog() const{
//    if ( _workingCatalog.hasLocalData())
//        return static_cast<Catalog *>(_workingCatalog.localData());

    return _workingCatalog;
}

const ICatalog &IlwisContext::systemCatalog() const
{
    return _systemCatalog;
}

void IlwisContext::setWorkingCatalog(const ICatalog &cat)
{
    if ( !cat.isValid())
        return;

    mastercatalog()->addContainer(cat->source().url());
    _workingCatalog = cat;
    context()->configurationRef().putValue("users/" + currentUser() + "/workingcatalog",cat->source().url().toString());
}

QUrl IlwisContext::cacheLocation() const
{
    return _cacheLocation;
}

QUrl IlwisContext::persistentInternalCatalog() const
{
    return _persistentInternalCatalog;
}

quint64 IlwisContext::memoryLeft() const
{
    return _memoryLeft;
}
quint64 IlwisContext::changeMemoryLeft(quint64 amount)
{
    if ( _memoryLeft + std::abs(amount) > 0) {
        _memoryLeft += amount;
    }
    else
        _memoryLeft = 0;

    return _memoryLeft;
}

IlwisConfiguration &IlwisContext::configurationRef()
{
    return _configuration;
}

const IlwisConfiguration &IlwisContext::configuration() const
{
    return _configuration;
}

QFileInfo IlwisContext::resourceRoot() const
{
    QString root = ilwisconfig("system-settings/resource-root",QString("app-base"));
    if ( root == "app-base"){
        return QFileInfo(ilwisFolder().absoluteFilePath() + "/resources");
    }
    QFileInfo inf(root + "/resources");
    if ( inf.exists())
        return inf;

    return QFileInfo(ilwisFolder().absoluteFilePath() + "/resources");
}

QString IlwisContext::ipv4() const
{
    if ( _ipv4 == sUNDEF){
        const_cast<IlwisContext *>(this)->_ipv4 = const_cast<IlwisContext *>(this)->configurationRef()("server-settings/ipv4-address", QString(""));
    }
    return _ipv4;
}

QString IlwisContext::currentUser() const
{
    return "user-0"; // by default atm,.
}

int IlwisContext::runMode() const
{
    return _runMode;
}

void IlwisContext::runMode(int mode)
{
    _runMode = mode;
}

<commit_msg>workingcatalog is set from the config<commit_after>#include <QCoreApplication>
#include <QSettings>
#include <QDir>
#include <QDesktopServices>
#include <QJsonDocument>
#include "kernel.h"
#include "ilwisdata.h"
#include "errorobject.h"
#include "abstractfactory.h"
#include "connectorinterface.h"
#include "ilwisobjectconnector.h"
#include "catalogexplorer.h"
#include "catalogconnector.h"
#include "catalog.h"
#include "ilwiscontext.h"
#include "mastercatalog.h"

Ilwis::IlwisContext *Ilwis::IlwisContext::_context = 0;

using namespace Ilwis;

IlwisContext* Ilwis::context() {
    if (Ilwis::IlwisContext::_context == 0) {
        Ilwis::IlwisContext::_context = new Ilwis::IlwisContext();
        Ilwis::IlwisContext::_context->init();

    }
    return Ilwis::IlwisContext::_context;
}

IlwisContext::IlwisContext() : _workingCatalog(0), _memoryLimit(9e8), _memoryLeft(_memoryLimit)
{
    //TODO relocate directories through configuration
    QDir localDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation));
    _cacheLocation = QUrl::fromLocalFile(localDir.absolutePath());
    QString datalocation = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/internalcatalog";
    localDir = QDir(datalocation);
    if (!localDir.exists()){
        localDir.mkpath(datalocation);
    }
    _persistentInternalCatalog = QUrl::fromLocalFile(datalocation);
    QStringList files = localDir.entryList(QStringList() << "*.*", QDir::Files);
    foreach(QString file, files)
        localDir.remove(file);
    _workingCatalog = new Catalog(); // empty catalog>

}

IlwisContext::~IlwisContext()
{
}

void IlwisContext::addSystemLocation(const QUrl &resource)
{
    if ( std::find(_systemlocations.begin(), _systemlocations.end(), resource) == _systemlocations.end() ) {
        _systemlocations.push_back(resource);
    }

}

void IlwisContext::removeSystemLocation(const QUrl &)
{
    //TODO:
}

void IlwisContext::loadIlwisLocationFile(QFileInfo configFile){
    if (configFile.exists()){
        QSettings settings(configFile.filePath(), QSettings::IniFormat);
        this->_ilwisDir = QFileInfo(settings.value("Paths/ilwisDir").toString());
        if (!this->_ilwisDir.isDir()){
            printf("Ilwis directory %s from config file not found\n",this->_ilwisDir.filePath().toStdString().c_str());
            this->_ilwisDir = QFileInfo( qApp->applicationDirPath());
        }
    }else{
        this->_ilwisDir = QFileInfo( qApp->applicationDirPath());
    }
}

QFileInfo IlwisContext::ilwisFolder() const {
    return this->_ilwisDir;
}

void IlwisContext::init()
{

    QFileInfo inf(qApp->applicationDirPath() + "/ilwislocation.config");
    loadIlwisLocationFile(inf)   ;

    QString loc = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation);

    QString configfile = loc + "/" + "ilwis.config";
    QFileInfo file;
    file.setFile(configfile);
    if ( !file.exists()){
        if ( _ilwisDir.exists()){
            configfile = _ilwisDir.absoluteFilePath() + "/resources/ilwis.config";
            file.setFile(configfile);
            if (!file.exists()){
                configfile = _ilwisDir.absoluteFilePath() + "/ilwis.config";
                file.setFile(configfile);
            }
        } else{

            configfile = _ilwisDir.absoluteFilePath() + "/resources/ilwis.config";
            file.setFile(configfile);
        }
    }
    mastercatalog()->addContainer(QUrl("ilwis://internalcatalog"));
    mastercatalog()->addContainer(persistentInternalCatalog());

    _systemCatalog.prepare("ilwis://system");

    _configuration.prepare(file.absoluteFilePath());
    loc = _configuration("users/" + currentUser() + "/workingcatalog",QString(""));
    if ( loc != "")
        _workingCatalog = ICatalog(loc);

}

ICatalog IlwisContext::workingCatalog() const{
//    if ( _workingCatalog.hasLocalData())
//        return static_cast<Catalog *>(_workingCatalog.localData());

    return _workingCatalog;
}

const ICatalog &IlwisContext::systemCatalog() const
{
    return _systemCatalog;
}

void IlwisContext::setWorkingCatalog(const ICatalog &cat)
{
    if ( !cat.isValid())
        return;

    mastercatalog()->addContainer(cat->source().url());
    _workingCatalog = cat;
    context()->configurationRef().putValue("users/" + currentUser() + "/workingcatalog",cat->source().url().toString());
}

QUrl IlwisContext::cacheLocation() const
{
    return _cacheLocation;
}

QUrl IlwisContext::persistentInternalCatalog() const
{
    return _persistentInternalCatalog;
}

quint64 IlwisContext::memoryLeft() const
{
    return _memoryLeft;
}
quint64 IlwisContext::changeMemoryLeft(quint64 amount)
{
    if ( _memoryLeft + std::abs(amount) > 0) {
        _memoryLeft += amount;
    }
    else
        _memoryLeft = 0;

    return _memoryLeft;
}

IlwisConfiguration &IlwisContext::configurationRef()
{
    return _configuration;
}

const IlwisConfiguration &IlwisContext::configuration() const
{
    return _configuration;
}

QFileInfo IlwisContext::resourceRoot() const
{
    QString root = ilwisconfig("system-settings/resource-root",QString("app-base"));
    if ( root == "app-base"){
        return QFileInfo(ilwisFolder().absoluteFilePath() + "/resources");
    }
    QFileInfo inf(root + "/resources");
    if ( inf.exists())
        return inf;

    return QFileInfo(ilwisFolder().absoluteFilePath() + "/resources");
}

QString IlwisContext::ipv4() const
{
    if ( _ipv4 == sUNDEF){
        const_cast<IlwisContext *>(this)->_ipv4 = const_cast<IlwisContext *>(this)->configurationRef()("server-settings/ipv4-address", QString(""));
    }
    return _ipv4;
}

QString IlwisContext::currentUser() const
{
    return "user-0"; // by default atm,.
}

int IlwisContext::runMode() const
{
    return _runMode;
}

void IlwisContext::runMode(int mode)
{
    _runMode = mode;
}

<|endoftext|>