<commit_before>#include "mpdas.h"

#define ROOTURL		"http://ws.audioscrobbler.com/2.0/"
#define APIKEY		"a0ed2629d3d28606f67d7214c916788d"
#define	SECRET		"295f31c5d28215215b1503fb0327cc01"

CAudioScrobbler* AudioScrobbler = 0;

#define CLEANUP()	_response.clear()

size_t
writecb(void* ptr, size_t size, size_t nmemb, void *stream)
{
	AudioScrobbler->ReportResponse((char*)ptr, size*nmemb);
}

CAudioScrobbler::CAudioScrobbler()
{
	_failcount = 0;
	_authed = false;
	_response = "";
	_handle = curl_easy_init();
	if(!_handle) {
		eprintf("%s", "Could not initialize CURL.");
		exit(EXIT_FAILURE);
	}
}

void
CAudioScrobbler::OpenURL(std::string url, const char* postfields = 0, char* errbuf = 0)
{
	curl_easy_setopt(_handle, CURLOPT_DNS_CACHE_TIMEOUT, 0);
	curl_easy_setopt(_handle, CURLOPT_NOPROGRESS, 1);
	curl_easy_setopt(_handle, CURLOPT_WRITEFUNCTION, writecb);

	if(postfields) {
		curl_easy_setopt(_handle, CURLOPT_POST, 1);
		curl_easy_setopt(_handle, CURLOPT_POSTFIELDS, postfields);
	}
	else
		curl_easy_setopt(_handle, CURLOPT_POST, 0);
	if(errbuf)
		curl_easy_setopt(_handle, CURLOPT_ERRORBUFFER, errbuf);

	curl_easy_setopt(_handle, CURLOPT_URL, url.c_str());
	curl_easy_perform(_handle);
}

void
CAudioScrobbler::ReportResponse(char* buf, size_t size)
{
	_response.append(buf);
}

std::string
CAudioScrobbler::CreateScrobbleMessage(int index, centry_t* entry)
{
	std::ostringstream msg, sigmsg ;
	std::string artist, title, album, array = "=";

	char* temp = 0;
	temp = curl_easy_escape(_handle, entry->artist.c_str(), entry->artist.length());
	artist = temp;
	curl_free(temp);
	temp = curl_easy_escape(_handle, entry->title.c_str(), entry->title.length());
	title = temp;
	curl_free(temp);
	temp = curl_easy_escape(_handle, entry->album.c_str(), entry->album.length());
	album = temp;
	curl_free(temp);

	msg << "&album" << array << album;
	msg << "&api_key=" << APIKEY;
	msg << "&artist" << array << artist;
	msg << "&duration" << array << entry->time;
	msg << "&method=track.Scrobble";
	msg << "&timestamp" << array << entry->starttime;
	msg << "&track" << array << title;
	msg << "&sk=" << _sessionid;

	array = "";

	sigmsg << "album" << array << entry->album;
	sigmsg << "api_key" << APIKEY;
	sigmsg << "artist" << array << entry->artist;
	sigmsg << "duration" << array << entry->time;
	sigmsg << "methodtrack.Scrobble";
	sigmsg << "sk" << _sessionid;
	sigmsg << "timestamp" << array << entry->starttime;
	sigmsg << "track" << array << entry->title;
	sigmsg << SECRET;

	std::string sighash(md5sum((char*)"%s", sigmsg.str().c_str()));
	msg << "&api_sig=" << sighash;

	return msg.str();
}

void
CAudioScrobbler::Failure()
{
	_failcount += 1;
	if(_failcount >= 3) {
		eprintf("%s", "Re-Handshaking!");
		_failcount = 0;
		Handshake();
	}
}

bool
CAudioScrobbler::CheckFailure(std::string response)
{
	bool retval = false;

	size_t start, end;
	start = _response.find("<error code=\"")+13;
	end = _response.find(">", start)-1;
	std::string errorcode = _response.substr(start, end-start);
	int code = strtol(errorcode.c_str(), 0, 10);

	eprintf("%s%i", "Code: ", code);

	switch(code) {
		case 3:
			eprintf("Invalid Method. This should not happen.");
			retval = true;
			break;
		case 4:
			eprintf("Authentification failed. Please check your login data.");
			exit(EXIT_FAILURE);
		case 9:
			eprintf("Invalid session key. Reauthentificating.");
			retval = true;
			_failcount = 3;
			break;
		case 10:
			eprintf("Invalid API-Key. Let's bugger off.");
			exit(EXIT_FAILURE);
		case 16:
			eprintf("The service is temporarily unavailable, we will try again later..");
			retval = true;
			break;
		case 26:
			eprintf("Uh oh. Suspended API key - Access for your account has been suspended, please contact Last.fm");
			exit(EXIT_FAILURE);
	}

	return retval;
}

bool
CAudioScrobbler::Scrobble(centry_t* entry)
{
	bool retval = false;
	if(!_authed) {
		eprintf("Handshake hasn't been done yet.");
		Handshake();
		return retval;
	}
	iprintf("Scrobbling: %s - %s", entry->artist.c_str(), entry->title.c_str());

	OpenURL(ROOTURL, CreateScrobbleMessage(0, entry).c_str());
	if(_response.find("<lfm status=\"ok\">") != std::string::npos) {
		iprintf("%s", "Scrobbled successfully.");
		retval = true;
	}
	else if(_response.find("<lfm status=\"failed\">") != std::string::npos) {
		eprintf("%s%s", "Last.fm returned an error while scrobbling:\n", _response.c_str());
		if(CheckFailure(_response))
			Failure();
	}
	CLEANUP();

	return retval;
}

bool
CAudioScrobbler::SendNowPlaying(mpd_Song* song)
{
	bool retval = false;
	if(!song || !song->artist || !song->title) return retval;

	char* artist = curl_easy_escape(_handle, song->artist, 0);
	char* title = curl_easy_escape(_handle, song->title, 0);
	char* album = 0;
	if(song->album)
		album = curl_easy_escape(_handle, song->album, 0);

	std::ostringstream query, sig;
	query << "method=track.updateNowPlaying&track=" << title << "&artist=" << artist << "&duration=" << song->time << "&api_key=" << APIKEY << "&sk=" << _sessionid;
	if(album) {
		query << "&album=" << album;
		sig << "album" << song->album;
	}

	sig << "api_key" << APIKEY << "artist" << song->artist << "duration" << song->time << "methodtrack.updateNowPlaying" << "sk" << _sessionid << "track" << song->title << SECRET;

	std::string sighash(md5sum((char*)"%s", sig.str().c_str()));

	query << "&api_sig=" << sighash;

	OpenURL(ROOTURL, query.str().c_str());

	if(_response.find("<lfm status=\"ok\">") != std::string::npos) {
		iprintf("%s", "Updated \"Now Playing\" status successfully.");
		retval = true;
	}
	else if(_response.find("<lfm status=\"failed\">") != std::string::npos) {
		eprintf("%s%s", "Last.fm returned an error while updating the currently playing track:\n", _response.c_str());
		if(CheckFailure(_response))
			Failure();
	}

	CLEANUP();
	return retval;
}

void
CAudioScrobbler::Handshake()
{
	std::string username="";
	for(unsigned int i = 0; i < Config->getLUsername().length(); i++) {
		username.append(1, tolower(Config->getLUsername().c_str()[i]));
	}
	std::string authtoken(md5sum((char*)"%s%s", username.c_str(), Config->getLPassword().c_str()));

	std::ostringstream query, sig;
	query << "method=auth.getMobileSession&username=" << Config->getLUsername() << "&authToken=" << authtoken << "&api_key=" << APIKEY;

	sig << "api_key" << APIKEY << "authToken" << authtoken << "methodauth.getMobileSessionusername" << Config->getLUsername() << SECRET;
	std::string sighash(md5sum((char*)"%s", sig.str().c_str()));

	query << "&api_sig=" << sighash;

	OpenURL(ROOTURL, query.str().c_str());

	if(_response.find("<lfm status=\"ok\">") != std::string::npos) {
		size_t start, end;
		start = _response.find("<key>") + 5;
		end = _response.find("</key>");
		_sessionid = _response.substr(start, end-start);
		iprintf("%s%s", "Last.fm handshake successful. SessionID: ", _sessionid.c_str());
		_authed = true;
	}
	else if(_response.find("<lfm status=\"failed\">") != std::string::npos) {
		CheckFailure(_response);
		exit(EXIT_FAILURE);
	}

	CLEANUP();
}
<commit_msg>fix spelling<commit_after>#include "mpdas.h"

#define ROOTURL		"http://ws.audioscrobbler.com/2.0/"
#define APIKEY		"a0ed2629d3d28606f67d7214c916788d"
#define	SECRET		"295f31c5d28215215b1503fb0327cc01"

CAudioScrobbler* AudioScrobbler = 0;

#define CLEANUP()	_response.clear()

size_t
writecb(void* ptr, size_t size, size_t nmemb, void *stream)
{
	AudioScrobbler->ReportResponse((char*)ptr, size*nmemb);
}

CAudioScrobbler::CAudioScrobbler()
{
	_failcount = 0;
	_authed = false;
	_response = "";
	_handle = curl_easy_init();
	if(!_handle) {
		eprintf("%s", "Could not initialize CURL.");
		exit(EXIT_FAILURE);
	}
}

void
CAudioScrobbler::OpenURL(std::string url, const char* postfields = 0, char* errbuf = 0)
{
	curl_easy_setopt(_handle, CURLOPT_DNS_CACHE_TIMEOUT, 0);
	curl_easy_setopt(_handle, CURLOPT_NOPROGRESS, 1);
	curl_easy_setopt(_handle, CURLOPT_WRITEFUNCTION, writecb);

	if(postfields) {
		curl_easy_setopt(_handle, CURLOPT_POST, 1);
		curl_easy_setopt(_handle, CURLOPT_POSTFIELDS, postfields);
	}
	else
		curl_easy_setopt(_handle, CURLOPT_POST, 0);
	if(errbuf)
		curl_easy_setopt(_handle, CURLOPT_ERRORBUFFER, errbuf);

	curl_easy_setopt(_handle, CURLOPT_URL, url.c_str());
	curl_easy_perform(_handle);
}

void
CAudioScrobbler::ReportResponse(char* buf, size_t size)
{
	_response.append(buf);
}

std::string
CAudioScrobbler::CreateScrobbleMessage(int index, centry_t* entry)
{
	std::ostringstream msg, sigmsg ;
	std::string artist, title, album, array = "=";

	char* temp = 0;
	temp = curl_easy_escape(_handle, entry->artist.c_str(), entry->artist.length());
	artist = temp;
	curl_free(temp);
	temp = curl_easy_escape(_handle, entry->title.c_str(), entry->title.length());
	title = temp;
	curl_free(temp);
	temp = curl_easy_escape(_handle, entry->album.c_str(), entry->album.length());
	album = temp;
	curl_free(temp);

	msg << "&album" << array << album;
	msg << "&api_key=" << APIKEY;
	msg << "&artist" << array << artist;
	msg << "&duration" << array << entry->time;
	msg << "&method=track.Scrobble";
	msg << "&timestamp" << array << entry->starttime;
	msg << "&track" << array << title;
	msg << "&sk=" << _sessionid;

	array = "";

	sigmsg << "album" << array << entry->album;
	sigmsg << "api_key" << APIKEY;
	sigmsg << "artist" << array << entry->artist;
	sigmsg << "duration" << array << entry->time;
	sigmsg << "methodtrack.Scrobble";
	sigmsg << "sk" << _sessionid;
	sigmsg << "timestamp" << array << entry->starttime;
	sigmsg << "track" << array << entry->title;
	sigmsg << SECRET;

	std::string sighash(md5sum((char*)"%s", sigmsg.str().c_str()));
	msg << "&api_sig=" << sighash;

	return msg.str();
}

void
CAudioScrobbler::Failure()
{
	_failcount += 1;
	if(_failcount >= 3) {
		eprintf("%s", "Re-Handshaking!");
		_failcount = 0;
		Handshake();
	}
}

