<commit_before>#include "NumberTest.h"
#include "SimpleAudioEngine.h"
#include "LanguageManager.h"
#include "Planet.h"

USING_NS_CC;
using namespace CocosDenshion;

bool NumberTest::tutActive = true;
NumberTest * NumberTest::create(int _number, Sprite * _bg)
{
	NumberTest * tip = new NumberTest();

	if (tip && tip->init())
	{
		tip->autorelease();
		tip->initNumberTest(_number, _bg);
		return tip;
	}
	CC_SAFE_DELETE(tip);
	return NULL;
}

NumberTest::~NumberTest()
{

}

void NumberTest::initNumberTest(int _number, Sprite * _bg)
{
	number = _number;
	setupDirector();
	setupBoundary();
	setupSprite();
	setupAudio();
	setupLabel();
	consumed = false;
	this->setScale(0.9);
	bg = _bg;
	NumberTest::tutActive = true;
	BaseObject::initObject();
}

void NumberTest::setupDirector()
{
	visibleSize = Director::getInstance()->getVisibleSize();
	winSize = Director::getInstance()->getWinSize(); //design size?
	frameSize = Director::getInstance()->getOpenGLView()->getFrameSize();
	origin = Director::getInstance()->getVisibleOrigin(); // common to all maps i hope
}

void NumberTest::setupBoundary()
{
	boundary.shape = SHAPE::circle;
	boundary.active = true;
	boundary.r = 20;
}

void NumberTest::setupSprite()
{
	auto sprite = Sprite::createWithSpriteFrameName("tip.png");
	auto moveUp = EaseInOut::create(MoveBy::create(2, Vec2(0, 5.0f)), 2);
	auto moveBack = EaseInOut::create(MoveBy::create(2, Vec2(0, -5.0f)), 2);
	auto seq1 = Sequence::create(moveUp, moveBack, nullptr);
	sprite->runAction(RepeatForever::create(seq1));
	this->addChild(sprite);
}

void NumberTest::setupAudio()
{
	auto audio = SimpleAudioEngine::getInstance();
	audio->preloadEffect("sfx/bot.wav");
	audio->preloadEffect("sfx/correct.wav");
	langCode = "en";
	if (CCApplication::getInstance()->getCurrentLanguage() == LanguageType::SWAHILI)
		langCode = "sw";
	for (int i = 0; i <= 10; i++)
	{
		audio->preloadEffect(("sfx/" + langCode + "/digit_" + std::to_string(i) + ".wav").c_str());
	}
}

void NumberTest::setupLabel()
{
	numberLabel = Label::createWithTTF(std::to_string(number), LanguageManager::getString("font"), 50);
	numberLabel->setPosition(Vec2(0, 100));
	auto action0 = ScaleTo::create(0.3f, 1.1f, 1.1f);
	auto action1 = ScaleTo::create(0.3f, 0.99f, 0.99f);
	ActionInterval *bouncingAction = Sequence::create(action0, action1, nullptr);
	auto action = RepeatForever::create(bouncingAction);
	numberLabel->runAction(action);
	numberLabel->setVisible(false);
	this->addChild(numberLabel);
}

void NumberTest::addTut(Vec2 position)
{
	Sprite * touch = Sprite::createWithSpriteFrameName("touch.png");
	touch->setPosition(position);
	touch->setOpacity(200);
	float d = 0.7;
	auto fadeO = FadeTo::create(d, 10);
	auto fadeI = FadeTo::create(d, 70);
	auto fadeTouch = Sequence::create(fadeO, fadeI, NULL);
	touch->runAction(RepeatForever::create(fadeTouch));
	touch->setScale(0.5);

	Vec2 handPosition = position + Vec2(0, -20);
	Sprite * hand = Sprite::createWithSpriteFrameName("hand.png");
	hand->setPosition(handPosition);
	hand->setOpacity(70);
	hand->setScale(0.5);

	bg->addChild(touch);
	bg->addChild(hand);
}

void NumberTest::update(bool hit)
{
	if (hit && !isMessagevisible && !consumed)
	{
		auto audio = SimpleAudioEngine::getInstance();
		isMessagevisible = true;
		audio->playEffect("sfx/bot.wav");

		Vector<FiniteTimeAction *>  allActions;
		auto action = MoveTo::create(1.5, Vec2(0, 0));
		TargetedAction * t1 = TargetedAction::create(bg, action);
		allActions.pushBack(t1);

		Vector<MenuItem *> menuItems;
		auto wrongChoice = [this, audio](Ref * sender) {
			audio->playEffect("sfx/hurt.wav");
		};
		auto rightChoice = [this, audio](Ref * sender) {
			audio->playEffect("sfx/correct.wav");
			auto * moveUp = MoveTo::create(1.5, Vec2(0, visibleSize.height));
			bg->runAction(moveUp);
			bg->removeAllChildren();
			consumed = true;
			numberLabel->setVisible(true);
		};

		int n = -1;
		int n2 = -1;
		int n3 = -1;
		int correctPicked = RandomHelper::random_int(1, 3);
		Label * labelA = Label::createWithTTF("", LanguageManager::getString("font"), 120);
		labelA->setScale(0.9);
		MenuItemLabel * mLabelA;
		if (correctPicked == 1)
		{
			labelA->setString(std::to_string(number));
			mLabelA = MenuItemLabel::create(labelA, rightChoice);
		}
		else
		{
			n = RandomHelper::random_int(1, 10);
			while (n == number)
			{
				n = RandomHelper::random_int(1, 10);
			}
			n2 = n;
			labelA->setString(std::to_string(n));
			mLabelA = MenuItemLabel::create(labelA, wrongChoice);
		}

		Label * labelB = Label::createWithTTF("", LanguageManager::getString("font"), 120);
		labelB->setScale(0.9);
		MenuItemLabel * mLabelB;
		if (correctPicked == 2)
		{
			labelB->setString(std::to_string(number));
			mLabelB = MenuItemLabel::create(labelB, rightChoice);
		}
		else
		{
			n = RandomHelper::random_int(1, 10);
			while (n == number || n == n2)
			{
				n = RandomHelper::random_int(1, 10);
			}
			n3 = n;
			labelB->setString(std::to_string(n));
			mLabelB = MenuItemLabel::create(labelB, wrongChoice);
		}

		Label * labelC = Label::createWithTTF("", LanguageManager::getString("font"), 120);
		labelC->setScale(0.9);
		MenuItemLabel * mLabelC;
		if (correctPicked == 3)
		{
			labelC->setString(std::to_string(number));
			mLabelC = MenuItemLabel::create(labelC, rightChoice);
		}
		else
		{
			n = RandomHelper::random_int(1, 10);
			while (n == number || n == n3 || n == n2)
			{
				n = RandomHelper::random_int(1, 10);
			}
			labelC->setString(std::to_string(n));
			mLabelC = MenuItemLabel::create(labelC, wrongChoice);
		}

		auto scaleUp = ScaleTo::create(1, 1.01);
		auto scaleDown = ScaleTo::create(1, 1);
		auto seqScale = Sequence::create(scaleUp, scaleDown, NULL);
		auto repScale = RepeatForever::create(seqScale);
		labelA->runAction(repScale);
		labelB->runAction(repScale->clone());
		labelC->runAction(repScale->clone());

		menuItems.pushBack(mLabelA);
		menuItems.pushBack(mLabelB);
		menuItems.pushBack(mLabelC);
		Menu * menu = Menu::createWithArray(menuItems);
		menu->setPosition(Vec2(visibleSize.width - 100, visibleSize.height / 2));
		menu->alignItemsVerticallyWithPadding(-20);
		menu->setEnabled(false);

		menu->setOpacity(100);
		bg->addChild(menu);

		auto scaleTo1 = ScaleTo::create(1.3, 1);
		int vLevel = 2;
		int hLevel = 1;
		for (int i = 1; i <= number; i++)
		{
			auto planet = Planet::create(-1);
			planet->setPosition(Vec2(105 * hLevel - 40, vLevel * visibleSize.height / 3));
			bg->addChild(planet);
			hLevel++;
			if (i == 5)
			{
				vLevel = 1;
				hLevel = 1;
			}
			planet->setScale(0.01);
			TargetedAction * tA = TargetedAction::create(planet, scaleTo1);
			allActions.pushBack(tA);
			auto playAudio = CallFunc::create([this, i]() {
				auto audio = SimpleAudioEngine::getInstance();
				audio->playEffect(("sfx/" + langCode + "/digit_" + std::to_string(i) + ".wav").c_str());
			});
			allActions.pushBack(playAudio);
		}
		auto * delay = DelayTime::create(1);
		allActions.pushBack(delay);

		auto * fadeIn = FadeIn::create(0.5);
		TargetedAction * fadeInMenu = TargetedAction::create(menu, fadeIn);
		allActions.pushBack(fadeInMenu);

		auto * enableMenuLambda = CallFunc::create([this, menu]() {
			menu->setEnabled(true);
			if (NumberTest::tutActive)
			{
				addTut(Vec2(visibleSize.width - 100, visibleSize.height / 2 - 230));
				addTut(Vec2(visibleSize.width - 100, visibleSize.height / 2 - 60));
				addTut(Vec2(visibleSize.width - 100, visibleSize.height / 2 + 110));
				NumberTest::tutActive = false;
			}
		});
		allActions.pushBack(enableMenuLambda);

		auto seq = Sequence::create(allActions);
		bg->stopAllActions();
		bg->runAction(seq);
	}
	else if (!hit && isMessagevisible)
	{
		isMessagevisible = false;
		auto action = MoveTo::create(1.5, Vec2(0, visibleSize.height));
		bg->stopAllActions();
		bg->runAction(action);
		bg->removeAllChildren();
	}

	if (hit && !isMessagevisible && consumed)
	{
		isMessagevisible = true;
		auto audio = SimpleAudioEngine::getInstance();
		audio->playEffect(("sfx/" + langCode + "/digit_" + std::to_string(number) + ".wav").c_str());
	}
}

<commit_msg>Added comments to the code for adding the hands and touch indicators<commit_after>#include "NumberTest.h"
#include "SimpleAudioEngine.h"
#include "LanguageManager.h"
#include "Planet.h"

USING_NS_CC;
using namespace CocosDenshion;

