<commit_before>/************************************************************************************
 *   Copyright (C) 2014-2015 by Savoir-Faire Linux                                  *
 *   Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com>         *
 *                                                                                *
 *   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 "fallbackpersoncollection.h"

//Qt
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QHash>
#include <QtCore/QTimer>
#include <QtCore/QUrl>
#include <QtCore/QCryptographicHash>
#include <QtWidgets/QApplication>
#include <QtCore/QStandardPaths>

//Ring
#include "person.h"
#include "personmodel.h"
#include "private/vcardutils.h"
#include "contactmethod.h"
#include "collectioneditor.h"
#include "delegates/pixmapmanipulationdelegate.h"
#include "delegates/itemmodelstateserializationdelegate.h"

class FallbackPersonBackendEditor : public CollectionEditor<Person>
{
public:
   FallbackPersonBackendEditor(CollectionMediator<Person>* m, const QString& path) : CollectionEditor<Person>(m),m_Path(path) {}
   virtual bool save       ( const Person* item ) override;
   virtual bool remove     ( const Person* item ) override;
   virtual bool edit       ( Person*       item ) override;
   virtual bool addNew     ( const Person* item ) override;
   virtual bool addExisting( const Person* item ) override;

   QVector<Person*>             m_lItems;
   QString                      m_Path  ;
   QHash<const Person*,QString> m_hPaths;

private:
   virtual QVector<Person*> items() const override;
};

class FallbackPersonCollectionPrivate : public QObject
{
   Q_OBJECT
public:
   FallbackPersonCollectionPrivate(FallbackPersonCollection* parent, CollectionMediator<Person>* mediator, const QString& path);
   CollectionMediator<Person>*  m_pMediator;
   QString                      m_Path     ;
   QString                      m_Name     ;

   FallbackPersonCollection* q_ptr;

public Q_SLOTS:
   void loadAsync();
};

FallbackPersonCollectionPrivate::FallbackPersonCollectionPrivate(FallbackPersonCollection* parent, CollectionMediator<Person>* mediator, const QString& path) : q_ptr(parent), m_pMediator(mediator), m_Path(path)
{
   //Default to somewhere ~/.local/share
   if (m_Path.isEmpty()) {
      m_Path = (QStandardPaths::writableLocation(QStandardPaths::DataLocation)) + "/vCard/";
      static_cast<FallbackPersonBackendEditor*>(q_ptr->editor<Person>())->m_Path = m_Path;
   }

   m_Name = path.split('/').last();
   if (m_Name.size())
      m_Name[0] = m_Name[0].toUpper();
   else
      m_Name = "vCard";
}

FallbackPersonCollection::FallbackPersonCollection(CollectionMediator<Person>* mediator, const QString& path, FallbackPersonCollection* parent) :
CollectionInterface(new FallbackPersonBackendEditor(mediator,path),parent),d_ptr(new FallbackPersonCollectionPrivate(this,mediator,path))
{
}

FallbackPersonCollection::~FallbackPersonCollection()
{

}

bool FallbackPersonBackendEditor::save(const Person* item)
{
   if (!item)
      return false;

   //An UID is required
   if (item->uid().isEmpty()) {
      QCryptographicHash hash(QCryptographicHash::Sha1);
      for (ContactMethod* n : item->phoneNumbers())
         hash.addData(n->uri().toLatin1());
      hash.addData(item->formattedName().toLatin1());
      QByteArray random;

      for (int i=0;i<5;i++)
         random.append(QChar((char)(rand()%255)));

      hash.addData(random);

      const_cast<Person*>(item)->setUid(hash.result().toHex());
   }

   QFile file(m_Path+'/'+item->uid()+".vcf");
   file.open(QIODevice::WriteOnly);
   file.write(item->toVCard({}));
   file.close();
   return true;
}

bool FallbackPersonBackendEditor::remove(const Person* item)
{
   if (!item)
      return false;

   QString path = m_hPaths[item];

   if (path.isEmpty())
      path = m_Path+'/'+item->uid()+".vcf";

   bool ret = QFile::remove(path);

   if (ret) {
      ret &= mediator()->removeItem(item);
   }

   return ret;
}

bool FallbackPersonBackendEditor::edit( Person* item)
{
   Q_UNUSED(item)
   return false;
}

bool FallbackPersonBackendEditor::addNew(const Person* item)
{
   bool ret = save(item);

   if (ret) {
      addExisting(item);
   }

   return ret;
}

bool FallbackPersonBackendEditor::addExisting(const Person* item)
{
   m_lItems << const_cast<Person*>(item);
   mediator()->addItem(item);
   return true;
}

QVector<Person*> FallbackPersonBackendEditor::items() const
{
   return m_lItems;
}

QString FallbackPersonCollection::name () const
{
   return d_ptr->m_Name;
}

QString FallbackPersonCollection::category () const
{
   return QObject::tr("Contact");
}

QVariant FallbackPersonCollection::icon() const
{
   return PixmapManipulationDelegate::instance()->collectionIcon(this,PixmapManipulationDelegate::CollectionIconHint::CONTACT);
}

bool FallbackPersonCollection::isEnabled() const
{
   return ItemModelStateSerializationDelegate::instance()->isChecked(this);
}

bool FallbackPersonCollection::load()
{
   bool ok;
   QList< Person* > ret =  VCardUtils::loadDir(QUrl(d_ptr->m_Path),ok,static_cast<FallbackPersonBackendEditor*>(editor<Person>())->m_hPaths);
   for(Person* p : ret) {
      p->setCollection(this);
      editor<Person>()->addExisting(p);
   }

   //Add all sub directories as new backends
   QTimer::singleShot(0,d_ptr,SLOT(loadAsync()));

   return true;
}

bool FallbackPersonCollection::reload()
{
   return false;
}

CollectionInterface::SupportedFeatures FallbackPersonCollection::supportedFeatures() const
{
   return (CollectionInterface::SupportedFeatures)       (
      CollectionInterface::SupportedFeatures::NONE       |
      CollectionInterface::SupportedFeatures::LOAD       |
      CollectionInterface::SupportedFeatures::CLEAR      |
      CollectionInterface::SupportedFeatures::MANAGEABLE |
      CollectionInterface::SupportedFeatures::REMOVE     |
      CollectionInterface::SupportedFeatures::ADD        );
}

bool FallbackPersonCollection::clear()
{
   QDir dir(d_ptr->m_Path);
   for (const QString& file : dir.entryList({"*.vcf"},QDir::Files))
      dir.remove(file);
   return true;
}

QByteArray FallbackPersonCollection::id() const
{
   return "fpc2"+d_ptr->m_Path.toLatin1();
}

void FallbackPersonCollectionPrivate::loadAsync()
{
   QDir d(m_Path);
   for (const QString& dir : d.entryList(QDir::AllDirs)) {
      if (dir != QString('.') && dir != "..") {
         CollectionInterface* col = PersonModel::instance()->addCollection<FallbackPersonCollection,QString,FallbackPersonCollection*>(m_Path+'/'+dir,q_ptr);
         if (ItemModelStateSerializationDelegate::instance()->isChecked(col)) {
            col->load();
         }
      }
   }
}

#include "fallbackpersoncollection.moc"
<commit_msg>android: Remove invalid #include<commit_after>/************************************************************************************
 *   Copyright (C) 2014-2015 by Savoir-Faire Linux                                  *
 *   Author : Emmanuel Lepage Vallee <emmanuel.lepage@savoirfairelinux.com>         *
 *                                                                                *
 *   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 "fallbackpersoncollection.h"

//Qt
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QHash>
#include <QtCore/QTimer>
#include <QtCore/QUrl>
#include <QtCore/QCryptographicHash>
#include <QtCore/QStandardPaths>

//Ring
#include "person.h"
#include "personmodel.h"
#include "private/vcardutils.h"
#include "contactmethod.h"
#include "collectioneditor.h"
#include "delegates/pixmapmanipulationdelegate.h"
#include "delegates/itemmodelstateserializationdelegate.h"

class FallbackPersonBackendEditor : public CollectionEditor<Person>
{
public:
   FallbackPersonBackendEditor(CollectionMediator<Person>* m, const QString& path) : CollectionEditor<Person>(m),m_Path(path) {}
   virtual bool save       ( const Person* item ) override;
   virtual bool remove     ( const Person* item ) override;
   virtual bool edit       ( Person*       item ) override;
   virtual bool addNew     ( const Person* item ) override;
   virtual bool addExisting( const Person* item ) override;

   QVector<Person*>             m_lItems;
   QString                      m_Path  ;
   QHash<const Person*,QString> m_hPaths;

private:
   virtual QVector<Person*> items() const override;
};

class FallbackPersonCollectionPrivate : public QObject
{
   Q_OBJECT
public:
   FallbackPersonCollectionPrivate(FallbackPersonCollection* parent, CollectionMediator<Person>* mediator, const QString& path);
   CollectionMediator<Person>*  m_pMediator;
   QString                      m_Path     ;
   QString                      m_Name     ;

   FallbackPersonCollection* q_ptr;

public Q_SLOTS:
   void loadAsync();
};

FallbackPersonCollectionPrivate::FallbackPersonCollectionPrivate(FallbackPersonCollection* parent, CollectionMediator<Person>* mediator, const QString& path) : q_ptr(parent), m_pMediator(mediator), m_Path(path)
{
   //Default to somewhere ~/.local/share
   if (m_Path.isEmpty()) {
      m_Path = (QStandardPaths::writableLocation(QStandardPaths::DataLocation)) + "/vCard/";
      static_cast<FallbackPersonBackendEditor*>(q_ptr->editor<Person>())->m_Path = m_Path;
   }

   m_Name = path.split('/').last();
   if (m_Name.size())
      m_Name[0] = m_Name[0].toUpper();
   else
      m_Name = "vCard";
}

FallbackPersonCollection::FallbackPersonCollection(CollectionMediator<Person>* mediator, const QString& path, FallbackPersonCollection* parent) :
CollectionInterface(new FallbackPersonBackendEditor(mediator,path),parent),d_ptr(new FallbackPersonCollectionPrivate(this,mediator,path))
{
}

FallbackPersonCollection::~FallbackPersonCollection()
{

}

bool FallbackPersonBackendEditor::save(const Person* item)
{
   if (!item)
      return false;

   //An UID is required
   if (item->uid().isEmpty()) {
      QCryptographicHash hash(QCryptographicHash::Sha1);
      for (ContactMethod* n : item->phoneNumbers())
         hash.addData(n->uri().toLatin1());
      hash.addData(item->formattedName().toLatin1());
      QByteArray random;

      for (int i=0;i<5;i++)
         random.append(QChar((char)(rand()%255)));

      hash.addData(random);

      const_cast<Person*>(item)->setUid(hash.result().toHex());
   }

   QFile file(m_Path+'/'+item->uid()+".vcf");
   file.open(QIODevice::WriteOnly);
   file.write(item->toVCard({}));
   file.close();
   return true;
}

bool FallbackPersonBackendEditor::remove(const Person* item)
{
   if (!item)
      return false;

   QString path = m_hPaths[item];

   if (path.isEmpty())
      path = m_Path+'/'+item->uid()+".vcf";

   bool ret = QFile::remove(path);

   if (ret) {
      ret &= mediator()->removeItem(item);
   }

   return ret;
}

bool FallbackPersonBackendEditor::edit( Person* item)
{
   Q_UNUSED(item)
   return false;
}

bool FallbackPersonBackendEditor::addNew(const Person* item)
{
   bool ret = save(item);

   if (ret) {
      addExisting(item);
   }

   return ret;
}

bool FallbackPersonBackendEditor::addExisting(const Person* item)
{
   m_lItems << const_cast<Person*>(item);
   mediator()->addItem(item);
   return true;
}

QVector<Person*> FallbackPersonBackendEditor::items() const
{
   return m_lItems;
}

QString FallbackPersonCollection::name () const
{
   return d_ptr->m_Name;
}

QString FallbackPersonCollection::category () const
{
   return QObject::tr("Contact");
}

QVariant FallbackPersonCollection::icon() const
{
   return PixmapManipulationDelegate::instance()->collectionIcon(this,PixmapManipulationDelegate::CollectionIconHint::CONTACT);
}

bool FallbackPersonCollection::isEnabled() const
{
   return ItemModelStateSerializationDelegate::instance()->isChecked(this);
}

bool FallbackPersonCollection::load()
{
   bool ok;
   QList< Person* > ret =  VCardUtils::loadDir(QUrl(d_ptr->m_Path),ok,static_cast<FallbackPersonBackendEditor*>(editor<Person>())->m_hPaths);
   for(Person* p : ret) {
      p->setCollection(this);
      editor<Person>()->addExisting(p);
   }

   //Add all sub directories as new backends
   QTimer::singleShot(0,d_ptr,SLOT(loadAsync()));

   return true;
}

bool FallbackPersonCollection::reload()
{
   return false;
}

CollectionInterface::SupportedFeatures FallbackPersonCollection::supportedFeatures() const
{
   return (CollectionInterface::SupportedFeatures)       (
      CollectionInterface::SupportedFeatures::NONE       |
      CollectionInterface::SupportedFeatures::LOAD       |
      CollectionInterface::SupportedFeatures::CLEAR      |
      CollectionInterface::SupportedFeatures::MANAGEABLE |
      CollectionInterface::SupportedFeatures::REMOVE     |
      CollectionInterface::SupportedFeatures::ADD        );
}

bool FallbackPersonCollection::clear()
{
   QDir dir(d_ptr->m_Path);
   for (const QString& file : dir.entryList({"*.vcf"},QDir::Files))
      dir.remove(file);
   return true;
}

QByteArray FallbackPersonCollection::id() const
{
   return "fpc2"+d_ptr->m_Path.toLatin1();
}

void FallbackPersonCollectionPrivate::loadAsync()
{
   QDir d(m_Path);
   for (const QString& dir : d.entryList(QDir::AllDirs)) {
      if (dir != QString('.') && dir != "..") {
         CollectionInterface* col = PersonModel::instance()->addCollection<FallbackPersonCollection,QString,FallbackPersonCollection*>(m_Path+'/'+dir,q_ptr);
         if (ItemModelStateSerializationDelegate::instance()->isChecked(col)) {
            col->load();
         }
      }
   }
}

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


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

class tst_qmlfontloader : public QObject

{
    Q_OBJECT
public:
    tst_qmlfontloader();

private slots:
    void namedfont();
    void localfont();

private slots:

private:
    QmlEngine engine;
};

tst_qmlfontloader::tst_qmlfontloader()
{
}

void tst_qmlfontloader::namedfont()
{
    QString componentStr = "import Qt 4.6\nFontLoader { name: \"Helvetica\" }";
    QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://"));
    QmlFontLoader *fontObject = qobject_cast<QmlFontLoader*>(component.create());

    QVERIFY(fontObject != 0);
    QCOMPARE(fontObject->name(), QString("Helvetica"));
}

void tst_qmlfontloader::localfont()
{
    QString componentStr = "import Qt 4.6\nFontLoader { source: \"data/Fontin-Bold.ttf\" }";
    QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://"));
    QmlFontLoader *fontObject = qobject_cast<QmlFontLoader*>(component.create());

    QVERIFY(fontObject != 0);
    QCOMPARE(fontObject->name(), QString("Fontin"));
}

QTEST_MAIN(tst_qmlfontloader)

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

class tst_qmlfontloader : public QObject

{
    Q_OBJECT
public:
    tst_qmlfontloader();

private slots:
    void nofont();
    void namedfont();
    void localfont();
    void webfont();

private slots:

private:
    QmlEngine engine;
};

tst_qmlfontloader::tst_qmlfontloader()
{
}

void tst_qmlfontloader::nofont()
{
    QString componentStr = "import Qt 4.6\nFontLoader { }";
    QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://"));
    QmlFontLoader *fontObject = qobject_cast<QmlFontLoader*>(component.create());

    QVERIFY(fontObject != 0);
    QCOMPARE(fontObject->name(), QString(""));
}

void tst_qmlfontloader::namedfont()
{
    QString componentStr = "import Qt 4.6\nFontLoader { name: \"Helvetica\" }";
    QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://"));
    QmlFontLoader *fontObject = qobject_cast<QmlFontLoader*>(component.create());

    QVERIFY(fontObject != 0);
    QCOMPARE(fontObject->name(), QString("Helvetica"));
}

void tst_qmlfontloader::localfont()
{
    QString componentStr = "import Qt 4.6\nFontLoader { source: \"data/Fontin-Bold.ttf\" }";
    QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://"));
    QmlFontLoader *fontObject = qobject_cast<QmlFontLoader*>(component.create());

    QVERIFY(fontObject != 0);
    QCOMPARE(fontObject->name(), QString("Fontin"));
}

void tst_qmlfontloader::webfont()
{
    QString componentStr = "import Qt 4.6\nFontLoader { source: \"http://www.princexml.com/fonts/steffmann/Starburst.ttf\" }";
    QmlComponent component(&engine, componentStr.toLatin1(), QUrl("file://"));
    QmlFontLoader *fontObject = qobject_cast<QmlFontLoader*>(component.create());

    QVERIFY(fontObject != 0);
    QTRY_COMPARE(fontObject->name(), QString("Starburst"));
}

QTEST_MAIN(tst_qmlfontloader)

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


<commit_before>/*
 *  Vehicle.cpp
 *  openc2e
 *
 *  Created by Alyssa Milburn on Tue May 25 2004.
 *  Copyright (c) 2004 Alyssa Milburn. All rights reserved.
 *
 *  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 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.
 *
 */