bool
CAudioScrobbler::CheckFailure(std::string response)
{
	bool retval = false;

	size_t start, end;
	start = _response.find("<error code=\"")+13;
	end = _response.find(">", start)-1;
	std::string errorcode = _response.substr(start, end-start);
	int code = strtol(errorcode.c_str(), 0, 10);

	eprintf("%s%i", "Code: ", code);

	switch(code) {
		case 3:
			eprintf("Invalid Method. This should not happen.");
			retval = true;
			break;
		case 4:
			eprintf("Authentication failed. Please check your login data.");
			exit(EXIT_FAILURE);
		case 9:
			eprintf("Invalid session key. Re-authenticating.");
			retval = true;
			_failcount = 3;
			break;
		case 10:
			eprintf("Invalid API-Key. Let's bugger off.");
			exit(EXIT_FAILURE);
		case 16:
			eprintf("The service is temporarily unavailable, we will try again later..");
			retval = true;
			break;
		case 26:
			eprintf("Uh oh. Suspended API key - Access for your account has been suspended, please contact Last.fm");
			exit(EXIT_FAILURE);
	}

	return retval;
}

bool
CAudioScrobbler::Scrobble(centry_t* entry)
{
	bool retval = false;
	if(!_authed) {
		eprintf("Handshake hasn't been done yet.");
		Handshake();
		return retval;
	}
	iprintf("Scrobbling: %s - %s", entry->artist.c_str(), entry->title.c_str());

	OpenURL(ROOTURL, CreateScrobbleMessage(0, entry).c_str());
	if(_response.find("<lfm status=\"ok\">") != std::string::npos) {
		iprintf("%s", "Scrobbled successfully.");
		retval = true;
	}
	else if(_response.find("<lfm status=\"failed\">") != std::string::npos) {
		eprintf("%s%s", "Last.fm returned an error while scrobbling:\n", _response.c_str());
		if(CheckFailure(_response))
			Failure();
	}
	CLEANUP();

	return retval;
}

bool
CAudioScrobbler::SendNowPlaying(mpd_Song* song)
{
	bool retval = false;
	if(!song || !song->artist || !song->title) return retval;

	char* artist = curl_easy_escape(_handle, song->artist, 0);
	char* title = curl_easy_escape(_handle, song->title, 0);
	char* album = 0;
	if(song->album)
		album = curl_easy_escape(_handle, song->album, 0);

	std::ostringstream query, sig;
	query << "method=track.updateNowPlaying&track=" << title << "&artist=" << artist << "&duration=" << song->time << "&api_key=" << APIKEY << "&sk=" << _sessionid;
	if(album) {
		query << "&album=" << album;
		sig << "album" << song->album;
	}

	sig << "api_key" << APIKEY << "artist" << song->artist << "duration" << song->time << "methodtrack.updateNowPlaying" << "sk" << _sessionid << "track" << song->title << SECRET;

	std::string sighash(md5sum((char*)"%s", sig.str().c_str()));

	query << "&api_sig=" << sighash;

	OpenURL(ROOTURL, query.str().c_str());

	if(_response.find("<lfm status=\"ok\">") != std::string::npos) {
		iprintf("%s", "Updated \"Now Playing\" status successfully.");
		retval = true;
	}
	else if(_response.find("<lfm status=\"failed\">") != std::string::npos) {
		eprintf("%s%s", "Last.fm returned an error while updating the currently playing track:\n", _response.c_str());
		if(CheckFailure(_response))
			Failure();
	}

	CLEANUP();
	return retval;
}

void
CAudioScrobbler::Handshake()
{
	std::string username="";
	for(unsigned int i = 0; i < Config->getLUsername().length(); i++) {
		username.append(1, tolower(Config->getLUsername().c_str()[i]));
	}
	std::string authtoken(md5sum((char*)"%s%s", username.c_str(), Config->getLPassword().c_str()));

	std::ostringstream query, sig;
	query << "method=auth.getMobileSession&username=" << Config->getLUsername() << "&authToken=" << authtoken << "&api_key=" << APIKEY;

	sig << "api_key" << APIKEY << "authToken" << authtoken << "methodauth.getMobileSessionusername" << Config->getLUsername() << SECRET;
	std::string sighash(md5sum((char*)"%s", sig.str().c_str()));

	query << "&api_sig=" << sighash;

	OpenURL(ROOTURL, query.str().c_str());

	if(_response.find("<lfm status=\"ok\">") != std::string::npos) {
		size_t start, end;
		start = _response.find("<key>") + 5;
		end = _response.find("</key>");
		_sessionid = _response.substr(start, end-start);
		iprintf("%s%s", "Last.fm handshake successful. SessionID: ", _sessionid.c_str());
		_authed = true;
	}
	else if(_response.find("<lfm status=\"failed\">") != std::string::npos) {
		CheckFailure(_response);
		exit(EXIT_FAILURE);
	}

	CLEANUP();
}
<|endoftext|>