bool NumberTest::tutActive = true;
NumberTest * NumberTest::create(int _number, Sprite * _bg)
{
	NumberTest * tip = new NumberTest();

	if (tip && tip->init())
	{
		tip->autorelease();
		tip->initNumberTest(_number, _bg);
		return tip;
	}
	CC_SAFE_DELETE(tip);
	return NULL;
}

NumberTest::~NumberTest()
{

}

void NumberTest::initNumberTest(int _number, Sprite * _bg)
{
	number = _number;
	setupDirector();
	setupBoundary();
	setupSprite();
	setupAudio();
	setupLabel();
	consumed = false;
	this->setScale(0.9);
	bg = _bg;
	NumberTest::tutActive = true;
	BaseObject::initObject();
}

void NumberTest::setupDirector()
{
	visibleSize = Director::getInstance()->getVisibleSize();
	winSize = Director::getInstance()->getWinSize(); //design size?
	frameSize = Director::getInstance()->getOpenGLView()->getFrameSize();
	origin = Director::getInstance()->getVisibleOrigin(); // common to all maps i hope
}

void NumberTest::setupBoundary()
{
	boundary.shape = SHAPE::circle;
	boundary.active = true;
	boundary.r = 20;
}

void NumberTest::setupSprite()
{
	auto sprite = Sprite::createWithSpriteFrameName("tip.png");
	auto moveUp = EaseInOut::create(MoveBy::create(2, Vec2(0, 5.0f)), 2);
	auto moveBack = EaseInOut::create(MoveBy::create(2, Vec2(0, -5.0f)), 2);
	auto seq1 = Sequence::create(moveUp, moveBack, nullptr);
	sprite->runAction(RepeatForever::create(seq1));
	this->addChild(sprite);
}

void NumberTest::setupAudio()
{
	auto audio = SimpleAudioEngine::getInstance();
	audio->preloadEffect("sfx/bot.wav");
	audio->preloadEffect("sfx/correct.wav");
	langCode = "en";
	if (CCApplication::getInstance()->getCurrentLanguage() == LanguageType::SWAHILI)
		langCode = "sw";
	for (int i = 0; i <= 10; i++)
	{
		audio->preloadEffect(("sfx/" + langCode + "/digit_" + std::to_string(i) + ".wav").c_str());
	}
}

void NumberTest::setupLabel()
{
	numberLabel = Label::createWithTTF(std::to_string(number), LanguageManager::getString("font"), 50);
	numberLabel->setPosition(Vec2(0, 100));
	auto action0 = ScaleTo::create(0.3f, 1.1f, 1.1f);
	auto action1 = ScaleTo::create(0.3f, 0.99f, 0.99f);
	ActionInterval *bouncingAction = Sequence::create(action0, action1, nullptr);
	auto action = RepeatForever::create(bouncingAction);
	numberLabel->runAction(action);
	numberLabel->setVisible(false);
	this->addChild(numberLabel);
}

/*
	Adds the hand and touch indicators at the specified position for instruction
*/
void NumberTest::addTut(Vec2 position)
{
	Sprite * touch = Sprite::createWithSpriteFrameName("touch.png");
	touch->setPosition(position);
	touch->setOpacity(200);
	float d = 0.7;
	auto fadeO = FadeTo::create(d, 10);
	auto fadeI = FadeTo::create(d, 70);
	auto fadeTouch = Sequence::create(fadeO, fadeI, NULL);
	touch->runAction(RepeatForever::create(fadeTouch));
	touch->setScale(0.5);

	Vec2 handPosition = position + Vec2(0, -20);
	Sprite * hand = Sprite::createWithSpriteFrameName("hand.png");
	hand->setPosition(handPosition);
	hand->setOpacity(70);
	hand->setScale(0.5);

	bg->addChild(touch);
	bg->addChild(hand);
}

void NumberTest::update(bool hit)
{
	if (hit && !isMessagevisible && !consumed)
	{
		auto audio = SimpleAudioEngine::getInstance();
		isMessagevisible = true;
		audio->playEffect("sfx/bot.wav");

		Vector<FiniteTimeAction *>  allActions;
		auto action = MoveTo::create(1.5, Vec2(0, 0));
		TargetedAction * t1 = TargetedAction::create(bg, action);
		allActions.pushBack(t1);

		Vector<MenuItem *> menuItems;
		auto wrongChoice = [this, audio](Ref * sender) {
			audio->playEffect("sfx/hurt.wav");
		};
		auto rightChoice = [this, audio](Ref * sender) {
			audio->playEffect("sfx/correct.wav");
			auto * moveUp = MoveTo::create(1.5, Vec2(0, visibleSize.height));
			bg->runAction(moveUp);
			bg->removeAllChildren();
			consumed = true;
			numberLabel->setVisible(true);
		};

		int n = -1;
		int n2 = -1;
		int n3 = -1;
		int correctPicked = RandomHelper::random_int(1, 3);
		Label * labelA = Label::createWithTTF("", LanguageManager::getString("font"), 120);
		labelA->setScale(0.9);
		MenuItemLabel * mLabelA;
		if (correctPicked == 1)
		{
			labelA->setString(std::to_string(number));
			mLabelA = MenuItemLabel::create(labelA, rightChoice);
		}
		else
		{
			n = RandomHelper::random_int(1, 10);
			while (n == number)
			{
				n = RandomHelper::random_int(1, 10);
			}
			n2 = n;
			labelA->setString(std::to_string(n));
			mLabelA = MenuItemLabel::create(labelA, wrongChoice);
		}

		Label * labelB = Label::createWithTTF("", LanguageManager::getString("font"), 120);
		labelB->setScale(0.9);
		MenuItemLabel * mLabelB;
		if (correctPicked == 2)
		{
			labelB->setString(std::to_string(number));
			mLabelB = MenuItemLabel::create(labelB, rightChoice);
		}
		else
		{
			n = RandomHelper::random_int(1, 10);
			while (n == number || n == n2)
			{
				n = RandomHelper::random_int(1, 10);
			}
			n3 = n;
			labelB->setString(std::to_string(n));
			mLabelB = MenuItemLabel::create(labelB, wrongChoice);
		}

		Label * labelC = Label::createWithTTF("", LanguageManager::getString("font"), 120);
		labelC->setScale(0.9);
		MenuItemLabel * mLabelC;
		if (correctPicked == 3)
		{
			labelC->setString(std::to_string(number));
			mLabelC = MenuItemLabel::create(labelC, rightChoice);
		}
		else
		{
			n = RandomHelper::random_int(1, 10);
			while (n == number || n == n3 || n == n2)
			{
				n = RandomHelper::random_int(1, 10);
			}
			labelC->setString(std::to_string(n));
			mLabelC = MenuItemLabel::create(labelC, wrongChoice);
		}

		auto scaleUp = ScaleTo::create(1, 1.01);
		auto scaleDown = ScaleTo::create(1, 1);
		auto seqScale = Sequence::create(scaleUp, scaleDown, NULL);
		auto repScale = RepeatForever::create(seqScale);
		labelA->runAction(repScale);
		labelB->runAction(repScale->clone());
		labelC->runAction(repScale->clone());

		menuItems.pushBack(mLabelA);
		menuItems.pushBack(mLabelB);
		menuItems.pushBack(mLabelC);
		Menu * menu = Menu::createWithArray(menuItems);
		menu->setPosition(Vec2(visibleSize.width - 100, visibleSize.height / 2));
		menu->alignItemsVerticallyWithPadding(-20);
		menu->setEnabled(false);

		menu->setOpacity(100);
		bg->addChild(menu);

		auto scaleTo1 = ScaleTo::create(1.3, 1);
		int vLevel = 2;
		int hLevel = 1;
		for (int i = 1; i <= number; i++)
		{
			auto planet = Planet::create(-1);
			planet->setPosition(Vec2(105 * hLevel - 40, vLevel * visibleSize.height / 3));
			bg->addChild(planet);
			hLevel++;
			if (i == 5)
			{
				vLevel = 1;
				hLevel = 1;
			}
			planet->setScale(0.01);
			TargetedAction * tA = TargetedAction::create(planet, scaleTo1);
			allActions.pushBack(tA);
			auto playAudio = CallFunc::create([this, i]() {
				auto audio = SimpleAudioEngine::getInstance();
				audio->playEffect(("sfx/" + langCode + "/digit_" + std::to_string(i) + ".wav").c_str());
			});
			allActions.pushBack(playAudio);
		}
		auto * delay = DelayTime::create(1);
		allActions.pushBack(delay);

		auto * fadeIn = FadeIn::create(0.5);
		TargetedAction * fadeInMenu = TargetedAction::create(menu, fadeIn);
		allActions.pushBack(fadeInMenu);

		auto * enableMenuLambda = CallFunc::create([this, menu]() {
			menu->setEnabled(true);
			//Add the hand and touch indicators next to each of the numbers,
			//tutActive will be set to false so the hands show up only the first time
			if (NumberTest::tutActive)
			{
				//visibleSize correspond to the size currently visible in the screen
				addTut(Vec2(visibleSize.width - 100, visibleSize.height / 2 - 230));
				addTut(Vec2(visibleSize.width - 100, visibleSize.height / 2 - 60));
				addTut(Vec2(visibleSize.width - 100, visibleSize.height / 2 + 110));
				NumberTest::tutActive = false;
			}
		});
		allActions.pushBack(enableMenuLambda);

		auto seq = Sequence::create(allActions);
		bg->stopAllActions();
		bg->runAction(seq);
	}
	else if (!hit && isMessagevisible)
	{
		isMessagevisible = false;
		auto action = MoveTo::create(1.5, Vec2(0, visibleSize.height));
		bg->stopAllActions();
		bg->runAction(action);
		bg->removeAllChildren();
	}

	if (hit && !isMessagevisible && consumed)
	{
		isMessagevisible = true;
		auto audio = SimpleAudioEngine::getInstance();
		audio->playEffect(("sfx/" + langCode + "/digit_" + std::to_string(number) + ".wav").c_str());
	}
}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qplacesearchrequest.h"
#include "qgeocoordinate.h"
#include "qgeoboundingarea.h"

#include <QtCore/QSharedData>

QT_BEGIN_NAMESPACE

class QPlaceSearchRequestPrivate : public QSharedData
{
public:
    QPlaceSearchRequestPrivate();
    QPlaceSearchRequestPrivate(const QPlaceSearchRequestPrivate &other);
    ~QPlaceSearchRequestPrivate();

