<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Alexander Rössler
** License: LGPL version 2.1
**
** This file is part of QtQuickVcp.
**
** All rights reserved. This program and the accompanying materials
** are made available under the terms of the GNU Lesser General Public License
** (LGPL) version 2.1 which accompanies this distribution, and is available at
** http://www.gnu.org/licenses/lgpl-2.1.html
**
** 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.
**
** Contributors:
** Alexander Rössler @ The Cool Tool GmbH <mail DOT aroessler AT gmail DOT com>
**
****************************************************************************/

#include "qapplicationfile.h"

QApplicationFile::QApplicationFile(QObject *parent) :
    AbstractServiceImplementation(parent),
    m_uri(""),
    m_localFilePath(""),
    m_remoteFilePath(""),
    m_localPath(""),
    m_remotePath(""),
    m_transferState(NoTransfer),
    m_error(NoError),
    m_errorString(""),
    m_progress(0.0),
    m_networkReady(false),
    m_model(NULL),
    m_networkManager(NULL),
    m_file(NULL),
    m_ftp(NULL)
{
    m_localPath = generateTempPath();

    m_model = new QApplicationFileModel(this);

    m_networkManager = new QNetworkAccessManager(this);
    connect(m_networkManager, SIGNAL(networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility)),
            this, SLOT(networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility)));

    if (m_networkManager->networkAccessible() == QNetworkAccessManager::Accessible)
    {
        initializeFtp();
    }
}

QApplicationFile::~QApplicationFile()
{
    cleanupTempPath();
    cleanupFtp();
    cleanupFile();
    m_networkManager->deleteLater();
    m_model->deleteLater();
}

void QApplicationFile::startUpload()
{
    QUrl url;
    QFileInfo fileInfo(QUrl(m_localFilePath).toLocalFile());
    QString remotePath;

    if (!ready() || (m_transferState != NoTransfer))
    {
        return;
    }

    url.setUrl(m_uri + "/" + fileInfo.fileName());
    remotePath = QUrl(m_remotePath).toLocalFile();
    m_remoteFilePath = QUrl::fromLocalFile(QDir(remotePath).filePath(fileInfo.fileName())).toString();
    emit remoteFilePathChanged(m_remoteFilePath);

    m_file = new QFile(fileInfo.filePath(), this);

    if (m_file->open(QIODevice::ReadOnly))
    {
        m_ftp->connectToHost(url.host(), url.port());
        m_ftp->login();
        m_ftp->put(m_file, fileInfo.fileName(), QFtp::Binary);
        m_ftp->close();

        m_progress = 0.0;
        emit progressChanged(m_progress);
        updateState(UploadRunning);
        updateError(NoError, "");
    }
    else
    {
        updateState(Error);
        updateError(FileError, m_file->errorString());
    }
}

void QApplicationFile::startDownload()
{
    QUrl url;
    QDir dir;
    QString localFilePath;
    QString remoteFilePath;
    QString remotePath;
    QString fileName;

    if (!ready() || (m_transferState != NoTransfer))
    {
        return;
    }

    remoteFilePath = QUrl(m_remoteFilePath).toLocalFile();
    remotePath = QUrl(m_remotePath).toLocalFile();
    fileName = remoteFilePath.mid(remotePath.length() + 1);

    url.setUrl(m_uri + "/" + fileName);

    localFilePath = applicationFilePath(fileName);
    m_localFilePath = QUrl::fromLocalFile(localFilePath).toString();
    emit localFilePathChanged(m_localFilePath);

    QFileInfo fileInfo(localFilePath);

    if (!dir.mkpath(fileInfo.absolutePath()))
    {
        updateState(Error);
        updateError(FileError, tr("Cannot create directory"));
        return;
    }

    m_file = new QFile(localFilePath, this);

    if (m_file->open(QIODevice::WriteOnly))
    {
        m_ftp->connectToHost(url.host(), url.port());
        m_ftp->login();
        m_ftp->get(fileName, m_file, QFtp::Binary);
        m_ftp->close();
        m_progress = 0.0;
        emit progressChanged(m_progress);
        updateState(DownloadRunning);
        updateError(NoError, "");
    }
    else
    {
        updateState(Error);
        updateError(FileError, m_file->errorString());
    }
}

void QApplicationFile::refreshFiles()
{
    QUrl url(m_uri);

    if (!ready() || (m_transferState != NoTransfer))
    {
        return;
    }

    m_model->clear();
    m_ftp->connectToHost(url.host(), url.port());
    m_ftp->login();
    m_ftp->list();
    m_ftp->close();
    updateState(RefreshRunning);
}

void QApplicationFile::removeFile(QString name)
{
    QUrl url(m_uri);

    if (!ready() || (m_transferState != NoTransfer))
    {
        return;
    }

    m_ftp->connectToHost(url.host(), url.port());
    m_ftp->login();
    m_ftp->remove(name);
    m_ftp->close();
    updateState(RemoveRunning);
}

void QApplicationFile::abort()
{
    if (!m_ftp)
    {
        return;
    }
    updateState(NoTransfer);
    m_ftp->abort();
    m_ftp->close();
}

void QApplicationFile::clearError()
{
    updateState(NoTransfer);
    updateError(NoError, "");
}

void QApplicationFile::updateState(QApplicationFile::TransferState state)
{
    if (state != m_transferState)
    {
        m_transferState = state;
        emit transferStateChanged(m_transferState);
    }
}

void QApplicationFile::updateError(QApplicationFile::TransferError error, const QString &errorString)
{
    if (m_errorString != errorString)
    {
        m_errorString = errorString;
        emit errorStringChanged(m_errorString);
    }

    if (m_error != error)
    {
        m_error = error;
        emit errorChanged(m_error);
    }
}

QString QApplicationFile::generateTempPath()
{
    return QUrl::fromLocalFile(QString("%1/machinekit-%2").arg(QDir::tempPath())
            .arg(QCoreApplication::applicationPid())).toString();
}

void QApplicationFile::cleanupTempPath()
{
    QDir dir(m_localPath);

    dir.removeRecursively();
}

QString QApplicationFile::applicationFilePath(const QString &fileName)
{
    return QDir(QUrl(m_localPath).toLocalFile()).filePath(fileName);
}

void QApplicationFile::initializeFtp()
{
    m_ftp = new QFtp(this);
    connect(m_ftp, SIGNAL(commandFinished(int,bool)),
    this, SLOT(ftpCommandFinished(int,bool)));
    connect(m_ftp, SIGNAL(listInfo(QUrlInfo)),
    this, SLOT(addToList(QUrlInfo)));
    connect(m_ftp, SIGNAL(dataTransferProgress(qint64,qint64)),
    this, SLOT(transferProgress(qint64,qint64)));

    m_networkReady = true;
    emit readyChanged(m_networkReady);
}

void QApplicationFile::cleanupFtp()
{
    if (m_ftp == NULL)
    {
        return;
    }

    m_ftp->abort();
    m_ftp->deleteLater();
    m_ftp = NULL;

    m_networkReady = false;
    emit readyChanged(m_networkReady);
}

void QApplicationFile::cleanupFile()
{
    if (m_file == NULL)
    {
        return;
    }

    m_file->close();
    m_file->deleteLater();
    m_file = NULL;
}

void QApplicationFile::transferProgress(qint64 bytesSent, qint64 bytesTotal)
{
    m_progress = (double)bytesSent / (double)bytesTotal;
    emit progressChanged(m_progress);
}

void QApplicationFile::networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility accesible)
{
    if (accesible == QNetworkAccessManager::Accessible)
    {
        initializeFtp();
    }
    else
    {
        cleanupFtp();
    }
}

void QApplicationFile::addToList(const QUrlInfo &urlInfo)
{
    QApplicationFileItem *item;

    if (!urlInfo.isDir()) // for now disable folders
    {
        item = new QApplicationFileItem();
        item->setName(urlInfo.name());
        item->setSize(urlInfo.size());
        item->setOwner(urlInfo.owner());
        item->setGroup(urlInfo.group());
        item->setLastModified(urlInfo.lastModified());
        item->setDir(urlInfo.isDir());

        m_model->addItem(item);
    }
}

void QApplicationFile::ftpCommandFinished(int, bool error)
{
    if (error)
    {
        cleanupFile();
        m_ftp->close();

        if (m_transferState != NoTransfer) // may be a user abort operation
        {
            updateState(Error);
            updateError(FtpError, m_ftp->errorString());
        }

        return;
    }

    if (m_ftp->currentCommand() == QFtp::Get)
    {
        cleanupFile();
        emit downloadFinished();
        updateState(NoTransfer);

        return;
    }

    if (m_ftp->currentCommand() == QFtp::Put)
    {
        cleanupFile();
        emit uploadFinished();
        updateState(NoTransfer);
        refreshFiles();

        return;
    }

    if (m_ftp->currentCommand() == QFtp::List)
    {
        emit refreshFinished();
        updateState(NoTransfer);

        return;
    }

    if (m_ftp->currentCommand() == QFtp::Remove)
    {
        emit removeFinished();
        updateState(NoTransfer);
        refreshFiles();
    }
}
<commit_msg>ApplicationFile: fix ftp urls<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Alexander Rössler
** License: LGPL version 2.1
**
** This file is part of QtQuickVcp.
**
** All rights reserved. This program and the accompanying materials
** are made available under the terms of the GNU Lesser General Public License
** (LGPL) version 2.1 which accompanies this distribution, and is available at
** http://www.gnu.org/licenses/lgpl-2.1.html
**
** 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.
**
** Contributors:
** Alexander Rössler @ The Cool Tool GmbH <mail DOT aroessler AT gmail DOT com>
**
****************************************************************************/

#include "qapplicationfile.h"

QApplicationFile::QApplicationFile(QObject *parent) :
    AbstractServiceImplementation(parent),
    m_uri(""),
    m_localFilePath(""),
    m_remoteFilePath(""),
    m_localPath(""),
    m_remotePath(""),
    m_transferState(NoTransfer),
    m_error(NoError),
    m_errorString(""),
    m_progress(0.0),
    m_networkReady(false),
    m_model(NULL),
    m_networkManager(NULL),
    m_file(NULL),
    m_ftp(NULL)
{
    m_localPath = generateTempPath();

    m_model = new QApplicationFileModel(this);

    m_networkManager = new QNetworkAccessManager(this);
    connect(m_networkManager, SIGNAL(networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility)),
            this, SLOT(networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility)));

    if (m_networkManager->networkAccessible() == QNetworkAccessManager::Accessible)
    {
        initializeFtp();
    }
}

QApplicationFile::~QApplicationFile()
{
    cleanupTempPath();
    cleanupFtp();
    cleanupFile();
    m_networkManager->deleteLater();
    m_model->deleteLater();
}

void QApplicationFile::startUpload()
{
    QUrl url;
    QFileInfo fileInfo(QUrl(m_localFilePath).toLocalFile());
    QString remotePath;

    if (!ready() || (m_transferState != NoTransfer))
    {
        return;
    }

    url.setUrl(m_uri);
    remotePath = QUrl(m_remotePath).toLocalFile();
    m_remoteFilePath = QUrl::fromLocalFile(QDir(remotePath).filePath(fileInfo.fileName())).toString();
    emit remoteFilePathChanged(m_remoteFilePath);

    m_file = new QFile(fileInfo.filePath(), this);

    if (m_file->open(QIODevice::ReadOnly))
    {
        m_ftp->connectToHost(url.host(), url.port());
        m_ftp->login();
        m_ftp->put(m_file, fileInfo.fileName(), QFtp::Binary);
        m_ftp->close();

        m_progress = 0.0;
        emit progressChanged(m_progress);
        updateState(UploadRunning);
        updateError(NoError, "");
    }
    else
    {
        updateState(Error);
        updateError(FileError, m_file->errorString());
    }
}