<commit_before>/*
    Copyright (C) 2012 Aleix Pol <aleixpol@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 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
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "pinned-contacts-model.h"
#include "conversations-model.h"
#include "conversation.h"

#include <TelepathyQt/Types>
#include <TelepathyQt/AvatarData>
#include <TelepathyQt/Presence>
#include <TelepathyQt/Account>
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/PendingReady>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/PendingContacts>

#include <KConfigGroup>
#include "debug.h"

#include "KTp/presence.h"
#include "KTp/contact.h"
#include "KTp/persistent-contact.h"

class PinnedContactsModelPrivate {
public:
    PinnedContactsModelPrivate() {
        conversations = 0;
    }

    QList<KTp::PersistentContactPtr> m_pins;
    Tp::AccountManagerPtr accountManager;
    ConversationsModel *conversations;

    QStringList pinsToString() const {
        QStringList ret;
        Q_FOREACH(const KTp::PersistentContactPtr &p, m_pins) {
            ret += p->accountId();
            ret += p->contactId();
        }
        return ret;
    }
};

PinnedContactsModel::PinnedContactsModel(QObject *parent)
    : QAbstractListModel(parent)
    , d(new PinnedContactsModelPrivate)
{
    connect(this, SIGNAL(rowsInserted(QModelIndex,int,int)), SIGNAL(countChanged()));
    connect(this, SIGNAL(rowsRemoved(QModelIndex,int,int)), SIGNAL(countChanged()));
}

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

QHash<int, QByteArray> PinnedContactsModel::roleNames() const
{
    QHash<int, QByteArray> roles = QAbstractListModel::roleNames();
    roles[PresenceIconRole] = "presenceIcon";
    roles[AvailabilityRole] = "available";
    roles[ContactRole] = "contact";
    roles[AccountRole] = "account";
    roles[AlreadyChattingRole] = "alreadyChatting";
    return roles;
}

QStringList PinnedContactsModel::state() const
{
    return d->pinsToString();
}

void PinnedContactsModel::setState(const QStringList &pins)
{
    for (int i = 0; i < pins.count(); i += 2) {
        appendContactPin(KTp::PersistentContact::create(pins[0], pins[1]));
    }
}

QModelIndex PinnedContactsModel::indexForContact(const KTp::ContactPtr &contact) const
{
    for (int i=0; i<d->m_pins.size() && contact; i++) {
        if (d->m_pins[i]->contactId() == contact->id()) {
            return index(i);
        }
    }
    return QModelIndex();
}

void PinnedContactsModel::setPinning(const Tp::AccountPtr &account, const KTp::ContactPtr &contact, bool newState)
{
    QModelIndex idx = indexForContact(contact);
    bool found = idx.isValid();
    if (newState && !found) {
        KTp::PersistentContactPtr p = KTp::PersistentContact::create(account->uniqueIdentifier(), contact->id());
        appendContactPin(p);
    } else if (!newState && found) {
        removeContactPin(d->m_pins[idx.row()]);
    }
}

QVariant PinnedContactsModel::data(const QModelIndex &index, int role) const
{
    if (index.isValid()) {
        KTp::PersistentContactPtr p = d->m_pins[index.row()];
        switch(role) {
        case Qt::DisplayRole:
            if (p->contact()) {
                return p->contact()->alias();
            }
            break;
        case PresenceIconRole:
            if (p->contact()) {
                return KTp::Presence(p->contact()->presence()).icon();
            } else {
                return KTp::Presence(Tp::Presence::offline()).icon();
            }
            break;
        case AvailabilityRole:
            if (!p->contact()) {
                return false;
            }
            else {
                return p->contact()->presence().type()!=Tp::ConnectionPresenceTypeOffline
                        && p->contact()->presence().type()!=Tp::ConnectionPresenceTypeError
                        && p->contact()->presence().type()!=Tp::ConnectionPresenceTypeUnset
                        && p->contact()->presence().type()!=Tp::ConnectionPresenceTypeUnknown;
            }
        case ContactRole:
            return QVariant::fromValue<KTp::ContactPtr>(p->contact());
        case AccountRole:
            return QVariant::fromValue<Tp::AccountPtr>(p->account());
        case AlreadyChattingRole: {
            if (!p->contact()) {
                return false;
            }
            bool found = false;
            for (int i = 0; !found && i < d->conversations->rowCount(); i++) {
                QModelIndex idx = d->conversations->index(i, 0);
                KTp::ContactPtr contact = idx.data(ConversationsModel::ConversationRole).value<Conversation*>()->targetContact();
                found |= contact->id() == p->contact()->id();
            }
            return found;
        }
        case Qt::DecorationRole: {
            QIcon icon;
            if (p->contact()) {
                QString file = p->contact()->avatarData().fileName;
                if (!file.isEmpty()) {
                    icon = QIcon::fromTheme(file);
                }
            }
            if (icon.isNull()) {
                icon = QIcon::fromTheme(QStringLiteral("im-user"));
            }
            return icon;
        }
        }
    }
    return QVariant();
}

int PinnedContactsModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid()) {
        return 0;
    }
    return d->m_pins.count();
}

void PinnedContactsModel::removeContactPin(const KTp::PersistentContactPtr &pin)
{
    int row = d->m_pins.indexOf(pin);
    if (row>=0) {
        beginRemoveRows(QModelIndex(), row, row);
        d->m_pins.removeAt(row);
        endRemoveRows();

        Q_EMIT stateChanged();
    } else
        qWarning() << "trying to remove missing pin" << pin->contactId();
}

void PinnedContactsModel::appendContactPin(const KTp::PersistentContactPtr &pin)
{
    auto samePin = [pin](const KTp::PersistentContactPtr &p) -> bool { return p->contactId() == pin->contactId(); };
    if (std::find_if(d->m_pins.constBegin(), d->m_pins.constEnd(), samePin) != d->m_pins.constEnd()) {
        return;
    }

    int s = d->m_pins.size();
    beginInsertRows(QModelIndex(), s, s);
    d->m_pins += pin;
    endInsertRows();

    if (d->accountManager && d->accountManager->isReady()) {
        pin->setAccountManager(d->accountManager);
    }

    if (pin->contact()) {
        contactChanged(pin->contact());
    }
    connect(pin.data(), SIGNAL(contactChanged(KTp::ContactPtr)), SLOT(contactChanged(KTp::ContactPtr)));

    Q_EMIT stateChanged();
}

void PinnedContactsModel::contactChanged(const KTp::ContactPtr &contact)
{
    if (contact) {
        connect(contact.data(),
                SIGNAL(avatarDataChanged(Tp::AvatarData)),
                SLOT(contactDataChanged()));
        connect(contact.data(),
                SIGNAL(aliasChanged(QString)),
                SLOT(contactDataChanged()));
        connect(contact.data(),
                SIGNAL(presenceChanged(Tp::Presence)),
                SLOT(contactDataChanged()));
    }

    QModelIndex index = indexForContact(contact);
    Q_EMIT dataChanged(index, index);
}

void PinnedContactsModel::contactDataChanged()
{
    KTp::Contact *c = qobject_cast<KTp::Contact*>(sender());
    QModelIndex index = indexForContact(KTp::ContactPtr(c));
    Q_EMIT dataChanged(index, index);
}

void PinnedContactsModel::setConversationsModel(ConversationsModel *model)
{
    beginResetModel();
    if (d->conversations) {
        disconnect(d->conversations, &QAbstractItemModel::rowsAboutToBeRemoved, this, &PinnedContactsModel::conversationsStateChanged);
        disconnect(d->conversations, &QAbstractItemModel::rowsInserted, this, &PinnedContactsModel::conversationsStateChanged);
    }

    d->conversations = model;
    if (model) {
        connect(d->conversations, &QAbstractItemModel::rowsAboutToBeRemoved, this, &PinnedContactsModel::conversationsStateChanged);
        connect(d->conversations, &QAbstractItemModel::rowsInserted, this, &PinnedContactsModel::conversationsStateChanged);
    }
    endResetModel();
}

void PinnedContactsModel::conversationsStateChanged(const QModelIndex &parent, int start, int end)
{
    for (int i = start; i <= end; i++) {
        QModelIndex idx = d->conversations->index(i, 0, parent);
        Conversation* conv = idx.data(ConversationsModel::ConversationRole).value<Conversation*>();
        QString contactId = conv->targetContact()->id();

        Q_FOREACH(const KTp::PersistentContactPtr &p, d->m_pins) {
            if (p->contactId() == contactId) {
                QModelIndex contactIdx = indexForContact(p->contact());
                //We need to delay the dataChanged until the next event loop, when endRowsRemoved has been called
                QMetaObject::invokeMethod(this, "dataChanged", Qt::QueuedConnection, Q_ARG(QModelIndex, contactIdx), Q_ARG(QModelIndex, contactIdx));
            }
        }
    }
}

ConversationsModel* PinnedContactsModel::conversationsModel() const
{
    return d->conversations;
}

Tp::AccountManagerPtr PinnedContactsModel::accountManager() const
{
    return d->accountManager;
}

void PinnedContactsModel::setAccountManager(const Tp::AccountManagerPtr &accounts)
{
    d->accountManager = accounts;

    connect(d->accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountManagerReady()));
}

void PinnedContactsModel::onAccountManagerReady()
{
    Q_FOREACH(const KTp::PersistentContactPtr &p, d->m_pins) {
        p->setAccountManager(d->accountManager);
    }
}
<commit_msg>Don't crash if the ConversationsModel has been disabled<commit_after>/*
    Copyright (C) 2012 Aleix Pol <aleixpol@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 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
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "pinned-contacts-model.h"
#include "conversations-model.h"
#include "conversation.h"

#include <TelepathyQt/Types>
#include <TelepathyQt/AvatarData>
#include <TelepathyQt/Presence>
#include <TelepathyQt/Account>
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/PendingReady>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/PendingContacts>

#include <KConfigGroup>
#include "debug.h"

#include "KTp/presence.h"
#include "KTp/contact.h"
#include "KTp/persistent-contact.h"

class PinnedContactsModelPrivate {
public:
    PinnedContactsModelPrivate() {
        conversations = 0;
    }

    QList<KTp::PersistentContactPtr> m_pins;
    Tp::AccountManagerPtr accountManager;
    ConversationsModel *conversations;

    QStringList pinsToString() const {
        QStringList ret;
        Q_FOREACH(const KTp::PersistentContactPtr &p, m_pins) {
            ret += p->accountId();
            ret += p->contactId();
        }
        return ret;
    }
};

PinnedContactsModel::PinnedContactsModel(QObject *parent)
    : QAbstractListModel(parent)
    , d(new PinnedContactsModelPrivate)
{
    connect(this, SIGNAL(rowsInserted(QModelIndex,int,int)), SIGNAL(countChanged()));
    connect(this, SIGNAL(rowsRemoved(QModelIndex,int,int)), SIGNAL(countChanged()));
}

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

QHash<int, QByteArray> PinnedContactsModel::roleNames() const
{
    QHash<int, QByteArray> roles = QAbstractListModel::roleNames();
    roles[PresenceIconRole] = "presenceIcon";
    roles[AvailabilityRole] = "available";
    roles[ContactRole] = "contact";
    roles[AccountRole] = "account";
    roles[AlreadyChattingRole] = "alreadyChatting";
    return roles;
}

QStringList PinnedContactsModel::state() const
{
    return d->pinsToString();
}

void PinnedContactsModel::setState(const QStringList &pins)
{
    for (int i = 0; i < pins.count(); i += 2) {
        appendContactPin(KTp::PersistentContact::create(pins[0], pins[1]));
    }
}

QModelIndex PinnedContactsModel::indexForContact(const KTp::ContactPtr &contact) const
{
    for (int i=0; i<d->m_pins.size() && contact; i++) {
        if (d->m_pins[i]->contactId() == contact->id()) {
            return index(i);
        }
    }
    return QModelIndex();
}

void PinnedContactsModel::setPinning(const Tp::AccountPtr &account, const KTp::ContactPtr &contact, bool newState)
{
    QModelIndex idx = indexForContact(contact);
    bool found = idx.isValid();
    if (newState && !found) {
        KTp::PersistentContactPtr p = KTp::PersistentContact::create(account->uniqueIdentifier(), contact->id());
        appendContactPin(p);
    } else if (!newState && found) {
        removeContactPin(d->m_pins[idx.row()]);
    }
}

QVariant PinnedContactsModel::data(const QModelIndex &index, int role) const
{
    if (index.isValid()) {
        KTp::PersistentContactPtr p = d->m_pins[index.row()];
        switch(role) {
        case Qt::DisplayRole:
            if (p->contact()) {
                return p->contact()->alias();
            }
            break;
        case PresenceIconRole:
            if (p->contact()) {
                return KTp::Presence(p->contact()->presence()).icon();
            } else {
                return KTp::Presence(Tp::Presence::offline()).icon();
            }
            break;
        case AvailabilityRole:
            if (!p->contact()) {
                return false;
            }
            else {
                return p->contact()->presence().type()!=Tp::ConnectionPresenceTypeOffline
                        && p->contact()->presence().type()!=Tp::ConnectionPresenceTypeError
                        && p->contact()->presence().type()!=Tp::ConnectionPresenceTypeUnset
                        && p->contact()->presence().type()!=Tp::ConnectionPresenceTypeUnknown;
            }
        case ContactRole:
            return QVariant::fromValue<KTp::ContactPtr>(p->contact());
        case AccountRole:
            return QVariant::fromValue<Tp::AccountPtr>(p->account());
        case AlreadyChattingRole: {
            if (!p->contact() || !d->conversations) {
                return false;
            }
            bool found = false;
            for (int i = 0; !found && i < d->conversations->rowCount(); i++) {
                QModelIndex idx = d->conversations->index(i, 0);
                KTp::ContactPtr contact = idx.data(ConversationsModel::ConversationRole).value<Conversation*>()->targetContact();
                found |= contact->id() == p->contact()->id();
            }
            return found;
        }
        case Qt::DecorationRole: {
            QIcon icon;
            if (p->contact()) {
                QString file = p->contact()->avatarData().fileName;
                if (!file.isEmpty()) {
                    icon = QIcon::fromTheme(file);
                }
            }
            if (icon.isNull()) {
                icon = QIcon::fromTheme(QStringLiteral("im-user"));
            }
            return icon;
        }
        }
    }
    return QVariant();
}

int PinnedContactsModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid()) {
        return 0;
    }
    return d->m_pins.count();
}

void PinnedContactsModel::removeContactPin(const KTp::PersistentContactPtr &pin)
{
    int row = d->m_pins.indexOf(pin);
    if (row>=0) {
        beginRemoveRows(QModelIndex(), row, row);
        d->m_pins.removeAt(row);
        endRemoveRows();

        Q_EMIT stateChanged();
    } else
        qWarning() << "trying to remove missing pin" << pin->contactId();
}

void PinnedContactsModel::appendContactPin(const KTp::PersistentContactPtr &pin)
{
    auto samePin = [pin](const KTp::PersistentContactPtr &p) -> bool { return p->contactId() == pin->contactId(); };
    if (std::find_if(d->m_pins.constBegin(), d->m_pins.constEnd(), samePin) != d->m_pins.constEnd()) {
        return;
    }

    int s = d->m_pins.size();
    beginInsertRows(QModelIndex(), s, s);
    d->m_pins += pin;
    endInsertRows();

    if (d->accountManager && d->accountManager->isReady()) {
        pin->setAccountManager(d->accountManager);
    }

    if (pin->contact()) {
        contactChanged(pin->contact());
    }
    connect(pin.data(), SIGNAL(contactChanged(KTp::ContactPtr)), SLOT(contactChanged(KTp::ContactPtr)));

    Q_EMIT stateChanged();
}

void PinnedContactsModel::contactChanged(const KTp::ContactPtr &contact)
{
    if (contact) {
        connect(contact.data(),
                SIGNAL(avatarDataChanged(Tp::AvatarData)),
                SLOT(contactDataChanged()));
        connect(contact.data(),
                SIGNAL(aliasChanged(QString)),
                SLOT(contactDataChanged()));
        connect(contact.data(),
                SIGNAL(presenceChanged(Tp::Presence)),
                SLOT(contactDataChanged()));
    }

    QModelIndex index = indexForContact(contact);
    Q_EMIT dataChanged(index, index);
}

void PinnedContactsModel::contactDataChanged()
{
    KTp::Contact *c = qobject_cast<KTp::Contact*>(sender());
    QModelIndex index = indexForContact(KTp::ContactPtr(c));
    Q_EMIT dataChanged(index, index);
}

void PinnedContactsModel::setConversationsModel(ConversationsModel *model)
{
    beginResetModel();
    if (d->conversations) {
        disconnect(d->conversations, &QAbstractItemModel::rowsAboutToBeRemoved, this, &PinnedContactsModel::conversationsStateChanged);
        disconnect(d->conversations, &QAbstractItemModel::rowsInserted, this, &PinnedContactsModel::conversationsStateChanged);
    }

    d->conversations = model;
    if (model) {
        connect(d->conversations, &QAbstractItemModel::rowsAboutToBeRemoved, this, &PinnedContactsModel::conversationsStateChanged);
        connect(d->conversations, &QAbstractItemModel::rowsInserted, this, &PinnedContactsModel::conversationsStateChanged);
    }
    endResetModel();
}

void PinnedContactsModel::conversationsStateChanged(const QModelIndex &parent, int start, int end)
{
    for (int i = start; i <= end; i++) {
        QModelIndex idx = d->conversations->index(i, 0, parent);
        Conversation* conv = idx.data(ConversationsModel::ConversationRole).value<Conversation*>();
        QString contactId = conv->targetContact()->id();

        Q_FOREACH(const KTp::PersistentContactPtr &p, d->m_pins) {
            if (p->contactId() == contactId) {
                QModelIndex contactIdx = indexForContact(p->contact());
                //We need to delay the dataChanged until the next event loop, when endRowsRemoved has been called
                QMetaObject::invokeMethod(this, "dataChanged", Qt::QueuedConnection, Q_ARG(QModelIndex, contactIdx), Q_ARG(QModelIndex, contactIdx));
            }
        }
    }
}

ConversationsModel* PinnedContactsModel::conversationsModel() const
{
    return d->conversations;
}

Tp::AccountManagerPtr PinnedContactsModel::accountManager() const
{
    return d->accountManager;
}

void PinnedContactsModel::setAccountManager(const Tp::AccountManagerPtr &accounts)
{
    d->accountManager = accounts;

    connect(d->accountManager->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountManagerReady()));
}

void PinnedContactsModel::onAccountManagerReady()
{
    Q_FOREACH(const KTp::PersistentContactPtr &p, d->m_pins) {
        p->setAccountManager(d->accountManager);
    }
}
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS fwk79 (1.2.62); FILE MERGED 2007/12/13 06:18:07 cd 1.2.62.1: #i84193# Add merged command URLs to the list of dirty images<commit_after><|endoftext|>


<commit_before>/***************************************************************************
                          FilterPMail.cxx  -  Pegasus-Mail import
                             -------------------
    begin                : Sat Jan 6 2001
    copyright            : (C) 2001 by Holger Schurig
                           (C) 2006 by Danny Kukawka
    email                : holgerschurig@gmx.de
                           danny.kukawka@web.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include <config.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <qregexp.h>
#include <ktempfile.h>
#include <kdebug.h>

#include "filter_pmail.hxx"

FilterPMail::FilterPMail() :
        Filter(i18n("Import Folders From Pegasus-Mail"),
               "Holger Schurig
( rewritten by Danny Kukawka )",
               i18n("
Select the Pegasus-Mail directory on your system (containing *.CNM, *.PMM and *.MBX files). "
                    "On many systems this is stored in C:\\pmail\\mail or C:\\pmail\\mail\\admin
"
                    "
Note: Since it is possible to recreate the folder structure all folders "
                    "stored under: \"PegasusMail-Import\".
"))
{}

FilterPMail::~FilterPMail()
{
    endImport();
}

void FilterPMail::import(FilterInfo *info)
{
    inf = info;

    // Select directory from where I have to import files
    KFileDialog *kfd;
    kfd = new KFileDialog( QDir::homeDirPath(), "", 0, "kfiledialog", true );
    kfd->setMode(KFile::Directory | KFile::LocalOnly);
    kfd->exec();
    chosenDir = kfd->selectedFile();

    if (chosenDir.isEmpty()) {
        info->alert(i18n("No directory selected."));
        return;
    }

    // Count total number of files to be processed
    info->addLog(i18n("Counting files..."));
    dir.setPath (chosenDir);
    QStringList files = dir.entryList("*.[cC][nN][mM]; *.[pP][mM][mM]; *.[mM][bB][xX]", QDir::Files, QDir::Name);
    totalFiles = files.count();
    currentFile = 0;
    kdDebug() << "Count is " << totalFiles << endl;

    if(!(folderParsed = parseFolderMatrix())) {
        info->addLog(i18n("Can't parse the folder structure. Continue import without subfolder support!"));
    }

    info->addLog(i18n("Importing new mail files ('.cnm')..."));
    processFiles("*.[cC][nN][mM]", &FilterPMail::importNewMessage);
    info->addLog(i18n("Importing mail folders ('.pmm')..."));
    processFiles("*.[pP][mM][mM]", &FilterPMail::importMailFolder);
    info->addLog(i18n("Importing 'UNIX' mail folders ('.mbx')..."));
    processFiles("*.[mM][bB][xX]", &FilterPMail::importUnixMailFolder);

    info->addLog( i18n("Finished importing emails from %1").arg( chosenDir ));
    info->setCurrent(100);
    info->setOverall(100);
}

/** this looks for all files with the filemask 'mask' and calls the 'workFunc' on each of them */
void FilterPMail::processFiles(const QString& mask, void(FilterPMail::* workFunc)(const QString&) )
{
    if (inf->shouldTerminate()) return;

    QStringList files = dir.entryList(mask, QDir::Files, QDir::Name);
    //kdDebug() << "Mask is " << mask << " count is " << files.count() << endl;
    for ( QStringList::Iterator mailFile = files.begin(); mailFile != files.end(); ++mailFile ) {
        // Notify current file
        QFileInfo mailfileinfo(*mailFile);
        inf->setFrom(mailfileinfo.fileName());

        // Clear the other fields
        inf->setTo(QString::null);
        inf->setCurrent(QString::null);
        inf->setCurrent(-1);

        // call worker function, increase progressbar
        (this->*workFunc)(dir.filePath(*mailFile));
        ++currentFile;
        inf->setOverall( (int) ((float) currentFile / totalFiles * 100));
        inf->setCurrent( 100 );
        if (inf->shouldTerminate()) return;
    }
}