    QPlaceSearchRequestPrivate &operator=(const QPlaceSearchRequestPrivate &other);
    bool operator==(const QPlaceSearchRequestPrivate &other) const;

    void clear();

    QString searchTerm;
    QList<QPlaceCategory> categories;
    QGeoBoundingArea  *searchArea;
    int dymNumber;
    QtLocation::VisibilityScope visibilityScope;
    QPlaceSearchRequest::RelevanceHint relevanceHint;
    int limit;
    int offset;
};

QPlaceSearchRequestPrivate::QPlaceSearchRequestPrivate()
    :   QSharedData(),
        searchArea(0), dymNumber(0),
        visibilityScope(QtLocation::UnspecifiedVisibility), relevanceHint(QPlaceSearchRequest::UnspecifiedHint),
        limit(-1), offset(0)
{
}

QPlaceSearchRequestPrivate::QPlaceSearchRequestPrivate(const QPlaceSearchRequestPrivate &other)
    : QSharedData(other),
      searchTerm(other.searchTerm),
      categories(other.categories),
      dymNumber(other.dymNumber),
      visibilityScope(other.visibilityScope),
      relevanceHint(other.relevanceHint),
      limit(other.limit),
      offset(other.offset)
{

    if (other.searchArea)
        searchArea = other.searchArea->clone();
    else
        searchArea = 0;
}

QPlaceSearchRequestPrivate::~QPlaceSearchRequestPrivate()
{
    delete searchArea;
}

QPlaceSearchRequestPrivate &QPlaceSearchRequestPrivate::operator=(const QPlaceSearchRequestPrivate &other)
{
    searchTerm = other.searchTerm;
    categories = other.categories;
    if (other.searchArea)
        searchArea = other.searchArea->clone();
    else
        searchArea = 0;
    dymNumber = other.dymNumber;
    visibilityScope = other.visibilityScope;
    relevanceHint = other.relevanceHint;
    limit = other.limit;
    offset = other.offset;
}

bool QPlaceSearchRequestPrivate::operator==(const QPlaceSearchRequestPrivate &other) const
{
    bool searchAreaMatch = false;
    if ((searchArea == 0) && (other.searchArea == 0)) {
        searchAreaMatch = true;
    } else if (searchArea && other.searchArea) {
        if (*searchArea == *(other.searchArea))
            searchAreaMatch = true;
        else
            searchAreaMatch = false;
    } else {
        searchAreaMatch = false;
    }

    return (
            searchTerm == other.searchTerm
            && categories == other.categories
            && dymNumber == other.dymNumber
            && searchAreaMatch
            && visibilityScope == other.visibilityScope
            && relevanceHint == other.relevanceHint
            && limit == other.limit
            && offset == other.offset
    );
}

void QPlaceSearchRequestPrivate::clear()
{
    limit = -1;
    offset = 0;
    searchTerm.clear();
    categories.clear();
    delete searchArea;
    searchArea = 0;
    dymNumber = 0;
    visibilityScope = QtLocation::UnspecifiedVisibility;
    relevanceHint = QPlaceSearchRequest::UnspecifiedHint;
}

/*!
    \class QPlaceSearchRequest
    \inmodule QtLocation
    \ingroup QtLocation-places
    \since QtLocation 5.0

    \brief The QPlaceSearchRequest class represents the set of parameters for a search request.

    A typical search request may look like the following:
    \snippet snippets/places/requesthandler.h Search request

    Note that specifying a search center can be done by setting a circular search area that has
    a center but no radius.    The default radius is set to -1, which indicates an undefined radius.  The provider will
    interpret this as being free to choose its own default radius.

    The QPlaceSearchRequest will assume ownership of the bounding area and will be responsible
    for its destruction.

    The QPlaceSearchRequest is primarily used with the QPlaceManager to
    \l {QPlaceManager::search()} {search for places}, however it is also
    used to provide parameters for \l {QPlaceManager::textPredictions()}{generating text predictions}
    and \l {QPlaceManager::recommendations()} {retreiving recommendations}.  Note that depending on usage
    some parameters may not be relevant, e.g. the relevance hint is not important for text predictions.  However
    in general most of the parameters are useful for each of these operations, eg for a recommendation, a search area
    and categories can be useful in narrowing down recommendation candidates.

    Also be aware that providers may vary by which parameters they support e.g. some providers may not support
    paging while others do, some providers may honor relevance hints while others may completely ignore them.
*/

/*!
    \enum QPlaceSearchRequest::RelevanceHint

    Defines hints to help rank place results.
    \value UnspecifiedHint
        No explicit hint has been specified.
    \value DistanceHint
        Distance to a search center is relevant for the user.  Closer places
        are more highly weighted.  This hint is only useful
        if a circular bounding area is used in the query.
    \value LexicalPlaceNameHint
        Alphabetic ordering of places according to name is relevant to the user.
*/

/*!
    Default constructor. Constructs an new request object.
*/
QPlaceSearchRequest::QPlaceSearchRequest()
    : d_ptr(new QPlaceSearchRequestPrivate())
{
}

/*!
    Constructs a copy of \a other.
*/
QPlaceSearchRequest::QPlaceSearchRequest(const QPlaceSearchRequest &other)
    : d_ptr(other.d_ptr)
{
}

/*!
    Destroys the request object.
*/
QPlaceSearchRequest::~QPlaceSearchRequest()
{
}

/*!
    Assigns \a other to this search request and returns a reference
    to this search request.
*/
QPlaceSearchRequest &QPlaceSearchRequest::operator= (const QPlaceSearchRequest & other)
{
    Q_D(QPlaceSearchRequest);
    d_ptr = other.d_ptr;
    return *this;
}

/*!
    Returns true if \a other is equal to this search request,
    otherwise returns false.
*/
bool QPlaceSearchRequest::operator== (const QPlaceSearchRequest &other) const
{
    Q_D(const QPlaceSearchRequest);
    return *d == *other.d_func();
}

/*!
    Returns true if \a other is not equal to this search request,
    otherwise returns false.
*/
bool QPlaceSearchRequest::operator!= (const QPlaceSearchRequest &other) const
{
    Q_D(const QPlaceSearchRequest);
    return !(*d == *other.d_func());
}

/*!
    Returns the search term.
*/
QString QPlaceSearchRequest::searchTerm() const
{
    Q_D(const QPlaceSearchRequest);
    return d->searchTerm;
}

/*!
    Sets the search \a term.
*/
void QPlaceSearchRequest::setSearchTerm(const QString &term)
{
    Q_D(QPlaceSearchRequest);
    d->searchTerm = term;
}

/*!
    Return the categories to be used in the search request.
    Places need only to belong to one of the categories
    to be considered a match by the request.
*/
QList<QPlaceCategory> QPlaceSearchRequest::categories() const
{
    Q_D(const QPlaceSearchRequest);
    return d->categories;
}

/*!
    Sets the search request to search by a single \a category

    \sa setCategories()
*/
void QPlaceSearchRequest::setCategory(const QPlaceCategory &category)
{
    Q_D(QPlaceSearchRequest);
    d->categories.clear();

    if (!category.categoryId().isEmpty())
        d->categories.append(category);
}

/*!
    Sets the search request to search from the list of given \a categories.

    It is possible that some backends may not support multiple categories.  In this case,
    the first category is used and the rest are ignored.

    \sa setCategory()
*/
void QPlaceSearchRequest::setCategories(const QList<QPlaceCategory> &categories)
{
    Q_D(QPlaceSearchRequest);
    d->categories = categories;
}

/*!
    Returns search area.  The default search area is a null pointer.
*/
QGeoBoundingArea *QPlaceSearchRequest::searchArea() const
{
    Q_D(const QPlaceSearchRequest);
    return d->searchArea;
}

/*!
    Sets the search request to search within the given \a area.  Ownership of the \a area is
    transferred to the request  who is responsible for pointer deletion.  If a new \a area
    is being assigned, the old area is deleted.
*/
void QPlaceSearchRequest::setSearchArea(QGeoBoundingArea *area)
{
    Q_D(QPlaceSearchRequest);
    if (d->searchArea != area)
        delete d->searchArea;

    d->searchArea = area;
}

/*!
    Returns the maximum number of search term corrections that may be returned.
*/
int QPlaceSearchRequest::maximumCorrections() const
{
    Q_D(const QPlaceSearchRequest);
    return d->dymNumber;
}

/*!
    Sets maximum \a number of search term corrections that may be returned.
*/
void QPlaceSearchRequest::setMaximumCorrections(int number)
{
    Q_D(QPlaceSearchRequest);
    d->dymNumber = number;
}

/*!
    Returns the visibility scope used when searching for places.  The default value is
    QtLocation::UnspecifiedVisibility meaning that no explicit scope has been assigned.  It is up
    to the manager implementation to decide what scope it searches by default.
*/
QtLocation::VisibilityScope QPlaceSearchRequest::visibilityScope() const
{
    Q_D(const QPlaceSearchRequest);
    return d->visibilityScope;
}

/*!
    Sets the visibiliy \a scope used when searching for places.
*/
void QPlaceSearchRequest::setVisibilityScope(QtLocation::VisibilityScope scope)
{
    Q_D(QPlaceSearchRequest);
    d->visibilityScope = scope;
}

/*!
    Returns the relevance hint of the request.  The hint is given to the provider
    to help but not dictate the ranking of results.  eg providng a distance hint
    may give closer places a higher ranking but it doesn't necessarily mean
    that he results will be ordered strictly according to distance.
*/
QPlaceSearchRequest::RelevanceHint QPlaceSearchRequest::relevanceHint() const
{
    Q_D(const QPlaceSearchRequest);
    return d->relevanceHint;
}

/*!
    Sets the relevance \a hint to be used when searching for a place.
*/
void QPlaceSearchRequest::setRelevanceHint(QPlaceSearchRequest::RelevanceHint hint)
{
    Q_D(QPlaceSearchRequest);
    d->relevanceHint = hint;
}

/*!
    Returns the maximum number of search results to retrieve.

    A negative value for limit means that it is undefined.  It is left up to the backend
    provider to choose an appropriate number of results to return.
*/
int QPlaceSearchRequest::limit() const
{
    Q_D(const QPlaceSearchRequest);
    return d->limit;
}