#include "Vehicle.h"
#include "Engine.h"
#include "World.h"
#include "MetaRoom.h"

Vehicle::Vehicle(unsigned int family, unsigned int genus, unsigned int species, unsigned int plane,
		std::string spritefile, unsigned int firstimage, unsigned int imagecount) :
		CompoundAgent(family, genus, species, plane, spritefile, firstimage, imagecount) {
	capacity = 0;
	bump = 0;

	cabinleft = 0; cabintop = 0; cabinright = getWidth(); cabinbottom = getHeight();
	cabinplane = 1; // TODO: is this sane? seems to be the default in c2e
}

Vehicle::Vehicle(std::string spritefile, unsigned int firstimage, unsigned int imagecount) : CompoundAgent(spritefile, firstimage, imagecount) {
	capacity = 0;
	bump = 0;

	// TODO: set cabin bounds? we don't know width/height at this point..
	cabinplane = 95; // TODO: arbitarily-chosen value (see also SFCFile)
}

void Vehicle::tick() {
	CompoundAgent::tick();
	if (paused) return;

	// move by xvec/yvec!
	moveTo(x + xvec.getInt() / 256.0, y + yvec.getInt() / 256.0);
}

void Vehicle::carry(AgentRef passenger) {
	// TODO: 'return' is not a good idea here, because the callung function already does stuff

	if (passenger->carriedby) return; // TODO: change to assert?
	if (passenger->invehicle) return; // TODO: change to assert?

	int cabinwidth = cabinright - cabinleft;
	int cabinheight = cabinbottom - cabintop;

	if (engine.version > 2) {
		// reject if passenger is too big
		if ((int)passenger->getWidth() > cabinwidth) return;
		if ((int)passenger->getHeight() > cabinheight) return;
	}

	// push into our cabin
	// TODO: should we use moveTo here?
	if (passenger->x + passenger->getWidth() > (x + cabinright)) passenger->x = x + cabinright - passenger->getWidth();
	if (passenger->x < (x + cabinleft)) passenger->x = x + cabinleft;
	if (engine.version > 1) {
		// TODO: not sure if this is good for too-high agents, if it's possible for them to exist (see comment above)
		if (passenger->y + passenger->getHeight() > (y + cabinbottom)) passenger->y = y + cabinbottom - passenger->getHeight();
		if (passenger->y < (y + cabintop)) passenger->y = y + cabintop;
	} else {
		passenger->y = y + cabinbottom - passenger->getHeight();
	}

	passengers.push_back(passenger);
	passenger->invehicle = this;

	if (engine.version >= 3)
		passenger->queueScript(121, this); // Vehicle Pickup, TODO: is this valid call?
}

void Vehicle::drop(AgentRef passenger) {
	std::vector<AgentRef>::iterator i = std::find(passengers.begin(), passengers.end(), passenger);
	assert(i != passengers.end());
	assert(passenger->invehicle == AgentRef(this));
	passengers.erase(i);

	passenger->beDropped();

	if (engine.version >= 3)
		passenger->queueScript(122, this); // Vehicle Drop, TODO: is this valid call?
}

void Vehicle::adjustCarried(float xoffset, float yoffset) {
	Agent::adjustCarried(xoffset, yoffset);

	for (std::vector<AgentRef>::iterator i = passengers.begin(); i != passengers.end(); i++) {
		if (!(*i)) continue; // TODO: muh
		(*i)->moveTo((*i)->x + xoffset, (*i)->y + yoffset);
	}
}

void Vehicle::kill() {
	// TODO: sane?
	while (passengers.size() > 0) {
		if (passengers[0]) dropCarried(passengers[0]);
		else passengers.erase(passengers.begin());
	}
}

/* vim: set noet: */
<commit_msg>call Agent::kill from Vehicle::kill (oops)<commit_after>/*
 *  Vehicle.cpp
 *  openc2e
 *
 *  Created by Alyssa Milburn on Tue May 25 2004.
 *  Copyright (c) 2004 Alyssa Milburn. All rights reserved.
 *
 *  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 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.
 *
 */