/** this function imports one *.CNM message */
void FilterPMail::importNewMessage(const QString& file)
{
    QString destFolder("PegasusMail-Import/New Messages");
    inf->setTo(destFolder);

    /* comment by Danny Kukawka:
     * addMessage() == old function, need more time and check for duplicates
     * addMessage_fastImport == new function, faster and no check for duplicates
     */
    if(inf->removeDupMsg)
        addMessage( inf, destFolder, file );
    else
        addMessage_fastImport( inf, destFolder, file );
}

/** this function imports one mail folder file (*.PMM) */
void FilterPMail::importMailFolder(const QString& file)
{
    // Format of a PMM file:
    // First comes a header with 128 bytes. At the beginning is the name of
    // the folder. Then there are some unknown bytes (strings). At offset 128
    // the first message starts.
    //
    // Each message is terminated by a 0x1A byte. The next message follows
    // immediately.
    //
    // The last message is followed by a 0x1A, too.
    //
    // 000000 6d 61 69 6c 73 65 72 76 65 72 2d 70 72 6f 6a 65    mailserver-proje
    // 000010 63 74 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ct..............
    // 000020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
    // 000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
    // 000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
    // 000050 00 00 00 00 00 00 36 30 34 37 35 37 32 45 3a 36    ......6047572E:6
    // 000060 46 34 39 3a 46 4f 4c 30 31 33 35 35 00 00 00 00    F49:FOL01355....
    // 000070 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
    // 000080 52 65 74 75 72 6e 2d 50 61 74 68 3a 20 3c 75 72    Return-Path: <ur
    // ...
    // 000cb0 2d 2d 2d 2d 2d 2d 2d 2d 2d 2b 0d 0a 1a 52 65 74    ---------+...Ret
    // 000cc0 75 72 6e 2d 50 61 74 68 3a 20 3c 62 6f 75 6e 63    urn-Path: <bounc
    // ...
    // 04dc50 46 30 33 38 44 2e 36 31 35 44 37 34 44 30 2d 2d    F038D.615D74D0--
    // 04dc60 0d 0a 1a

    struct {
        char folder[86];
        char id[42];
    } pmm_head;

    long l = 0;
    QFile f(file);
    if (!f.open(IO_ReadOnly)) {
        inf->alert(i18n("Unable to open %1, skipping").arg(file));
    } else {
        // Get folder name
        l = f.readBlock((char *) &pmm_head, sizeof(pmm_head));
        QString folder("PegasusMail-Import/");
        if(folderParsed)
            folder.append(getFolderName((QString)pmm_head.id));
        else
            folder.append(pmm_head.folder);
        inf->setTo(folder);
        inf->addLog(i18n("Importing %1").arg("../" + QString(pmm_head.folder)));

        QByteArray input(MAX_LINE);
        bool first_msg = true;

        while (!f.atEnd()) {
            KTempFile tempfile;
            inf->setCurrent( (int) ( ( (float) f.at() / f.size() ) * 100 ) );

            if(!first_msg) {
                // set the filepos back to last line minus the seperate char (0x1a)
                f.at(f.at() - l + 1);
            }

            // no problem to loose the last line in file. This only contains a seperate char
            while ( ! f.atEnd() &&  (l = f.readLine(input.data(),MAX_LINE))) {
                    if (inf->shouldTerminate()){
                        tempfile.close();
                        tempfile.unlink();
                        return;
                    }
                    if(input[0] == 0x1a ) {
                        break;
                    } else {
                        tempfile.file()->writeBlock( input, l );
                    }
            }
            tempfile.close();

            if(inf->removeDupMsg)
                addMessage( inf, folder, tempfile.name() );
            else
                addMessage_fastImport( inf, folder, tempfile.name() );

            first_msg = false;
            tempfile.unlink();
        }
    }
    f.close();
}

/** imports a 'unix' format mail folder (*.MBX) */
void FilterPMail::importUnixMailFolder(const QString& file)
{
    struct {
        char folder[58];
        char id[31];
    } pmg_head;

    QFile f;
    QString folder("PegasusMail-Import/"), s(file), seperate;
    QByteArray line(MAX_LINE);
    int n = 0, l = 0;

    /** Get the folder name */
    s.replace( QRegExp("mbx$"), "pmg");
    s.replace( QRegExp("MBX$"), "PMG");
    f.setName(s);
    if (! f.open( IO_ReadOnly ) ) {
        inf->alert( i18n("Unable to open %1, skipping").arg( s ) );
        return;
    } else {
        f.readBlock((char *) &pmg_head, sizeof(pmg_head));
        f.close();

         if(folderParsed)
            folder.append(getFolderName((QString)pmg_head.id));
        else
            folder.append(pmg_head.folder);

        inf->setTo(folder);
        inf->setTo(folder);
    }

    /** Read in the mbox */
    f.setName(file);
    if (! f.open( IO_ReadOnly ) ) {
        inf->alert( i18n("Unable to open %1, skipping").arg( s ) );
    } else {
        inf->addLog(i18n("Importing %1").arg("../" + QString(pmg_head.folder)));
        l = f.readLine( line.data(),MAX_LINE); // read the first line which is unneeded
        while ( ! f.atEnd() ) {
            KTempFile tempfile;

            // we lost the last line, which is the first line of the new message in
            // this lopp, but this is ok, because this is the seperate line with
            // "From ???@???" and we can forget them
            while ( ! f.atEnd() &&  (l = f.readLine(line.data(),MAX_LINE)) && ((seperate = line.data()).left(5) != "From ")) {
                tempfile.file()->writeBlock(line.data(), l);
                if (inf->shouldTerminate()){
                    tempfile.close();
                    tempfile.unlink();
                    return;
                }
            }
            tempfile.close();
            if(inf->removeDupMsg)
                addMessage( inf, folder, tempfile.name() );
            else
                addMessage_fastImport( inf, folder, tempfile.name() );
            tempfile.unlink();

            n++;
            inf->setCurrent(i18n("Message %1").arg(n));
            inf->setCurrent( (int) ( ( (float) f.at() / f.size() ) * 100 ) );
        }
    }
    f.close();
}

/** Parse the information about folderstructure to folderMatrix */
bool FilterPMail::parseFolderMatrix()
{
    kdDebug() << "Start parsing the foldermatrix." << endl;
    inf->addLog(i18n("Parsing the folder structure..."));

    QFile hierarch(chosenDir + "/hierarch.pm");
    if (! hierarch.open( IO_ReadOnly ) ) {
        inf->alert( i18n("Unable to open %1, skipping").arg( chosenDir + "hierarch.pm" ) );
        return false;
    } else {
        QStringList tmpList;
        QString tmpRead;
        while ( !hierarch.atEnd() &&  hierarch.readLine(tmpRead,100)) {
            QString tmpArray[5];
            tmpRead.remove(tmpRead.length() -2,2);
            QStringList tmpList = QStringList::split(",", tmpRead, false);
            int i = 0;
            for ( QStringList::Iterator it = tmpList.begin(); it != tmpList.end(); ++it, i++) {
                QString _tmp = *it;
                if(i < 5) tmpArray[i] = _tmp.remove("\"");
                else {
                    hierarch.close();
                    return false;
                }
            }
            folderMatrix.append(tmpArray);
        }
    }
    hierarch.close();
    return true;
}

/** get the foldername for a given file ID from folderMatrix */
QString FilterPMail::getFolderName(QString ID)
{
    bool found = false;
    QString folder = "";
    QString search = ID;

    while (!found)
    {
        for ( QValueList<QString[5]>::Iterator it = folderMatrix.begin(); it != folderMatrix.end(); it++) {
            QString tmp[5] = *it;

            QString _ID = tmp[2];
            if(_ID == search) {
                QString _type = tmp[0] + tmp[1];
                if(( _type == "21")) {
                    found = true;
                    break;
                }
                else {
                    folder.prepend((tmp[4] + "/"));
                    search = tmp[3];
                }
            }
        }
    }
    return folder;
}
<commit_msg>- fixed/changed the date in copyright section<commit_after>/***************************************************************************
                          FilterPMail.cxx  -  Pegasus-Mail import
                             -------------------
    begin                : Sat Jan 6 2001
    copyright            : (C) 2001 by Holger Schurig
                           (C) 2005 by Danny Kukawka
    email                : holgerschurig@gmx.de
                           danny.kukawka@web.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include <config.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <qregexp.h>
#include <ktempfile.h>
#include <kdebug.h>

#include "filter_pmail.hxx"

FilterPMail::FilterPMail() :
        Filter(i18n("Import Folders From Pegasus-Mail"),
               "Holger Schurig
( rewritten by Danny Kukawka )",
               i18n("
Select the Pegasus-Mail directory on your system (containing *.CNM, *.PMM and *.MBX files). "
                    "On many systems this is stored in C:\\pmail\\mail or C:\\pmail\\mail\\admin
"
                    "
Note: Since it is possible to recreate the folder structure all folders "
                    "stored under: \"PegasusMail-Import\".
"))
{}

FilterPMail::~FilterPMail()
{
    endImport();
}

void FilterPMail::import(FilterInfo *info)
{
    inf = info;

    // Select directory from where I have to import files
    KFileDialog *kfd;
    kfd = new KFileDialog( QDir::homeDirPath(), "", 0, "kfiledialog", true );
    kfd->setMode(KFile::Directory | KFile::LocalOnly);
    kfd->exec();
    chosenDir = kfd->selectedFile();

    if (chosenDir.isEmpty()) {
        info->alert(i18n("No directory selected."));
        return;
    }

    // Count total number of files to be processed
    info->addLog(i18n("Counting files..."));
    dir.setPath (chosenDir);
    QStringList files = dir.entryList("*.[cC][nN][mM]; *.[pP][mM][mM]; *.[mM][bB][xX]", QDir::Files, QDir::Name);
    totalFiles = files.count();
    currentFile = 0;
    kdDebug() << "Count is " << totalFiles << endl;

    if(!(folderParsed = parseFolderMatrix())) {
        info->addLog(i18n("Can't parse the folder structure. Continue import without subfolder support!"));
    }

    info->addLog(i18n("Importing new mail files ('.cnm')..."));
    processFiles("*.[cC][nN][mM]", &FilterPMail::importNewMessage);
    info->addLog(i18n("Importing mail folders ('.pmm')..."));
    processFiles("*.[pP][mM][mM]", &FilterPMail::importMailFolder);
    info->addLog(i18n("Importing 'UNIX' mail folders ('.mbx')..."));
    processFiles("*.[mM][bB][xX]", &FilterPMail::importUnixMailFolder);

    info->addLog( i18n("Finished importing emails from %1").arg( chosenDir ));
    info->setCurrent(100);
    info->setOverall(100);
}

/** this looks for all files with the filemask 'mask' and calls the 'workFunc' on each of them */
void FilterPMail::processFiles(const QString& mask, void(FilterPMail::* workFunc)(const QString&) )
{
    if (inf->shouldTerminate()) return;

    QStringList files = dir.entryList(mask, QDir::Files, QDir::Name);
    //kdDebug() << "Mask is " << mask << " count is " << files.count() << endl;
    for ( QStringList::Iterator mailFile = files.begin(); mailFile != files.end(); ++mailFile ) {
        // Notify current file
        QFileInfo mailfileinfo(*mailFile);
        inf->setFrom(mailfileinfo.fileName());

        // Clear the other fields
        inf->setTo(QString::null);
        inf->setCurrent(QString::null);
        inf->setCurrent(-1);

        // call worker function, increase progressbar
        (this->*workFunc)(dir.filePath(*mailFile));
        ++currentFile;
        inf->setOverall( (int) ((float) currentFile / totalFiles * 100));
        inf->setCurrent( 100 );
        if (inf->shouldTerminate()) return;
    }
}