void QApplicationFile::startDownload()
{
    QUrl url;
    QDir dir;
    QString localFilePath;
    QString remoteFilePath;
    QString remotePath;
    QString fileName;

    if (!ready() || (m_transferState != NoTransfer))
    {
        return;
    }

    remoteFilePath = QUrl(m_remoteFilePath).toLocalFile();
    remotePath = QUrl(m_remotePath).toLocalFile();
    fileName = remoteFilePath.mid(remotePath.length() + 1);

    url.setUrl(m_uri);

    localFilePath = applicationFilePath(fileName);
    m_localFilePath = QUrl::fromLocalFile(localFilePath).toString();
    emit localFilePathChanged(m_localFilePath);

    QFileInfo fileInfo(localFilePath);

    if (!dir.mkpath(fileInfo.absolutePath()))
    {
        updateState(Error);
        updateError(FileError, tr("Cannot create directory"));
        return;
    }

    m_file = new QFile(localFilePath, this);

    if (m_file->open(QIODevice::WriteOnly))
    {
        m_ftp->connectToHost(url.host(), url.port());
        m_ftp->login();
        m_ftp->get(fileName, m_file, QFtp::Binary);
        m_ftp->close();
        m_progress = 0.0;
        emit progressChanged(m_progress);
        updateState(DownloadRunning);
        updateError(NoError, "");
    }
    else
    {
        updateState(Error);
        updateError(FileError, m_file->errorString());
    }
}

void QApplicationFile::refreshFiles()
{
    QUrl url(m_uri);

    if (!ready() || (m_transferState != NoTransfer))
    {
        return;
    }

    m_model->clear();
    m_ftp->connectToHost(url.host(), url.port());
    m_ftp->login();
    m_ftp->list();
    m_ftp->close();
    updateState(RefreshRunning);
}

void QApplicationFile::removeFile(QString name)
{
    QUrl url(m_uri);

    if (!ready() || (m_transferState != NoTransfer))
    {
        return;
    }

    m_ftp->connectToHost(url.host(), url.port());
    m_ftp->login();
    m_ftp->remove(name);
    m_ftp->close();
    updateState(RemoveRunning);
}

void QApplicationFile::abort()
{
    if (!m_ftp)
    {
        return;
    }
    updateState(NoTransfer);
    m_ftp->abort();
    m_ftp->close();
}

void QApplicationFile::clearError()
{
    updateState(NoTransfer);
    updateError(NoError, "");
}

void QApplicationFile::updateState(QApplicationFile::TransferState state)
{
    if (state != m_transferState)
    {
        m_transferState = state;
        emit transferStateChanged(m_transferState);
    }
}

void QApplicationFile::updateError(QApplicationFile::TransferError error, const QString &errorString)
{
    if (m_errorString != errorString)
    {
        m_errorString = errorString;
        emit errorStringChanged(m_errorString);
    }

    if (m_error != error)
    {
        m_error = error;
        emit errorChanged(m_error);
    }
}

QString QApplicationFile::generateTempPath()
{
    return QUrl::fromLocalFile(QString("%1/machinekit-%2").arg(QDir::tempPath())
            .arg(QCoreApplication::applicationPid())).toString();
}

void QApplicationFile::cleanupTempPath()
{
    QDir dir(m_localPath);

    dir.removeRecursively();
}

QString QApplicationFile::applicationFilePath(const QString &fileName)
{
    return QDir(QUrl(m_localPath).toLocalFile()).filePath(fileName);
}

void QApplicationFile::initializeFtp()
{
    m_ftp = new QFtp(this);
    connect(m_ftp, SIGNAL(commandFinished(int,bool)),
    this, SLOT(ftpCommandFinished(int,bool)));
    connect(m_ftp, SIGNAL(listInfo(QUrlInfo)),
    this, SLOT(addToList(QUrlInfo)));
    connect(m_ftp, SIGNAL(dataTransferProgress(qint64,qint64)),
    this, SLOT(transferProgress(qint64,qint64)));

    m_networkReady = true;
    emit readyChanged(m_networkReady);
}

void QApplicationFile::cleanupFtp()
{
    if (m_ftp == NULL)
    {
        return;
    }

    m_ftp->abort();
    m_ftp->deleteLater();
    m_ftp = NULL;

    m_networkReady = false;
    emit readyChanged(m_networkReady);
}

void QApplicationFile::cleanupFile()
{
    if (m_file == NULL)
    {
        return;
    }

    m_file->close();
    m_file->deleteLater();
    m_file = NULL;
}

void QApplicationFile::transferProgress(qint64 bytesSent, qint64 bytesTotal)
{
    m_progress = (double)bytesSent / (double)bytesTotal;
    emit progressChanged(m_progress);
}

void QApplicationFile::networkAccessibleChanged(QNetworkAccessManager::NetworkAccessibility accesible)
{
    if (accesible == QNetworkAccessManager::Accessible)
    {
        initializeFtp();
    }
    else
    {
        cleanupFtp();
    }
}

void QApplicationFile::addToList(const QUrlInfo &urlInfo)
{
    QApplicationFileItem *item;

    if (!urlInfo.isDir()) // for now disable folders
    {
        item = new QApplicationFileItem();
        item->setName(urlInfo.name());
        item->setSize(urlInfo.size());
        item->setOwner(urlInfo.owner());
        item->setGroup(urlInfo.group());
        item->setLastModified(urlInfo.lastModified());
        item->setDir(urlInfo.isDir());

        m_model->addItem(item);
    }
}

void QApplicationFile::ftpCommandFinished(int, bool error)
{
    if (error)
    {
        cleanupFile();
        m_ftp->close();

        if (m_transferState != NoTransfer) // may be a user abort operation
        {
            updateState(Error);
            updateError(FtpError, m_ftp->errorString());
        }

        return;
    }

    if (m_ftp->currentCommand() == QFtp::Get)
    {
        cleanupFile();
        emit downloadFinished();
        updateState(NoTransfer);

        return;
    }

    if (m_ftp->currentCommand() == QFtp::Put)
    {
        cleanupFile();
        emit uploadFinished();
        updateState(NoTransfer);
        refreshFiles();

        return;
    }

    if (m_ftp->currentCommand() == QFtp::List)
    {
        emit refreshFinished();
        updateState(NoTransfer);

        return;
    }

    if (m_ftp->currentCommand() == QFtp::Remove)
    {
        emit removeFinished();
        updateState(NoTransfer);
        refreshFiles();
    }
}
<|endoftext|>


<commit_before>/*
 * thread.hpp
 *
 *  Created on: Oct 04, 2013
 *	  Author: philip
 */
/*
#include "irrlight/scene/thread.hpp"
*/
//TODO KILL BOOST

#ifndef _IRRLIGHT_SCENE_THREAD_HPP_
#define _IRRLIGHT_SCENE_THREAD_HPP_

#include "irrlicht.h"

#include "kul/except.hpp"
#include "kul/threads.hpp"
#include "irrlight/scene.hpp"

using namespace irr;
namespace irrlight{

class SceneThreadException : public kul::Exception{
	public:
		SceneThreadException(const char*f, const int l, std::string s) : kul::Exception(f, l, s){}
};

class SceneThread  {
	public:
		SceneThread(AScene& aScene) throw(SceneThreadException)
				: aScene(aScene), device(irr::createDevice(video::EDT_NULL, core::dimension2d<u32>(512, 384))), ref(*this), thread(ref){
			this->check();
			thread.run();
		}
		~SceneThread() {
			thread.interrupt();
		}
		IrrlichtDevice * getDevice(){ return this->device.get();}
		AScene   * getScene()		{ return &this->aScene;}
		bool isFinished(){
			return thread.finished();
		}
		void operator()() { go(); }

	protected:
		AScene& aScene;
		std::shared_ptr<IrrlichtDevice> device;
		kul::Ref<SceneThread> ref;
		kul::Thread thread;
		void go(){
			KLOG(INFO);
			thread.sleep(1000);
			this->aScene.setUp(this->getDevice());
		}

		SceneThread();

		void check() throw(SceneThreadException){
			if (!&aScene || !&device){
				throw SceneThreadException(__FILE__, __LINE__, "Scene or device cannot be null");
			}
		}

		// prevent copying and assignment; not implemented
		SceneThread& operator=(const AScene &);
		SceneThread& operator=(IrrlichtDevice &);
};

class GUISceneThread  : public SceneThread{
	public:
		GUISceneThread(AGUIScene & aGUIScene): SceneThread (aGUIScene){}
		~GUISceneThread(){}
		void operator()(){
			go();
		}
	protected:
		void go(){
			((AGUIScene*)this->getScene())->setUpUI(this->getDevice()->getGUIEnvironment());
		}
};

};
#endif /* _IRRLIGHT_SCENE_THREAD_HPP_ */
<commit_msg>Update thread.hpp<commit_after>/**

./inc/irrlight/scene/thread.hpp

Created on: 16 May 2013

Copyright (c) 2013, Philip Deegan

This file is part of irrlight.

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, see <http://www.gnu.org/licenses/>.
*/
#ifndef _IRRLIGHT_SCENE_THREAD_HPP_
#define _IRRLIGHT_SCENE_THREAD_HPP_

#include "irrlicht.h"

#include "kul/except.hpp"
#include "kul/threads.hpp"
#include "irrlight/scene.hpp"

using namespace irr;
namespace irrlight{

class SceneThreadException : public kul::Exception{
	public:
		SceneThreadException(const char*f, const int l, std::string s) : kul::Exception(f, l, s){}
};

class SceneThread  {
	public:
		SceneThread(AScene& aScene) throw(SceneThreadException)
				: aScene(aScene), device(irr::createDevice(video::EDT_NULL, core::dimension2d<u32>(512, 384))), ref(*this), thread(ref){
			this->check();
			thread.run();
		}
		~SceneThread() {
			thread.interrupt();
		}
		IrrlichtDevice * getDevice(){ return this->device.get();}
		AScene   * getScene()		{ return &this->aScene;}
		bool isFinished(){
			return thread.finished();
		}
		void operator()() { go(); }

	protected:
		AScene& aScene;
		std::shared_ptr<IrrlichtDevice> device;
		kul::Ref<SceneThread> ref;
		kul::Thread thread;
		void go(){
			KLOG(INFO);
			thread.sleep(1000);
			this->aScene.setUp(this->getDevice());
		}

		SceneThread();

		void check() throw(SceneThreadException){
			if (!&aScene || !&device){
				throw SceneThreadException(__FILE__, __LINE__, "Scene or device cannot be null");
			}
		}

		// prevent copying and assignment; not implemented
		SceneThread& operator=(const AScene &);
		SceneThread& operator=(IrrlichtDevice &);
};

class GUISceneThread  : public SceneThread{
	public:
		GUISceneThread(AGUIScene & aGUIScene): SceneThread (aGUIScene){}
		~GUISceneThread(){}
		void operator()(){
			go();
		}
	protected:
		void go(){
			((AGUIScene*)this->getScene())->setUpUI(this->getDevice()->getGUIEnvironment());
		}
};

};
#endif /* _IRRLIGHT_SCENE_THREAD_HPP_ */
<|endoftext|>


<commit_before>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#ifndef GUARD_MIOPEN_LOCK_FILE_HPP_
#define GUARD_MIOPEN_LOCK_FILE_HPP_