/*!
    Set the maximum number of search results to retrieve to \a limit.
*/
void QPlaceSearchRequest::setLimit(int limit)
{
    Q_D(QPlaceSearchRequest);
    d->limit = limit;
}

/*!
    Returns the index of the first item that is to be retrieved.
*/
int QPlaceSearchRequest::offset() const
{
    Q_D(const QPlaceSearchRequest);
    return d->offset;
}

/*!
    Sets the starting index of the first item to be retrieved
    to \a offset.
*/
void QPlaceSearchRequest::setOffset(int offset)
{
    Q_D(QPlaceSearchRequest);
    d->offset = offset;
}

/*!
    Clears the search request.
*/
void QPlaceSearchRequest::clear()
{
    Q_D(QPlaceSearchRequest);
    d->clear();
}

inline QPlaceSearchRequestPrivate* QPlaceSearchRequest::d_func()
{
    return static_cast<QPlaceSearchRequestPrivate *>(d_ptr.data());
}

inline const QPlaceSearchRequestPrivate* QPlaceSearchRequest::d_func() const
{
    return static_cast<const QPlaceSearchRequestPrivate *>(d_ptr.constData());
}

QT_END_NAMESPACE
<commit_msg>Make QtLocation compile<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qplacesearchrequest.h"
#include "qgeocoordinate.h"
#include "qgeoboundingarea.h"

#include <QtCore/QSharedData>
#include <QtCore/QList>

QT_BEGIN_NAMESPACE

class QPlaceSearchRequestPrivate : public QSharedData
{
public:
    QPlaceSearchRequestPrivate();
    QPlaceSearchRequestPrivate(const QPlaceSearchRequestPrivate &other);
    ~QPlaceSearchRequestPrivate();

    QPlaceSearchRequestPrivate &operator=(const QPlaceSearchRequestPrivate &other);
    bool operator==(const QPlaceSearchRequestPrivate &other) const;

    void clear();

    QString searchTerm;
    QList<QPlaceCategory> categories;
    QGeoBoundingArea  *searchArea;
    int dymNumber;
    QtLocation::VisibilityScope visibilityScope;
    QPlaceSearchRequest::RelevanceHint relevanceHint;
    int limit;
    int offset;
};

QPlaceSearchRequestPrivate::QPlaceSearchRequestPrivate()
    :   QSharedData(),
        searchArea(0), dymNumber(0),
        visibilityScope(QtLocation::UnspecifiedVisibility), relevanceHint(QPlaceSearchRequest::UnspecifiedHint),
        limit(-1), offset(0)
{
}

QPlaceSearchRequestPrivate::QPlaceSearchRequestPrivate(const QPlaceSearchRequestPrivate &other)
    : QSharedData(other),
      searchTerm(other.searchTerm),
      categories(other.categories),
      dymNumber(other.dymNumber),
      visibilityScope(other.visibilityScope),
      relevanceHint(other.relevanceHint),
      limit(other.limit),
      offset(other.offset)
{

    if (other.searchArea)
        searchArea = other.searchArea->clone();
    else
        searchArea = 0;
}

QPlaceSearchRequestPrivate::~QPlaceSearchRequestPrivate()
{
    delete searchArea;
}

QPlaceSearchRequestPrivate &QPlaceSearchRequestPrivate::operator=(const QPlaceSearchRequestPrivate &other)
{
    searchTerm = other.searchTerm;
    categories = other.categories;
    if (other.searchArea)
        searchArea = other.searchArea->clone();
    else
        searchArea = 0;
    dymNumber = other.dymNumber;
    visibilityScope = other.visibilityScope;
    relevanceHint = other.relevanceHint;
    limit = other.limit;
    offset = other.offset;
}

bool QPlaceSearchRequestPrivate::operator==(const QPlaceSearchRequestPrivate &other) const
{
    bool searchAreaMatch = false;
    if ((searchArea == 0) && (other.searchArea == 0)) {
        searchAreaMatch = true;
    } else if (searchArea && other.searchArea) {
        if (*searchArea == *(other.searchArea))
            searchAreaMatch = true;
        else
            searchAreaMatch = false;
    } else {
        searchAreaMatch = false;
    }

    return (
            searchTerm == other.searchTerm
            && categories == other.categories
            && dymNumber == other.dymNumber
            && searchAreaMatch
            && visibilityScope == other.visibilityScope
            && relevanceHint == other.relevanceHint
            && limit == other.limit
            && offset == other.offset
    );
}

void QPlaceSearchRequestPrivate::clear()
{
    limit = -1;
    offset = 0;
    searchTerm.clear();
    categories.clear();
    delete searchArea;
    searchArea = 0;
    dymNumber = 0;
    visibilityScope = QtLocation::UnspecifiedVisibility;
    relevanceHint = QPlaceSearchRequest::UnspecifiedHint;
}

/*!
    \class QPlaceSearchRequest
    \inmodule QtLocation
    \ingroup QtLocation-places
    \since QtLocation 5.0

    \brief The QPlaceSearchRequest class represents the set of parameters for a search request.

    A typical search request may look like the following:
    \snippet snippets/places/requesthandler.h Search request

    Note that specifying a search center can be done by setting a circular search area that has
    a center but no radius.    The default radius is set to -1, which indicates an undefined radius.  The provider will
    interpret this as being free to choose its own default radius.

    The QPlaceSearchRequest will assume ownership of the bounding area and will be responsible
    for its destruction.

    The QPlaceSearchRequest is primarily used with the QPlaceManager to
    \l {QPlaceManager::search()} {search for places}, however it is also
    used to provide parameters for \l {QPlaceManager::textPredictions()}{generating text predictions}
    and \l {QPlaceManager::recommendations()} {retreiving recommendations}.  Note that depending on usage
    some parameters may not be relevant, e.g. the relevance hint is not important for text predictions.  However
    in general most of the parameters are useful for each of these operations, eg for a recommendation, a search area
    and categories can be useful in narrowing down recommendation candidates.

    Also be aware that providers may vary by which parameters they support e.g. some providers may not support
    paging while others do, some providers may honor relevance hints while others may completely ignore them.
*/

/*!
    \enum QPlaceSearchRequest::RelevanceHint

    Defines hints to help rank place results.
    \value UnspecifiedHint
        No explicit hint has been specified.
    \value DistanceHint
        Distance to a search center is relevant for the user.  Closer places
        are more highly weighted.  This hint is only useful
        if a circular bounding area is used in the query.
    \value LexicalPlaceNameHint
        Alphabetic ordering of places according to name is relevant to the user.
*/

/*!
    Default constructor. Constructs an new request object.
*/
QPlaceSearchRequest::QPlaceSearchRequest()
    : d_ptr(new QPlaceSearchRequestPrivate())
{
}

/*!
    Constructs a copy of \a other.
*/
QPlaceSearchRequest::QPlaceSearchRequest(const QPlaceSearchRequest &other)
    : d_ptr(other.d_ptr)
{
}

/*!
    Destroys the request object.
*/
QPlaceSearchRequest::~QPlaceSearchRequest()
{
}

/*!
    Assigns \a other to this search request and returns a reference
    to this search request.
*/
QPlaceSearchRequest &QPlaceSearchRequest::operator= (const QPlaceSearchRequest & other)
{
    Q_D(QPlaceSearchRequest);
    d_ptr = other.d_ptr;
    return *this;
}

/*!
    Returns true if \a other is equal to this search request,
    otherwise returns false.
*/
bool QPlaceSearchRequest::operator== (const QPlaceSearchRequest &other) const
{
    Q_D(const QPlaceSearchRequest);
    return *d == *other.d_func();
}

/*!
    Returns true if \a other is not equal to this search request,
    otherwise returns false.
*/
bool QPlaceSearchRequest::operator!= (const QPlaceSearchRequest &other) const
{
    Q_D(const QPlaceSearchRequest);
    return !(*d == *other.d_func());
}

/*!
    Returns the search term.
*/
QString QPlaceSearchRequest::searchTerm() const
{
    Q_D(const QPlaceSearchRequest);
    return d->searchTerm;
}

/*!
    Sets the search \a term.
*/
void QPlaceSearchRequest::setSearchTerm(const QString &term)
{
    Q_D(QPlaceSearchRequest);
    d->searchTerm = term;
}

/*!
    Return the categories to be used in the search request.
    Places need only to belong to one of the categories
    to be considered a match by the request.
*/
QList<QPlaceCategory> QPlaceSearchRequest::categories() const
{
    Q_D(const QPlaceSearchRequest);
    return d->categories;
}

/*!
    Sets the search request to search by a single \a category

    \sa setCategories()
*/
void QPlaceSearchRequest::setCategory(const QPlaceCategory &category)
{
    Q_D(QPlaceSearchRequest);
    d->categories.clear();

    if (!category.categoryId().isEmpty())
        d->categories.append(category);
}

/*!
    Sets the search request to search from the list of given \a categories.

    It is possible that some backends may not support multiple categories.  In this case,
    the first category is used and the rest are ignored.

    \sa setCategory()
*/
void QPlaceSearchRequest::setCategories(const QList<QPlaceCategory> &categories)
{
    Q_D(QPlaceSearchRequest);
    d->categories = categories;
}

/*!
    Returns search area.  The default search area is a null pointer.
*/
QGeoBoundingArea *QPlaceSearchRequest::searchArea() const
{
    Q_D(const QPlaceSearchRequest);
    return d->searchArea;
}

/*!
    Sets the search request to search within the given \a area.  Ownership of the \a area is
    transferred to the request  who is responsible for pointer deletion.  If a new \a area
    is being assigned, the old area is deleted.
*/
void QPlaceSearchRequest::setSearchArea(QGeoBoundingArea *area)
{
    Q_D(QPlaceSearchRequest);
    if (d->searchArea != area)
        delete d->searchArea;

    d->searchArea = area;
}

/*!
    Returns the maximum number of search term corrections that may be returned.
*/
int QPlaceSearchRequest::maximumCorrections() const
{
    Q_D(const QPlaceSearchRequest);
    return d->dymNumber;
}

/*!
    Sets maximum \a number of search term corrections that may be returned.
*/
void QPlaceSearchRequest::setMaximumCorrections(int number)
{
    Q_D(QPlaceSearchRequest);
    d->dymNumber = number;
}