/** this function imports one *.CNM message */
void FilterPMail::importNewMessage(const QString& file)
{
    QString destFolder("PegasusMail-Import/New Messages");
    inf->setTo(destFolder);

    /* comment by Danny Kukawka:
     * addMessage() == old function, need more time and check for duplicates
     * addMessage_fastImport == new function, faster and no check for duplicates
     */
    if(inf->removeDupMsg)
        addMessage( inf, destFolder, file );
    else
        addMessage_fastImport( inf, destFolder, file );
}

/** this function imports one mail folder file (*.PMM) */
void FilterPMail::importMailFolder(const QString& file)
{
    // Format of a PMM file:
    // First comes a header with 128 bytes. At the beginning is the name of
    // the folder. Then there are some unknown bytes (strings). At offset 128
    // the first message starts.
    //
    // Each message is terminated by a 0x1A byte. The next message follows
    // immediately.
    //
    // The last message is followed by a 0x1A, too.
    //
    // 000000 6d 61 69 6c 73 65 72 76 65 72 2d 70 72 6f 6a 65    mailserver-proje
    // 000010 63 74 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ct..............
    // 000020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
    // 000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
    // 000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
    // 000050 00 00 00 00 00 00 36 30 34 37 35 37 32 45 3a 36    ......6047572E:6
    // 000060 46 34 39 3a 46 4f 4c 30 31 33 35 35 00 00 00 00    F49:FOL01355....
    // 000070 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
    // 000080 52 65 74 75 72 6e 2d 50 61 74 68 3a 20 3c 75 72    Return-Path: <ur
    // ...
    // 000cb0 2d 2d 2d 2d 2d 2d 2d 2d 2d 2b 0d 0a 1a 52 65 74    ---------+...Ret
    // 000cc0 75 72 6e 2d 50 61 74 68 3a 20 3c 62 6f 75 6e 63    urn-Path: <bounc
    // ...
    // 04dc50 46 30 33 38 44 2e 36 31 35 44 37 34 44 30 2d 2d    F038D.615D74D0--
    // 04dc60 0d 0a 1a

    struct {
        char folder[86];
        char id[42];
    } pmm_head;

    long l = 0;
    QFile f(file);
    if (!f.open(IO_ReadOnly)) {
        inf->alert(i18n("Unable to open %1, skipping").arg(file));
    } else {
        // Get folder name
        l = f.readBlock((char *) &pmm_head, sizeof(pmm_head));
        QString folder("PegasusMail-Import/");
        if(folderParsed)
            folder.append(getFolderName((QString)pmm_head.id));
        else
            folder.append(pmm_head.folder);
        inf->setTo(folder);
        inf->addLog(i18n("Importing %1").arg("../" + QString(pmm_head.folder)));

        QByteArray input(MAX_LINE);
        bool first_msg = true;

        while (!f.atEnd()) {
            KTempFile tempfile;
            inf->setCurrent( (int) ( ( (float) f.at() / f.size() ) * 100 ) );

            if(!first_msg) {
                // set the filepos back to last line minus the seperate char (0x1a)
                f.at(f.at() - l + 1);
            }

            // no problem to loose the last line in file. This only contains a seperate char
            while ( ! f.atEnd() &&  (l = f.readLine(input.data(),MAX_LINE))) {
                    if (inf->shouldTerminate()){
                        tempfile.close();
                        tempfile.unlink();
                        return;
                    }
                    if(input[0] == 0x1a ) {
                        break;
                    } else {
                        tempfile.file()->writeBlock( input, l );
                    }
            }
            tempfile.close();

            if(inf->removeDupMsg)
                addMessage( inf, folder, tempfile.name() );
            else
                addMessage_fastImport( inf, folder, tempfile.name() );

            first_msg = false;
            tempfile.unlink();
        }
    }
    f.close();
}

/** imports a 'unix' format mail folder (*.MBX) */
void FilterPMail::importUnixMailFolder(const QString& file)
{
    struct {
        char folder[58];
        char id[31];
    } pmg_head;

    QFile f;
    QString folder("PegasusMail-Import/"), s(file), seperate;
    QByteArray line(MAX_LINE);
    int n = 0, l = 0;

    /** Get the folder name */
    s.replace( QRegExp("mbx$"), "pmg");
    s.replace( QRegExp("MBX$"), "PMG");
    f.setName(s);
    if (! f.open( IO_ReadOnly ) ) {
        inf->alert( i18n("Unable to open %1, skipping").arg( s ) );
        return;
    } else {
        f.readBlock((char *) &pmg_head, sizeof(pmg_head));
        f.close();

         if(folderParsed)
            folder.append(getFolderName((QString)pmg_head.id));
        else
            folder.append(pmg_head.folder);

        inf->setTo(folder);
        inf->setTo(folder);
    }

    /** Read in the mbox */
    f.setName(file);
    if (! f.open( IO_ReadOnly ) ) {
        inf->alert( i18n("Unable to open %1, skipping").arg( s ) );
    } else {
        inf->addLog(i18n("Importing %1").arg("../" + QString(pmg_head.folder)));
        l = f.readLine( line.data(),MAX_LINE); // read the first line which is unneeded
        while ( ! f.atEnd() ) {
            KTempFile tempfile;

            // we lost the last line, which is the first line of the new message in
            // this lopp, but this is ok, because this is the seperate line with
            // "From ???@???" and we can forget them
            while ( ! f.atEnd() &&  (l = f.readLine(line.data(),MAX_LINE)) && ((seperate = line.data()).left(5) != "From ")) {
                tempfile.file()->writeBlock(line.data(), l);
                if (inf->shouldTerminate()){
                    tempfile.close();
                    tempfile.unlink();
                    return;
                }
            }
            tempfile.close();
            if(inf->removeDupMsg)
                addMessage( inf, folder, tempfile.name() );
            else
                addMessage_fastImport( inf, folder, tempfile.name() );
            tempfile.unlink();

            n++;
            inf->setCurrent(i18n("Message %1").arg(n));
            inf->setCurrent( (int) ( ( (float) f.at() / f.size() ) * 100 ) );
        }
    }
    f.close();
}

/** Parse the information about folderstructure to folderMatrix */
bool FilterPMail::parseFolderMatrix()
{
    kdDebug() << "Start parsing the foldermatrix." << endl;
    inf->addLog(i18n("Parsing the folder structure..."));

    QFile hierarch(chosenDir + "/hierarch.pm");
    if (! hierarch.open( IO_ReadOnly ) ) {
        inf->alert( i18n("Unable to open %1, skipping").arg( chosenDir + "hierarch.pm" ) );
        return false;
    } else {
        QStringList tmpList;
        QString tmpRead;
        while ( !hierarch.atEnd() &&  hierarch.readLine(tmpRead,100)) {
            QString tmpArray[5];
            tmpRead.remove(tmpRead.length() -2,2);
            QStringList tmpList = QStringList::split(",", tmpRead, false);
            int i = 0;
            for ( QStringList::Iterator it = tmpList.begin(); it != tmpList.end(); ++it, i++) {
                QString _tmp = *it;
                if(i < 5) tmpArray[i] = _tmp.remove("\"");
                else {
                    hierarch.close();
                    return false;
                }
            }
            folderMatrix.append(tmpArray);
        }
    }
    hierarch.close();
    return true;
}

/** get the foldername for a given file ID from folderMatrix */
QString FilterPMail::getFolderName(QString ID)
{
    bool found = false;
    QString folder = "";
    QString search = ID;

    while (!found)
    {
        for ( QValueList<QString[5]>::Iterator it = folderMatrix.begin(); it != folderMatrix.end(); it++) {
            QString tmp[5] = *it;

            QString _ID = tmp[2];
            if(_ID == search) {
                QString _type = tmp[0] + tmp[1];
                if(( _type == "21")) {
                    found = true;
                    break;
                }
                else {
                    folder.prepend((tmp[4] + "/"));
                    search = tmp[3];
                }
            }
        }
    }
    return folder;
}
<|endoftext|>


<commit_before>#ifndef STAN_MATH_FWD_MAT_FUN_TRACE_QUAD_FORM_HPP
#define STAN_MATH_FWD_MAT_FUN_TRACE_QUAD_FORM_HPP

#include <boost/type_traits.hpp>
#include <stan/math/prim/mat/err/check_multiplicable.hpp>
#include <stan/math/prim/mat/err/check_square.hpp>
#include <stan/math/fwd/mat/fun/multiply.hpp>
#include <stan/math/prim/mat/fun/multiply.hpp>
#include <stan/math/prim/mat/fun/transpose.hpp>
#include <stan/math/prim/mat/fun/trace.hpp>
#include <stan/math/fwd/core.hpp>

namespace stan {
  namespace math {

    template<int RA, int CA, int RB, int CB, typename T>
    inline fvar<T>
    trace_quad_form(const Eigen::Matrix<fvar<T>, RA, CA> &A,
                    const Eigen::Matrix<fvar<T>, RB, CB> &B) {
      using stan::math::multiply;
      check_square("trace_quad_form", "A", A);
      check_multiplicable("trace_quad_form",
                                      "A", A,
                                      "B", B);
      return trace(multiply(transpose(B),
                                        multiply(A, B)));
    }

    template<int RA, int CA, int RB, int CB, typename T>
    inline fvar<T>
    trace_quad_form(const Eigen::Matrix<fvar<T>, RA, CA> &A,
                    const Eigen::Matrix<double, RB, CB> &B) {
      using stan::math::multiply;
      check_square("trace_quad_form", "A", A);
      check_multiplicable("trace_quad_form",
                                      "A", A,
                                      "B", B);
      return trace(multiply(transpose(B),
                                        multiply(A, B)));
    }

    template<int RA, int CA, int RB, int CB, typename T>
    inline fvar<T>
    trace_quad_form(const Eigen::Matrix<double, RA, CA> &A,
                    const Eigen::Matrix<fvar<T>, RB, CB> &B) {
      using stan::math::multiply;
      check_square("trace_quad_form", "A", A);
      check_multiplicable("trace_quad_form",
                                      "A", A,
                                      "B", B);
      return trace(multiply(transpose(B),
                                        multiply(A, B)));
    }
  }
}

#endif