#include <boost/filesystem.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include <chrono>
#include <fstream>
#include <shared_mutex>
#include <mutex>

namespace miopen {
// LockFile class is a wrapper around boost::interprocess::file_lock providing MT-safety.
// One process should never have more than one instance of this class with same path at the same
// time. It may lead to undefined behaviour on Windows.
// Also on windows mutex can be removed because file locks are MT-safe there.
class LockFile
{
    private:
    class PassKey
    {
    };

    public:
    LockFile(const char* path, PassKey)
    {
        std::ofstream{path};
        flock = path;
    }
    LockFile(const LockFile&) = delete;
    LockFile operator=(const LockFile&) = delete;

    void lock()
    {
        std::lock(access_mutex, flock);
    }
    void lock_shared()
    {
        access_mutex.lock_shared();
        flock.lock_sharable();
    }
    bool try_lock()
    {
        return std::try_lock(access_mutex, flock);
    }
    bool try_lock_shared()
    {
        if(!access_mutex.try_lock_shared())
            return false;

        if(!flock.try_lock_sharable())
        {
            access_mutex.unlock_shared();
            return false;
        }
        return true;
    }
    void unlock()
    {
        flock.unlock();
        access_mutex.unlock();
    }
    void unlock_shared()
    {
        flock.unlock_sharable();
        access_mutex.unlock_shared();
    }

    static LockFile& Get(const char* path);

    template <class TDuration>
    bool try_lock_for(TDuration duration)
    {
        if(!access_mutex.try_lock_for(duration))
            return false;

        if(!flock.timed_lock(ToPTime(duration)))
        {
            access_mutex.unlock();
            return false;
        }
        return true;
    }

    template <class TDuration>
    bool try_lock_shared_for(TDuration duration)
    {
        if(!access_mutex.try_lock_shared_for(duration))
            return false;

        if(!flock.timed_lock_sharable(ToPTime(duration)))
        {
            access_mutex.unlock();
            return false;
        }
        return true;
    }

    template <class TPoint>
    bool try_lock_until(TPoint point)
    {
        return try_lock_for(point - std::chrono::system_clock::now());
    }

    template <class TPoint>
    bool try_lock_shared_until(TPoint point)
    {
        return try_lock_shared_for(point - std::chrono::system_clock::now());
    }

    private:
    std::shared_timed_mutex access_mutex;
    boost::interprocess::file_lock flock;

    static std::map<std::string, LockFile>& LockFiles()
    {
        static std::map<std::string, LockFile> lock_files;
        return lock_files;
    }

    template <class TDuration>
    static boost::posix_time::ptime ToPTime(TDuration duration)
    {
        return boost::posix_time::second_clock::universal_time() +
               boost::posix_time::milliseconds(
                   std::chrono::duration_cast<std::chrono::milliseconds>(duration).count());
    }
};
} // namespace miopen

#endif // GUARD_MIOPEN_LOCK_FILE_HPP_
<commit_msg>Formatting<commit_after>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2017 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#ifndef GUARD_MIOPEN_LOCK_FILE_HPP_
#define GUARD_MIOPEN_LOCK_FILE_HPP_

#include <boost/filesystem.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include <chrono>
#include <fstream>
#include <shared_mutex>
#include <mutex>

namespace miopen {
// LockFile class is a wrapper around boost::interprocess::file_lock providing MT-safety.
// One process should never have more than one instance of this class with same path at the same
// time. It may lead to undefined behaviour on Windows.
// Also on windows mutex can be removed because file locks are MT-safe there.
class LockFile
{
    private:
    class PassKey
    {
    };

    public:
    LockFile(const char* path, PassKey)
    {
        std::ofstream{path};
        flock = path;
    }
    LockFile(const LockFile&) = delete;
    LockFile operator=(const LockFile&) = delete;

    void lock() { std::lock(access_mutex, flock); }
    void lock_shared()
    {
        access_mutex.lock_shared();
        flock.lock_sharable();
    }
    bool try_lock() { return std::try_lock(access_mutex, flock); }
    bool try_lock_shared()
    {
        if(!access_mutex.try_lock_shared())
            return false;

        if(!flock.try_lock_sharable())
        {
            access_mutex.unlock_shared();
            return false;
        }
        return true;
    }
    void unlock()
    {
        flock.unlock();
        access_mutex.unlock();
    }
    void unlock_shared()
    {
        flock.unlock_sharable();
        access_mutex.unlock_shared();
    }

    static LockFile& Get(const char* path);

    template <class TDuration>
    bool try_lock_for(TDuration duration)
    {
        if(!access_mutex.try_lock_for(duration))
            return false;

        if(!flock.timed_lock(ToPTime(duration)))
        {
            access_mutex.unlock();
            return false;
        }
        return true;
    }

    template <class TDuration>
    bool try_lock_shared_for(TDuration duration)
    {
        if(!access_mutex.try_lock_shared_for(duration))
            return false;

        if(!flock.timed_lock_sharable(ToPTime(duration)))
        {
            access_mutex.unlock();
            return false;
        }
        return true;
    }

    template <class TPoint>
    bool try_lock_until(TPoint point)
    {
        return try_lock_for(point - std::chrono::system_clock::now());
    }

    template <class TPoint>
    bool try_lock_shared_until(TPoint point)
    {
        return try_lock_shared_for(point - std::chrono::system_clock::now());
    }

    private:
    std::shared_timed_mutex access_mutex;
    boost::interprocess::file_lock flock;

    static std::map<std::string, LockFile>& LockFiles()
    {
        static std::map<std::string, LockFile> lock_files;
        return lock_files;
    }

    template <class TDuration>
    static boost::posix_time::ptime ToPTime(TDuration duration)
    {
        return boost::posix_time::second_clock::universal_time() +
               boost::posix_time::milliseconds(
                   std::chrono::duration_cast<std::chrono::milliseconds>(duration).count());
    }
};
} // namespace miopen

#endif // GUARD_MIOPEN_LOCK_FILE_HPP_
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svl.hxx"

#include "ddemlimp.hxx"

#ifdef OV_DEBUG
#include <svgen.hxx>
#endif

#if defined(OV_DEBUG)

void ImpAddHSZ( HSZ hszString, String& rStr )
{
    char aBuf[ 128 ];
    ImpDdeMgr::DdeQueryString( hszString,aBuf,sizeof(aBuf),850);
    rStr += " (\""; rStr += aBuf; rStr += "\",";
    HATOMTBL hAtomTable = WinQuerySystemAtomTable();
    ULONG nRefCount = 0;
    if( hszString )
        nRefCount = WinQueryAtomUsage(hAtomTable, (ATOM)hszString );
    rStr += nRefCount; rStr += ')';
}

void ImpWriteDdeStatus(char* aFilename, char* pAppContext)
{
    char aBuf[ 128 ];
    USHORT nCtr;
    HWND* pAppPtr;
    ImpHCONV* pConvPtr;
    Transaction* pTransPtr;

    ImpDdeMgrData* pData = ImpDdeMgr::AccessMgrData();
    if( !pData )
        return;
    SvFileStream aStrm(aFilename, STREAM_READWRITE );
    String aLine;
    aStrm.Seek( STREAM_SEEK_TO_END );
    aStrm << endl;
    aStrm.WriteLine("********************** DDEML-Log ***********************");
    aStrm << endl;
    if( pAppContext )
    {
        aLine = Application::GetAppName();
        aLine += ':';
        aLine += "App-Context:"; aLine += pAppContext;
        aStrm.WriteLine( aLine ); aStrm << endl;
    }
    aStrm.WriteLine("----------------- ImpDdeMgrData -------------------");
    aStrm << endl;
    aLine= "TotalSize      :"; aLine+= pData->nTotalSize; aStrm.WriteLine(aLine);
    aLine= "nOffsAppTable  :"; aLine+= pData->nOffsAppTable; aStrm.WriteLine(aLine);
    aLine= "nOffsConvTable :"; aLine+= pData->nOffsConvTable; aStrm.WriteLine(aLine);
    aLine= "nOffsTransTable:"; aLine+= pData->nOffsTransTable; aStrm.WriteLine(aLine);
    aLine= "nMaxAppCount   :"; aLine+= pData->nMaxAppCount; aStrm.WriteLine(aLine);
    aLine= "nMaxConvCount  :"; aLine+= pData->nMaxConvCount; aStrm.WriteLine(aLine);
    aLine= "nMaxTransCount :"; aLine+= pData->nMaxTransCount; aStrm.WriteLine(aLine);
    aLine= "nLastErr       :"; aLine+= pData->nLastErr; aStrm.WriteLine(aLine);
    aLine= "nCurConvCount  :"; aLine+= pData->nCurConvCount; aStrm.WriteLine(aLine);
    aLine= "nCurTransCount :"; aLine+= pData->nCurTransCount; aStrm.WriteLine(aLine);
    aStrm << endl;
    aStrm.WriteLine("---------- Registered DDEML-Applications -----------");
    aStrm << endl;
    pAppPtr = ImpDdeMgr::GetAppTable( pData );
    for( nCtr = 0; nCtr < pData->nMaxAppCount; nCtr++, pAppPtr++ )
    {
        if( *pAppPtr )
        {
            aLine = "App."; aLine += nCtr; aLine += " HWND:";
            aLine += (ULONG)*pAppPtr; aStrm.WriteLine(aLine);
        }
    }

    aStrm << endl;
    aStrm.WriteLine("-------------- Conversation handles ----------------");
    aStrm << endl;

    USHORT nCurCount = pData->nCurConvCount;

    if( nCurCount )
    {
    pConvPtr = ImpDdeMgr::GetConvTable( pData );
    for( nCtr = 0; nCtr < pData->nMaxConvCount; nCtr++, pConvPtr++ )
    {
        if( pConvPtr->hWndThis )
        {
            aLine = "HCONV:";  aLine += nCtr;
            aLine += " HCONVpartner: "; aLine += (USHORT)pConvPtr->hConvPartner;
            if( !pConvPtr->hConvPartner ) aLine += "(Non-DDEML-App)";
            aLine += " hszPartner: "; aLine += (USHORT)pConvPtr->hszPartner;
            ImpAddHSZ( pConvPtr->hszPartner, aLine );
            aStrm.WriteLine( aLine );

            aLine = "hszService: "; aLine += (USHORT)pConvPtr->hszServiceReq;
            ImpAddHSZ( pConvPtr->hszServiceReq, aLine );
            aLine += " hszTopic: "; aLine += (USHORT)pConvPtr->hszTopic;
            ImpAddHSZ( pConvPtr->hszTopic, aLine );
            aStrm.WriteLine( aLine );

            aLine= "Status: "; aLine+= pConvPtr->nStatus;
            if( pConvPtr->nStatus & ST_CLIENT ) aLine += " (Client)";
            if( pConvPtr->nStatus & ST_INLIST ) aLine += " (Inlist)";
            aStrm.WriteLine(aLine);

            aLine = "pidOwner: "; aLine += (ULONG)pConvPtr->pidOwner;
            aStrm.WriteLine( aLine );
            aLine = "hWndThis: "; aLine += (ULONG)pConvPtr->hWndThis;
            aStrm.WriteLine( aLine );
            aLine = "hWndPartner: "; aLine += (ULONG)pConvPtr->hWndPartner;
            aStrm.WriteLine( aLine );

            aLine = "hConvList: "; aLine += (ULONG)pConvPtr->hConvList;
            aLine += " Prev: "; aLine += pConvPtr->nPrevHCONV;
            aLine += " Next: "; aLine += pConvPtr->nNextHCONV;
            aStrm.WriteLine( aLine );
            aStrm.WriteLine("----------------------------------------------------");

            nCurCount--;
            if( !nCurCount )
                break;
        }
    }
    }

    aStrm.WriteLine("----------------- Transaction Ids ------------------");

    nCurCount = pData->nCurTransCount;
    if( nCurCount )
    {
    pTransPtr = ImpDdeMgr::GetTransTable( pData );
    for( nCtr = 0; nCtr < pData->nMaxTransCount; nCtr++, pTransPtr++ )
    {

        if( pTransPtr->hConvOwner )
        {
            aLine = "TransactionId:"; aLine += nCtr;
            aLine += " hConvOwner: "; aLine += (USHORT)pTransPtr->hConvOwner;
            aStrm.WriteLine( aLine );
            aLine = "Item: "; aLine += (USHORT)pTransPtr->hszItem;
            ImpAddHSZ( pTransPtr->hszItem, aLine );
            aLine += " Format: "; aLine += pTransPtr->nFormat;
            aStrm.WriteLine( aLine );
            aLine = "TransactionType: "; aLine += pTransPtr->nType;
            aLine += " Convst: "; aLine += pTransPtr->nConvst;
            aLine += " LastErr: "; aLine += pTransPtr->nLastError;
            aLine += " Userhandle: "; aLine += pTransPtr->nUser;
            aStrm.WriteLine( aLine );
            aStrm.WriteLine("--------------------------------------------------");

            nCurCount--;
            if( !nCurCount )
                break;
        }
    }
    }
    aStrm << endl;
    aStrm.WriteLine("******************* End of DDEML-Log *******************");
}