#include "Vehicle.h"
#include "Engine.h"
#include "World.h"
#include "MetaRoom.h"

Vehicle::Vehicle(unsigned int family, unsigned int genus, unsigned int species, unsigned int plane,
		std::string spritefile, unsigned int firstimage, unsigned int imagecount) :
		CompoundAgent(family, genus, species, plane, spritefile, firstimage, imagecount) {
	capacity = 0;
	bump = 0;

	cabinleft = 0; cabintop = 0; cabinright = getWidth(); cabinbottom = getHeight();
	cabinplane = 1; // TODO: is this sane? seems to be the default in c2e
}

Vehicle::Vehicle(std::string spritefile, unsigned int firstimage, unsigned int imagecount) : CompoundAgent(spritefile, firstimage, imagecount) {
	capacity = 0;
	bump = 0;

	// TODO: set cabin bounds? we don't know width/height at this point..
	cabinplane = 95; // TODO: arbitarily-chosen value (see also SFCFile)
}

void Vehicle::tick() {
	CompoundAgent::tick();
	if (paused) return;

	// move by xvec/yvec!
	moveTo(x + xvec.getInt() / 256.0, y + yvec.getInt() / 256.0);
}

void Vehicle::carry(AgentRef passenger) {
	// TODO: 'return' is not a good idea here, because the callung function already does stuff

	if (passenger->carriedby) return; // TODO: change to assert?
	if (passenger->invehicle) return; // TODO: change to assert?

	int cabinwidth = cabinright - cabinleft;
	int cabinheight = cabinbottom - cabintop;

	if (engine.version > 2) {
		// reject if passenger is too big
		if ((int)passenger->getWidth() > cabinwidth) return;
		if ((int)passenger->getHeight() > cabinheight) return;
	}

	// push into our cabin
	// TODO: should we use moveTo here?
	if (passenger->x + passenger->getWidth() > (x + cabinright)) passenger->x = x + cabinright - passenger->getWidth();
	if (passenger->x < (x + cabinleft)) passenger->x = x + cabinleft;
	if (engine.version > 1) {
		// TODO: not sure if this is good for too-high agents, if it's possible for them to exist (see comment above)
		if (passenger->y + passenger->getHeight() > (y + cabinbottom)) passenger->y = y + cabinbottom - passenger->getHeight();
		if (passenger->y < (y + cabintop)) passenger->y = y + cabintop;
	} else {
		passenger->y = y + cabinbottom - passenger->getHeight();
	}

	passengers.push_back(passenger);
	passenger->invehicle = this;

	if (engine.version >= 3)
		passenger->queueScript(121, this); // Vehicle Pickup, TODO: is this valid call?
}

void Vehicle::drop(AgentRef passenger) {
	std::vector<AgentRef>::iterator i = std::find(passengers.begin(), passengers.end(), passenger);
	assert(i != passengers.end());
	assert(passenger->invehicle == AgentRef(this));
	passengers.erase(i);

	passenger->beDropped();

	if (engine.version >= 3)
		passenger->queueScript(122, this); // Vehicle Drop, TODO: is this valid call?
}

void Vehicle::adjustCarried(float xoffset, float yoffset) {
	Agent::adjustCarried(xoffset, yoffset);

	for (std::vector<AgentRef>::iterator i = passengers.begin(); i != passengers.end(); i++) {
		if (!(*i)) continue; // TODO: muh
		(*i)->moveTo((*i)->x + xoffset, (*i)->y + yoffset);
	}
}

void Vehicle::kill() {
	// TODO: sane?
	while (passengers.size() > 0) {
		if (passengers[0]) dropCarried(passengers[0]);
		else passengers.erase(passengers.begin());
	}

	Agent::kill();
}

/* vim: set noet: */
<|endoftext|>


<commit_before>#include "gamestates/skirmishstate.hpp"

#include "gamestates/deploystate.hpp"
#include "engine/square.hpp"
#include "engine/pathfinding/astar.hpp"
#include "engine/pathfinding/path.hpp"
#include "gui/texturemanager.hpp"
#include "gui/ng/label.hpp"
#include "gui/ng/spritewidget.hpp"
#include "gui/ng/button.hpp"
#include "gui/squaredetailwindow.hpp"

#include <SFML/Graphics/Sprite.hpp>

#include <iostream>
#include <memory>

namespace qrw
{

SkirmishState::SkirmishState(sf::RenderWindow* renderWindow)
	: SceneState(renderWindow, EGameStateId::EGSID_SKIRMISH_STATE),
	  _squareMarker(new SquareMarker())
{
    _squareDetailWindow = new SquareDetailWindow();
    _guiUptr->addWidget(_squareDetailWindow);

	_squareMarker->setVisible(false);

	_playerNameText = new namelessgui::Text();
	_playerNameText->setText("Player Name");
	_playerNameText->setParentAnchor({0.5, 0});
	_playerNameText->setAnchor({0.5, 0});
	_toolBar->addWidget(_playerNameText);

	namelessgui::Button* endTurnButton = new namelessgui::Button();
	endTurnButton->setText("End Turn");
	endTurnButton->setSize({140, 30});
	endTurnButton->setParentAnchor({0.5, 1});
	endTurnButton->setAnchor({0.5, 1.0});
	endTurnButton->setRelativePosition({0.0f, -5.0f});
	endTurnButton->signalclicked.connect(std::bind(&SkirmishState::endTurn, this));
	_toolBar->addWidget(endTurnButton);
}

void SkirmishState::init(GameState *previousState)
{
    SceneState::init(previousState);

    if(previousState->getId() != EGameStateId::EGSID_DEPLOY_STATE)
        return;

    DeployState* deployState = static_cast<DeployState*>(previousState);

    _board = deployState->getBoard();
    _scene->setBoard(_board);

	_players = deployState->getPlayers();
	_currentPlayer = 0;
	_playerNameText->setText(_players[_currentPlayer]->getName());

    // Initialize square detail window.
    Coordinates cursorPosition = _scene->getCursorPosition();
	Unit::Ptr unit = _board->getUnit(cursorPosition);
	Terrain::Ptr terrain = _board->getSquare(cursorPosition)->getTerrain();
	_squareDetailWindow->setUnitAndTerrain(unit, terrain);
}

void SkirmishState::draw()
{
	SceneState::draw();
	_squareMarker->draw(*_renderWindow, sf::RenderStates::Default);
	drawPath();
}

EGameStateId SkirmishState::update()
{
    if(_backToMainMenu)
        return EGameStateId::EGSID_MAIN_MENU_STATE;

    return EGameStateId::EGSID_NO_CHANGE;
}

void SkirmishState::slotCursorMoved(const Coordinates &boardPosition, bool isOnBoard)
{
    if(isOnBoard)
	{
		Unit::Ptr unitUnderCursor = _board->getUnit(boardPosition);
		Terrain::Ptr terrainUnderCursor = _board->getSquare(boardPosition)->getTerrain();
		_squareDetailWindow->setUnitAndTerrain(unitUnderCursor, terrainUnderCursor);

		if(_selectedUnit)
		{
			_path.reset(_board->findPath(_selectedUnit->getPosition(), boardPosition));

			if(_path)
			{
				if(_path->getMovementCosts() > _selectedUnit->getCurrentMovement())
					_scene->getCursor().setFillColor(Cursor::Color::ESC_WARNING);
				else
					_scene->getCursor().setFillColor(Cursor::Color::ESC_DEFAULT);
			}
		}
	}
    else
		_squareDetailWindow->setUnitAndTerrain(nullptr, nullptr);
}

void SkirmishState::moveUnit()
{
	if(!_selectedUnit) return;
	if(!_path) return;

	int pathCosts = _path->getMovementCosts();
	if(pathCosts == 0) return;

	int maxDistance = _selectedUnit->getCurrentMovement();
	if(pathCosts > maxDistance) return;

	int remainingMovement = maxDistance - pathCosts;
	_selectedUnit->setCurrentMovement(remainingMovement);

	_board->getSquare(_squareMarker->getBoardPosition())->setUnit(nullptr);
	_board->getSquare(_path->getTargetPosition())->setUnit(_selectedUnit);

	std::cout << "Move unit." << std::endl;
}

void SkirmishState::performAttack()
{
	std::cout << "Attack unit." << std::endl;
}

void SkirmishState::replenishTroops()
{
	for(int w = 0; w < _board->getWidth(); ++w)
	{
		for(int h = 0; h < _board->getHeight(); ++h)
		{
			auto unit = _board->getSquare(Coordinates(w, h))->getUnit();
			if(unit)
				unit->setCurrentMovement(unit->getMovement());
		}
	}
}

void SkirmishState::slotCursorLeftClicked(const Coordinates &boardPosition)
{
	Unit::Ptr unitUnderCursor = _board->getUnit(boardPosition);
	Terrain::Ptr terrainUnderCursor = _board->getSquare(boardPosition)->getTerrain();

	_squareDetailWindow->setUnitAndTerrain(unitUnderCursor, terrainUnderCursor);

	// Case 1: Unit is selected and instructed to move.
	if(_selectedUnit && !unitUnderCursor)
	{
		// Move unit
		moveUnit();
		deselectUnit();
		return;
	}

	// Case 2: Unit is selected and instructed to attack enemy.
	if(_selectedUnit && unitUnderCursor && unitUnderCursor->getPlayer() != _selectedUnit->getPlayer())
	{
		performAttack();
		return;
	}

	// Do not allow to select units of other player
	if(unitUnderCursor && unitUnderCursor->getPlayer() != _players[_currentPlayer])
	{
		// Select unit
		_selectedUnit = unitUnderCursor;
		_squareMarker->setBoardPosition(boardPosition);
		_squareMarker->setVisible(true);

		return;
	}

	deselectUnit();
}

bool SkirmishState::handleEvent(sf::Event& event)
{
	if(SceneState::handleEvent(event))
		return true;

	if(event.type == sf::Event::MouseButtonReleased)
	{
		if(event.mouseButton.button == sf::Mouse::Right)
		{
			deselectUnit();
			return true;
		}
	}

	return false;
}

void SkirmishState::endTurn()
{
	_currentPlayer = (_currentPlayer + 1) % _players.size();
	_playerNameText->setText(_players[_currentPlayer]->getName());

	deselectUnit();
	replenishTroops();
}

void SkirmishState::drawPath()
{
	if(!_path)
		return;

	const int pathLength = _path->getLength();

	Square* previous = 0;
	Square* current  = _path->getStep(0);
	Square* next     = _path->getStep(1);

	sf::Sprite footstep = sf::Sprite(*TextureManager::getInstance()->getTexture("footstep"));

	// Do not render first step.
	for(int i = 1; i < pathLength; ++i)
	{
		previous = current;
		current  = next;

		// Reset the previously applied transformations.
		footstep.setOrigin(16, 16);
		footstep.setScale(1, 1);
		footstep.setRotation(0);

		// Transformations relative to the previous step
		Coordinates prevDelta(previous->getCoordinates() - current->getCoordinates());
		if(prevDelta.getX() != 0)
			footstep.rotate(-90 * prevDelta.getX());
		if(prevDelta.getY() != 0)
			footstep.scale(1, prevDelta.getY());

		// Transformations relative to the next step (if possible)
		if(i < pathLength - 1)
		{
			next = _path->getStep(i+1);

			Coordinates prevNextDelta(previous->getCoordinates() - next->getCoordinates());

			// If the path has a corner at this position
			if(prevNextDelta.getX() != 0 && prevNextDelta.getY() != 0)
			{
				int rotationdirection = 0;
				// horizontal
				if(prevDelta.getX() == 0)
				{
					rotationdirection = -1;
				}
				// vertical
				else if(prevDelta.getY() == 0)
				{
					rotationdirection = +1;
				}
				footstep.rotate(rotationdirection * 45 * (prevNextDelta.getX() * prevNextDelta.getY()));
			}
		}

		footstep.setPosition(
			32 * (0.5f + current->getXPosition()),
			32 * (0.5f + current->getYPosition())
		);

		_renderWindow->draw(footstep);
	}
}

void SkirmishState::deselectUnit()
{
	_selectedUnit = nullptr;
	_squareMarker->setVisible(false);
	_scene->getCursor().setFillColor(Cursor::Color::ESC_DEFAULT);
	_path.reset();
}

} // namespace qrw
<commit_msg>Fixed movement for square independent unit.<commit_after>#include "gamestates/skirmishstate.hpp"