<commit_msg>removed using statements<commit_after>#ifndef STAN_MATH_FWD_MAT_FUN_TRACE_QUAD_FORM_HPP
#define STAN_MATH_FWD_MAT_FUN_TRACE_QUAD_FORM_HPP

#include <boost/type_traits.hpp>
#include <stan/math/prim/mat/err/check_multiplicable.hpp>
#include <stan/math/prim/mat/err/check_square.hpp>
#include <stan/math/fwd/mat/fun/multiply.hpp>
#include <stan/math/prim/mat/fun/multiply.hpp>
#include <stan/math/prim/mat/fun/transpose.hpp>
#include <stan/math/prim/mat/fun/trace.hpp>
#include <stan/math/fwd/core.hpp>

namespace stan {
  namespace math {

    template<int RA, int CA, int RB, int CB, typename T>
    inline fvar<T>
    trace_quad_form(const Eigen::Matrix<fvar<T>, RA, CA> &A,
                    const Eigen::Matrix<fvar<T>, RB, CB> &B) {
      check_square("trace_quad_form", "A", A);
      check_multiplicable("trace_quad_form",
                                      "A", A,
                                      "B", B);
      return trace(multiply(transpose(B),
                                        multiply(A, B)));
    }

    template<int RA, int CA, int RB, int CB, typename T>
    inline fvar<T>
    trace_quad_form(const Eigen::Matrix<fvar<T>, RA, CA> &A,
                    const Eigen::Matrix<double, RB, CB> &B) {
      check_square("trace_quad_form", "A", A);
      check_multiplicable("trace_quad_form",
                                      "A", A,
                                      "B", B);
      return trace(multiply(transpose(B),
                                        multiply(A, B)));
    }

    template<int RA, int CA, int RB, int CB, typename T>
    inline fvar<T>
    trace_quad_form(const Eigen::Matrix<double, RA, CA> &A,
                    const Eigen::Matrix<fvar<T>, RB, CB> &B) {
      check_square("trace_quad_form", "A", A);
      check_multiplicable("trace_quad_form",
                                      "A", A,
                                      "B", B);
      return trace(multiply(transpose(B),
                                        multiply(A, B)));
    }
  }
}

#endif

<|endoftext|>


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

#include "config.h"
#include "NetworkStateNotifier.h"

namespace WebCore {

// Chromium doesn't currently support network state notifications. This causes
// an extra DLL to get loaded into the renderer which can slow things down a
// bit. We may want an alternate design.

void NetworkStateNotifier::updateState()
{
}

// TODO(darin): Kill this once we stop defining PLATFORM(MAC)
#if PLATFORM(MAC)
void NetworkStateNotifier::networkStateChangeTimerFired(Timer<NetworkStateNotifier>*)
{
}
#endif

#if PLATFORM(WIN) || PLATFORM(MAC)
NetworkStateNotifier::NetworkStateNotifier()
    : m_isOnLine(true)
#if PLATFORM(MAC)
    , m_networkStateChangeTimer(this, &NetworkStateNotifier::networkStateChangeTimerFired)
#endif
{
}
#endif

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

#include "config.h"
#include "NetworkStateNotifier.h"

namespace WebCore {

// Chromium doesn't currently support network state notifications. This causes
// an extra DLL to get loaded into the renderer which can slow things down a
// bit. We may want an alternate design.

void NetworkStateNotifier::updateState()
{
}

// TODO(darin): Kill this once we stop defining PLATFORM(MAC)
#if PLATFORM(MAC)
void NetworkStateNotifier::networkStateChangeTimerFired(Timer<NetworkStateNotifier>*)
{
}
#endif

#if PLATFORM(OS_WIN) || PLATFORM(MAC)
NetworkStateNotifier::NetworkStateNotifier()
    : m_isOnLine(true)
#if PLATFORM(MAC)
    , m_networkStateChangeTimer(this, &NetworkStateNotifier::networkStateChangeTimerFired)
#endif
{
}
#endif

}
<|endoftext|>


<commit_before>/*******************************************************************
 KNotes -- Notes for the KDE project

 Copyright (c) 1997-2005, The KNotes Developers

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
*******************************************************************/

#include <QCheckBox>
#include <QComboBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QTabWidget>
#include <QVBoxLayout>

#include <kapplication.h>
#include <kcolorbutton.h>
#include <kconfig.h>
#include <kfontrequester.h>
#include <kiconloader.h>
#include <klineedit.h>
#include <klocale.h>
#include <knuminput.h>
#include <kwindowsystem.h>

#include "knote.h"
#include "knoteconfigdlg.h"
#include "knotesglobalconfig.h"
#include "version.h"

KNoteConfigDlg::KNoteConfigDlg( KNoteConfig *config, const QString &title,
                                QWidget *parent, const QString &name )
  : KConfigDialog( parent, name, config ? config : KNotesGlobalConfig::self() )
{
  setFaceType( KPageDialog::List );
  setButtons( config ? Default | Ok | Apply | Cancel : Default | Ok | Cancel );
  setDefaultButton( Ok );

  setCaption( title );
#ifdef Q_WS_X11
  KWindowSystem::setIcons( winId(),
                           qApp->windowIcon().pixmap(
                             IconSize( KIconLoader::Desktop ),
                             IconSize( KIconLoader::Desktop ) ),
                           qApp->windowIcon().pixmap(
                             IconSize( KIconLoader::Small ),
                             IconSize( KIconLoader::Small ) ) );
#endif
  //setIconListAllVisible( true );
  showButtonSeparator( true );

  if ( config ) {
    addPage( makeDisplayPage( false ), i18n( "Display" ), "knotes",
             i18n( "Display Settings" ) );
    addPage( makeEditorPage( false ), i18n( "Editor" ), "accessories-text-editor",
             i18n( "Editor Settings" ) );
  } else {
    config = KNotesGlobalConfig::self();
    addPage( makeDefaultsPage(), i18n( "Defaults" ), "knotes",
             i18n( "Default Settings for New Notes" ) );
    addPage( makeActionsPage(), i18n( "Actions" ), "preferences-other",
             i18n( "Action Settings" ) );
    addPage( makeNetworkPage(), i18n( "Network" ), "network-wired",
             i18n( "Network Settings" ) );
    addPage( makeStylePage(), i18n( "Style" ), "preferences-desktop-theme",
             i18n( "Style Settings" ) );
  }

  config->setVersion( KNOTES_VERSION );
}

KNoteConfigDlg::~KNoteConfigDlg()
{
}

void KNoteConfigDlg::slotUpdateCaption()
{
  KNote *note = ::qobject_cast<KNote *>( sender() );
  if ( note ) {
    setCaption( note->name() );
  }
}

QWidget *KNoteConfigDlg::makeDisplayPage( bool defaults )
{
  QWidget *displayPage = new QWidget();
  QGridLayout *layout = new QGridLayout( displayPage );
  layout->setSpacing( spacingHint() );
  layout->setMargin( defaults ? marginHint() : 0 );

  QLabel *label_FgColor = new QLabel( i18n( "&Text color:" ), displayPage );
  label_FgColor->setObjectName( "label_FgColor" );
  layout->addWidget( label_FgColor, 0, 0 );

  KColorButton *kcfg_FgColor = new KColorButton( displayPage );
  kcfg_FgColor->setObjectName( "kcfg_FgColor" );
  label_FgColor->setBuddy( kcfg_FgColor );
  layout->addWidget( kcfg_FgColor, 0, 1 );

  QLabel *label_BgColor = new QLabel( i18n( "&Background color:" ),
                                      displayPage );
  label_BgColor->setObjectName( "label_BgColor" );
  layout->addWidget( label_BgColor, 1, 0 );

  KColorButton *kcfg_BgColor = new KColorButton( displayPage );
  kcfg_BgColor->setObjectName( "kcfg_BgColor" );
  label_BgColor->setBuddy( kcfg_BgColor );
  layout->addWidget( kcfg_BgColor, 1, 1 );

  QCheckBox *kcfg_ShowInTaskbar =
      new QCheckBox( i18n( "&Show note in taskbar" ), displayPage );
  kcfg_ShowInTaskbar->setObjectName( "kcfg_ShowInTaskbar" );

  QCheckBox *kcfg_RememberDesktop =
      new QCheckBox( i18n( "&Remember desktop" ), displayPage );
  kcfg_RememberDesktop->setObjectName( "kcfg_RememberDesktop" );

  if ( defaults ) {
    QLabel *label_Width = new QLabel( i18n( "Default &width:" ), displayPage );

    label_Width->setObjectName( "label_Width" );
    layout->addWidget( label_Width, 2, 0 );

    KIntNumInput *kcfg_Width = new KIntNumInput( displayPage );
    kcfg_Width->setObjectName( "kcfg_Width" );
    label_Width->setBuddy( kcfg_Width );
    kcfg_Width->setRange( 50, 2000, 10 );
    kcfg_Width->setSliderEnabled( false );
    layout->addWidget( kcfg_Width, 2, 1 );

    QLabel *label_Height = new QLabel( i18n( "Default &height:" ),
                                       displayPage );
    label_Height->setObjectName( "label_Height" );
    layout->addWidget( label_Height, 3, 0 );

    KIntNumInput *kcfg_Height = new KIntNumInput( displayPage );
    kcfg_Height->setObjectName( "kcfg_Height" );
    kcfg_Height->setRange( 50, 2000, 10 );
    kcfg_Height->setSliderEnabled( false );
    label_Height->setBuddy( kcfg_Height );
    layout->addWidget( kcfg_Height, 3, 1 );

    layout->addWidget( kcfg_ShowInTaskbar, 4, 0 );
    layout->addWidget( kcfg_RememberDesktop, 5, 0 );
  } else {
    layout->addWidget( kcfg_ShowInTaskbar, 2, 0 );
    layout->addWidget( kcfg_RememberDesktop, 3, 0 );
  }
  return displayPage;
}

QWidget *KNoteConfigDlg::makeEditorPage( bool defaults )
{
  QWidget *editorPage = new QWidget();
  QGridLayout *layout = new QGridLayout( editorPage );
  layout->setSpacing( spacingHint() );
  layout->setMargin( defaults ? marginHint() : 0 );

  QLabel *label_TabSize = new QLabel( i18n( "&Tab size:" ), editorPage );
  label_TabSize->setObjectName( "label_TabSize" );
  layout->addWidget( label_TabSize, 0, 0, 1, 2 );

  KIntNumInput *kcfg_TabSize = new KIntNumInput( editorPage );
  kcfg_TabSize->setObjectName( "kcfg_TabSize" );
  kcfg_TabSize->setRange( 0, 40 );
  kcfg_TabSize->setSliderEnabled( false );
  label_TabSize->setBuddy( kcfg_TabSize );
  layout->addWidget( kcfg_TabSize, 0, 2 );

  QCheckBox *kcfg_AutoIndent = new QCheckBox( i18n( "Auto &indent" ),
                                              editorPage );
  kcfg_AutoIndent->setObjectName( "kcfg_AutoIndent" );
  layout->addWidget( kcfg_AutoIndent, 1, 0, 1, 2 );

  QCheckBox *kcfg_RichText = new QCheckBox( i18n( "&Rich text" ), editorPage );
  kcfg_RichText->setObjectName( "kcfg_RichText" );
  layout->addWidget( kcfg_RichText, 1, 2 );

  QLabel *label_Font = new QLabel( i18n( "Text font:" ), editorPage );
  label_Font->setObjectName( "label_Font" );
  layout->addWidget( label_Font, 3, 0 );

  KFontRequester *kcfg_Font = new KFontRequester( editorPage );
  kcfg_Font->setObjectName( "kcfg_Font" );
  kcfg_Font->setSizePolicy( QSizePolicy( QSizePolicy::Minimum,
                                         QSizePolicy::Fixed ) );
  layout->addWidget( kcfg_Font, 3, 1, 1, 2 );

  QLabel *label_TitleFont = new QLabel( i18n( "Title font:" ), editorPage );
  label_TitleFont->setObjectName( "label_TitleFont" );
  layout->addWidget( label_TitleFont, 2, 0 );

  KFontRequester *kcfg_TitleFont = new KFontRequester( editorPage );
  kcfg_TitleFont->setObjectName( "kcfg_TitleFont" );
  kcfg_TitleFont->setSizePolicy( QSizePolicy( QSizePolicy::Minimum,
                                 QSizePolicy::Fixed ) );
  layout->addWidget( kcfg_TitleFont, 2, 1, 1, 2 );

  return editorPage;
}

QWidget *KNoteConfigDlg::makeDefaultsPage()
{
  QTabWidget *defaultsPage = new QTabWidget();
  defaultsPage->addTab( makeDisplayPage( true ), KIcon( "knotes" ),
                        i18n( "Displa&y" ) );
  defaultsPage->addTab( makeEditorPage( true ), KIcon( "document-properties" ),
                        i18n( "&Editor" ) );

  return defaultsPage;
}

QWidget *KNoteConfigDlg::makeActionsPage()
{
  QWidget *actionsPage = new QWidget();
  QGridLayout *layout = new QGridLayout( actionsPage );
  layout->setSpacing( spacingHint() );
  layout->setMargin( 0 );

  QLabel *label_MailAction = new QLabel( i18n( "&Mail action:" ), actionsPage );
  label_MailAction->setObjectName( "label_MailAction" );
  layout->addWidget( label_MailAction, 0, 0 );

  KLineEdit *kcfg_MailAction = new KLineEdit( actionsPage );
  kcfg_MailAction->setObjectName( "kcfg_MailAction" );
  label_MailAction->setBuddy( kcfg_MailAction );
  layout->addWidget( kcfg_MailAction, 0, 1 );

  return actionsPage;
}

QWidget *KNoteConfigDlg::makeNetworkPage()
{
  QWidget *networkPage = new QWidget();
  QVBoxLayout *layout = new QVBoxLayout;
  layout->setSpacing( spacingHint() );
  layout->setMargin( 0 );

  QGroupBox *incoming = new QGroupBox( i18n( "Incoming Notes" ) );
  QHBoxLayout *tmpLayout = new QHBoxLayout;

  QCheckBox *tmpChkB=new QCheckBox( i18n( "Accept incoming notes" ) );
  tmpChkB->setObjectName( "kcfg_ReceiveNotes" );
  tmpLayout->addWidget( tmpChkB );
  incoming->setLayout( tmpLayout );
  layout->addWidget( incoming );

  QGroupBox *outgoing = new QGroupBox( i18n( "Outgoing Notes" ) );
  tmpLayout = new QHBoxLayout;

  QLabel *label_SenderID = new QLabel( i18n( "&Sender ID:" ) );
  label_SenderID->setObjectName( "label_SenderID" );
  KLineEdit *kcfg_SenderID = new KLineEdit;
  kcfg_SenderID->setObjectName( "kcfg_SenderID" );
  label_SenderID->setBuddy( kcfg_SenderID );
  tmpLayout->addWidget( label_SenderID );
  tmpLayout->addWidget( kcfg_SenderID );
  outgoing->setLayout( tmpLayout );
  layout->addWidget( outgoing );

  tmpLayout = new QHBoxLayout;

  QLabel *label_Port = new QLabel( i18n( "&Port:" ) );
  label_Port->setObjectName( "label_Port" );

  tmpLayout->addWidget( label_Port );

  KIntNumInput *kcfg_Port = new KIntNumInput;
  kcfg_Port->setObjectName( "kcfg_Port" );
  kcfg_Port->setRange( 0, 65535 );
  kcfg_Port->setSliderEnabled( false );
  label_Port->setBuddy( kcfg_Port );
  tmpLayout->addWidget( kcfg_Port );
  layout->addLayout( tmpLayout );

  networkPage->setLayout( layout );
  return networkPage;
}

QWidget *KNoteConfigDlg::makeStylePage()
{
  QWidget *stylePage = new QWidget();
  QGridLayout *layout = new QGridLayout( stylePage );
  layout->setSpacing( spacingHint() );
  layout->setMargin( 0 );

  QLabel *label_Style = new QLabel( i18n( "&Style:" ), stylePage );
  label_Style->setObjectName( "label_Style" );
  layout->addWidget( label_Style, 0, 0 );

  QComboBox *kcfg_Style = new QComboBox( stylePage );
  kcfg_Style->setObjectName( "kcfg_Style" );
  QStringList list;
  list << i18n( "Plain" );
  kcfg_Style->addItems( list );
  label_Style->setBuddy( kcfg_Style );
  layout->addWidget( kcfg_Style, 0, 1 );

  return stylePage;
}

#include "knoteconfigdlg.moc"
<commit_msg>Backport: don't show this option in os != X11<commit_after>/*******************************************************************
 KNotes -- Notes for the KDE project