void ImpWriteDdeData(char* aFilename, DDESTRUCT* pData)
{
    char aBuf[ 128 ];
    USHORT nCtr;
    SvFileStream aStrm(aFilename, STREAM_READWRITE );
    aStrm.Seek( STREAM_SEEK_TO_END );
    String aLine;
    aStrm << endl;
    aLine = "cbData:"; aLine += pData->cbData; aStrm.WriteLine( aLine );
    aLine = "fsStatus:"; aLine += pData->fsStatus; aStrm.WriteLine( aLine );
    aLine = "usFormat:"; aLine += pData->usFormat; aStrm.WriteLine( aLine );
    aLine = "ItemName:"; aLine += (char*)((char*)pData+pData->offszItemName);
    aStrm.WriteLine( aLine );
    aLine = "offabData:"; aLine += pData->offabData; aStrm.WriteLine(aLine);
    char* pBuf = (char*)pData+pData->offabData;
    USHORT nLen = pData->cbData; // - pData->offabData;
    while( nLen )
    {
        aStrm << *pBuf;
        nLen--;
        pBuf++;
    }
    aStrm << endl;
}

void ImpWriteLogFile(char* pFilename, char* pStr)
{
    SvFileStream aStrm(pFilename, STREAM_READWRITE );
    aStrm.Seek( STREAM_SEEK_TO_END );
    String aStr( Application::GetAppName() );
    aStr += ':'; aStr += pStr;
    aStrm.WriteLine( (char*)aStr.GetStr() );
}

#else

void ImpWriteDdeStatus(char*, char* ) {}
void ImpWriteDdeData(char*, DDESTRUCT*) {}
void ImpWriteLogFile(char*, char*) {}

#endif

APIRET MyDosAllocSharedMem(void** ppBaseAddress, char* pszName, unsigned long ulObjectSize,
    unsigned long ulFlags, char* pContextStr )
{
    APIRET nRet = DosAllocSharedMem(ppBaseAddress,pszName,ulObjectSize,ulFlags );
#if 0 && defined(OV_DEBUG) && defined(LOGFILE)
    String aStr("DosAllocSharedMem:");
    aStr += pContextStr;
    aStr += ": ";
    aStr += ulObjectSize;
    aStr += " (";
    aStr += (ULONG)*((char**)ppBaseAddress);
    aStr += ')';
    ImpWriteLogFile("\\ddeml.mem", (char*)aStr.GetStr() );
#endif
    return nRet;
}

APIRET MyDosAllocMem(void** ppBaseAddress, unsigned long ulObjectSize,
    unsigned long ulFlags, char* pContextStr )
{
    APIRET nRet = DosAllocMem(ppBaseAddress, ulObjectSize,ulFlags );
#if 0 && defined(OV_DEBUG) && defined(LOGFILE)
    String aStr("DosAllocMem:");
    aStr += pContextStr;
    aStr += ": ";
    aStr += ulObjectSize;
    aStr += " (";
    aStr += (ULONG)*((char**)ppBaseAddress);
    aStr += ')';
    ImpWriteLogFile("\\ddeml.mem", (char*)aStr.GetStr() );
#endif
    return nRet;
}