/*!
    Returns the visibility scope used when searching for places.  The default value is
    QtLocation::UnspecifiedVisibility meaning that no explicit scope has been assigned.  It is up
    to the manager implementation to decide what scope it searches by default.
*/
QtLocation::VisibilityScope QPlaceSearchRequest::visibilityScope() const
{
    Q_D(const QPlaceSearchRequest);
    return d->visibilityScope;
}

/*!
    Sets the visibiliy \a scope used when searching for places.
*/
void QPlaceSearchRequest::setVisibilityScope(QtLocation::VisibilityScope scope)
{
    Q_D(QPlaceSearchRequest);
    d->visibilityScope = scope;
}

/*!
    Returns the relevance hint of the request.  The hint is given to the provider
    to help but not dictate the ranking of results.  eg providng a distance hint
    may give closer places a higher ranking but it doesn't necessarily mean
    that he results will be ordered strictly according to distance.
*/
QPlaceSearchRequest::RelevanceHint QPlaceSearchRequest::relevanceHint() const
{
    Q_D(const QPlaceSearchRequest);
    return d->relevanceHint;
}

/*!
    Sets the relevance \a hint to be used when searching for a place.
*/
void QPlaceSearchRequest::setRelevanceHint(QPlaceSearchRequest::RelevanceHint hint)
{
    Q_D(QPlaceSearchRequest);
    d->relevanceHint = hint;
}

/*!
    Returns the maximum number of search results to retrieve.

    A negative value for limit means that it is undefined.  It is left up to the backend
    provider to choose an appropriate number of results to return.
*/
int QPlaceSearchRequest::limit() const
{
    Q_D(const QPlaceSearchRequest);
    return d->limit;
}

/*!
    Set the maximum number of search results to retrieve to \a limit.
*/
void QPlaceSearchRequest::setLimit(int limit)
{
    Q_D(QPlaceSearchRequest);
    d->limit = limit;
}

/*!
    Returns the index of the first item that is to be retrieved.
*/
int QPlaceSearchRequest::offset() const
{
    Q_D(const QPlaceSearchRequest);
    return d->offset;
}

/*!
    Sets the starting index of the first item to be retrieved
    to \a offset.
*/
void QPlaceSearchRequest::setOffset(int offset)
{
    Q_D(QPlaceSearchRequest);
    d->offset = offset;
}

/*!
    Clears the search request.
*/
void QPlaceSearchRequest::clear()
{
    Q_D(QPlaceSearchRequest);
    d->clear();
}

inline QPlaceSearchRequestPrivate* QPlaceSearchRequest::d_func()
{
    return static_cast<QPlaceSearchRequestPrivate *>(d_ptr.data());
}

inline const QPlaceSearchRequestPrivate* QPlaceSearchRequest::d_func() const
{
    return static_cast<const QPlaceSearchRequestPrivate *>(d_ptr.constData());
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>// Scintilla source code edit control
/** @file LexScriptol.cxx
 ** Lexer for Scriptol.
 **/

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>

#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"

#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

static void ClassifyWordSol(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler, char *prevWord)
{
    char s[100];
    bool wordIsNumber = isdigit(styler[start]) != 0;
    for (unsigned int i = 0; i < end - start + 1 && i < 30; i++)
     {
           s[i] = styler[start + i];
           s[i + 1] = '\0';
     }
    char chAttr = SCE_SCRIPTOL_IDENTIFIER;
    if (0 == strcmp(prevWord, "class"))       chAttr = SCE_SCRIPTOL_CLASSNAME;
    else if (wordIsNumber)                    chAttr = SCE_SCRIPTOL_NUMBER;
    else if (keywords.InList(s))              chAttr = SCE_SCRIPTOL_KEYWORD;
    else for (unsigned int i = 0; i < end - start + 1; i++)  // test dotted idents
    {
        if (styler[start + i] == '.')
        {
            styler.ColourTo(start + i - 1, chAttr);
            styler.ColourTo(start + i, SCE_SCRIPTOL_OPERATOR);
        }
    }
    styler.ColourTo(end, chAttr);
    strcpy(prevWord, s);
}

static bool IsSolComment(Accessor &styler, int pos, int len)
{
   if(len > 0)
   {
     char c = styler[pos];
     if(c == '`') return true;
     if(len > 1)
     {
        if(c == '/')
        {
          c = styler[pos + 1];
          if(c == '/') return true;
          if(c == '*') return true;
        }
     }
   }
   return false;
}

static bool IsSolStringStart(char ch)
{
    if (ch == '\'' || ch == '"')  return true;
    return false;
}

static bool IsSolWordStart(char ch)
{
    return (iswordchar(ch) && !IsSolStringStart(ch));
}

static int GetSolStringState(Accessor &styler, int i, int *nextIndex)
{
	char ch = styler.SafeGetCharAt(i);
	char chNext = styler.SafeGetCharAt(i + 1);

        if (ch != '\"' && ch != '\'')
        {
            *nextIndex = i + 1;
            return SCE_SCRIPTOL_DEFAULT;
	}
        // ch is either single or double quotes in string
        // code below seem non-sense but is here for future extensions
	if (ch == chNext && ch == styler.SafeGetCharAt(i + 2))
        {
          *nextIndex = i + 3;
          if(ch == '\"') return SCE_SCRIPTOL_TRIPLE;
          if(ch == '\'') return SCE_SCRIPTOL_TRIPLE;
          return SCE_SCRIPTOL_STRING;
	}
        else
        {
          *nextIndex = i + 1;
          if (ch == '"') return SCE_SCRIPTOL_STRING;
          else           return SCE_SCRIPTOL_STRING;
	}
}

static void ColouriseSolDoc(unsigned int startPos, int length, int initStyle,
                            WordList *keywordlists[], Accessor &styler)
 {

	int lengthDoc = startPos + length;
        char stringType = '\"';

	if (startPos > 0)
        {
            int lineCurrent = styler.GetLine(startPos);
            if (lineCurrent > 0)
            {
              startPos = styler.LineStart(lineCurrent-1);
              if (startPos == 0) initStyle = SCE_SCRIPTOL_DEFAULT;
              else               initStyle = styler.StyleAt(startPos-1);
            }
	}

	styler.StartAt(startPos, 127);

	WordList &keywords = *keywordlists[0];

	int whingeLevel = styler.GetPropertyInt("tab.timmy.whinge.level");
	char prevWord[200];
	prevWord[0] = '\0';
        if (length == 0)  return;

	int state = initStyle & 31;

	int nextIndex = 0;
        char chPrev  = ' ';
        char chPrev2 = ' ';
        char chNext  = styler[startPos];
	styler.StartSegment(startPos);
	bool atStartLine = true;
	int spaceFlags = 0;
	for (int i = startPos; i < lengthDoc; i++)
        {

         if (atStartLine)
         {
         char chBad = static_cast<char>(64);
         char chGood = static_cast<char>(0);
         char chFlags = chGood;

         if (whingeLevel == 1)
         {
             chFlags = (spaceFlags & wsInconsistent) ? chBad : chGood;
         }
         else if (whingeLevel == 2)
         {
             chFlags = (spaceFlags & wsSpaceTab) ? chBad : chGood;
         }
         else if (whingeLevel == 3)
         {
             chFlags = (spaceFlags & wsSpace) ? chBad : chGood;
         }
         else if (whingeLevel == 4)
         {
              chFlags = (spaceFlags & wsTab) ? chBad : chGood;
         }
         styler.SetFlags(chFlags, static_cast<char>(state));
         atStartLine = false;
       }

       char ch = chNext;
       chNext = styler.SafeGetCharAt(i + 1);

       if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == lengthDoc))
       {
          if ((state == SCE_SCRIPTOL_DEFAULT) ||
              (state == SCE_SCRIPTOL_TRIPLE) ||
              (state == SCE_SCRIPTOL_COMMENTBLOCK))
          {
              styler.ColourTo(i, state);
          }
          atStartLine = true;
        }

        if (styler.IsLeadByte(ch))
         {
             chNext = styler.SafeGetCharAt(i + 2);
             chPrev  = ' ';
             chPrev2 = ' ';
             i += 1;
             continue;
         }

        if (state == SCE_SCRIPTOL_STRINGEOL)
         {
             if (ch != '\r' && ch != '\n')
             {
                    styler.ColourTo(i - 1, state);
                    state = SCE_SCRIPTOL_DEFAULT;
             }
         }

        if (state == SCE_SCRIPTOL_DEFAULT)
         {
            if (IsSolWordStart(ch))
            {
                 styler.ColourTo(i - 1, state);
                 state = SCE_SCRIPTOL_KEYWORD;
            }
            else if (ch == '`')
            {
                styler.ColourTo(i - 1, state);
                state = SCE_SCRIPTOL_COMMENTLINE;
            }
            else if (ch == '/')
            {
                styler.ColourTo(i - 1, state);
                if(chNext == '/') state = SCE_SCRIPTOL_CSTYLE;
                if(chNext == '*') state = SCE_SCRIPTOL_COMMENTBLOCK;
            }

            else if (IsSolStringStart(ch))
            {
               styler.ColourTo(i - 1, state);
               state = GetSolStringState(styler, i, &nextIndex);
               if(state == SCE_SCRIPTOL_STRING)
               {
                 stringType = ch;
               }
               if (nextIndex != i + 1)
               {
                   i = nextIndex - 1;
                   ch = ' ';
                   chPrev = ' ';
                   chNext = styler.SafeGetCharAt(i + 1);
               }
           }
            else if (isoperator(ch))
            {
                 styler.ColourTo(i - 1, state);
                 styler.ColourTo(i, SCE_SCRIPTOL_OPERATOR);
            }
          }
          else if (state == SCE_SCRIPTOL_KEYWORD)
          {
              if (!iswordchar(ch))
              {
                 ClassifyWordSol(styler.GetStartSegment(), i - 1, keywords, styler, prevWord);
                 state = SCE_SCRIPTOL_DEFAULT;
                 if (ch == '`')
                 {
                     state = chNext == '`' ? SCE_SCRIPTOL_PERSISTENT : SCE_SCRIPTOL_COMMENTLINE;
                 }
                 else if (IsSolStringStart(ch))
                 {
                    styler.ColourTo(i - 1, state);
                    state = GetSolStringState(styler, i, &nextIndex);
                    if (nextIndex != i + 1)
                    {
                       i = nextIndex - 1;
                       ch = ' ';
                       chPrev = ' ';
                       chNext = styler.SafeGetCharAt(i + 1);
                     }
                 }
                 else if (isoperator(ch))
                 {
                     styler.ColourTo(i, SCE_SCRIPTOL_OPERATOR);
                 }
             }
          }
          else
          {
            if (state == SCE_SCRIPTOL_COMMENTLINE ||
                state == SCE_SCRIPTOL_PERSISTENT ||
                state == SCE_SCRIPTOL_CSTYLE)
            {
                 if (ch == '\r' || ch == '\n')
                 {
                     styler.ColourTo(i - 1, state);
                     state = SCE_SCRIPTOL_DEFAULT;
                 }
            }
            else if(state == SCE_SCRIPTOL_COMMENTBLOCK)
            {
              if(chPrev == '*' && ch == '/')
              {
                styler.ColourTo(i, state);
                state = SCE_SCRIPTOL_DEFAULT;
              }
            }
            else if ((state == SCE_SCRIPTOL_STRING) ||
                     (state == SCE_SCRIPTOL_CHARACTER))
            {
               if ((ch == '\r' || ch == '\n') && (chPrev != '\\'))
                {
                    styler.ColourTo(i - 1, state);
                    state = SCE_SCRIPTOL_STRINGEOL;
                }
                else if (ch == '\\')
                {
                   if (chNext == '\"' || chNext == '\'' || chNext == '\\')
                   {
                        i++;
                        ch = chNext;
                        chNext = styler.SafeGetCharAt(i + 1);
                   }
                 }
                else if ((ch == '\"') || (ch == '\''))
                {
                    // must match the entered quote type
                    if(ch == stringType)
                    {
                      styler.ColourTo(i, state);
                      state = SCE_SCRIPTOL_DEFAULT;
                    }
                 }
             }
             else if (state == SCE_SCRIPTOL_TRIPLE)
             {
                if ((ch == '\'' && chPrev == '\'' && chPrev2 == '\'') ||
                    (ch == '\"' && chPrev == '\"' && chPrev2 == '\"'))
                 {
                    styler.ColourTo(i, state);
                    state = SCE_SCRIPTOL_DEFAULT;
                 }
             }

           }
          chPrev2 = chPrev;
          chPrev = ch;
	}
        if (state == SCE_SCRIPTOL_KEYWORD)
        {
            ClassifyWordSol(styler.GetStartSegment(),
                 lengthDoc-1, keywords, styler, prevWord);
	}
        else
        {
            styler.ColourTo(lengthDoc-1, state);
	}
}