#include "gamestates/deploystate.hpp"
#include "engine/square.hpp"
#include "engine/pathfinding/astar.hpp"
#include "engine/pathfinding/path.hpp"
#include "gui/texturemanager.hpp"
#include "gui/ng/label.hpp"
#include "gui/ng/spritewidget.hpp"
#include "gui/ng/button.hpp"
#include "gui/squaredetailwindow.hpp"

#include <SFML/Graphics/Sprite.hpp>

#include <iostream>
#include <memory>

namespace qrw
{

SkirmishState::SkirmishState(sf::RenderWindow* renderWindow)
	: SceneState(renderWindow, EGameStateId::EGSID_SKIRMISH_STATE),
	  _squareMarker(new SquareMarker())
{
    _squareDetailWindow = new SquareDetailWindow();
    _guiUptr->addWidget(_squareDetailWindow);

	_squareMarker->setVisible(false);

	_playerNameText = new namelessgui::Text();
	_playerNameText->setText("Player Name");
	_playerNameText->setParentAnchor({0.5, 0});
	_playerNameText->setAnchor({0.5, 0});
	_toolBar->addWidget(_playerNameText);

	namelessgui::Button* endTurnButton = new namelessgui::Button();
	endTurnButton->setText("End Turn");
	endTurnButton->setSize({140, 30});
	endTurnButton->setParentAnchor({0.5, 1});
	endTurnButton->setAnchor({0.5, 1.0});
	endTurnButton->setRelativePosition({0.0f, -5.0f});
	endTurnButton->signalclicked.connect(std::bind(&SkirmishState::endTurn, this));
	_toolBar->addWidget(endTurnButton);
}

void SkirmishState::init(GameState *previousState)
{
    SceneState::init(previousState);

    if(previousState->getId() != EGameStateId::EGSID_DEPLOY_STATE)
        return;

    DeployState* deployState = static_cast<DeployState*>(previousState);

    _board = deployState->getBoard();
    _scene->setBoard(_board);

	_players = deployState->getPlayers();
	_currentPlayer = 0;
	_playerNameText->setText(_players[_currentPlayer]->getName());

    // Initialize square detail window.
    Coordinates cursorPosition = _scene->getCursorPosition();
	Unit::Ptr unit = _board->getUnit(cursorPosition);
	Terrain::Ptr terrain = _board->getSquare(cursorPosition)->getTerrain();
	_squareDetailWindow->setUnitAndTerrain(unit, terrain);
}

void SkirmishState::draw()
{
	SceneState::draw();
	_squareMarker->draw(*_renderWindow, sf::RenderStates::Default);
	drawPath();
}

EGameStateId SkirmishState::update()
{
    if(_backToMainMenu)
        return EGameStateId::EGSID_MAIN_MENU_STATE;

    return EGameStateId::EGSID_NO_CHANGE;
}

void SkirmishState::slotCursorMoved(const Coordinates &boardPosition, bool isOnBoard)
{
    if(isOnBoard)
	{
		Unit::Ptr unitUnderCursor = _board->getUnit(boardPosition);
		Terrain::Ptr terrainUnderCursor = _board->getSquare(boardPosition)->getTerrain();
		_squareDetailWindow->setUnitAndTerrain(unitUnderCursor, terrainUnderCursor);

		if(_selectedUnit)
		{
			_path.reset(_board->findPath(_selectedUnit->getPosition(), boardPosition));

			if(_path)
			{
				if(_path->getMovementCosts() > _selectedUnit->getCurrentMovement())
					_scene->getCursor().setFillColor(Cursor::Color::ESC_WARNING);
				else
					_scene->getCursor().setFillColor(Cursor::Color::ESC_DEFAULT);
			}
		}
	}
    else
		_squareDetailWindow->setUnitAndTerrain(nullptr, nullptr);
}

void SkirmishState::moveUnit()
{
	if(!_selectedUnit) return;
	if(!_path) return;

	int pathCosts = _path->getMovementCosts();
	if(pathCosts == 0) return;

	int maxDistance = _selectedUnit->getCurrentMovement();
	if(pathCosts > maxDistance) return;

	int remainingMovement = maxDistance - pathCosts;
	_selectedUnit->setCurrentMovement(remainingMovement);

	_board->moveUnit(_squareMarker->getBoardPosition(), _path->getTargetPosition());
	_selectedUnit->setPosition(_path->getTargetPosition());

	std::cout << "Move unit." << std::endl;
}

void SkirmishState::performAttack()
{
	std::cout << "Attack unit." << std::endl;
}

void SkirmishState::replenishTroops()
{
	for(int w = 0; w < _board->getWidth(); ++w)
	{
		for(int h = 0; h < _board->getHeight(); ++h)
		{
			auto unit = _board->getSquare(Coordinates(w, h))->getUnit();
			if(unit)
				unit->setCurrentMovement(unit->getMovement());
		}
	}
}

void SkirmishState::slotCursorLeftClicked(const Coordinates &boardPosition)
{
	Unit::Ptr unitUnderCursor = _board->getUnit(boardPosition);
	Terrain::Ptr terrainUnderCursor = _board->getSquare(boardPosition)->getTerrain();

	_squareDetailWindow->setUnitAndTerrain(unitUnderCursor, terrainUnderCursor);

	// Case 1: Unit is selected and instructed to move.
	if(_selectedUnit && !unitUnderCursor)
	{
		// Move unit
		moveUnit();
		deselectUnit();
		return;
	}

	// Case 2: Unit is selected and instructed to attack enemy.
	if(_selectedUnit && unitUnderCursor && unitUnderCursor->getPlayer() != _selectedUnit->getPlayer())
	{
		performAttack();
		return;
	}

	// Do not allow to select units of other player
	if(unitUnderCursor && unitUnderCursor->getPlayer() != _players[_currentPlayer])
	{
		// Select unit
		_selectedUnit = unitUnderCursor;
		_squareMarker->setBoardPosition(boardPosition);
		_squareMarker->setVisible(true);

		return;
	}

	deselectUnit();
}

bool SkirmishState::handleEvent(sf::Event& event)
{
	if(SceneState::handleEvent(event))
		return true;

	if(event.type == sf::Event::MouseButtonReleased)
	{
		if(event.mouseButton.button == sf::Mouse::Right)
		{
			deselectUnit();
			return true;
		}
	}

	return false;
}

void SkirmishState::endTurn()
{
	_currentPlayer = (_currentPlayer + 1) % _players.size();
	_playerNameText->setText(_players[_currentPlayer]->getName());

	deselectUnit();
	replenishTroops();
}

void SkirmishState::drawPath()
{
	if(!_path)
		return;

	const int pathLength = _path->getLength();

	Square* previous = 0;
	Square* current  = _path->getStep(0);
	Square* next     = _path->getStep(1);

	sf::Sprite footstep = sf::Sprite(*TextureManager::getInstance()->getTexture("footstep"));

	// Do not render first step.
	for(int i = 1; i < pathLength; ++i)
	{
		previous = current;
		current  = next;

		// Reset the previously applied transformations.
		footstep.setOrigin(16, 16);
		footstep.setScale(1, 1);
		footstep.setRotation(0);

		// Transformations relative to the previous step
		Coordinates prevDelta(previous->getCoordinates() - current->getCoordinates());
		if(prevDelta.getX() != 0)
			footstep.rotate(-90 * prevDelta.getX());
		if(prevDelta.getY() != 0)
			footstep.scale(1, prevDelta.getY());

		// Transformations relative to the next step (if possible)
		if(i < pathLength - 1)
		{
			next = _path->getStep(i+1);

			Coordinates prevNextDelta(previous->getCoordinates() - next->getCoordinates());

			// If the path has a corner at this position
			if(prevNextDelta.getX() != 0 && prevNextDelta.getY() != 0)
			{
				int rotationdirection = 0;
				// horizontal
				if(prevDelta.getX() == 0)
				{
					rotationdirection = -1;
				}
				// vertical
				else if(prevDelta.getY() == 0)
				{
					rotationdirection = +1;
				}
				footstep.rotate(rotationdirection * 45 * (prevNextDelta.getX() * prevNextDelta.getY()));
			}
		}

		footstep.setPosition(
			32 * (0.5f + current->getXPosition()),
			32 * (0.5f + current->getYPosition())
		);

		_renderWindow->draw(footstep);
	}
}

void SkirmishState::deselectUnit()
{
	_selectedUnit = nullptr;
	_squareMarker->setVisible(false);
	_scene->getCursor().setFillColor(Cursor::Color::ESC_DEFAULT);
	_path.reset();
}

} // namespace qrw
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: precompiled_sc.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2006-12-05 14:26:12 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): Generated on 2006-07-11 15:52:42.937361

#ifdef PRECOMPILED_HEADERS
#include "scitems.hxx"

#include <algorithm>
#include <assert.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <iosfwd>
#include <limits.h>
#include <limits>
#include <list>
#include <math.h>
#include <memory>
#include <new>
#include <cfloat>