APIRET MyDosFreeMem( void* pBaseAddress, char* pContextStr )
{
    APIRET nRet = DosFreeMem( pBaseAddress );
#if 0 && defined(OV_DEBUG) && defined(LOGFILE)
    String aStr("DosFreeMem:");
    aStr += pContextStr;
    aStr += ": ";
    aStr += (ULONG)pBaseAddress;
    ImpWriteLogFile("\\ddeml.mem", (char*)aStr.GetStr());
#endif
    return nRet;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>cppcheck: remove unused variable aBuf.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svl.hxx"

#include "ddemlimp.hxx"

#ifdef OV_DEBUG
#include <svgen.hxx>
#endif

#if defined(OV_DEBUG)

void ImpAddHSZ( HSZ hszString, String& rStr )
{
    char aBuf[ 128 ];
    ImpDdeMgr::DdeQueryString( hszString,aBuf,sizeof(aBuf),850);
    rStr += " (\""; rStr += aBuf; rStr += "\",";
    HATOMTBL hAtomTable = WinQuerySystemAtomTable();
    ULONG nRefCount = 0;
    if( hszString )
        nRefCount = WinQueryAtomUsage(hAtomTable, (ATOM)hszString );
    rStr += nRefCount; rStr += ')';
}

void ImpWriteDdeStatus(char* aFilename, char* pAppContext)
{
    USHORT nCtr;
    HWND* pAppPtr;
    ImpHCONV* pConvPtr;
    Transaction* pTransPtr;

    ImpDdeMgrData* pData = ImpDdeMgr::AccessMgrData();
    if( !pData )
        return;
    SvFileStream aStrm(aFilename, STREAM_READWRITE );
    String aLine;
    aStrm.Seek( STREAM_SEEK_TO_END );
    aStrm << endl;
    aStrm.WriteLine("********************** DDEML-Log ***********************");
    aStrm << endl;
    if( pAppContext )
    {
        aLine = Application::GetAppName();
        aLine += ':';
        aLine += "App-Context:"; aLine += pAppContext;
        aStrm.WriteLine( aLine ); aStrm << endl;
    }
    aStrm.WriteLine("----------------- ImpDdeMgrData -------------------");
    aStrm << endl;
    aLine= "TotalSize      :"; aLine+= pData->nTotalSize; aStrm.WriteLine(aLine);
    aLine= "nOffsAppTable  :"; aLine+= pData->nOffsAppTable; aStrm.WriteLine(aLine);
    aLine= "nOffsConvTable :"; aLine+= pData->nOffsConvTable; aStrm.WriteLine(aLine);
    aLine= "nOffsTransTable:"; aLine+= pData->nOffsTransTable; aStrm.WriteLine(aLine);
    aLine= "nMaxAppCount   :"; aLine+= pData->nMaxAppCount; aStrm.WriteLine(aLine);
    aLine= "nMaxConvCount  :"; aLine+= pData->nMaxConvCount; aStrm.WriteLine(aLine);
    aLine= "nMaxTransCount :"; aLine+= pData->nMaxTransCount; aStrm.WriteLine(aLine);
    aLine= "nLastErr       :"; aLine+= pData->nLastErr; aStrm.WriteLine(aLine);
    aLine= "nCurConvCount  :"; aLine+= pData->nCurConvCount; aStrm.WriteLine(aLine);
    aLine= "nCurTransCount :"; aLine+= pData->nCurTransCount; aStrm.WriteLine(aLine);
    aStrm << endl;
    aStrm.WriteLine("---------- Registered DDEML-Applications -----------");
    aStrm << endl;
    pAppPtr = ImpDdeMgr::GetAppTable( pData );
    for( nCtr = 0; nCtr < pData->nMaxAppCount; nCtr++, pAppPtr++ )
    {
        if( *pAppPtr )
        {
            aLine = "App."; aLine += nCtr; aLine += " HWND:";
            aLine += (ULONG)*pAppPtr; aStrm.WriteLine(aLine);
        }
    }

    aStrm << endl;
    aStrm.WriteLine("-------------- Conversation handles ----------------");
    aStrm << endl;

    USHORT nCurCount = pData->nCurConvCount;

    if( nCurCount )
    {
    pConvPtr = ImpDdeMgr::GetConvTable( pData );
    for( nCtr = 0; nCtr < pData->nMaxConvCount; nCtr++, pConvPtr++ )
    {
        if( pConvPtr->hWndThis )
        {
            aLine = "HCONV:";  aLine += nCtr;
            aLine += " HCONVpartner: "; aLine += (USHORT)pConvPtr->hConvPartner;
            if( !pConvPtr->hConvPartner ) aLine += "(Non-DDEML-App)";
            aLine += " hszPartner: "; aLine += (USHORT)pConvPtr->hszPartner;
            ImpAddHSZ( pConvPtr->hszPartner, aLine );
            aStrm.WriteLine( aLine );

            aLine = "hszService: "; aLine += (USHORT)pConvPtr->hszServiceReq;
            ImpAddHSZ( pConvPtr->hszServiceReq, aLine );
            aLine += " hszTopic: "; aLine += (USHORT)pConvPtr->hszTopic;
            ImpAddHSZ( pConvPtr->hszTopic, aLine );
            aStrm.WriteLine( aLine );

            aLine= "Status: "; aLine+= pConvPtr->nStatus;
            if( pConvPtr->nStatus & ST_CLIENT ) aLine += " (Client)";
            if( pConvPtr->nStatus & ST_INLIST ) aLine += " (Inlist)";
            aStrm.WriteLine(aLine);

            aLine = "pidOwner: "; aLine += (ULONG)pConvPtr->pidOwner;
            aStrm.WriteLine( aLine );
            aLine = "hWndThis: "; aLine += (ULONG)pConvPtr->hWndThis;
            aStrm.WriteLine( aLine );
            aLine = "hWndPartner: "; aLine += (ULONG)pConvPtr->hWndPartner;
            aStrm.WriteLine( aLine );

            aLine = "hConvList: "; aLine += (ULONG)pConvPtr->hConvList;
            aLine += " Prev: "; aLine += pConvPtr->nPrevHCONV;
            aLine += " Next: "; aLine += pConvPtr->nNextHCONV;
            aStrm.WriteLine( aLine );
            aStrm.WriteLine("----------------------------------------------------");

            nCurCount--;
            if( !nCurCount )
                break;
        }
    }
    }

    aStrm.WriteLine("----------------- Transaction Ids ------------------");

    nCurCount = pData->nCurTransCount;
    if( nCurCount )
    {
    pTransPtr = ImpDdeMgr::GetTransTable( pData );
    for( nCtr = 0; nCtr < pData->nMaxTransCount; nCtr++, pTransPtr++ )
    {

        if( pTransPtr->hConvOwner )
        {
            aLine = "TransactionId:"; aLine += nCtr;
            aLine += " hConvOwner: "; aLine += (USHORT)pTransPtr->hConvOwner;
            aStrm.WriteLine( aLine );
            aLine = "Item: "; aLine += (USHORT)pTransPtr->hszItem;
            ImpAddHSZ( pTransPtr->hszItem, aLine );
            aLine += " Format: "; aLine += pTransPtr->nFormat;
            aStrm.WriteLine( aLine );
            aLine = "TransactionType: "; aLine += pTransPtr->nType;
            aLine += " Convst: "; aLine += pTransPtr->nConvst;
            aLine += " LastErr: "; aLine += pTransPtr->nLastError;
            aLine += " Userhandle: "; aLine += pTransPtr->nUser;
            aStrm.WriteLine( aLine );
            aStrm.WriteLine("--------------------------------------------------");

            nCurCount--;
            if( !nCurCount )
                break;
        }
    }
    }
    aStrm << endl;
    aStrm.WriteLine("******************* End of DDEML-Log *******************");
}

void ImpWriteDdeData(char* aFilename, DDESTRUCT* pData)
{
    USHORT nCtr;
    SvFileStream aStrm(aFilename, STREAM_READWRITE );
    aStrm.Seek( STREAM_SEEK_TO_END );
    String aLine;
    aStrm << endl;
    aLine = "cbData:"; aLine += pData->cbData; aStrm.WriteLine( aLine );
    aLine = "fsStatus:"; aLine += pData->fsStatus; aStrm.WriteLine( aLine );
    aLine = "usFormat:"; aLine += pData->usFormat; aStrm.WriteLine( aLine );
    aLine = "ItemName:"; aLine += (char*)((char*)pData+pData->offszItemName);
    aStrm.WriteLine( aLine );
    aLine = "offabData:"; aLine += pData->offabData; aStrm.WriteLine(aLine);
    char* pBuf = (char*)pData+pData->offabData;
    USHORT nLen = pData->cbData; // - pData->offabData;
    while( nLen )
    {
        aStrm << *pBuf;
        nLen--;
        pBuf++;
    }
    aStrm << endl;
}

void ImpWriteLogFile(char* pFilename, char* pStr)
{
    SvFileStream aStrm(pFilename, STREAM_READWRITE );
    aStrm.Seek( STREAM_SEEK_TO_END );
    String aStr( Application::GetAppName() );
    aStr += ':'; aStr += pStr;
    aStrm.WriteLine( (char*)aStr.GetStr() );
}

#else

void ImpWriteDdeStatus(char*, char* ) {}
void ImpWriteDdeData(char*, DDESTRUCT*) {}
void ImpWriteLogFile(char*, char*) {}

#endif

APIRET MyDosAllocSharedMem(void** ppBaseAddress, char* pszName, unsigned long ulObjectSize,
    unsigned long ulFlags, char* pContextStr )
{
    APIRET nRet = DosAllocSharedMem(ppBaseAddress,pszName,ulObjectSize,ulFlags );
#if 0 && defined(OV_DEBUG) && defined(LOGFILE)
    String aStr("DosAllocSharedMem:");
    aStr += pContextStr;
    aStr += ": ";
    aStr += ulObjectSize;
    aStr += " (";
    aStr += (ULONG)*((char**)ppBaseAddress);
    aStr += ')';
    ImpWriteLogFile("\\ddeml.mem", (char*)aStr.GetStr() );
#endif
    return nRet;
}

APIRET MyDosAllocMem(void** ppBaseAddress, unsigned long ulObjectSize,
    unsigned long ulFlags, char* pContextStr )
{
    APIRET nRet = DosAllocMem(ppBaseAddress, ulObjectSize,ulFlags );
#if 0 && defined(OV_DEBUG) && defined(LOGFILE)
    String aStr("DosAllocMem:");
    aStr += pContextStr;
    aStr += ": ";
    aStr += ulObjectSize;
    aStr += " (";
    aStr += (ULONG)*((char**)ppBaseAddress);
    aStr += ')';
    ImpWriteLogFile("\\ddeml.mem", (char*)aStr.GetStr() );
#endif
    return nRet;
}

APIRET MyDosFreeMem( void* pBaseAddress, char* pContextStr )
{
    APIRET nRet = DosFreeMem( pBaseAddress );
#if 0 && defined(OV_DEBUG) && defined(LOGFILE)
    String aStr("DosFreeMem:");
    aStr += pContextStr;
    aStr += ": ";
    aStr += (ULONG)pBaseAddress;
    ImpWriteLogFile("\\ddeml.mem", (char*)aStr.GetStr());
#endif
    return nRet;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SDRPAGEWINDOW_HXX
#define _SDRPAGEWINDOW_HXX

#include <com/sun/star/awt/XWindowListener.hpp>
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#include <com/sun/star/awt/XControlContainer.hpp>
#include <com/sun/star/util/XModeChangeListener.hpp>
#include <cppuhelper/implbase4.hxx>
#include <svx/sdr/overlay/overlaymanager.hxx>
#include <svx/svdtypes.hxx> // for SdrLayerID
#include <tools/contnr.hxx>
#include <svx/sdrpagewindow.hxx>
#include "svx/svxdllapi.h"

#include <vector>

////////////////////////////////////////////////////////////////////////////////////////////////////
// predeclarations

class Region;
class SdrUnoObj;
class SdrPageView;

// #110094#
namespace sdr
{
    namespace contact
    {
        class ObjectContact;
        class ViewObjectContactRedirector;
    } // end of namespace contact

    namespace overlay
    {
        class OverlayManager;
    } // end of namespace overlay
} // end of namespace sdr

namespace basegfx
{
    class B2DRange;
} // end of namespace basegfx

class SdrPaintWindow;
class Link;

////////////////////////////////////////////////////////////////////////////////////////////////////

class SVX_DLLPUBLIC SdrPageWindow
{
    // #110094# ObjectContact section
    sdr::contact::ObjectContact*                        mpObjectContact;

    // the SdrPageView this window belongs to
    SdrPageView&                                        mrPageView;

    // the PaintWindow to paint on. Here is access to OutDev etc.
    // #i72752# change to pointer to allow patcing it in DrawLayer() if necessary
    SdrPaintWindow*                                     mpPaintWindow;
    SdrPaintWindow*                                     mpOriginalPaintWindow;

    // UNO stuff for xControls
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > mxControlContainer;

    sdr::contact::ObjectContact* CreateViewSpecificObjectContact();

public:
    SdrPageWindow(SdrPageView& rNewPageView, SdrPaintWindow& rPaintWindow);
    ~SdrPageWindow();

    // data read accesses
    SdrPageView& GetPageView() const { return mrPageView; }
    SdrPaintWindow& GetPaintWindow() const { return *mpPaintWindow; }
    const SdrPaintWindow* GetOriginalPaintWindow() const { return mpOriginalPaintWindow; }
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > GetControlContainer( bool _bCreateIfNecessary = true ) const;

    // OVERLAYMANAGER
    rtl::Reference< ::sdr::overlay::OverlayManager > GetOverlayManager() const;

    // #i72752# allow patcing SdrPaintWindow from SdrPageView::DrawLayer if needed
    void patchPaintWindow(SdrPaintWindow& rPaintWindow);
    void unpatchPaintWindow();

    // the repaint method. For migration from pPaintProc, use one more parameter
    void PrePaint();
    void PrepareRedraw(const Region& rReg);
    void RedrawAll(sdr::contact::ViewObjectContactRedirector* pRedirector) const;
    void RedrawLayer(const SdrLayerID* pId, sdr::contact::ViewObjectContactRedirector* pRedirector) const;

    // Invalidate call, used from ObjectContact(OfPageView) in InvalidatePartOfView(...)
    void InvalidatePageWindow(const basegfx::B2DRange& rRange);

    // #110094# ObjectContact section
    sdr::contact::ObjectContact& GetObjectContact() const;
    /// determines whether there already exists an ObjectContact
    bool                         HasObjectContact() const;

    // #i26631#
    void ResetObjectContact();

    /** sets all elements in the view which support a design and a alive mode into the given mode
    */
    void    SetDesignMode( bool _bDesignMode ) const;
};

// typedefs for a list of SdrPageWindow
typedef ::std::vector< SdrPageWindow* > SdrPageWindowVector;

////////////////////////////////////////////////////////////////////////////////////////////////////

#endif //_SDRPAGEWINDOW_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove unnecessary include<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SDRPAGEWINDOW_HXX
#define _SDRPAGEWINDOW_HXX

#include <com/sun/star/awt/XWindowListener.hpp>
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#include <com/sun/star/awt/XControlContainer.hpp>
#include <com/sun/star/util/XModeChangeListener.hpp>
#include <cppuhelper/implbase4.hxx>
#include <svx/sdr/overlay/overlaymanager.hxx>
#include <svx/svdtypes.hxx> // for SdrLayerID
#include <svx/sdrpagewindow.hxx>
#include "svx/svxdllapi.h"

#include <vector>

////////////////////////////////////////////////////////////////////////////////////////////////////
// predeclarations

class Region;
class SdrUnoObj;
class SdrPageView;

// #110094#
namespace sdr
{
    namespace contact
    {
        class ObjectContact;
        class ViewObjectContactRedirector;
    } // end of namespace contact

    namespace overlay
    {
        class OverlayManager;
    } // end of namespace overlay
} // end of namespace sdr

namespace basegfx
{
    class B2DRange;
} // end of namespace basegfx

class SdrPaintWindow;
class Link;

////////////////////////////////////////////////////////////////////////////////////////////////////

class SVX_DLLPUBLIC SdrPageWindow
{
    // #110094# ObjectContact section
    sdr::contact::ObjectContact*                        mpObjectContact;

    // the SdrPageView this window belongs to
    SdrPageView&                                        mrPageView;

    // the PaintWindow to paint on. Here is access to OutDev etc.
    // #i72752# change to pointer to allow patcing it in DrawLayer() if necessary
    SdrPaintWindow*                                     mpPaintWindow;
    SdrPaintWindow*                                     mpOriginalPaintWindow;

    // UNO stuff for xControls
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > mxControlContainer;

    sdr::contact::ObjectContact* CreateViewSpecificObjectContact();

public:
    SdrPageWindow(SdrPageView& rNewPageView, SdrPaintWindow& rPaintWindow);
    ~SdrPageWindow();

    // data read accesses
    SdrPageView& GetPageView() const { return mrPageView; }
    SdrPaintWindow& GetPaintWindow() const { return *mpPaintWindow; }
    const SdrPaintWindow* GetOriginalPaintWindow() const { return mpOriginalPaintWindow; }
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > GetControlContainer( bool _bCreateIfNecessary = true ) const;

    // OVERLAYMANAGER
    rtl::Reference< ::sdr::overlay::OverlayManager > GetOverlayManager() const;

    // #i72752# allow patcing SdrPaintWindow from SdrPageView::DrawLayer if needed
    void patchPaintWindow(SdrPaintWindow& rPaintWindow);
    void unpatchPaintWindow();

    // the repaint method. For migration from pPaintProc, use one more parameter
    void PrePaint();
    void PrepareRedraw(const Region& rReg);
    void RedrawAll(sdr::contact::ViewObjectContactRedirector* pRedirector) const;
    void RedrawLayer(const SdrLayerID* pId, sdr::contact::ViewObjectContactRedirector* pRedirector) const;

    // Invalidate call, used from ObjectContact(OfPageView) in InvalidatePartOfView(...)
    void InvalidatePageWindow(const basegfx::B2DRange& rRange);

    // #110094# ObjectContact section
    sdr::contact::ObjectContact& GetObjectContact() const;
    /// determines whether there already exists an ObjectContact
    bool                         HasObjectContact() const;

    // #i26631#
    void ResetObjectContact();

    /** sets all elements in the view which support a design and a alive mode into the given mode
    */
    void    SetDesignMode( bool _bDesignMode ) const;
};

// typedefs for a list of SdrPageWindow
typedef ::std::vector< SdrPageWindow* > SdrPageWindowVector;

////////////////////////////////////////////////////////////////////////////////////////////////////

#endif //_SDRPAGEWINDOW_HXX

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: contimp.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 12:08:15 $
 *
 *  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 _CONTIMP_HXX_
#define _CONTIMP_HXX_

#ifndef _CONTDLG_HXX
#include "contdlg.hxx"
#endif
#ifndef _CONTWND_HXX
#include "contwnd.hxx"
#endif
#ifndef _SV_TOOLBOX_HXX
#include <vcl/toolbox.hxx>
#endif
#ifndef _SV_STATUS_HXX
#include <vcl/status.hxx>
#endif

#define CONT_RESID(nId)  ResId( nId, DIALOG_MGR() )

/*************************************************************************
|*
|*
|*
\************************************************************************/

class SvxSuperContourDlg : public SvxContourDlg
{
    using SvxContourDlg::GetPolyPolygon;

    Graphic             aGraphic;
    Graphic             aUndoGraphic;
    Graphic             aRedoGraphic;
    Graphic             aUpdateGraphic;
    PolyPolygon         aUpdatePolyPoly;
    Timer               aUpdateTimer;
    Timer               aCreateTimer;
    Size                aLastSize;
    void*               pUpdateEditingObject;
    void*               pCheckObj;
    SvxContourDlgItem   aContourItem;
    ToolBox             aTbx1;
    MetricField         aMtfTolerance;
    ContourWindow       aContourWnd;
    StatusBar           aStbStatus;
    ULONG               nGrfChanged;
    BOOL                bExecState;
    BOOL                bPipetteMode;
    BOOL                bWorkplaceMode;
    BOOL                bUpdateGraphicLinked;
    BOOL                bGraphicLinked;
    ImageList           maImageList;
    ImageList           maImageListH;

    virtual void        Resize();
    virtual BOOL        Close();

    void                DoAutoCreate();
    void                ReducePoints( const long nTol = 8 );

                        DECL_LINK( Tbx1ClickHdl, ToolBox* );
                        DECL_LINK( MousePosHdl, ContourWindow* );
                        DECL_LINK( GraphSizeHdl, ContourWindow* );
                        DECL_LINK( UpdateHdl, Timer* );
                        DECL_LINK( CreateHdl, Timer* );
                        DECL_LINK( StateHdl, ContourWindow* );
                        DECL_LINK( PipetteHdl, ContourWindow* );
                        DECL_LINK( PipetteClickHdl, ContourWindow* );
                        DECL_LINK( WorkplaceClickHdl, ContourWindow* );
                        DECL_LINK( MiscHdl, void* );

public:

                        SvxSuperContourDlg( SfxBindings *pBindings, SfxChildWindow *pCW,
                                            Window* pParent, const ResId& rResId );
                        ~SvxSuperContourDlg();

    void                SetExecState( BOOL bEnable );

    void                SetGraphic( const Graphic& rGraphic );
    void                SetGraphicLinked( BOOL bLinked ) { bGraphicLinked = bLinked; }
    const Graphic&      GetGraphic() const { return aGraphic; }
    BOOL                IsGraphicChanged() const { return nGrfChanged > 0UL; }

    void                SetPolyPolygon( const PolyPolygon& rPolyPoly );
    PolyPolygon         GetPolyPolygon( BOOL bRescaleToGraphic = TRUE );

    void                SetEditingObject( void* pObj ) { pCheckObj = pObj; }
    const void*         GetEditingObject() const { return pCheckObj; }

    BOOL                IsUndoPossible() const;
    BOOL                IsRedoPossible() const;

    void                UpdateGraphic( const Graphic& rGraphic, BOOL bGraphicLinked,
                                const PolyPolygon* pPolyPoly = NULL,
                                void* pEditingObj = NULL );

    /** switches the toolbox images depending on the actuall high contrast display mode state */
    void                ApplyImageList();

    /** virtual method from Window is used to detect change in high contrast display mode
        to switch the toolbox images */
    virtual void        DataChanged( const DataChangedEvent& rDCEvt );

};

#endif // _CONTIMP_HXX_

<commit_msg>INTEGRATION: CWS vgbugs07 (1.5.322); FILE MERGED 2007/06/04 13:26:14 vg 1.5.322.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: contimp.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 16:56:01 $
 *
 *  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 _CONTIMP_HXX_
#define _CONTIMP_HXX_

#ifndef _CONTDLG_HXX
#include <svx/contdlg.hxx>
#endif
#ifndef _CONTWND_HXX
#include "contwnd.hxx"
#endif
#ifndef _SV_TOOLBOX_HXX
#include <vcl/toolbox.hxx>
#endif
#ifndef _SV_STATUS_HXX
#include <vcl/status.hxx>
#endif

#define CONT_RESID(nId)  ResId( nId, DIALOG_MGR() )

/*************************************************************************
|*
|*
|*
\************************************************************************/

class SvxSuperContourDlg : public SvxContourDlg
{
    using SvxContourDlg::GetPolyPolygon;

    Graphic             aGraphic;
    Graphic             aUndoGraphic;
    Graphic             aRedoGraphic;
    Graphic             aUpdateGraphic;
    PolyPolygon         aUpdatePolyPoly;
    Timer               aUpdateTimer;
    Timer               aCreateTimer;
    Size                aLastSize;
    void*               pUpdateEditingObject;
    void*               pCheckObj;
    SvxContourDlgItem   aContourItem;
    ToolBox             aTbx1;
    MetricField         aMtfTolerance;
    ContourWindow       aContourWnd;
    StatusBar           aStbStatus;
    ULONG               nGrfChanged;
    BOOL                bExecState;
    BOOL                bPipetteMode;
    BOOL                bWorkplaceMode;
    BOOL                bUpdateGraphicLinked;
    BOOL                bGraphicLinked;
    ImageList           maImageList;
    ImageList           maImageListH;

    virtual void        Resize();
    virtual BOOL        Close();

    void                DoAutoCreate();
    void                ReducePoints( const long nTol = 8 );

                        DECL_LINK( Tbx1ClickHdl, ToolBox* );
                        DECL_LINK( MousePosHdl, ContourWindow* );
                        DECL_LINK( GraphSizeHdl, ContourWindow* );
                        DECL_LINK( UpdateHdl, Timer* );
                        DECL_LINK( CreateHdl, Timer* );
                        DECL_LINK( StateHdl, ContourWindow* );
                        DECL_LINK( PipetteHdl, ContourWindow* );
                        DECL_LINK( PipetteClickHdl, ContourWindow* );
                        DECL_LINK( WorkplaceClickHdl, ContourWindow* );
                        DECL_LINK( MiscHdl, void* );

public:

                        SvxSuperContourDlg( SfxBindings *pBindings, SfxChildWindow *pCW,
                                            Window* pParent, const ResId& rResId );
                        ~SvxSuperContourDlg();

    void                SetExecState( BOOL bEnable );

    void                SetGraphic( const Graphic& rGraphic );
    void                SetGraphicLinked( BOOL bLinked ) { bGraphicLinked = bLinked; }
    const Graphic&      GetGraphic() const { return aGraphic; }
    BOOL                IsGraphicChanged() const { return nGrfChanged > 0UL; }

    void                SetPolyPolygon( const PolyPolygon& rPolyPoly );
    PolyPolygon         GetPolyPolygon( BOOL bRescaleToGraphic = TRUE );

    void                SetEditingObject( void* pObj ) { pCheckObj = pObj; }
    const void*         GetEditingObject() const { return pCheckObj; }

    BOOL                IsUndoPossible() const;
    BOOL                IsRedoPossible() const;

    void                UpdateGraphic( const Graphic& rGraphic, BOOL bGraphicLinked,
                                const PolyPolygon* pPolyPoly = NULL,
                                void* pEditingObj = NULL );

    /** switches the toolbox images depending on the actuall high contrast display mode state */
    void                ApplyImageList();

    /** virtual method from Window is used to detect change in high contrast display mode
        to switch the toolbox images */
    virtual void        DataChanged( const DataChangedEvent& rDCEvt );

};

#endif // _CONTIMP_HXX_

<|endoftext|>


<commit_before>/*
    Пример применения генератора псевдослучайных чисел (ГПЧ) из
    стандартной библиотеки C++
*/

#include <iostream>
#include <ctime>  // Библиотека работы со временем
#include <random> // Библиотека с различными генераторами

using namespace std;

/*
    Функция для получения действительного случайного числа,
    равномерно распределённого в диапазоне [0.0; 1.0].

    Пока только объявление.
*/
double real_rnd_0_1();

int main()
{
    /*
        Используем тип mt19937_64 для создания переменной,
        которая и будет создавать случайные числа.

        При создании переменной-генератора ей передаётся
        количество секунд, прошедших с 01.01.1970 00:00:00,
        которое используется в качестве зерна ГПЧ. Это число
        возращается функцией time, определённой в <ctime>.
        Данная функция ожидает адрес некоторой библиотечной
        структуры, но вместо него можно передать и специальный
        нулевой адрес. Этот нулевой адрес представлен ключевым
        словом - nullptr
    */
    mt19937_64 gnr( time(nullptr) );

    /*
        Случайное число создаётся с помощью вызова специального оператора -
        пары круглых скобок. Очень похоже на вызов функции, но применяется
        к переменным некоторых составных (сложных) типов данных.

        Каждое случайное число является беззнаковым целым из
        диапазона [0; MAX], где MAX - величина относящаяся
        к алгоритму ГПЧ. Случайные числа выбираются из указанного
        интервала равномерно.
    */
    cout << "Случайное число: " << gnr() << "\n";
    cout << "ещё одно: " << gnr() << "\n";

    // Получить максимально возможное случайно число:
    cout << "Максимальное число, доступное ГПЧ: " << gnr.max() << "\n";

    cout << "Случайное число от 0 до 1: " << real_rnd_0_1() << "\n";
}

double real_rnd_0_1()
{
    /*
        Пример статической переменной: данная переменная создаётся
        при начале работы программы один раз и не меняется/удаляется
        при любом количестве вызовов данной функции.
    */
    static mt19937_64 gener( time(nullptr) );
    static unsigned long long max_num = gener.max();

    /*
        Что ниже происходит?

        gener() - возращает целое число, max_num - тоже целое.
        Для того, чтобы результат деления был действительным,
        а не целочисленным (при таком делении результат выражения -
        всегда нуль), нужно сделать явное приведение хотя бы
        одного целочисленного значения к действительному типу данных.

        Это делайтся в C++ с помощью специального оператора: static_cast.
        Он работает следующим образом: в треугольных скобках указан тип,
        к которому нужно привести значение, в круглых скобках - само значение.

        После его выполнения, деление проходит по правилам действительных чисел
        и мы получаем число от 0.0 до 1.0
    */
    return static_cast<double>( gener() ) / max_num;
}
<commit_msg>c++, fp: extend third practice example<commit_after>/*
    Пример применения генератора псевдослучайных чисел (ГПЧ) из
    стандартной библиотеки C++
*/

#include <iostream>
#include <ctime>  // Библиотека работы со временем
#include <random> // Библиотека с различными генераторами

using namespace std;

/*
    Функция для получения действительного случайного числа,
    равномерно распределённого в диапазоне [0.0; 1.0].

    Пока только объявление.
*/
double real_rnd_0_1();

/*
    Функция для получнния случайного действительного числа
    в интервале [a; b]. Значения правого и левого краёв
    передаются через 2 аргумента. Внутри используется функция
    real_rnd_0_1
*/
double real_rnd_a_b(double a, double b);

int main()
{
    /*
        Используем тип mt19937_64 для создания переменной,
        которая и будет создавать случайные числа.

        При создании переменной-генератора ей передаётся
        количество секунд, прошедших с 01.01.1970 00:00:00,
        которое используется в качестве зерна ГПЧ. Это число
        возращается функцией time, определённой в <ctime>.
        Данная функция ожидает адрес некоторой библиотечной
        структуры, но вместо него можно передать и специальный
        нулевой адрес. Этот нулевой адрес представлен ключевым
        словом - nullptr
    */
    mt19937_64 gnr( time(nullptr) );

    /*
        Случайное число создаётся с помощью вызова специального оператора -
        пары круглых скобок. Очень похоже на вызов функции, но применяется
        к переменным некоторых составных (сложных) типов данных.

        Каждое случайное число является беззнаковым целым из
        диапазона [0; MAX], где MAX - величина относящаяся
        к алгоритму ГПЧ. Случайные числа выбираются из указанного
        интервала равномерно.
    */
    cout << "Случайное число: " << gnr() << "\n";
    cout << "ещё одно: " << gnr() << "\n";

    // Получить максимально возможное случайно число:
    cout << "Максимальное число, доступное ГПЧ: " << gnr.max() << "\n";

    cout << "Случайное число от 0 до 1: " << real_rnd_0_1() << "\n";

    // Пример заполнения статического массива числами из заданного интервала: [-1.5; 7.8]
    double arr_2D[11][7];
    for (unsigned i = 0; i < 11; ++i) {
        for (unsigned j = 0; j < 7; ++j) {
            arr_2D[i][j] = real_rnd_a_b(-1.5, 7.8);
        }
    }

    cout << "Созданный массив:\n";
    // Используем специальный цикл for (for-range) для печати элементов
    // двумерного массива
    for (const auto& row : arr_2D) { // Этот цикл переберает все строчки
        for (double elem : row) {    // Этот - все элементы в конкретной строке
            cout << elem << " ";
        }
        cout << "\n";
    }
    cout << "\n";
}

double real_rnd_0_1()
{
    /*
        Пример статической переменной: данная переменная создаётся
        при начале работы программы один раз и не меняется/удаляется
        при любом количестве вызовов данной функции.
    */
    static mt19937_64 gener( time(nullptr) );
    static unsigned long long max_num = gener.max();

    /*
        Что ниже происходит?

        gener() - возращает целое число, max_num - тоже целое.
        Для того, чтобы результат деления был действительным,
        а не целочисленным (при таком делении результат выражения -
        всегда нуль), нужно сделать явное приведение хотя бы
        одного целочисленного значения к действительному типу данных.

        Это делайтся в C++ с помощью специального оператора: static_cast.
        Он работает следующим образом: в треугольных скобках указан тип,
        к которому нужно привести значение, в круглых скобках - само значение.

        После его выполнения, деление проходит по правилам действительных чисел
        и мы получаем число от 0.0 до 1.0.

        Дополнение: альтернативным способом для задания явного приведения между
        численными типами данных является следующий синтаксис:

            double( gener() )

        , где указывается тип данных, к которому нужно привести значение, а затем
        - само значение.
    */
    return static_cast<double>( gener() ) / max_num;
}

double real_rnd_a_b(double a, double b)
{
    return (b - a) * real_rnd_0_1() + a;
}
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2012 The WebM project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/util.h"

namespace {

class AqSegmentTest
    : public ::libvpx_test::EncoderTest,
      public ::libvpx_test::CodecTestWith2Params<libvpx_test::TestMode, int> {
 protected:
  AqSegmentTest() : EncoderTest(GET_PARAM(0)) {}
  virtual ~AqSegmentTest() {}

  virtual void SetUp() {
    InitializeConfig();
    SetMode(GET_PARAM(1));
    set_cpu_used_ = GET_PARAM(2);
    aq_mode_ = 0;
  }

  virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
                                  ::libvpx_test::Encoder *encoder) {
    if (video->frame() == 1) {
      encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_);
      encoder->Control(VP9E_SET_AQ_MODE, aq_mode_);
      encoder->Control(VP8E_SET_MAX_INTRA_BITRATE_PCT, 100);
    }
  }

  int set_cpu_used_;
  int aq_mode_;
};

// Validate that this AQ segmentation mode (AQ=1, variance_ap)
// encodes and decodes without a mismatch.
TEST_P(AqSegmentTest, TestNoMisMatchAQ1) {
  cfg_.rc_min_quantizer = 8;
  cfg_.rc_max_quantizer = 56;
  cfg_.rc_end_usage = VPX_CBR;
  cfg_.g_lag_in_frames = 0;
  cfg_.rc_buf_initial_sz = 500;
  cfg_.rc_buf_optimal_sz = 500;
  cfg_.rc_buf_sz = 1000;
  cfg_.rc_target_bitrate = 300;

  aq_mode_ = 1;

  ::libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288,
                                        30, 1, 0, 100);

  ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
}