 Copyright (c) 1997-2005, The KNotes Developers

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
*******************************************************************/

#include <QCheckBox>
#include <QComboBox>
#include <QGridLayout>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QLabel>
#include <QTabWidget>
#include <QVBoxLayout>

#include <kapplication.h>
#include <kcolorbutton.h>
#include <kconfig.h>
#include <kfontrequester.h>
#include <kiconloader.h>
#include <klineedit.h>
#include <klocale.h>
#include <knuminput.h>
#include <kwindowsystem.h>

#include "knote.h"
#include "knoteconfigdlg.h"
#include "knotesglobalconfig.h"
#include "version.h"

KNoteConfigDlg::KNoteConfigDlg( KNoteConfig *config, const QString &title,
                                QWidget *parent, const QString &name )
  : KConfigDialog( parent, name, config ? config : KNotesGlobalConfig::self() )
{
  setFaceType( KPageDialog::List );
  setButtons( config ? Default | Ok | Apply | Cancel : Default | Ok | Cancel );
  setDefaultButton( Ok );

  setCaption( title );
#ifdef Q_WS_X11
  KWindowSystem::setIcons( winId(),
                           qApp->windowIcon().pixmap(
                             IconSize( KIconLoader::Desktop ),
                             IconSize( KIconLoader::Desktop ) ),
                           qApp->windowIcon().pixmap(
                             IconSize( KIconLoader::Small ),
                             IconSize( KIconLoader::Small ) ) );
#endif
  //setIconListAllVisible( true );
  showButtonSeparator( true );

  if ( config ) {
    addPage( makeDisplayPage( false ), i18n( "Display" ), "knotes",
             i18n( "Display Settings" ) );
    addPage( makeEditorPage( false ), i18n( "Editor" ), "accessories-text-editor",
             i18n( "Editor Settings" ) );
  } else {
    config = KNotesGlobalConfig::self();
    addPage( makeDefaultsPage(), i18n( "Defaults" ), "knotes",
             i18n( "Default Settings for New Notes" ) );
    addPage( makeActionsPage(), i18n( "Actions" ), "preferences-other",
             i18n( "Action Settings" ) );
    addPage( makeNetworkPage(), i18n( "Network" ), "network-wired",
             i18n( "Network Settings" ) );
    addPage( makeStylePage(), i18n( "Style" ), "preferences-desktop-theme",
             i18n( "Style Settings" ) );
  }

  config->setVersion( KNOTES_VERSION );
}

KNoteConfigDlg::~KNoteConfigDlg()
{
}

void KNoteConfigDlg::slotUpdateCaption()
{
  KNote *note = ::qobject_cast<KNote *>( sender() );
  if ( note ) {
    setCaption( note->name() );
  }
}

QWidget *KNoteConfigDlg::makeDisplayPage( bool defaults )
{
  QWidget *displayPage = new QWidget();
  QGridLayout *layout = new QGridLayout( displayPage );
  layout->setSpacing( spacingHint() );
  layout->setMargin( defaults ? marginHint() : 0 );

  QLabel *label_FgColor = new QLabel( i18n( "&Text color:" ), displayPage );
  label_FgColor->setObjectName( "label_FgColor" );
  layout->addWidget( label_FgColor, 0, 0 );

  KColorButton *kcfg_FgColor = new KColorButton( displayPage );
  kcfg_FgColor->setObjectName( "kcfg_FgColor" );
  label_FgColor->setBuddy( kcfg_FgColor );
  layout->addWidget( kcfg_FgColor, 0, 1 );

  QLabel *label_BgColor = new QLabel( i18n( "&Background color:" ),
                                      displayPage );
  label_BgColor->setObjectName( "label_BgColor" );
  layout->addWidget( label_BgColor, 1, 0 );

  KColorButton *kcfg_BgColor = new KColorButton( displayPage );
  kcfg_BgColor->setObjectName( "kcfg_BgColor" );
  label_BgColor->setBuddy( kcfg_BgColor );
  layout->addWidget( kcfg_BgColor, 1, 1 );

  QCheckBox *kcfg_ShowInTaskbar =
      new QCheckBox( i18n( "&Show note in taskbar" ), displayPage );
  kcfg_ShowInTaskbar->setObjectName( "kcfg_ShowInTaskbar" );

#ifdef Q_WS_X11
  QCheckBox *kcfg_RememberDesktop =
      new QCheckBox( i18n( "&Remember desktop" ), displayPage );
  kcfg_RememberDesktop->setObjectName( "kcfg_RememberDesktop" );
#endif
  if ( defaults ) {
    QLabel *label_Width = new QLabel( i18n( "Default &width:" ), displayPage );

    label_Width->setObjectName( "label_Width" );
    layout->addWidget( label_Width, 2, 0 );

    KIntNumInput *kcfg_Width = new KIntNumInput( displayPage );
    kcfg_Width->setObjectName( "kcfg_Width" );
    label_Width->setBuddy( kcfg_Width );
    kcfg_Width->setRange( 50, 2000, 10 );
    kcfg_Width->setSliderEnabled( false );
    layout->addWidget( kcfg_Width, 2, 1 );

    QLabel *label_Height = new QLabel( i18n( "Default &height:" ),
                                       displayPage );
    label_Height->setObjectName( "label_Height" );
    layout->addWidget( label_Height, 3, 0 );

    KIntNumInput *kcfg_Height = new KIntNumInput( displayPage );
    kcfg_Height->setObjectName( "kcfg_Height" );
    kcfg_Height->setRange( 50, 2000, 10 );
    kcfg_Height->setSliderEnabled( false );
    label_Height->setBuddy( kcfg_Height );
    layout->addWidget( kcfg_Height, 3, 1 );

    layout->addWidget( kcfg_ShowInTaskbar, 4, 0 );
#ifdef Q_WS_X11
    layout->addWidget( kcfg_RememberDesktop, 5, 0 );
#endif
  } else {
    layout->addWidget( kcfg_ShowInTaskbar, 2, 0 );
#ifdef Q_WS_X11
    layout->addWidget( kcfg_RememberDesktop, 3, 0 );
#endif
  }
  return displayPage;
}

QWidget *KNoteConfigDlg::makeEditorPage( bool defaults )
{
  QWidget *editorPage = new QWidget();
  QGridLayout *layout = new QGridLayout( editorPage );
  layout->setSpacing( spacingHint() );
  layout->setMargin( defaults ? marginHint() : 0 );

  QLabel *label_TabSize = new QLabel( i18n( "&Tab size:" ), editorPage );
  label_TabSize->setObjectName( "label_TabSize" );
  layout->addWidget( label_TabSize, 0, 0, 1, 2 );

  KIntNumInput *kcfg_TabSize = new KIntNumInput( editorPage );
  kcfg_TabSize->setObjectName( "kcfg_TabSize" );
  kcfg_TabSize->setRange( 0, 40 );
  kcfg_TabSize->setSliderEnabled( false );
  label_TabSize->setBuddy( kcfg_TabSize );
  layout->addWidget( kcfg_TabSize, 0, 2 );

  QCheckBox *kcfg_AutoIndent = new QCheckBox( i18n( "Auto &indent" ),
                                              editorPage );
  kcfg_AutoIndent->setObjectName( "kcfg_AutoIndent" );
  layout->addWidget( kcfg_AutoIndent, 1, 0, 1, 2 );

  QCheckBox *kcfg_RichText = new QCheckBox( i18n( "&Rich text" ), editorPage );
  kcfg_RichText->setObjectName( "kcfg_RichText" );
  layout->addWidget( kcfg_RichText, 1, 2 );

  QLabel *label_Font = new QLabel( i18n( "Text font:" ), editorPage );
  label_Font->setObjectName( "label_Font" );
  layout->addWidget( label_Font, 3, 0 );

  KFontRequester *kcfg_Font = new KFontRequester( editorPage );
  kcfg_Font->setObjectName( "kcfg_Font" );
  kcfg_Font->setSizePolicy( QSizePolicy( QSizePolicy::Minimum,
                                         QSizePolicy::Fixed ) );
  layout->addWidget( kcfg_Font, 3, 1, 1, 2 );

  QLabel *label_TitleFont = new QLabel( i18n( "Title font:" ), editorPage );
  label_TitleFont->setObjectName( "label_TitleFont" );
  layout->addWidget( label_TitleFont, 2, 0 );

  KFontRequester *kcfg_TitleFont = new KFontRequester( editorPage );
  kcfg_TitleFont->setObjectName( "kcfg_TitleFont" );
  kcfg_TitleFont->setSizePolicy( QSizePolicy( QSizePolicy::Minimum,
                                 QSizePolicy::Fixed ) );
  layout->addWidget( kcfg_TitleFont, 2, 1, 1, 2 );

  return editorPage;
}

QWidget *KNoteConfigDlg::makeDefaultsPage()
{
  QTabWidget *defaultsPage = new QTabWidget();
  defaultsPage->addTab( makeDisplayPage( true ), KIcon( "knotes" ),
                        i18n( "Displa&y" ) );
  defaultsPage->addTab( makeEditorPage( true ), KIcon( "document-properties" ),
                        i18n( "&Editor" ) );

  return defaultsPage;
}

QWidget *KNoteConfigDlg::makeActionsPage()
{
  QWidget *actionsPage = new QWidget();
  QGridLayout *layout = new QGridLayout( actionsPage );
  layout->setSpacing( spacingHint() );
  layout->setMargin( 0 );

  QLabel *label_MailAction = new QLabel( i18n( "&Mail action:" ), actionsPage );
  label_MailAction->setObjectName( "label_MailAction" );
  layout->addWidget( label_MailAction, 0, 0 );

  KLineEdit *kcfg_MailAction = new KLineEdit( actionsPage );
  kcfg_MailAction->setObjectName( "kcfg_MailAction" );
  label_MailAction->setBuddy( kcfg_MailAction );
  layout->addWidget( kcfg_MailAction, 0, 1 );

  return actionsPage;
}

QWidget *KNoteConfigDlg::makeNetworkPage()
{
  QWidget *networkPage = new QWidget();
  QVBoxLayout *layout = new QVBoxLayout;
  layout->setSpacing( spacingHint() );
  layout->setMargin( 0 );

  QGroupBox *incoming = new QGroupBox( i18n( "Incoming Notes" ) );
  QHBoxLayout *tmpLayout = new QHBoxLayout;

  QCheckBox *tmpChkB=new QCheckBox( i18n( "Accept incoming notes" ) );
  tmpChkB->setObjectName( "kcfg_ReceiveNotes" );
  tmpLayout->addWidget( tmpChkB );
  incoming->setLayout( tmpLayout );
  layout->addWidget( incoming );

  QGroupBox *outgoing = new QGroupBox( i18n( "Outgoing Notes" ) );
  tmpLayout = new QHBoxLayout;

  QLabel *label_SenderID = new QLabel( i18n( "&Sender ID:" ) );
  label_SenderID->setObjectName( "label_SenderID" );
  KLineEdit *kcfg_SenderID = new KLineEdit;
  kcfg_SenderID->setObjectName( "kcfg_SenderID" );
  label_SenderID->setBuddy( kcfg_SenderID );
  tmpLayout->addWidget( label_SenderID );
  tmpLayout->addWidget( kcfg_SenderID );
  outgoing->setLayout( tmpLayout );
  layout->addWidget( outgoing );

  tmpLayout = new QHBoxLayout;

  QLabel *label_Port = new QLabel( i18n( "&Port:" ) );
  label_Port->setObjectName( "label_Port" );

  tmpLayout->addWidget( label_Port );

  KIntNumInput *kcfg_Port = new KIntNumInput;
  kcfg_Port->setObjectName( "kcfg_Port" );
  kcfg_Port->setRange( 0, 65535 );
  kcfg_Port->setSliderEnabled( false );
  label_Port->setBuddy( kcfg_Port );
  tmpLayout->addWidget( kcfg_Port );
  layout->addLayout( tmpLayout );

  networkPage->setLayout( layout );
  return networkPage;
}

QWidget *KNoteConfigDlg::makeStylePage()
{
  QWidget *stylePage = new QWidget();
  QGridLayout *layout = new QGridLayout( stylePage );
  layout->setSpacing( spacingHint() );
  layout->setMargin( 0 );

  QLabel *label_Style = new QLabel( i18n( "&Style:" ), stylePage );
  label_Style->setObjectName( "label_Style" );
  layout->addWidget( label_Style, 0, 0 );

  QComboBox *kcfg_Style = new QComboBox( stylePage );
  kcfg_Style->setObjectName( "kcfg_Style" );
  QStringList list;
  list << i18n( "Plain" );
  kcfg_Style->addItems( list );
  label_Style->setBuddy( kcfg_Style );
  layout->addWidget( kcfg_Style, 0, 1 );

  return stylePage;
}

#include "knoteconfigdlg.moc"
<|endoftext|>


<commit_before><commit_msg>remove SJIS text<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2011 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 "base/stringprintf.h"
#include "base/string_piece.h"
#include "chrome/test/base/v8_unit_test.h"

V8UnitTest::V8UnitTest() {}

V8UnitTest::~V8UnitTest() {}

void V8UnitTest::SetUp() {
  v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
  global->Set(v8::String::New("log"),
              v8::FunctionTemplate::New(&V8UnitTest::Log));
  context_ = v8::Context::New(NULL, global);
}

void V8UnitTest::SetGlobalStringVar(const std::string& var_name,
                                    const std::string& value) {
  v8::Context::Scope context_scope(context_);
  context_->Global()->Set(v8::String::New(var_name.c_str(), var_name.length()),
                          v8::String::New(value.c_str(), value.length()));
}

void V8UnitTest::ExecuteScriptInContext(const base::StringPiece& script_source,
                                        const base::StringPiece& script_name) {
  v8::Context::Scope context_scope(context_);
  v8::HandleScope handle_scope;
  v8::Handle<v8::String> source = v8::String::New(script_source.data(),
                                                  script_source.size());
  v8::Handle<v8::String> name = v8::String::New(script_name.data(),
                                                script_source.size());

  v8::TryCatch try_catch;
  v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
  // Ensure the script compiled without errors.
  if (script.IsEmpty()) {
    FAIL() << ExceptionToString(&try_catch);
  }
  v8::Handle<v8::Value> result = script->Run();
  // Ensure the script ran without errors.
  if (result.IsEmpty()) {
    FAIL() << ExceptionToString(&try_catch);
  }
}

std::string V8UnitTest::ExceptionToString(v8::TryCatch* try_catch) {
  std::string str;
  v8::HandleScope handle_scope;
  v8::String::Utf8Value exception(try_catch->Exception());
  v8::Handle<v8::Message> message = try_catch->Message();
  if (message.IsEmpty()) {
    str.append(base::StringPrintf("%s\n", *exception));
  } else {
    v8::String::Utf8Value filename(message->GetScriptResourceName());
    int linenum = message->GetLineNumber();
    int colnum = message->GetStartColumn();
    str.append(base::StringPrintf(
        "%s:%i:%i %s\n", *filename, linenum, colnum, *exception));
    v8::String::Utf8Value sourceline(message->GetSourceLine());
    str.append(base::StringPrintf("%s\n", *sourceline));
  }
  return str;
}

void V8UnitTest::TestFunction(const std::string& function_name) {
  v8::Context::Scope context_scope(context_);
  v8::HandleScope handle_scope;

  v8::Handle<v8::Value> functionProperty =
      context_->Global()->Get(v8::String::New(function_name.c_str()));
  ASSERT_FALSE(functionProperty.IsEmpty());
  ASSERT_TRUE(functionProperty->IsFunction());
  v8::Handle<v8::Function> function =
      v8::Handle<v8::Function>::Cast(functionProperty);

  v8::TryCatch try_catch;
  v8::Handle<v8::Value> result = function->Call(context_->Global(), 0, NULL);
  // The test fails if an exception was thrown.
  if (result.IsEmpty()) {
    FAIL() << ExceptionToString(&try_catch);
  }
}

// static
v8::Handle<v8::Value> V8UnitTest::Log(const v8::Arguments& args) {
  std::string message;
  bool first = true;
  for (int i = 0; i < args.Length(); i++) {
    v8::HandleScope handle_scope;
    if (first) {
      first = false;
    } else {
      message += " ";
    }
    v8::String::Utf8Value str(args[i]);
    message += *str;
  }
  std::cout << message << "\n";
  return v8::Undefined();
}
<commit_msg>Fix a typo that led to OOB read of kJsonSchema in JsonSchemaTest.TestFormatError<commit_after>// Copyright (c) 2011 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 "base/stringprintf.h"
#include "base/string_piece.h"
#include "chrome/test/base/v8_unit_test.h"

V8UnitTest::V8UnitTest() {}

V8UnitTest::~V8UnitTest() {}

void V8UnitTest::SetUp() {
  v8::Handle<v8::ObjectTemplate> global = v8::ObjectTemplate::New();
  global->Set(v8::String::New("log"),
              v8::FunctionTemplate::New(&V8UnitTest::Log));
  context_ = v8::Context::New(NULL, global);
}

void V8UnitTest::SetGlobalStringVar(const std::string& var_name,
                                    const std::string& value) {
  v8::Context::Scope context_scope(context_);
  context_->Global()->Set(v8::String::New(var_name.c_str(), var_name.length()),
                          v8::String::New(value.c_str(), value.length()));
}

void V8UnitTest::ExecuteScriptInContext(const base::StringPiece& script_source,
                                        const base::StringPiece& script_name) {
  v8::Context::Scope context_scope(context_);
  v8::HandleScope handle_scope;
  v8::Handle<v8::String> source = v8::String::New(script_source.data(),
                                                  script_source.size());
  v8::Handle<v8::String> name = v8::String::New(script_name.data(),
                                                script_name.size());

  v8::TryCatch try_catch;
  v8::Handle<v8::Script> script = v8::Script::Compile(source, name);
  // Ensure the script compiled without errors.
  if (script.IsEmpty()) {
    FAIL() << ExceptionToString(&try_catch);
  }
  v8::Handle<v8::Value> result = script->Run();
  // Ensure the script ran without errors.
  if (result.IsEmpty()) {
    FAIL() << ExceptionToString(&try_catch);
  }
}

std::string V8UnitTest::ExceptionToString(v8::TryCatch* try_catch) {
  std::string str;
  v8::HandleScope handle_scope;
  v8::String::Utf8Value exception(try_catch->Exception());
  v8::Handle<v8::Message> message = try_catch->Message();
  if (message.IsEmpty()) {
    str.append(base::StringPrintf("%s\n", *exception));
  } else {
    v8::String::Utf8Value filename(message->GetScriptResourceName());
    int linenum = message->GetLineNumber();
    int colnum = message->GetStartColumn();
    str.append(base::StringPrintf(
        "%s:%i:%i %s\n", *filename, linenum, colnum, *exception));
    v8::String::Utf8Value sourceline(message->GetSourceLine());
    str.append(base::StringPrintf("%s\n", *sourceline));
  }
  return str;
}

void V8UnitTest::TestFunction(const std::string& function_name) {
  v8::Context::Scope context_scope(context_);
  v8::HandleScope handle_scope;

  v8::Handle<v8::Value> functionProperty =
      context_->Global()->Get(v8::String::New(function_name.c_str()));
  ASSERT_FALSE(functionProperty.IsEmpty());
  ASSERT_TRUE(functionProperty->IsFunction());
  v8::Handle<v8::Function> function =
      v8::Handle<v8::Function>::Cast(functionProperty);

  v8::TryCatch try_catch;
  v8::Handle<v8::Value> result = function->Call(context_->Global(), 0, NULL);
  // The test fails if an exception was thrown.
  if (result.IsEmpty()) {
    FAIL() << ExceptionToString(&try_catch);
  }
}

// static
v8::Handle<v8::Value> V8UnitTest::Log(const v8::Arguments& args) {
  std::string message;
  bool first = true;
  for (int i = 0; i < args.Length(); i++) {
    v8::HandleScope handle_scope;
    if (first) {
      first = false;
    } else {
      message += " ";
    }
    v8::String::Utf8Value str(args[i]);
    message += *str;
  }
  std::cout << message << "\n";
  return v8::Undefined();
}
<|endoftext|>


<commit_before><commit_msg>Pass mesh by const& in new texture extraction<commit_after><|endoftext|>