#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b3dpolygon.hxx>
#include <basegfx/polygon/b3dpolypolygon.hxx>
#include <com/sun/star/uno/Any.h>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Sequence.h>
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/uno/Type.hxx>
#include <config/_epilog.h>
#include <config/_msvc_warnings_off.h>
#include <config/_prolog.h>
#include <cppu/macros.hxx>
#include <cppuhelper/weakref.hxx>
#include <cstddef>
#include <cwchar>
#include <float.h>
#include <functional>
#include <goodies/b3dcolor.hxx>
#include <goodies/b3dcompo.hxx>
#include <goodies/b3dentty.hxx>
#include <goodies/b3dlight.hxx>
#include <goodies/bucket.hxx>
#include <goodies/matril3d.hxx>
#include <offuh/com/sun/star/awt/Point.hdl>
#include <offuh/com/sun/star/awt/Point.hpp>
#include <offuh/com/sun/star/awt/Size.hdl>
#include <offuh/com/sun/star/awt/Size.hpp>
#include <offuh/com/sun/star/beans/PropertyVetoException.hdl>
#include <offuh/com/sun/star/beans/PropertyVetoException.hpp>
#include <offuh/com/sun/star/container/ElementExistException.hdl>
#include <offuh/com/sun/star/container/ElementExistException.hpp>
#include <offuh/com/sun/star/container/NoSuchElementException.hpp>
#include <offuh/com/sun/star/container/xElementAccess.hdl>
#include <offuh/com/sun/star/container/xElementAccess.hpp>
#include <offuh/com/sun/star/container/xNameAccess.hpp>
#include <offuh/com/sun/star/datatransfer/dataflavor.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/draggestureevent.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/dragsourcedragevent.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/dragsourcedragevent.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/dragsourcedropevent.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/dragsourceevent.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/droptargetdragenterevent.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/droptargetdragenterevent.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/droptargetdragevent.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/droptargetdragevent.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/droptargetdropevent.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/droptargetevent.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/droptargetevent.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/xdraggesturelistener.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/xdraggesturelistener.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/xdragsource.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/xdragsource.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/xdragsourcecontext.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/xdragsourcecontext.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/xdragsourcelistener.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/xdragsourcelistener.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/xdroptargetdragcontext.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/xdroptargetlistener.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/xdroptargetlistener.hpp>
#include <offuh/com/sun/star/datatransfer/unsupportedflavorexception.hdl>
#include <offuh/com/sun/star/datatransfer/xtransferable.hpp>
#include <offuh/com/sun/star/drawing/xshape.hpp>
#include <offuh/com/sun/star/embed/invalidstorageexception.hpp>
#include <offuh/com/sun/star/embed/storagewrappedtargetexception.hdl>
#include <offuh/com/sun/star/embed/storagewrappedtargetexception.hpp>
#include <offuh/com/sun/star/embed/xstorage.hdl>
#include <offuh/com/sun/star/embed/xstorage.hpp>
#include <offuh/com/sun/star/io/buffersizeexceededexception.hpp>
#include <offuh/com/sun/star/io/ioexception.hdl>
#include <offuh/com/sun/star/io/notconnectedexception.hdl>
#include <offuh/com/sun/star/io/notconnectedexception.hpp>
#include <offuh/com/sun/star/io/xinputstream.hdl>
#include <offuh/com/sun/star/io/xinputstream.hpp>
#include <offuh/com/sun/star/io/xoutputstream.hdl>
#include <offuh/com/sun/star/io/xoutputstream.hpp>
#include <offuh/com/sun/star/io/xstream.hdl>
#include <offuh/com/sun/star/lang/eventobject.hdl>
#include <offuh/com/sun/star/lang/illegalargumentexception.hpp>
#include <offuh/com/sun/star/lang/wrappedtargetexception.hdl>
#include <offuh/com/sun/star/lang/wrappedtargetexception.hpp>
#include <offuh/com/sun/star/lang/xcomponent.hpp>
#include <offuh/com/sun/star/lang/xeventlistener.hpp>
#include <offuh/com/sun/star/packages/noencryptionexception.hdl>
#include <offuh/com/sun/star/packages/noencryptionexception.hpp>
#include <offuh/com/sun/star/packages/wrongpasswordexception.hdl>
#include <offuh/com/sun/star/packages/wrongpasswordexception.hpp>
#include <offuh/com/sun/star/uno/exception.hdl>
#include <offuh/com/sun/star/uno/exception.hpp>
#include <offuh/com/sun/star/uno/runtimeexception.hdl>
#include <offuh/com/sun/star/uno/runtimeexception.hpp>
#include <offuh/com/sun/star/uno/xadapter.hdl>
#include <offuh/com/sun/star/uno/xadapter.hpp>
#include <offuh/com/sun/star/uno/xinterface.hdl>
#include <offuh/com/sun/star/uno/xreference.hdl>
#include <offuh/com/sun/star/uno/xreference.hpp>
#include <offuh/com/sun/star/uno/xweak.hpp>
#include <osl/endian.h>
#include <osl/interlck.h>
#include <osl/mutex.hxx>
#include <rtl/alloc.h>
#include <rtl/string.h>
#include <rtl/ustrbuf.h>
#include <rtl/ustring.h>
#include <sal/mathconf.h>
#include <sal/types.h>
#include <sot/exchange.hxx>
#include <sot/factory.hxx>
#include <sot/storage.hxx>
#include <svtools/brdcst.hxx>
#include <svtools/cenumitm.hxx>
#include <svtools/cintitem.hxx>
#include <svtools/fltrcfg.hxx>
#include <svtools/intitem.hxx>
#include <svtools/listener.hxx>
#include <svtools/lstner.hxx>
#include <svtools/pathoptions.hxx>
#include <svtools/solar.hrc>
#include <svtools/useroptions.hxx>
#include <svx/editobj.hxx>
#include <svx/eeitem.hxx>
#include <svx/fmglob.hxx>
#include <svx/outlobj.hxx>
#include <svx/sdangitm.hxx>
#include <svx/sderitm.hxx>
#include <svx/sdmetitm.hxx>
#include <svx/sdooitm.hxx>
#include <svx/sdprcitm.hxx>
#include <svx/sdrmasterpagedescriptor.hxx>
#include <svx/sdrpageuser.hxx>
#include <svx/sdtaitm.hxx>
#include <svx/svdglue.hxx>
#include <svx/svdlayer.hxx>
#include <svx/svdoattr.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdpage.hxx>
#include <svx/svdpool.hxx>
#include <svx/svdtrans.hxx>
#include <svx/svdtypes.hxx>
#include <svx/unoapi.hxx>
#include <svx/volume3d.hxx>
#include <svx/xcolit.hxx>
#include <svx/xenum.hxx>
#include <svx/xfillit0.hxx>
#include <svx/xflasit.hxx>
#include <svx/xlineit0.hxx>
#include <svx/xlnasit.hxx>
#include <svx/xtextit0.hxx>
#include <tools/date.hxx>
#include <tools/datetime.hxx>
#include <tools/errcode.hxx>
#include <tools/errinf.hxx>
#include <tools/gen.hxx>
#include <tools/globname.hxx>
#include <tools/list.hxx>
#include <tools/rc.hxx>
#include <tools/rtti.hxx>
#include <tools/solar.h>
#include <tools/string.hxx>
#include <tools/toolsdllapi.h>
#include <tools/weakbase.h>
#include <tools/weakbase.hxx>
#include <typeinfo.h>
#include <typeinfo>
#include <typelib/typeclass.h>
#include <typelib/typedescription.h>
#include <typelib/uik.h>
#include <uno/any2.h>
#include <uno/lbnames.h>
#include <uno/sequence2.h>
#include <unotools/ucbstreamhelper.hxx>

#include <vcl/apptypes.hxx>
#include <vcl/bitmap.hxx>
#include <vcl/bitmapex.hxx>
#include <vcl/dllapi.h>
#include <vcl/dndhelp.hxx>
#include <vcl/edit.hxx>
#include <vcl/field.hxx>
#include <vcl/fldunit.hxx>
#include <vcl/gdimtf.hxx>
#include <vcl/inputctx.hxx>
#include <vcl/jobset.hxx>
#include <vcl/mapmod.hxx>
#include <vcl/menu.hxx>
#include <vcl/pointr.hxx>
#include <vcl/print.hxx>
#include <vcl/prntypes.hxx>
#include <vcl/ptrstyle.hxx>
#include <vcl/region.hxx>
#include <vcl/salnativewidgets.hxx>
#include <vcl/spinfld.hxx>
#include <vcl/sv.h>
#include <vcl/svapp.hxx>
#include <vcl/vclevent.hxx>
#include <vcl/window.hxx>
#include <vcl/wintypes.hxx>
#include <vos/macros.hxx>
#include <vos/object.hxx>
#include <vos/types.hxx>
#include <wchar.h>

#endif

<commit_msg>#i10000# #include <sal/config.h><commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: precompiled_sc.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-14 16:17:59 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): Generated on 2006-07-11 15:52:42.937361

#ifdef PRECOMPILED_HEADERS
#include <sal/config.h>
#include "scitems.hxx"

#include <algorithm>
#include <assert.h>
#include <stdarg.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <iosfwd>
#include <limits.h>
#include <limits>
#include <list>
#include <math.h>
#include <memory>
#include <new>
#include <cfloat>