// Validate that this AQ segmentation mode (AQ=2, complexity_aq)
// encodes and decodes without a mismatch.
TEST_P(AqSegmentTest, TestNoMisMatchAQ2) {
  cfg_.rc_min_quantizer = 8;
  cfg_.rc_max_quantizer = 56;
  cfg_.rc_end_usage = VPX_CBR;
  cfg_.g_lag_in_frames = 0;
  cfg_.rc_buf_initial_sz = 500;
  cfg_.rc_buf_optimal_sz = 500;
  cfg_.rc_buf_sz = 1000;
  cfg_.rc_target_bitrate = 300;

  aq_mode_ = 2;

  ::libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288,
                                        30, 1, 0, 100);

  ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
}

// Validate that this AQ segmentation mode (AQ=3, cyclic_refresh_aq)
// encodes and decodes without a mismatch.
TEST_P(AqSegmentTest, TestNoMisMatchAQ3) {
  cfg_.rc_min_quantizer = 8;
  cfg_.rc_max_quantizer = 56;
  cfg_.rc_end_usage = VPX_CBR;
  cfg_.g_lag_in_frames = 0;
  cfg_.rc_buf_initial_sz = 500;
  cfg_.rc_buf_optimal_sz = 500;
  cfg_.rc_buf_sz = 1000;
  cfg_.rc_target_bitrate = 300;

  aq_mode_ = 3;

  ::libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv", 352, 288,
                                        30, 1, 0, 100);

  ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
}