static void FoldSolDoc(unsigned int startPos, int length, int initStyle,
						   WordList *[], Accessor &styler)
 {
	int lengthDoc = startPos + length;

	int lineCurrent = styler.GetLine(startPos);
	if (startPos > 0)
        {
          if (lineCurrent > 0)
          {
               lineCurrent--;
               startPos = styler.LineStart(lineCurrent);
               if (startPos == 0)
                    initStyle = SCE_SCRIPTOL_DEFAULT;
               else
                    initStyle = styler.StyleAt(startPos-1);
           }
	}
	int state = initStyle & 31;
	int spaceFlags = 0;
        int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsSolComment);
        if ((state == SCE_SCRIPTOL_TRIPLE))
             indentCurrent |= SC_FOLDLEVELWHITEFLAG;
	char chNext = styler[startPos];
	for (int i = startPos; i < lengthDoc; i++)
         {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);
		int style = styler.StyleAt(i) & 31;

		if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == lengthDoc))
                {
                   int lev = indentCurrent;
                   int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsSolComment);
                   if (style == SCE_SCRIPTOL_TRIPLE)
                        indentNext |= SC_FOLDLEVELWHITEFLAG;
                   if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG))
                    {
                        // Only non whitespace lines can be headers
                        if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK))
                        {
                              lev |= SC_FOLDLEVELHEADERFLAG;
                        }
                        else if (indentNext & SC_FOLDLEVELWHITEFLAG)
                        {
                             // Line after is blank so check the next - maybe should continue further?
                             int spaceFlags2 = 0;
                             int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsSolComment);
                             if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK))
                             {
                                   lev |= SC_FOLDLEVELHEADERFLAG;
                              }
                        }
                    }
                   indentCurrent = indentNext;
                   styler.SetLevel(lineCurrent, lev);
                   lineCurrent++;
		}
	}
}

LexerModule lmScriptol(SCLEX_SCRIPTOL, ColouriseSolDoc, "scriptol", FoldSolDoc);
<commit_msg>Fix warning from Clang.<commit_after>// Scintilla source code edit control
/** @file LexScriptol.cxx
 ** Lexer for Scriptol.
 **/

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <ctype.h>

#include "ILexer.h"
#include "Scintilla.h"
#include "SciLexer.h"

#include "WordList.h"
#include "LexAccessor.h"
#include "Accessor.h"
#include "StyleContext.h"
#include "CharacterSet.h"
#include "LexerModule.h"

#ifdef SCI_NAMESPACE
using namespace Scintilla;
#endif

static void ClassifyWordSol(unsigned int start, unsigned int end, WordList &keywords, Accessor &styler, char *prevWord)
{
    char s[100];
    bool wordIsNumber = isdigit(styler[start]) != 0;
    for (unsigned int i = 0; i < end - start + 1 && i < 30; i++)
     {
           s[i] = styler[start + i];
           s[i + 1] = '\0';
     }
    char chAttr = SCE_SCRIPTOL_IDENTIFIER;
    if (0 == strcmp(prevWord, "class"))       chAttr = SCE_SCRIPTOL_CLASSNAME;
    else if (wordIsNumber)                    chAttr = SCE_SCRIPTOL_NUMBER;
    else if (keywords.InList(s))              chAttr = SCE_SCRIPTOL_KEYWORD;
    else for (unsigned int i = 0; i < end - start + 1; i++)  // test dotted idents
    {
        if (styler[start + i] == '.')
        {
            styler.ColourTo(start + i - 1, chAttr);
            styler.ColourTo(start + i, SCE_SCRIPTOL_OPERATOR);
        }
    }
    styler.ColourTo(end, chAttr);
    strcpy(prevWord, s);
}

static bool IsSolComment(Accessor &styler, int pos, int len)
{
   if(len > 0)
   {
     char c = styler[pos];
     if(c == '`') return true;
     if(len > 1)
     {
        if(c == '/')
        {
          c = styler[pos + 1];
          if(c == '/') return true;
          if(c == '*') return true;
        }
     }
   }
   return false;
}

static bool IsSolStringStart(char ch)
{
    if (ch == '\'' || ch == '"')  return true;
    return false;
}

static bool IsSolWordStart(char ch)
{
    return (iswordchar(ch) && !IsSolStringStart(ch));
}

static int GetSolStringState(Accessor &styler, int i, int *nextIndex)
{
	char ch = styler.SafeGetCharAt(i);
	char chNext = styler.SafeGetCharAt(i + 1);

        if (ch != '\"' && ch != '\'')
        {
            *nextIndex = i + 1;
            return SCE_SCRIPTOL_DEFAULT;
	}
        // ch is either single or double quotes in string
        // code below seem non-sense but is here for future extensions
	if (ch == chNext && ch == styler.SafeGetCharAt(i + 2))
        {
          *nextIndex = i + 3;
          if(ch == '\"') return SCE_SCRIPTOL_TRIPLE;
          if(ch == '\'') return SCE_SCRIPTOL_TRIPLE;
          return SCE_SCRIPTOL_STRING;
	}
        else
        {
          *nextIndex = i + 1;
          if (ch == '"') return SCE_SCRIPTOL_STRING;
          else           return SCE_SCRIPTOL_STRING;
	}
}