#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b3dpolygon.hxx>
#include <basegfx/polygon/b3dpolypolygon.hxx>
#include <com/sun/star/uno/Any.h>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Sequence.h>
#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/uno/Type.hxx>
#include <config/_epilog.h>
#include <config/_msvc_warnings_off.h>
#include <config/_prolog.h>
#include <cppu/macros.hxx>
#include <cppuhelper/weakref.hxx>
#include <cstddef>
#include <cwchar>
#include <float.h>
#include <functional>
#include <goodies/b3dcolor.hxx>
#include <goodies/b3dcompo.hxx>
#include <goodies/b3dentty.hxx>
#include <goodies/b3dlight.hxx>
#include <goodies/bucket.hxx>
#include <goodies/matril3d.hxx>
#include <offuh/com/sun/star/awt/Point.hdl>
#include <offuh/com/sun/star/awt/Point.hpp>
#include <offuh/com/sun/star/awt/Size.hdl>
#include <offuh/com/sun/star/awt/Size.hpp>
#include <offuh/com/sun/star/beans/PropertyVetoException.hdl>
#include <offuh/com/sun/star/beans/PropertyVetoException.hpp>
#include <offuh/com/sun/star/container/ElementExistException.hdl>
#include <offuh/com/sun/star/container/ElementExistException.hpp>
#include <offuh/com/sun/star/container/NoSuchElementException.hpp>
#include <offuh/com/sun/star/container/xElementAccess.hdl>
#include <offuh/com/sun/star/container/xElementAccess.hpp>
#include <offuh/com/sun/star/container/xNameAccess.hpp>
#include <offuh/com/sun/star/datatransfer/dataflavor.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/draggestureevent.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/dragsourcedragevent.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/dragsourcedragevent.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/dragsourcedropevent.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/dragsourceevent.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/droptargetdragenterevent.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/droptargetdragenterevent.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/droptargetdragevent.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/droptargetdragevent.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/droptargetdropevent.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/droptargetevent.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/droptargetevent.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/xdraggesturelistener.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/xdraggesturelistener.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/xdragsource.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/xdragsource.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/xdragsourcecontext.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/xdragsourcecontext.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/xdragsourcelistener.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/xdragsourcelistener.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/xdroptargetdragcontext.hpp>
#include <offuh/com/sun/star/datatransfer/dnd/xdroptargetlistener.hdl>
#include <offuh/com/sun/star/datatransfer/dnd/xdroptargetlistener.hpp>
#include <offuh/com/sun/star/datatransfer/unsupportedflavorexception.hdl>
#include <offuh/com/sun/star/datatransfer/xtransferable.hpp>
#include <offuh/com/sun/star/drawing/xshape.hpp>
#include <offuh/com/sun/star/embed/invalidstorageexception.hpp>
#include <offuh/com/sun/star/embed/storagewrappedtargetexception.hdl>
#include <offuh/com/sun/star/embed/storagewrappedtargetexception.hpp>
#include <offuh/com/sun/star/embed/xstorage.hdl>
#include <offuh/com/sun/star/embed/xstorage.hpp>
#include <offuh/com/sun/star/io/buffersizeexceededexception.hpp>
#include <offuh/com/sun/star/io/ioexception.hdl>
#include <offuh/com/sun/star/io/notconnectedexception.hdl>
#include <offuh/com/sun/star/io/notconnectedexception.hpp>
#include <offuh/com/sun/star/io/xinputstream.hdl>
#include <offuh/com/sun/star/io/xinputstream.hpp>
#include <offuh/com/sun/star/io/xoutputstream.hdl>
#include <offuh/com/sun/star/io/xoutputstream.hpp>
#include <offuh/com/sun/star/io/xstream.hdl>
#include <offuh/com/sun/star/lang/eventobject.hdl>
#include <offuh/com/sun/star/lang/illegalargumentexception.hpp>
#include <offuh/com/sun/star/lang/wrappedtargetexception.hdl>
#include <offuh/com/sun/star/lang/wrappedtargetexception.hpp>
#include <offuh/com/sun/star/lang/xcomponent.hpp>
#include <offuh/com/sun/star/lang/xeventlistener.hpp>
#include <offuh/com/sun/star/packages/noencryptionexception.hdl>
#include <offuh/com/sun/star/packages/noencryptionexception.hpp>
#include <offuh/com/sun/star/packages/wrongpasswordexception.hdl>
#include <offuh/com/sun/star/packages/wrongpasswordexception.hpp>
#include <offuh/com/sun/star/uno/exception.hdl>
#include <offuh/com/sun/star/uno/exception.hpp>
#include <offuh/com/sun/star/uno/runtimeexception.hdl>
#include <offuh/com/sun/star/uno/runtimeexception.hpp>
#include <offuh/com/sun/star/uno/xadapter.hdl>
#include <offuh/com/sun/star/uno/xadapter.hpp>
#include <offuh/com/sun/star/uno/xinterface.hdl>
#include <offuh/com/sun/star/uno/xreference.hdl>
#include <offuh/com/sun/star/uno/xreference.hpp>
#include <offuh/com/sun/star/uno/xweak.hpp>
#include <osl/endian.h>
#include <osl/interlck.h>
#include <osl/mutex.hxx>
#include <rtl/alloc.h>
#include <rtl/string.h>
#include <rtl/ustrbuf.h>
#include <rtl/ustring.h>
#include <sal/mathconf.h>
#include <sal/types.h>
#include <sot/exchange.hxx>
#include <sot/factory.hxx>
#include <sot/storage.hxx>
#include <svtools/brdcst.hxx>
#include <svtools/cenumitm.hxx>
#include <svtools/cintitem.hxx>
#include <svtools/fltrcfg.hxx>
#include <svtools/intitem.hxx>
#include <svtools/listener.hxx>
#include <svtools/lstner.hxx>
#include <svtools/pathoptions.hxx>
#include <svtools/solar.hrc>
#include <svtools/useroptions.hxx>
#include <svx/editobj.hxx>
#include <svx/eeitem.hxx>
#include <svx/fmglob.hxx>
#include <svx/outlobj.hxx>
#include <svx/sdangitm.hxx>
#include <svx/sderitm.hxx>
#include <svx/sdmetitm.hxx>
#include <svx/sdooitm.hxx>
#include <svx/sdprcitm.hxx>
#include <svx/sdrmasterpagedescriptor.hxx>
#include <svx/sdrpageuser.hxx>
#include <svx/sdtaitm.hxx>
#include <svx/svdglue.hxx>
#include <svx/svdlayer.hxx>
#include <svx/svdoattr.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdpage.hxx>
#include <svx/svdpool.hxx>
#include <svx/svdtrans.hxx>
#include <svx/svdtypes.hxx>
#include <svx/unoapi.hxx>
#include <svx/volume3d.hxx>
#include <svx/xcolit.hxx>
#include <svx/xenum.hxx>
#include <svx/xfillit0.hxx>
#include <svx/xflasit.hxx>
#include <svx/xlineit0.hxx>
#include <svx/xlnasit.hxx>
#include <svx/xtextit0.hxx>
#include <tools/date.hxx>
#include <tools/datetime.hxx>
#include <tools/errcode.hxx>
#include <tools/errinf.hxx>
#include <tools/gen.hxx>
#include <tools/globname.hxx>
#include <tools/list.hxx>
#include <tools/rc.hxx>
#include <tools/rtti.hxx>
#include <tools/solar.h>
#include <tools/string.hxx>
#include <tools/toolsdllapi.h>
#include <tools/weakbase.h>
#include <tools/weakbase.hxx>
#include <typeinfo.h>
#include <typeinfo>
#include <typelib/typeclass.h>
#include <typelib/typedescription.h>
#include <typelib/uik.h>
#include <uno/any2.h>
#include <uno/lbnames.h>
#include <uno/sequence2.h>
#include <unotools/ucbstreamhelper.hxx>

#include <vcl/apptypes.hxx>
#include <vcl/bitmap.hxx>
#include <vcl/bitmapex.hxx>
#include <vcl/dllapi.h>
#include <vcl/dndhelp.hxx>
#include <vcl/edit.hxx>
#include <vcl/field.hxx>
#include <vcl/fldunit.hxx>
#include <vcl/gdimtf.hxx>
#include <vcl/inputctx.hxx>
#include <vcl/jobset.hxx>
#include <vcl/mapmod.hxx>
#include <vcl/menu.hxx>
#include <vcl/pointr.hxx>
#include <vcl/print.hxx>
#include <vcl/prntypes.hxx>
#include <vcl/ptrstyle.hxx>
#include <vcl/region.hxx>
#include <vcl/salnativewidgets.hxx>
#include <vcl/spinfld.hxx>
#include <vcl/sv.h>
#include <vcl/svapp.hxx>
#include <vcl/vclevent.hxx>
#include <vcl/window.hxx>
#include <vcl/wintypes.hxx>
#include <vos/macros.hxx>
#include <vos/object.hxx>
#include <vos/types.hxx>
#include <wchar.h>

#endif

<|endoftext|>


<commit_before><commit_msg>Revert this to build on msvc 2008<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: drformsh.hxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:44:58 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef DRFORMSH_HXX
#define DRFORMSH_HXX

#ifndef _SFX_SHELL_HXX //autogen
#include <sfx2/shell.hxx>
#endif
#include "shellids.hxx"
#ifndef _SFXMODULE_HXX //autogen
#include <sfx2/module.hxx>
#endif

#ifndef _SVDMARK_HXX //autogen
#include <svx/svdmark.hxx>
#endif

class ScViewData;

#include "drawsh.hxx"

class ScDrawFormShell: public ScDrawShell
{
public:

    TYPEINFO();
    SFX_DECL_INTERFACE(SCID_FORM_SHELL);

                ScDrawFormShell(ScViewData* pData);
    virtual     ~ScDrawFormShell();

//  void        Execute(SfxRequest &);
//  void        GetState(SfxItemSet &);
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.942); FILE MERGED 2005/09/05 15:05:18 rt 1.1.1.1.942.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: drformsh.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 21:22:40 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef DRFORMSH_HXX
#define DRFORMSH_HXX

#ifndef _SFX_SHELL_HXX //autogen
#include <sfx2/shell.hxx>
#endif
#include "shellids.hxx"
#ifndef _SFXMODULE_HXX //autogen
#include <sfx2/module.hxx>
#endif

#ifndef _SVDMARK_HXX //autogen
#include <svx/svdmark.hxx>
#endif

class ScViewData;

#include "drawsh.hxx"

class ScDrawFormShell: public ScDrawShell
{
public:

    TYPEINFO();
    SFX_DECL_INTERFACE(SCID_FORM_SHELL);

                ScDrawFormShell(ScViewData* pData);
    virtual     ~ScDrawFormShell();

//  void        Execute(SfxRequest &);
//  void        GetState(SfxItemSet &);
};

#endif
<|endoftext|>


<commit_before>//
//  weak_symbols.cpp
//  Parse
//
//  Created by Andrew Hunter on 06/05/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#include "TameParse/Lr/weak_symbols.h"

using namespace std;
using namespace dfa;
using namespace contextfree;
using namespace lr;

/// \brief Constructs a translator with no weak symbols
weak_symbols::weak_symbols(const grammar* gram)
: m_WeakSymbols(gram)
, m_Grammar(gram) {
}

/// \brief Constructs a rewriter with the specified map of strong to weak symbols
weak_symbols::weak_symbols(const item_map& map, const grammar* gram)
: m_StrongToWeak(map)
, m_WeakSymbols(gram)
, m_Grammar(gram) {
}

/// \brief Copy constructor
weak_symbols::weak_symbols(const weak_symbols& copyFrom)
: m_StrongToWeak(copyFrom.m_StrongToWeak)
, m_WeakSymbols(copyFrom.m_WeakSymbols)
, m_Grammar(copyFrom.m_Grammar) {
}

/// \brief Destructor
weak_symbols::~weak_symbols() {
}

/// \brief Maps the specified strong symbol to the specified set of weak symbols
void weak_symbols::add_symbols(const contextfree::item_container& strong, const contextfree::item_set& weak) {
    // Merge the set of symbols for this strong symbol
    item_map::iterator weakForStrong = m_StrongToWeak.find(strong);
    if (weakForStrong == m_StrongToWeak.end()) {
        weakForStrong = m_StrongToWeak.insert(item_map::value_type(strong, item_set(m_Grammar))).first;
    }

    weakForStrong->second.merge(weak);

    // Store these as weak symbols
    m_WeakSymbols.merge(weak);
}