VP9_INSTANTIATE_TEST_CASE(AqSegmentTest,
                          ::testing::Values(::libvpx_test::kRealTime,
                                            ::libvpx_test::kOnePassGood),
                          ::testing::Range(3, 9));
}  // namespace
<commit_msg>Turn on AqSegment tests for VP10<commit_after>/*
 *  Copyright (c) 2012 The WebM project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/i420_video_source.h"
#include "test/util.h"

namespace {

class AqSegmentTest
    : public ::libvpx_test::EncoderTest,
      public ::libvpx_test::CodecTestWith2Params<libvpx_test::TestMode, int> {
 protected:
  AqSegmentTest() : EncoderTest(GET_PARAM(0)) {}
  virtual ~AqSegmentTest() {}

  virtual void SetUp() {
    InitializeConfig();
    SetMode(GET_PARAM(1));
    set_cpu_used_ = GET_PARAM(2);
    aq_mode_ = 0;
  }

  virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
                                  ::libvpx_test::Encoder *encoder) {
    if (video->frame() == 1) {
      encoder->Control(VP8E_SET_CPUUSED, set_cpu_used_);
      encoder->Control(VP9E_SET_AQ_MODE, aq_mode_);
      encoder->Control(VP8E_SET_MAX_INTRA_BITRATE_PCT, 100);
    }
  }

  void DoTest(int aq_mode) {
    aq_mode_ = aq_mode;
    cfg_.kf_max_dist = 12;
    cfg_.rc_min_quantizer = 8;
    cfg_.rc_max_quantizer = 56;
    cfg_.rc_end_usage = VPX_CBR;
    cfg_.g_lag_in_frames = 6;
    cfg_.rc_buf_initial_sz = 500;
    cfg_.rc_buf_optimal_sz = 500;
    cfg_.rc_buf_sz = 1000;
    cfg_.rc_target_bitrate = 300;
    ::libvpx_test::I420VideoSource video("hantro_collage_w352h288.yuv",
                                         352, 288, 30, 1, 0, 15);
    ASSERT_NO_FATAL_FAILURE(RunLoop(&video));
  }

  int set_cpu_used_;
  int aq_mode_;
};

// Validate that this AQ segmentation mode (AQ=1, variance_ap)
// encodes and decodes without a mismatch.
TEST_P(AqSegmentTest, TestNoMisMatchAQ1) {
  DoTest(1);
}

// Validate that this AQ segmentation mode (AQ=2, complexity_aq)
// encodes and decodes without a mismatch.
TEST_P(AqSegmentTest, TestNoMisMatchAQ2) {
  DoTest(2);
}

// Validate that this AQ segmentation mode (AQ=3, cyclic_refresh_aq)
// encodes and decodes without a mismatch.
TEST_P(AqSegmentTest, TestNoMisMatchAQ3) {
  DoTest(3);
}

class AqSegmentTestLarge : public AqSegmentTest {};

TEST_P(AqSegmentTestLarge, TestNoMisMatchAQ1) {
  DoTest(1);
}

TEST_P(AqSegmentTestLarge, TestNoMisMatchAQ2) {
  DoTest(2);
}

TEST_P(AqSegmentTestLarge, TestNoMisMatchAQ3) {
  DoTest(3);
}

VP9_INSTANTIATE_TEST_CASE(AqSegmentTest,
                          ::testing::Values(::libvpx_test::kRealTime,
                                            ::libvpx_test::kOnePassGood),
                          ::testing::Range(3, 9));

VP10_INSTANTIATE_TEST_CASE(AqSegmentTest,
                           ::testing::Values(::libvpx_test::kRealTime,
                                             ::libvpx_test::kOnePassGood),
                           ::testing::Range(5, 9));
VP10_INSTANTIATE_TEST_CASE(AqSegmentTestLarge,
                           ::testing::Values(::libvpx_test::kRealTime,
                                             ::libvpx_test::kOnePassGood),
                           ::testing::Range(3, 5));
}  // namespace
<|endoftext|>


<commit_before>/*
	AtlasProtocolDecoder.cpp
	----------------
	begin   : 1999.11.29
	copyright   : (C) 1999 by John Barrett (ZW)
	email   : jbarrett@box100.com
*/

#include "AtlasObject.h"
#include "AtlasProtocol.h"
#include "AtlasPackedAsciiDecoder.h"

#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>

void APackedAsciiDecoder::newStream()
{
	// reset decoder
	state = 1;
	nestd = 0;
	token = 0;
}

void APackedAsciiDecoder::feedStream(string& data)
{
	buffer.append(data);
}

int APackedAsciiDecoder::getToken()
{
	int tmp = token;
	token = 0;
	return tmp;
}