static void ColouriseSolDoc(unsigned int startPos, int length, int initStyle,
                            WordList *keywordlists[], Accessor &styler)
 {

	int lengthDoc = startPos + length;
        char stringType = '\"';

	if (startPos > 0)
        {
            int lineCurrent = styler.GetLine(startPos);
            if (lineCurrent > 0)
            {
              startPos = styler.LineStart(lineCurrent-1);
              if (startPos == 0) initStyle = SCE_SCRIPTOL_DEFAULT;
              else               initStyle = styler.StyleAt(startPos-1);
            }
	}

	styler.StartAt(startPos, 127);

	WordList &keywords = *keywordlists[0];

	int whingeLevel = styler.GetPropertyInt("tab.timmy.whinge.level");
	char prevWord[200];
	prevWord[0] = '\0';
        if (length == 0)  return;

	int state = initStyle & 31;

	int nextIndex = 0;
        char chPrev  = ' ';
        char chPrev2 = ' ';
        char chNext  = styler[startPos];
	styler.StartSegment(startPos);
	bool atStartLine = true;
	int spaceFlags = 0;
	for (int i = startPos; i < lengthDoc; i++)
        {

         if (atStartLine)
         {
         char chBad = static_cast<char>(64);
         char chGood = static_cast<char>(0);
         char chFlags = chGood;

         if (whingeLevel == 1)
         {
             chFlags = (spaceFlags & wsInconsistent) ? chBad : chGood;
         }
         else if (whingeLevel == 2)
         {
             chFlags = (spaceFlags & wsSpaceTab) ? chBad : chGood;
         }
         else if (whingeLevel == 3)
         {
             chFlags = (spaceFlags & wsSpace) ? chBad : chGood;
         }
         else if (whingeLevel == 4)
         {
              chFlags = (spaceFlags & wsTab) ? chBad : chGood;
         }
         styler.SetFlags(chFlags, static_cast<char>(state));
         atStartLine = false;
       }

       char ch = chNext;
       chNext = styler.SafeGetCharAt(i + 1);

       if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == lengthDoc))
       {
          if ((state == SCE_SCRIPTOL_DEFAULT) ||
              (state == SCE_SCRIPTOL_TRIPLE) ||
              (state == SCE_SCRIPTOL_COMMENTBLOCK))
          {
              styler.ColourTo(i, state);
          }
          atStartLine = true;
        }

        if (styler.IsLeadByte(ch))
         {
             chNext = styler.SafeGetCharAt(i + 2);
             chPrev  = ' ';
             chPrev2 = ' ';
             i += 1;
             continue;
         }

        if (state == SCE_SCRIPTOL_STRINGEOL)
         {
             if (ch != '\r' && ch != '\n')
             {
                    styler.ColourTo(i - 1, state);
                    state = SCE_SCRIPTOL_DEFAULT;
             }
         }

        if (state == SCE_SCRIPTOL_DEFAULT)
         {
            if (IsSolWordStart(ch))
            {
                 styler.ColourTo(i - 1, state);
                 state = SCE_SCRIPTOL_KEYWORD;
            }
            else if (ch == '`')
            {
                styler.ColourTo(i - 1, state);
                state = SCE_SCRIPTOL_COMMENTLINE;
            }
            else if (ch == '/')
            {
                styler.ColourTo(i - 1, state);
                if(chNext == '/') state = SCE_SCRIPTOL_CSTYLE;
                if(chNext == '*') state = SCE_SCRIPTOL_COMMENTBLOCK;
            }

            else if (IsSolStringStart(ch))
            {
               styler.ColourTo(i - 1, state);
               state = GetSolStringState(styler, i, &nextIndex);
               if(state == SCE_SCRIPTOL_STRING)
               {
                 stringType = ch;
               }
               if (nextIndex != i + 1)
               {
                   i = nextIndex - 1;
                   ch = ' ';
                   chPrev = ' ';
                   chNext = styler.SafeGetCharAt(i + 1);
               }
           }
            else if (isoperator(ch))
            {
                 styler.ColourTo(i - 1, state);
                 styler.ColourTo(i, SCE_SCRIPTOL_OPERATOR);
            }
          }
          else if (state == SCE_SCRIPTOL_KEYWORD)
          {
              if (!iswordchar(ch))
              {
                 ClassifyWordSol(styler.GetStartSegment(), i - 1, keywords, styler, prevWord);
                 state = SCE_SCRIPTOL_DEFAULT;
                 if (ch == '`')
                 {
                     state = chNext == '`' ? SCE_SCRIPTOL_PERSISTENT : SCE_SCRIPTOL_COMMENTLINE;
                 }
                 else if (IsSolStringStart(ch))
                 {
                    styler.ColourTo(i - 1, state);
                    state = GetSolStringState(styler, i, &nextIndex);
                    if (nextIndex != i + 1)
                    {
                       i = nextIndex - 1;
                       ch = ' ';
                       chPrev = ' ';
                       chNext = styler.SafeGetCharAt(i + 1);
                     }
                 }
                 else if (isoperator(ch))
                 {
                     styler.ColourTo(i, SCE_SCRIPTOL_OPERATOR);
                 }
             }
          }
          else
          {
            if (state == SCE_SCRIPTOL_COMMENTLINE ||
                state == SCE_SCRIPTOL_PERSISTENT ||
                state == SCE_SCRIPTOL_CSTYLE)
            {
                 if (ch == '\r' || ch == '\n')
                 {
                     styler.ColourTo(i - 1, state);
                     state = SCE_SCRIPTOL_DEFAULT;
                 }
            }
            else if(state == SCE_SCRIPTOL_COMMENTBLOCK)
            {
              if(chPrev == '*' && ch == '/')
              {
                styler.ColourTo(i, state);
                state = SCE_SCRIPTOL_DEFAULT;
              }
            }
            else if ((state == SCE_SCRIPTOL_STRING) ||
                     (state == SCE_SCRIPTOL_CHARACTER))
            {
               if ((ch == '\r' || ch == '\n') && (chPrev != '\\'))
                {
                    styler.ColourTo(i - 1, state);
                    state = SCE_SCRIPTOL_STRINGEOL;
                }
                else if (ch == '\\')
                {
                   if (chNext == '\"' || chNext == '\'' || chNext == '\\')
                   {
                        i++;
                        ch = chNext;
                        chNext = styler.SafeGetCharAt(i + 1);
                   }
                 }
                else if ((ch == '\"') || (ch == '\''))
                {
                    // must match the entered quote type
                    if(ch == stringType)
                    {
                      styler.ColourTo(i, state);
                      state = SCE_SCRIPTOL_DEFAULT;
                    }
                 }
             }
             else if (state == SCE_SCRIPTOL_TRIPLE)
             {
                if ((ch == '\'' && chPrev == '\'' && chPrev2 == '\'') ||
                    (ch == '\"' && chPrev == '\"' && chPrev2 == '\"'))
                 {
                    styler.ColourTo(i, state);
                    state = SCE_SCRIPTOL_DEFAULT;
                 }
             }

           }
          chPrev2 = chPrev;
          chPrev = ch;
	}
        if (state == SCE_SCRIPTOL_KEYWORD)
        {
            ClassifyWordSol(styler.GetStartSegment(),
                 lengthDoc-1, keywords, styler, prevWord);
	}
        else
        {
            styler.ColourTo(lengthDoc-1, state);
	}
}

static void FoldSolDoc(unsigned int startPos, int length, int initStyle,
						   WordList *[], Accessor &styler)
 {
	int lengthDoc = startPos + length;

	int lineCurrent = styler.GetLine(startPos);
	if (startPos > 0)
        {
          if (lineCurrent > 0)
          {
               lineCurrent--;
               startPos = styler.LineStart(lineCurrent);
               if (startPos == 0)
                    initStyle = SCE_SCRIPTOL_DEFAULT;
               else
                    initStyle = styler.StyleAt(startPos-1);
           }
	}
	int state = initStyle & 31;
	int spaceFlags = 0;
        int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags, IsSolComment);
        if (state == SCE_SCRIPTOL_TRIPLE)
             indentCurrent |= SC_FOLDLEVELWHITEFLAG;
	char chNext = styler[startPos];
	for (int i = startPos; i < lengthDoc; i++)
         {
		char ch = chNext;
		chNext = styler.SafeGetCharAt(i + 1);
		int style = styler.StyleAt(i) & 31;

		if ((ch == '\r' && chNext != '\n') || (ch == '\n') || (i == lengthDoc))
                {
                   int lev = indentCurrent;
                   int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags, IsSolComment);
                   if (style == SCE_SCRIPTOL_TRIPLE)
                        indentNext |= SC_FOLDLEVELWHITEFLAG;
                   if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG))
                    {
                        // Only non whitespace lines can be headers
                        if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext & SC_FOLDLEVELNUMBERMASK))
                        {
                              lev |= SC_FOLDLEVELHEADERFLAG;
                        }
                        else if (indentNext & SC_FOLDLEVELWHITEFLAG)
                        {
                             // Line after is blank so check the next - maybe should continue further?
                             int spaceFlags2 = 0;
                             int indentNext2 = styler.IndentAmount(lineCurrent + 2, &spaceFlags2, IsSolComment);
                             if ((indentCurrent & SC_FOLDLEVELNUMBERMASK) < (indentNext2 & SC_FOLDLEVELNUMBERMASK))
                             {
                                   lev |= SC_FOLDLEVELHEADERFLAG;
                              }
                        }
                    }
                   indentCurrent = indentNext;
                   styler.SetLevel(lineCurrent, lev);
                   lineCurrent++;
		}
	}
}

LexerModule lmScriptol(SCLEX_SCRIPTOL, ColouriseSolDoc, "scriptol", FoldSolDoc);
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2009 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>
#include <QtCore>
#include "nanotree.h"

class NanoTreeUnitTest : public QObject
{
    Q_OBJECT

private:
    NanoTree buildBasic();
    NanoTree buildComplex();

private slots:
    void keyValue1();
    void keyValue2();
};

NanoTree NanoTreeUnitTest::buildBasic()
{
    QVariantList param1;
    param1 << QVariant("param1");
    param1 << QVariant("value1");

    QVariantList param2;
    param2 << QVariant("param2");
    param2 << QVariant("value2");

    QVariantList tree;
    tree << QVariant(param1);
    tree << QVariant(param2);

    return NanoTree(tree);
}

NanoTree NanoTreeUnitTest::buildComplex()
{
    QVariantList params;
    params << QVariant("params");

    QVariantList param1;
    param1 << QVariant("param1");
    param1 << QVariant("value1");

    QVariantList param2;
    param2 << QVariant("param2");
    param2 << QVariant("value2");

    params << QVariant(param1);
    params << QVariant(param2);

    QVariantList doc;
    doc << QVariant("doc");
    doc << QVariant("documentation");

    QVariantList tree;
    tree << QVariant(params);
    tree << QVariant(doc);

    return NanoTree(tree);
}

void NanoTreeUnitTest::keyValue1()
{
    NanoTree tree = buildBasic();
    QCOMPARE(tree.keyValue("param1").toString(), QString("value1"));
    QCOMPARE(tree.keyValue("param2").toString(), QString("value2"));
}

void NanoTreeUnitTest::keyValue2()
{
    NanoTree tree = buildComplex();
    QCOMPARE(tree.keyValue("params", "param1").toString(), QString("value1"));
    QCOMPARE(tree.keyValue("params", "param2").toString(), QString("value2"));
    QCOMPARE(tree.keyValue("doc").toString(), QString("documentation"));
}

#include "nanotreeunittest.moc"
QTEST_MAIN(NanoTreeUnitTest);
<commit_msg>NanoTree::keys() test.<commit_after>/*
 * Copyright (C) 2009 Nokia Corporation.
 *
 * Contact: Marius Vollmer <marius.vollmer@nokia.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 */

#include <QtTest/QtTest>
#include <QtCore>
#include "nanotree.h"

class NanoTreeUnitTest : public QObject
{
    Q_OBJECT

private:
    NanoTree buildBasic();
    NanoTree buildComplex();

private slots:
    void keyValue1();
    void keyValue2();
    void keys();
};

NanoTree NanoTreeUnitTest::buildBasic()
{
    QVariantList param1;
    param1 << QVariant("param1");
    param1 << QVariant("value1");

    QVariantList param2;
    param2 << QVariant("param2");
    param2 << QVariant("value2");

    QVariantList tree;
    tree << QVariant(param1);
    tree << QVariant(param2);

    return NanoTree(tree);
}