/// \brief Given a set of weak symbols and a DFA (note: NOT an NDFA), determines the appropriate strong symbols and adds them
void weak_symbols::add_symbols(ndfa& dfa, const item_set& weak, terminal_dictionary& terminals) {
    // Nothing to do if there are no weak symbols
    if (weak.empty()) {
        return;
    }

    // Create a set of the identifiers of the weak terminals in the set
    set<int> weakIdentifiers;

    for (item_set::const_iterator it = weak.begin(); it != weak.end(); ++it) {
        // Only terminal symbols are returned by a NDFA
        if ((*it)->type() != item::terminal) continue;

        // Map this item
        weakIdentifiers.insert((*it)->symbol());
    }

    // Map of weak to strong symbols
    map<int, int> weakToStrong;

    // Iterate through all of the DFA states
    typedef ndfa::accept_action_list accept_actions;
    for (int state = 0; state < dfa.count_states(); state++) {
        // Get the accepting actions for this state
        const accept_actions& accept = dfa.actions_for_state(state);

        // Ignore this state if it has no accepting actions
        if (accept.empty()) continue;

        // Iterate through the accepting action list and determine the 'strongest' symbol
        int         strongest   = 0x7fffffff;
        set<int>    usedWeak;

        for (accept_actions::const_iterator it = accept.begin(); it != accept.end(); it++) {
            int sym = (*it)->symbol();

            // Ignore weak symbols
            if (weakIdentifiers.find(sym) != weakIdentifiers.end()) {
                usedWeak.insert(sym);
                continue;
            }

            // Lower symbol IDs are stronger than weaker ones, and the strongest ID is the one that will be accepted
            // (Same as is defined in the ordering of accept_action)
            if (sym < strongest) {
                strongest = sym;
            }
        }

        // If no 'strongest' symbol was found, then all the symbols here are weak, and we can ignore this state
        if (strongest == 0x7fffffff)    continue;

        // Also can ignore the state if no weak symbols were found
        if (usedWeak.empty())           continue;

        // Map the weak symbols we found to this identifier
        for (set<int>::iterator it = usedWeak.begin(); it != usedWeak.end(); it++) {
            if (weakToStrong.find(*it) == weakToStrong.end()) {
                // This is the first conflict between the two symbols. Just mark out the mapping.
                weakToStrong[*it] = strongest;
            } else if (weakToStrong[*it] != strongest) {
                // The weak symbol is used somewhere else with a different meaning
                // NOTE: this isn't ideal, as if there's an identical conflict somewhere else we generate more and more symbols for each conflicting
                // state, while we only need one new symbol for each (weak, strong) pair.

                // Split the weak symbol so that we have two different meanings
                int splitSymbolId = terminals.split(*it);

                // Change the accepting action for this state so that it accepts the new symbol
                dfa.clear_accept(state);
                dfa.accept(state, splitSymbolId);

                // Map this in the weakToStrong table
                weakToStrong[splitSymbolId] = strongest;
            }
        }
    }

    // TODO: if a weak symbol maps to several strong identifiers, it needs to be split into several symbols

    // Fill in the strong map for each weak symbol
    for (map<int, int>::iterator it = weakToStrong.begin(); it != weakToStrong.end(); it++) {
        // Use the first strong symbol for this weak symbol
        item_container strongTerm(new terminal(it->second), true);
        item_container weakTerm(new terminal(it->first), true);

        item_map::iterator weakForStrong = m_StrongToWeak.find(strongTerm);
        if (weakForStrong == m_StrongToWeak.end()) {
            weakForStrong = m_StrongToWeak.insert(item_map::value_type(strongTerm, item_set(m_Grammar))).first;
        }

        weakForStrong->second.insert(weakTerm);
    }

    // Add to the list of weak symbols
    m_WeakSymbols.merge(weak);
}

/// \brief Modifies the specified set of actions according to the rules in this rewriter
///
/// To deal with weak symbols, several rewrites are performed.
///
///  * All shift actions are left intact (whether weak or strong)
///  * All actions for symbols that are 'strong' (not in the m_WeakSymbols table) are left intact
///  * Reduce actions on weak symbols where there is an equivalent shift or reduce action on a strong symbol
///    are changed to weak reduce actions
///  * For strong symbols, any equivalent weak symbol that does not have an action other than weak reduce, the
///    same action is added
///
/// For states that do not contain any actions containing strong symbols with weak equivalents, there is no
/// need to change the contents of the state.
///
/// Something to note is that this will change the reduce part of conflicts to refer to the action defined by
/// the strong symbol instead of the weak symbol.
///
/// Something else to note is that if a strong symbol is considered for an action before a weak symbol where
/// there is a potential clash, then it's likely that the parser will be incorrect as weak reduce actions for
/// the weak symbol will not be considered in many cases.
void weak_symbols::rewrite_actions(int state, lr_action_set& actions, const lalr_builder& builder) const {
    // Determine if there are any actions referring to strong symbols in this action set
    bool haveStrong = false;

    for (lr_action_set::const_iterator it = actions.begin(); it != actions.end(); it++) {
        // This only deals with actions on terminal items
        if ((*it)->item()->type() != item::terminal) continue;

        // See if the symbol is marked as being 'strong' and has weak symbols associated with it
        item_map::const_iterator found = m_StrongToWeak.find((*it)->item());
        if (found != m_StrongToWeak.end() && !found->second.empty()) {
            haveStrong = true;
            break;
        }
    }

    // If none of the actions reference strong items with weak equivalents, then the actions can be left as they are
    if (!haveStrong) return;

    // Start building up a new set of actions
    lr_action_set newActions;

    // Add actions for any strong symbols, and remember the weak symbols that already have actions
    map<int, int>               weakSymbols;                // Maps symbols to # actions that refer to them
    stack<lr_action_container>  weakActions;                // Weak actions not processed in the first pass
    stack<lr_action_container>  strongActions;              // Strong actions that might have associated weak symbols

    for (lr_action_set::const_iterator act = actions.begin(); act != actions.end(); act++) {
        // Actions on non-terminal symbols should be preserved
        if ((*act)->item()->type() != item::terminal) {
            newActions.insert(*act);
            continue;
        }

        // Work out if this action is on a strong symbol
        bool isStrong = !m_WeakSymbols.contains((*act)->item());

        // Actions on strong symbols should be preserved without alteration
        if (isStrong) {
            strongActions.push(*act);
            newActions.insert(*act);
            continue;
        }

        // Fetch the symbol for this action
        int sym = (*act)->item()->symbol();

        // Mark this weak symbol as having an existing action
        weakSymbols[sym]++;

        // Push on to the set of weak actions
        weakActions.push(*act);
    }

    // Transform the actions associated with weak symbols
    while (!weakActions.empty()) {
        // Get the next action
        const lr_action_container& act = weakActions.top();

        // How this is rewritten depends on the action
        switch (act->type()) {
            case lr_action::act_shift:
            case lr_action::act_shiftstrong:
            case lr_action::act_ignore:
            case lr_action::act_accept:
                // Preserve the action
                newActions.insert(act);
                break;

            case lr_action::act_reduce:
            case lr_action::act_weakreduce:
            {
                // Reduce actions are rewritten as weak reduce actions
                // TODO: if the strong symbol equivalent of this weak symbol is not present in the action, then
                // leave this as a standard reduce
                lr_action_container weakReduce(new lr_action(lr_action::act_weakreduce, act->item(), act->next_state(), act->rule()), true);
                newActions.insert(weakReduce);

                // Remove from the weak symbols table if there are no other actions for this symbol
                // This means that if there is a strong symbol that is equivalent to this weak symbol that the actions
                // for that symbol will be generated. If the strong symbol has a higher priority than the weak action
                // (by default: has a lower symbol ID), then its actions will be considered first, which is incorrect.
                int sym = act->item()->symbol();

                map<int, int>::iterator found = weakSymbols.find(sym);
                if (found != weakSymbols.end()) {
                    found->second--;
                    if (found->second < 0) {
                        weakSymbols.erase(found);
                    }
                }
                break;
           }

            default:
                // ?? unknown action ??
                // Remove unknown actions that seem to refer to weak symbols
                break;
        }

        // Next action
        weakActions.pop();
    }

    // For any action on a strong symbol, generate the same action for equivalent weak symbols (if there is no equivalent action)
    // TODO: if a new action is the same as an existing weak symbol action (ie, the weak symbol has produced a weak reduce
    // of the same rule) then we only need one action
    for (; !strongActions.empty(); strongActions.pop()) {
        // Get the next action
        const lr_action_container& act = strongActions.top();

        // Look up the equivalent weak symbols for this action
        item_map::const_iterator equivalent = m_StrongToWeak.find(act->item());

        // Nothing to do if there are no equivalent symbols
        if (equivalent == m_StrongToWeak.end()) continue;

        // Iterate through the weak symbols and generate equivalent actions
        for (item_set::const_iterator weakEquiv = equivalent->second.begin(); weakEquiv != equivalent->second.end(); ++weakEquiv) {
            // Can't deal with non-terminal symbols (should be none, but you can technically add them)
            if ((*weakEquiv)->type() != item::terminal) continue;

            // Get the symbol ID of this equivalent symbol
            int symId = (*weakEquiv)->symbol();

            // Nothing to do if this symbol has an alternative action
            if (weakSymbols.find(symId) != weakSymbols.end()) continue;

            // Add a duplicate action referring to the weak symbol, identical to the action for the strong symbol
            lr_action_container weakEquivAct(new lr_action(*act, *weakEquiv), true);

            // Shift actions become shift-strong actions (so the symbol ID is substituted)
            if (weakEquivAct->type() == lr_action::act_shift) {
                weakEquivAct->set_type(lr_action::act_shiftstrong);
            }

            newActions.insert(weakEquivAct);
        }
    }

    // Update the action table with our results
    actions = newActions;
}