int APackedAsciiDecoder::hasTokens()
{
	int	pos;
   //int	pos1;
	//int	ndx;
	int	chk;
	string	typ;

	//printf("BEG TOKEN=%i\n", token);

	if (token == -1) return-1; // buffer overflow !!!

	do {
		chk = 0;

		//printf("BEG STATE=%i\n", state);
		//printf("BEG BUFFR=%s\n", buffer.c_str());

		// this is where we are gonna put the state machine
		switch (state) {
		case 1:// start of message
			if((pos=buffer.find('{')) == -1) break;
			buffer = buffer.substr(pos+1);
			// change states
			token = AProtocol::atlasMSGBEG;
			state = 2;
			chk = 1;
			break;

		case 2:
			pos = buffer.find_first_of("[(%$#])}");
			if (pos == -1) break;
			if (pos != 0)
			{
				// bad protcol character
				token = AProtocol::atlasERRTOK;
				state = 1;
				break;
			}
			typ = buffer.substr(0,1);
			if (typ == ")") {
				// end of list
				buffer = buffer.substr(1);
				token = AProtocol::atlasATREND;
				type = AProtocol::atlasLST;
				state = 2;
				break;
			}
			if (typ == ">") {
				// end of typed list
				buffer = buffer.substr(1);
				token = AProtocol::atlasATREND;
				type = AProtocol::atlasLST;
				state = 2;
				break;
			}
			if (typ == "]") {
				// end of map
				buffer = buffer.substr(1);
				token = AProtocol::atlasATREND;
				type = AProtocol::atlasMAP;
				state = 2;
				break;
			}
			if (typ == "}") {
				// end of message
				buffer = buffer.substr(1);
				token = AProtocol::atlasMSGEND;
				state = 1;
				break;
			}
			// must be an attribute == wait until we got the name
			if ((pos=buffer.find('=')) == -1) break;
			// get the name out before proc
			name = buffer.substr(1,pos-1);
			buffer = buffer.substr(pos+1);
			// got an attribute name
			if (typ == "<") {
				typ = buffer.substr(0,1);
				if (typ == "!") type = AProtocol::atlasLSTURI;
				if (typ == "@") type = AProtocol::atlasLSTINT;
				if (typ == "#") type = AProtocol::atlasLSTFLT;
				if (typ == "$") type = AProtocol::atlasLSTSTR;
				if (typ == "%") type = AProtocol::atlasLSTLNG;
			}
			if (typ == "(") type = AProtocol::atlasLST;
			if (typ == "[") type = AProtocol::atlasMAP;
			if (typ == "@") type = AProtocol::atlasINT;
			if (typ == "%") type = AProtocol::atlasLNG;
			if (typ == "#") type = AProtocol::atlasFLT;
			if (typ == "$") type = AProtocol::atlasSTR;
			// change states, wait for value
			token = AProtocol::atlasATRBEG;
			if (type==AProtocol::atlasLST || type==AProtocol::atlasMAP) {
				state = 2;
			} else {
				state = 3;
			}
			chk = 1;
			break;

		case 3:
			pos = buffer.find_first_of("[(%$#])}");
			if (pos == -1) break;
			// got an end marker, pull the data
			sval = buffer.substr(0,pos);
			if (type == AProtocol::atlasINT) ival = atoi(sval.c_str());
			if (type == AProtocol::atlasFLT) fval = atof(sval.c_str());
			// strip up to token
			buffer = buffer.substr(pos);
			token = AProtocol::atlasATRVAL;
			state = 4;
			chk = 1;
			break;

		case 4:	// special state to end attributes
			token = AProtocol::atlasATREND;
			state = 2;
			chk = 1;
			break;

		default:
			// invalid state
			token =-1;
			state =1;
			break;
		}

	} while (chk == 1 && token == 0);

	// see if we have a token to return
	//printf("END TOKEN=%i\n", token);
	//printf("END STATE=%i\n", state);
	//printf("END BUFFR=%s\n\n\n", buffer.c_str());
	if (token != 0) {
		return 1;
	}
	return 0;
}

<commit_msg>Stream parser changes for typed lists and uris completed<commit_after>/*
	AtlasProtocolDecoder.cpp
	----------------
	begin   : 1999.11.29
	copyright   : (C) 1999 by John Barrett (ZW)
	email   : jbarrett@box100.com
*/

#include "AtlasObject.h"
#include "AtlasProtocol.h"
#include "AtlasPackedAsciiDecoder.h"

#include <memory.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>

void APackedAsciiDecoder::newStream()
{
	// reset decoder
	state = 1;
	nestd = 0;
	token = 0;
}

void APackedAsciiDecoder::feedStream(string& data)
{
	buffer.append(data);
}

int APackedAsciiDecoder::getToken()
{
	int tmp = token;
	token = 0;
	return tmp;
}

int APackedAsciiDecoder::hasTokens()
{
	int	pos;
   //int	pos1;
	//int	ndx;
	int	chk;
	string	typ;

	//printf("BEG TOKEN=%i\n", token);

	if (token == -1) return-1; // buffer overflow !!!

	do {
		chk = 0;

		//printf("BEG STATE=%i\n", state);
		//printf("BEG BUFFR=%s\n", buffer.c_str());

		// this is where we are gonna put the state machine
		switch (state) {
		case 1:// start of message
			if((pos=buffer.find('{')) == -1) break;
			buffer = buffer.substr(pos+1);
			// change states
			token = AProtocol::atlasMSGBEG;
			state = 2;
			chk = 1;
			break;

		case 2:
			pos = buffer.find_first_of("[<(%$#])>}");
			if (pos == -1) break;
			if (pos != 0)
			{
				// bad protcol character
				token = AProtocol::atlasERRTOK;
				state = 1;
				break;
			}
			typ = buffer.substr(0,1);
			if (typ == ")") {
				// end of list
				buffer = buffer.substr(1);
				token = AProtocol::atlasATREND;
				type = AProtocol::atlasLST;
				state = 2;
				break;
			}
			if (typ == ">") {
				// end of typed list
				buffer = buffer.substr(1);
				token = AProtocol::atlasATREND;
				type = AProtocol::atlasLST;
				state = 2;
				break;
			}
			if (typ == "]") {
				// end of map
				buffer = buffer.substr(1);
				token = AProtocol::atlasATREND;
				type = AProtocol::atlasMAP;
				state = 2;
				break;
			}
			if (typ == "}") {
				// end of message
				buffer = buffer.substr(1);
				token = AProtocol::atlasMSGEND;
				state = 1;
				break;
			}
			// must be an attribute == wait until we got the name
			if ((pos=buffer.find('=')) == -1) break;
			// get the name out before proc
			name = buffer.substr(1,pos-1);
			buffer = buffer.substr(pos+1);
			// got an attribute name
			if (typ == "<") {
				typ = buffer.substr(0,1);
				if (typ == "!") type = AProtocol::atlasLSTURI;
				if (typ == "@") type = AProtocol::atlasLSTINT;
				if (typ == "#") type = AProtocol::atlasLSTFLT;
				if (typ == "$") type = AProtocol::atlasLSTSTR;
				if (typ == "%") type = AProtocol::atlasLSTLNG;
			}
			if (typ == "(") type = AProtocol::atlasLST;
			if (typ == "[") type = AProtocol::atlasMAP;
			if (typ == "@") type = AProtocol::atlasINT;
			if (typ == "%") type = AProtocol::atlasLNG;
			if (typ == "#") type = AProtocol::atlasFLT;
			if (typ == "$") type = AProtocol::atlasSTR;
			// change states, wait for value
			token = AProtocol::atlasATRBEG;
			if (type==AProtocol::atlasLST || type==AProtocol::atlasMAP) {
				state = 2;
			} else {
				state = 3;
			}
			chk = 1;
			break;

		case 3:
			pos = buffer.find_first_of("[(<%$#]>)}");
			if (pos == -1) break;
			// got an end marker, pull the data
			sval = buffer.substr(0,pos);
			if (type == AProtocol::atlasINT) ival = atoi(sval.c_str());
			if (type == AProtocol::atlasFLT) fval = atof(sval.c_str());
			// strip up to token
			buffer = buffer.substr(pos);
			token = AProtocol::atlasATRVAL;
			state = 4;
			chk = 1;
			break;

		case 4:	// special state to end attributes
			token = AProtocol::atlasATREND;
			state = 2;
			chk = 1;
			break;

		default:
			// invalid state
			token =-1;
			state =1;
			break;
		}

	} while (chk == 1 && token == 0);

	// see if we have a token to return
	//printf("END TOKEN=%i\n", token);
	//printf("END STATE=%i\n", state);
	//printf("END BUFFR=%s\n\n\n", buffer.c_str());
	if (token != 0) {
		return 1;
	}
	return 0;
}

<|endoftext|>


<commit_before>/**
@file common_types.hpp
@brief Common types.

@author Tim Howard
@copyright 2013 Tim Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/

#ifndef HORD_COMMON_TYPES_HPP_
#define HORD_COMMON_TYPES_HPP_

#include "./config.hpp"

namespace Hord {

/** Generic object ID. */
typedef uint32_t ObjectID;

enum : ObjectID {
	/** Null object. */
	OBJECT_NULL
};

/**
	@addtogroup metadata
	@{
*/

/** MetaField type. */
typedef uint8_t MetaFieldType;

/** @} */ // end of doc-group metadata

/**
	@addtogroup node
	@{
*/

/** Node ID. */
typedef ObjectID NodeID;

/**
	@addtogroup rule
	@{
*/

/** Rule ID. */
typedef ObjectID RuleID;
/** Rule type. */
typedef uint32_t RuleType;

/** @} */ // end of doc-group rule
/** @} */ // end of doc-group node

} // namespace Hord

#endif // HORD_COMMON_TYPES_HPP_
<commit_msg>common_types: added HiveID typedef and note for specialized ID types.<commit_after>/**
@file common_types.hpp
@brief Common types.

@author Tim Howard
@copyright 2013 Tim Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/

#ifndef HORD_COMMON_TYPES_HPP_
#define HORD_COMMON_TYPES_HPP_

#include "./config.hpp"

namespace Hord {

/**
	@addtogroup object
	@{
*/

/** Generic object ID. */
typedef uint32_t ObjectID;

enum : ObjectID {
	/** Null object. */
	OBJECT_NULL=0
};

/** @} */ // end of doc-group object

/**
	@addtogroup metadata
	@{
*/

/** MetaField type. */
typedef uint8_t MetaFieldType;

/** @} */ // end of doc-group metadata

/**
	@addtogroup driver
	@{
*/
/**
	@addtogroup hive
	@{
*/

/**
	Hive ID.

	@note This type is only to telegraph intent in functions;
	it is entirely equivalent to ObjectID.
*/
typedef ObjectID HiveID;

/** @} */ // end of doc-group hive
/** @} */ // end of doc-group driver

/**
	@addtogroup node
	@{
*/

/**
	Node ID.

	@note This type is only to telegraph intent in functions;
	it is entirely equivalent to ObjectID.
*/
typedef ObjectID NodeID;

/**
	@addtogroup rule
	@{
*/

/**
	Rule ID.

	@note This type is only to telegraph intent in functions;
	it is entirely equivalent to ObjectID.
*/
typedef ObjectID RuleID;
/** Rule type. */
typedef uint32_t RuleType;

/** @} */ // end of doc-group rule
/** @} */ // end of doc-group node

} // namespace Hord

#endif // HORD_COMMON_TYPES_HPP_
<|endoftext|>


<commit_before><commit_msg>wait 10 sec before trying to resync clock again<commit_after><|endoftext|>