NanoTree NanoTreeUnitTest::buildComplex()
{
    QVariantList params;
    params << QVariant("params");

    QVariantList param1;
    param1 << QVariant("param1");
    param1 << QVariant("value1");

    QVariantList param2;
    param2 << QVariant("param2");
    param2 << QVariant("value2");

    params << QVariant(param1);
    params << QVariant(param2);

    QVariantList doc;
    doc << QVariant("doc");
    doc << QVariant("documentation");

    QVariantList tree;
    tree << QVariant(params);
    tree << QVariant(doc);

    return NanoTree(tree);
}

void NanoTreeUnitTest::keyValue1()
{
    NanoTree tree = buildBasic();
    QCOMPARE(tree.keyValue("param1").toString(), QString("value1"));
    QCOMPARE(tree.keyValue("param2").toString(), QString("value2"));
}

void NanoTreeUnitTest::keyValue2()
{
    NanoTree tree = buildComplex();
    QCOMPARE(tree.keyValue("params", "param1").toString(), QString("value1"));
    QCOMPARE(tree.keyValue("params", "param2").toString(), QString("value2"));
    QCOMPARE(tree.keyValue("doc").toString(), QString("documentation"));
}

void NanoTreeUnitTest::keys()
{
    NanoTree tree = buildComplex();
    QStringList lst1 = tree.keys();

    QCOMPARE(lst1.size(), 2);
    QVERIFY(lst1.contains("params"));
    QVERIFY(lst1.contains("doc"));

    QStringList lst2 = tree.keyNode("params").keys();
    QCOMPARE(lst2.size(), 2);
    QVERIFY(lst2.contains("param1"));
    QVERIFY(lst2.contains("param2"));

}

#include "nanotreeunittest.moc"
QTEST_MAIN(NanoTreeUnitTest);
<|endoftext|>


<commit_before>#include "controllers/pings/PingController.hpp"
#include "controllers/pings/PingModel.hpp"

namespace chatterino {

void PingController::initialize(Settings &settings, Paths &paths)
{
    this->initialized_ = true;
    for (const QString &channelName : this->pingSetting_.getValue())
    {
        this->channelVector.append(channelName);
    }

    this->channelVector.delayedItemsChanged.connect([this] {  //
        this->pingSetting_.setValue(this->channelVector.raw());
    });
}

PingModel *PingController::createModel(QObject *parent)
{
    PingModel *model = new PingModel(parent);
    model->initialize(&this->channelVector);
    return model;
}

bool PingController::isMuted(const QString &channelName)
{
    for (const auto &channel : this->channelVector)
    {
        if (channelName.toLower() == channel.toLower())
        {
            return true;
        }
    }
    return false;
}

void PingController::muteChannel(const QString &channelName)
{
    channelVector.append(channelName);
}

void PingController::unmuteChannel(const QString &channelName)
{
    for (std::vector<int>::size_type i = 0;
         i != channelVector.raw().size(); i++)
    {
        if (channelVector.raw()[i].toLower() == channelName.toLower())
        {
            channelVector.removeAt(i);
            i--;
        }
    }
}

bool PingController::toggleMuteChannel(const QString &channelName)
{
    if (this->isMuted(channelName))
    {
        unmuteChannel(channelName);
        return false;
    }
    else
    {
        muteChannel(channelName);
        return true;
    }
}

}  // namespace chatterino
<commit_msg>fixed formatting<commit_after>#include "controllers/pings/PingController.hpp"
#include "controllers/pings/PingModel.hpp"

namespace chatterino {

void PingController::initialize(Settings &settings, Paths &paths)
{
    this->initialized_ = true;
    for (const QString &channelName : this->pingSetting_.getValue())
    {
        this->channelVector.append(channelName);
    }

    this->channelVector.delayedItemsChanged.connect([this] {  //
        this->pingSetting_.setValue(this->channelVector.raw());
    });
}

PingModel *PingController::createModel(QObject *parent)
{
    PingModel *model = new PingModel(parent);
    model->initialize(&this->channelVector);
    return model;
}

bool PingController::isMuted(const QString &channelName)
{
    for (const auto &channel : this->channelVector)
    {
        if (channelName.toLower() == channel.toLower())
        {
            return true;
        }
    }
    return false;
}

void PingController::muteChannel(const QString &channelName)
{
    channelVector.append(channelName);
}

void PingController::unmuteChannel(const QString &channelName)
{
    for (std::vector<int>::size_type i = 0; i != channelVector.raw().size();
         i++)
    {
        if (channelVector.raw()[i].toLower() == channelName.toLower())
        {
            channelVector.removeAt(i);
            i--;
        }
    }
}

bool PingController::toggleMuteChannel(const QString &channelName)
{
    if (this->isMuted(channelName))
    {
        unmuteChannel(channelName);
        return false;
    }
    else
    {
        muteChannel(channelName);
        return true;
    }
}

}  // namespace chatterino
<|endoftext|>


<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

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

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

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

#include "paddle/fluid/operators/math/fc.h"
#include "paddle/fluid/operators/jit/kernels.h"
#include "paddle/fluid/operators/math/blas.h"

namespace paddle {
namespace operators {
namespace math {

template <typename T>
class FCFunctor<platform::CPUDeviceContext, T> {
 public:
  void operator()(const platform::CPUDeviceContext& context, const int M,
                  const int N, const int K, const T* X, const T* W, T* Y,
                  const T* B = nullptr, bool relu = false,
                  bool padding_weights = false) {
    auto blas = math::GetBlas<platform::CPUDeviceContext, T>(context);
    framework::Tensor Y1;
    T* Y1_data = nullptr;
    if (padding_weights) {
      const int NN = N + 4;
      const int KK = K + 4;
      framework::Tensor X1;
      T* X1_data = X1.mutable_data<T>({M * KK}, platform::CPUPlace());
      Y1_data = Y1.mutable_data<T>({M * (N + 4)}, platform::CPUPlace());
#ifdef PADDLE_WITH_MKLML
#pragma omp parallel for
#endif
      for (int i = 0; i < M; i++) {
        memcpy(X1_data + i * KK, X + i * K, K * sizeof(T));
      }
      blas.GEMM(false, false, M, N, K, static_cast<T>(1.0), X1_data, KK, W, NN,
                static_cast<T>(0.0), Y1_data, NN);
    } else {
      blas.MatMul(M, N, K, X, W, Y);
    }
    if (B == NULL) {
      if (padding_weights) {
#ifdef PADDLE_WITH_MKLML
#pragma omp parallel for
#endif
        for (int i = 0; i < M; i++) {
          memcpy(Y + i * N, Y1_data + i * (N + 4), N * sizeof(T));
        }
      }
      PADDLE_ENFORCE_EQ(relu, false,
                        platform::errors::PermissionDenied(
                            "When bias is NULL, relu can not be true."));
      return;
    }
    if (relu) {
      auto compute =
          jit::KernelFuncs<jit::VAddReluTuple<T>, platform::CPUPlace>::Cache()
              .At(N);
      for (int i = 0; i < M; i++) {
        T* dst = Y + i * N;
        T* src = (padding_weights) ? Y1_data + i * (N + 4) : dst;
        compute(B, src, dst, N);
      }
    } else {
      auto compute =
          jit::KernelFuncs<jit::VAddTuple<T>, platform::CPUPlace>::Cache().At(
              N);
#ifdef PADDLE_WITH_MKLML
#pragma omp parallel for
#endif
      for (int i = 0; i < M; i++) {
        T* dst = Y + i * N;
        T* src = (padding_weights) ? Y1_data + i * (N + 4) : dst;
        compute(B, src, dst, N);
      }
    }
  }
};

template class FCFunctor<platform::CPUDeviceContext, float>;
template class FCFunctor<platform::CPUDeviceContext, double>;

}  // namespace math
}  // namespace operators
}  // namespace paddle
<commit_msg>optimize fc jit (#21878)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

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

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

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

#include "paddle/fluid/operators/math/fc.h"
#include "paddle/fluid/operators/jit/kernels.h"
#include "paddle/fluid/operators/math/blas.h"

namespace paddle {
namespace operators {
namespace math {

template <typename T>
class FCFunctor<platform::CPUDeviceContext, T> {
 public:
  void operator()(const platform::CPUDeviceContext& context, const int M,
                  const int N, const int K, const T* X, const T* W, T* Y,
                  const T* B = nullptr, bool relu = false,
                  bool padding_weights = false) {
    auto blas = math::GetBlas<platform::CPUDeviceContext, T>(context);
    framework::Tensor Y1;
    T* Y1_data = nullptr;
    if (padding_weights) {
      const int NN = N + 4;
      const int KK = K + 4;
      framework::Tensor X1;
      T* X1_data = X1.mutable_data<T>({M * KK}, platform::CPUPlace());
      Y1_data = Y1.mutable_data<T>({M * (N + 4)}, platform::CPUPlace());
#ifdef PADDLE_WITH_MKLML
#pragma omp parallel for
#endif
      for (int i = 0; i < M; i++) {
        memcpy(X1_data + i * KK, X + i * K, K * sizeof(T));
      }
      blas.GEMM(false, false, M, N, K, static_cast<T>(1.0), X1_data, KK, W, NN,
                static_cast<T>(0.0), Y1_data, NN);
    } else {
      blas.MatMul(M, N, K, X, W, Y);
    }
    if (B == NULL) {
      if (padding_weights) {
#ifdef PADDLE_WITH_MKLML
#pragma omp parallel for
#endif
        for (int i = 0; i < M; i++) {
          memcpy(Y + i * N, Y1_data + i * (N + 4), N * sizeof(T));
        }
      }
      PADDLE_ENFORCE_EQ(relu, false,
                        platform::errors::PermissionDenied(
                            "When bias is NULL, relu can not be true."));
      return;
    }
    auto compute =
        relu
            ? jit::KernelFuncs<jit::VAddReluTuple<T>,
                               platform::CPUPlace>::Cache()
                  .At(N)
            : jit::KernelFuncs<jit::VAddTuple<T>, platform::CPUPlace>::Cache()
                  .At(N);
#ifdef PADDLE_WITH_MKLML
#pragma omp parallel for
#endif
    for (int i = 0; i < M; i++) {
      T* dst = Y + i * N;
      T* src = (padding_weights) ? Y1_data + i * (N + 4) : dst;
      compute(B, src, dst, N);
    }
  }
};

template class FCFunctor<platform::CPUDeviceContext, float>;
template class FCFunctor<platform::CPUDeviceContext, double>;

}  // namespace math
}  // namespace operators
}  // namespace paddle
<|endoftext|>