/// \brief Creates a clone of this rewriter
action_rewriter* weak_symbols::clone() const {
    return new weak_symbols(*this);
}
<commit_msg>A guard action does not 'use' a weak symbol as such (though you do end up with guard actions for both the strong and weak equivalents if there's a conflict)<commit_after>//
//  weak_symbols.cpp
//  Parse
//
//  Created by Andrew Hunter on 06/05/2011.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#include "TameParse/Lr/weak_symbols.h"

using namespace std;
using namespace dfa;
using namespace contextfree;
using namespace lr;

/// \brief Constructs a translator with no weak symbols
weak_symbols::weak_symbols(const grammar* gram)
: m_WeakSymbols(gram)
, m_Grammar(gram) {
}

/// \brief Constructs a rewriter with the specified map of strong to weak symbols
weak_symbols::weak_symbols(const item_map& map, const grammar* gram)
: m_StrongToWeak(map)
, m_WeakSymbols(gram)
, m_Grammar(gram) {
}

/// \brief Copy constructor
weak_symbols::weak_symbols(const weak_symbols& copyFrom)
: m_StrongToWeak(copyFrom.m_StrongToWeak)
, m_WeakSymbols(copyFrom.m_WeakSymbols)
, m_Grammar(copyFrom.m_Grammar) {
}

/// \brief Destructor
weak_symbols::~weak_symbols() {
}

/// \brief Maps the specified strong symbol to the specified set of weak symbols
void weak_symbols::add_symbols(const contextfree::item_container& strong, const contextfree::item_set& weak) {
    // Merge the set of symbols for this strong symbol
    item_map::iterator weakForStrong = m_StrongToWeak.find(strong);
    if (weakForStrong == m_StrongToWeak.end()) {
        weakForStrong = m_StrongToWeak.insert(item_map::value_type(strong, item_set(m_Grammar))).first;
    }

    weakForStrong->second.merge(weak);

    // Store these as weak symbols
    m_WeakSymbols.merge(weak);
}

/// \brief Given a set of weak symbols and a DFA (note: NOT an NDFA), determines the appropriate strong symbols and adds them
void weak_symbols::add_symbols(ndfa& dfa, const item_set& weak, terminal_dictionary& terminals) {
    // Nothing to do if there are no weak symbols
    if (weak.empty()) {
        return;
    }

    // Create a set of the identifiers of the weak terminals in the set
    set<int> weakIdentifiers;

    for (item_set::const_iterator it = weak.begin(); it != weak.end(); ++it) {
        // Only terminal symbols are returned by a NDFA
        if ((*it)->type() != item::terminal) continue;

        // Map this item
        weakIdentifiers.insert((*it)->symbol());
    }

    // Map of weak to strong symbols
    map<int, int> weakToStrong;

    // Iterate through all of the DFA states
    typedef ndfa::accept_action_list accept_actions;
    for (int state = 0; state < dfa.count_states(); state++) {
        // Get the accepting actions for this state
        const accept_actions& accept = dfa.actions_for_state(state);

        // Ignore this state if it has no accepting actions
        if (accept.empty()) continue;

        // Iterate through the accepting action list and determine the 'strongest' symbol
        int         strongest   = 0x7fffffff;
        set<int>    usedWeak;

        for (accept_actions::const_iterator it = accept.begin(); it != accept.end(); it++) {
            int sym = (*it)->symbol();

            // Ignore weak symbols
            if (weakIdentifiers.find(sym) != weakIdentifiers.end()) {
                usedWeak.insert(sym);
                continue;
            }

            // Lower symbol IDs are stronger than weaker ones, and the strongest ID is the one that will be accepted
            // (Same as is defined in the ordering of accept_action)
            if (sym < strongest) {
                strongest = sym;
            }
        }

        // If no 'strongest' symbol was found, then all the symbols here are weak, and we can ignore this state
        if (strongest == 0x7fffffff)    continue;

        // Also can ignore the state if no weak symbols were found
        if (usedWeak.empty())           continue;

        // Map the weak symbols we found to this identifier
        for (set<int>::iterator it = usedWeak.begin(); it != usedWeak.end(); it++) {
            if (weakToStrong.find(*it) == weakToStrong.end()) {
                // This is the first conflict between the two symbols. Just mark out the mapping.
                weakToStrong[*it] = strongest;
            } else if (weakToStrong[*it] != strongest) {
                // The weak symbol is used somewhere else with a different meaning
                // NOTE: this isn't ideal, as if there's an identical conflict somewhere else we generate more and more symbols for each conflicting
                // state, while we only need one new symbol for each (weak, strong) pair.

                // Split the weak symbol so that we have two different meanings
                int splitSymbolId = terminals.split(*it);

                // Change the accepting action for this state so that it accepts the new symbol
                dfa.clear_accept(state);
                dfa.accept(state, splitSymbolId);

                // Map this in the weakToStrong table
                weakToStrong[splitSymbolId] = strongest;
            }
        }
    }

    // TODO: if a weak symbol maps to several strong identifiers, it needs to be split into several symbols

    // Fill in the strong map for each weak symbol
    for (map<int, int>::iterator it = weakToStrong.begin(); it != weakToStrong.end(); it++) {
        // Use the first strong symbol for this weak symbol
        item_container strongTerm(new terminal(it->second), true);
        item_container weakTerm(new terminal(it->first), true);

        item_map::iterator weakForStrong = m_StrongToWeak.find(strongTerm);
        if (weakForStrong == m_StrongToWeak.end()) {
            weakForStrong = m_StrongToWeak.insert(item_map::value_type(strongTerm, item_set(m_Grammar))).first;
        }

        weakForStrong->second.insert(weakTerm);
    }

    // Add to the list of weak symbols
    m_WeakSymbols.merge(weak);
}

/// \brief Modifies the specified set of actions according to the rules in this rewriter
///
/// To deal with weak symbols, several rewrites are performed.
///
///  * All shift actions are left intact (whether weak or strong)
///  * All actions for symbols that are 'strong' (not in the m_WeakSymbols table) are left intact
///  * Reduce actions on weak symbols where there is an equivalent shift or reduce action on a strong symbol
///    are changed to weak reduce actions
///  * For strong symbols, any equivalent weak symbol that does not have an action other than weak reduce, the
///    same action is added
///
/// For states that do not contain any actions containing strong symbols with weak equivalents, there is no
/// need to change the contents of the state.
///
/// Something to note is that this will change the reduce part of conflicts to refer to the action defined by
/// the strong symbol instead of the weak symbol.
///
/// Something else to note is that if a strong symbol is considered for an action before a weak symbol where
/// there is a potential clash, then it's likely that the parser will be incorrect as weak reduce actions for
/// the weak symbol will not be considered in many cases.
void weak_symbols::rewrite_actions(int state, lr_action_set& actions, const lalr_builder& builder) const {
    // Determine if there are any actions referring to strong symbols in this action set
    bool haveStrong = false;

    for (lr_action_set::const_iterator it = actions.begin(); it != actions.end(); it++) {
        // This only deals with actions on terminal items
        if ((*it)->item()->type() != item::terminal) continue;

        // See if the symbol is marked as being 'strong' and has weak symbols associated with it
        item_map::const_iterator found = m_StrongToWeak.find((*it)->item());
        if (found != m_StrongToWeak.end() && !found->second.empty()) {
            haveStrong = true;
            break;
        }
    }

    // If none of the actions reference strong items with weak equivalents, then the actions can be left as they are
    if (!haveStrong) return;

    // Start building up a new set of actions
    lr_action_set newActions;

    // Add actions for any strong symbols, and remember the weak symbols that already have actions
    map<int, int>               weakSymbols;                // Maps symbols to # actions that refer to them
    stack<lr_action_container>  weakActions;                // Weak actions not processed in the first pass
    stack<lr_action_container>  strongActions;              // Strong actions that might have associated weak symbols

    for (lr_action_set::const_iterator act = actions.begin(); act != actions.end(); act++) {
        // Actions on non-terminal symbols should be preserved
        if ((*act)->item()->type() != item::terminal) {
            newActions.insert(*act);
            continue;
        }

        // Work out if this action is on a strong symbol
        bool isStrong = !m_WeakSymbols.contains((*act)->item());

        // Actions on strong symbols should be preserved without alteration
        if (isStrong) {
            strongActions.push(*act);
            newActions.insert(*act);
            continue;
        }

        // Guard actions do not mark a weak symbol as 'used'
        if ((*act)->type() == lr_action::act_guard) {
            continue;
        }

        // Fetch the symbol for this action
        int sym = (*act)->item()->symbol();

        // Mark this weak symbol as having an existing action
        weakSymbols[sym]++;

        // Push on to the set of weak actions
        weakActions.push(*act);
    }

    // Transform the actions associated with weak symbols
    while (!weakActions.empty()) {
        // Get the next action
        const lr_action_container& act = weakActions.top();

        // How this is rewritten depends on the action
        switch (act->type()) {
            case lr_action::act_shift:
            case lr_action::act_shiftstrong:
            case lr_action::act_ignore:
            case lr_action::act_accept:
            case lr_action::act_guard:
                // Preserve the action
                newActions.insert(act);
                break;

            case lr_action::act_reduce:
            case lr_action::act_weakreduce:
            {
                // Reduce actions are rewritten as weak reduce actions
                // TODO: if the strong symbol equivalent of this weak symbol is not present in the action, then
                // leave this as a standard reduce
                lr_action_container weakReduce(new lr_action(lr_action::act_weakreduce, act->item(), act->next_state(), act->rule()), true);
                newActions.insert(weakReduce);

                // Remove from the weak symbols table if there are no other actions for this symbol
                // This means that if there is a strong symbol that is equivalent to this weak symbol that the actions
                // for that symbol will be generated. If the strong symbol has a higher priority than the weak action
                // (by default: has a lower symbol ID), then its actions will be considered first, which is incorrect.
                int sym = act->item()->symbol();

                map<int, int>::iterator found = weakSymbols.find(sym);
                if (found != weakSymbols.end()) {
                    found->second--;
                    if (found->second < 0) {
                        weakSymbols.erase(found);
                    }
                }
                break;
           }

            default:
                // ?? unknown action ??
                // Remove unknown actions that seem to refer to weak symbols
                break;
        }

        // Next action
        weakActions.pop();
    }

    // For any action on a strong symbol, generate the same action for equivalent weak symbols (if there is no equivalent action)
    // TODO: if a new action is the same as an existing weak symbol action (ie, the weak symbol has produced a weak reduce
    // of the same rule) then we only need one action
    for (; !strongActions.empty(); strongActions.pop()) {
        // Get the next action
        const lr_action_container& act = strongActions.top();

        // Look up the equivalent weak symbols for this action
        item_map::const_iterator equivalent = m_StrongToWeak.find(act->item());

        // Nothing to do if there are no equivalent symbols
        if (equivalent == m_StrongToWeak.end()) continue;

        // Iterate through the weak symbols and generate equivalent actions
        for (item_set::const_iterator weakEquiv = equivalent->second.begin(); weakEquiv != equivalent->second.end(); ++weakEquiv) {
            // Can't deal with non-terminal symbols (should be none, but you can technically add them)
            if ((*weakEquiv)->type() != item::terminal) continue;

            // Get the symbol ID of this equivalent symbol
            int symId = (*weakEquiv)->symbol();

            // Nothing to do if this symbol has an alternative action
            if (weakSymbols.find(symId) != weakSymbols.end()) continue;

            // Add a duplicate action referring to the weak symbol, identical to the action for the strong symbol
            lr_action_container weakEquivAct(new lr_action(*act, *weakEquiv), true);

            // Shift actions become shift-strong actions (so the symbol ID is substituted)
            if (weakEquivAct->type() == lr_action::act_shift) {
                weakEquivAct->set_type(lr_action::act_shiftstrong);
            }

            newActions.insert(weakEquivAct);
        }
    }

    // Update the action table with our results
    actions = newActions;
}

/// \brief Creates a clone of this rewriter
action_rewriter* weak_symbols::clone() const {
    return new weak_symbols(*this);
}
<|endoftext|>