<commit_before>/*
 * Copyright 2010-2017 Branimir Karadzic. All rights reserved.
 * License: https://github.com/bkaradzic/bx#license-bsd-2-clause
 */

#include "bx_p.h"
#include <bx/file.h>
#include <bx/os.h>
#include <bx/readerwriter.h>

#if BX_PLATFORM_WINDOWS
extern "C" __declspec(dllimport) unsigned long __stdcall GetTempPathA(unsigned long _max, char* _ptr);
#endif // BX_PLATFORM_WINDOWS

namespace bx
{
	static bool isPathSeparator(char _ch)
	{
		return false
			|| '/'  == _ch
			|| '\\' == _ch
			;
	}

	static int32_t normalizeFilePath(char* _dst, int32_t _dstSize, const char* _src, int32_t _num)
	{
		// Reference: Lexical File Names in Plan 9 or Getting Dot-Dot Right
		// https://9p.io/sys/doc/lexnames.html

		const int32_t num = strLen(_src, _num);

		if (0 == num)
		{
			return strCopy(_dst, _dstSize, ".");
		}

		int32_t size = 0;

		StaticMemoryBlockWriter writer(_dst, _dstSize);
		Error err;

		int32_t idx      = 0;
		int32_t dotdot   = 0;

		if (2 <= num
		&&  ':' == _src[1])
		{
			size += write(&writer, toUpper(_src[idx]), &err);
			size += write(&writer, ':', &err);
			idx  += 2;
			dotdot = size;
		}

		const int32_t slashIdx = idx;

		bool rooted = isPathSeparator(_src[idx]);
		if (rooted)
		{
			size += write(&writer, '/', &err);
			++idx;
			dotdot = size;
		}

		while (idx < num && err.isOk() )
		{
			switch (_src[idx])
			{
			case '/':
			case '\\':
				++idx;
				break;

			case '.':
				if (idx+1 == num
				||  isPathSeparator(_src[idx+1]) )
				{
					++idx;
					break;
				}

				if ('.' == _src[idx+1]
				&& (idx+2 == num || isPathSeparator(_src[idx+2]) ) )
				{
					idx += 2;

					if (dotdot < size)
					{
						for (--size
							; dotdot < size && !isPathSeparator(_dst[size])
							; --size)
						{
						}
						seek(&writer, size, Whence::Begin);
					}
					else if (!rooted)
					{
						if (0 < size)
						{
							size += write(&writer, '/', &err);
						}

						size += write(&writer, "..", &err);
						dotdot = size;
					}

					break;
				}

				BX_FALLTHROUGH;

			default:
				if ( ( rooted && slashIdx+1 != size)
				||   (!rooted &&          0 != size) )
				{
					size += write(&writer, '/', &err);
				}

				for (; idx < num && !isPathSeparator(_src[idx]); ++idx)
				{
					size += write(&writer, _src[idx], &err);
				}

				break;
			}
		}

		if (0 == size)
		{
			size += write(&writer, '.', &err);
		}

		write(&writer, '\0', &err);

		return size;
	}

	static bool getEnv(const char* _name, FileInfo::Enum _type, char* _out, uint32_t* _inOutSize)
	{
		uint32_t len = *_inOutSize;
		*_out = '\0';

		if (getenv(_name, _out, &len) )
		{
			FileInfo fi;
			if (stat(_out, fi)
			&&  _type == fi.m_type)
			{
				*_inOutSize = len;
				return true;
			}
		}

		return false;
	}

	static bool getHomePath(char* _out, uint32_t* _inOutSize)
	{
		return false
#if BX_PLATFORM_WINDOWS
			|| getEnv("USERPROFILE", FileInfo::Directory, _out, _inOutSize)
#endif // BX_PLATFORM_WINDOWS
			|| getEnv("HOME", FileInfo::Directory, _out, _inOutSize)
			;
	}

	static bool getTempPath(char* _out, uint32_t* _inOutSize)
	{
#if BX_PLATFORM_WINDOWS
		uint32_t len = ::GetTempPathA(*_inOutSize, _out);
		bool result = len != 0 && len < *_inOutSize;
		*_inOutSize = len;
		return result;
#else
		static const char* s_tmp[] =
		{
			"TMPDIR",
			"TMP",
			"TEMP",
			"TEMPDIR",

			NULL
		};

		for (const char** tmp = s_tmp; *tmp != NULL; ++tmp)
		{
			uint32_t len = *_inOutSize;
			*_out = '\0';
			bool ok = getEnv(*tmp, FileInfo::Directory, _out, &len);

			if (ok
			&&  len != 0
			&&  len < *_inOutSize)
			{
				*_inOutSize = len;
				return ok;
			}
		}

		FileInfo fi;
		if (stat("/tmp", fi)
		&&  FileInfo::Directory == fi.m_type)
		{
			strCopy(_out, *_inOutSize, "/tmp");
			*_inOutSize = 4;
			return true;
		}

		return false;
#endif // BX_PLATFORM_*
	}

	FilePath::FilePath()
	{
		set("");
	}

	FilePath::FilePath(Dir::Enum _dir)
	{
		set(_dir);
	}

	FilePath::FilePath(const char* _rhs)
	{
		set(_rhs);
	}

	FilePath::FilePath(const StringView& _filePath)
	{
		set(_filePath);
	}

	FilePath& FilePath::operator=(const StringView& _rhs)
	{
		set(_rhs);
		return *this;
	}

	void FilePath::set(Dir::Enum _dir)
	{
		char tmp[kMaxFilePath];
		uint32_t len = BX_COUNTOF(tmp);

		switch (_dir)
		{
		case Dir::Temp:
			getTempPath(tmp, &len);
			break;

		case Dir::Home:
			getHomePath(tmp, &len);
bx::debugPrintf("%s", tmp);
			break;

		default:
			len = 0;
			break;
		}

		set(StringView(tmp, len) );
	}

	void FilePath::set(const StringView& _filePath)
	{
		normalizeFilePath(
			  m_filePath
			, BX_COUNTOF(m_filePath)
			, _filePath.getPtr()
			, _filePath.getLength()
			);
	}

	void FilePath::join(const StringView& _str)
	{
		char tmp[kMaxFilePath];
		strCopy(tmp, BX_COUNTOF(tmp), m_filePath);
		strCat(tmp, BX_COUNTOF(tmp), "/");
		strCat(tmp, BX_COUNTOF(tmp), _str);
		set(tmp);
	}

	const char* FilePath::get() const
	{
		return m_filePath;
	}

	const StringView FilePath::getPath() const
	{
		const char* end = strRFind(m_filePath, '/');
		if (NULL != end)
		{
			return StringView(m_filePath, end+1);
		}

		return StringView();
	}

	const StringView FilePath::getFileName() const
	{
		const char* fileName = strRFind(m_filePath, '/');
		if (NULL != fileName)
		{
			return StringView(fileName+1);
		}

		return get();
	}

	const StringView FilePath::getBaseName() const
	{
		const StringView fileName = getFileName();
		if (!fileName.isEmpty() )
		{
			const char* ext = strFind(fileName, '.');
			if (ext != NULL)
			{
				return StringView(fileName.getPtr(), ext);
			}
		}

		return StringView();
	}

	const StringView FilePath::getExt() const
	{
		const StringView fileName = getFileName();
		if (!fileName.isEmpty() )
		{
			const char* ext = strFind(fileName, '.');
			return StringView(ext);
		}

		return StringView();
	}

	bool FilePath::isAbsolute() const
	{
		return  '/' == m_filePath[0] // no drive letter
			|| (':' == m_filePath[1] && '/' == m_filePath[2]) // with drive letter
			;
	}

} // namespace bx
<commit_msg>Cleanup.<commit_after>/*
 * Copyright 2010-2017 Branimir Karadzic. All rights reserved.
 * License: https://github.com/bkaradzic/bx#license-bsd-2-clause
 */

#include "bx_p.h"
#include <bx/file.h>
#include <bx/os.h>
#include <bx/readerwriter.h>

#if BX_PLATFORM_WINDOWS
extern "C" __declspec(dllimport) unsigned long __stdcall GetTempPathA(unsigned long _max, char* _ptr);
#endif // BX_PLATFORM_WINDOWS

namespace bx
{
	static bool isPathSeparator(char _ch)
	{
		return false
			|| '/'  == _ch
			|| '\\' == _ch
			;
	}

	static int32_t normalizeFilePath(char* _dst, int32_t _dstSize, const char* _src, int32_t _num)
	{
		// Reference: Lexical File Names in Plan 9 or Getting Dot-Dot Right
		// https://9p.io/sys/doc/lexnames.html

		const int32_t num = strLen(_src, _num);

		if (0 == num)
		{
			return strCopy(_dst, _dstSize, ".");
		}

		int32_t size = 0;

		StaticMemoryBlockWriter writer(_dst, _dstSize);
		Error err;

		int32_t idx      = 0;
		int32_t dotdot   = 0;

		if (2 <= num
		&&  ':' == _src[1])
		{
			size += write(&writer, toUpper(_src[idx]), &err);
			size += write(&writer, ':', &err);
			idx  += 2;
			dotdot = size;
		}

		const int32_t slashIdx = idx;

		bool rooted = isPathSeparator(_src[idx]);
		if (rooted)
		{
			size += write(&writer, '/', &err);
			++idx;
			dotdot = size;
		}

		while (idx < num && err.isOk() )
		{
			switch (_src[idx])
			{
			case '/':
			case '\\':
				++idx;
				break;

			case '.':
				if (idx+1 == num
				||  isPathSeparator(_src[idx+1]) )
				{
					++idx;
					break;
				}

				if ('.' == _src[idx+1]
				&& (idx+2 == num || isPathSeparator(_src[idx+2]) ) )
				{
					idx += 2;

					if (dotdot < size)
					{
						for (--size
							; dotdot < size && !isPathSeparator(_dst[size])
							; --size)
						{
						}
						seek(&writer, size, Whence::Begin);
					}
					else if (!rooted)
					{
						if (0 < size)
						{
							size += write(&writer, '/', &err);
						}

						size += write(&writer, "..", &err);
						dotdot = size;
					}

					break;
				}

				BX_FALLTHROUGH;

			default:
				if ( ( rooted && slashIdx+1 != size)
				||   (!rooted &&          0 != size) )
				{
					size += write(&writer, '/', &err);
				}

				for (; idx < num && !isPathSeparator(_src[idx]); ++idx)
				{
					size += write(&writer, _src[idx], &err);
				}

				break;
			}
		}

		if (0 == size)
		{
			size += write(&writer, '.', &err);
		}

		write(&writer, '\0', &err);

		return size;
	}

	static bool getEnv(const char* _name, FileInfo::Enum _type, char* _out, uint32_t* _inOutSize)
	{
		uint32_t len = *_inOutSize;
		*_out = '\0';

		if (getenv(_name, _out, &len) )
		{
			FileInfo fi;
			if (stat(_out, fi)
			&&  _type == fi.m_type)
			{
				*_inOutSize = len;
				return true;
			}
		}

		return false;
	}

	static bool getHomePath(char* _out, uint32_t* _inOutSize)
	{
		return false
#if BX_PLATFORM_WINDOWS
			|| getEnv("USERPROFILE", FileInfo::Directory, _out, _inOutSize)
#endif // BX_PLATFORM_WINDOWS
			|| getEnv("HOME", FileInfo::Directory, _out, _inOutSize)
			;
	}

	static bool getTempPath(char* _out, uint32_t* _inOutSize)
	{
#if BX_PLATFORM_WINDOWS
		uint32_t len = ::GetTempPathA(*_inOutSize, _out);
		bool result = len != 0 && len < *_inOutSize;
		*_inOutSize = len;
		return result;
#else
		static const char* s_tmp[] =
		{
			"TMPDIR",
			"TMP",
			"TEMP",
			"TEMPDIR",

			NULL
		};

		for (const char** tmp = s_tmp; *tmp != NULL; ++tmp)
		{
			uint32_t len = *_inOutSize;
			*_out = '\0';
			bool ok = getEnv(*tmp, FileInfo::Directory, _out, &len);

			if (ok
			&&  len != 0
			&&  len < *_inOutSize)
			{
				*_inOutSize = len;
				return ok;
			}
		}

		FileInfo fi;
		if (stat("/tmp", fi)
		&&  FileInfo::Directory == fi.m_type)
		{
			strCopy(_out, *_inOutSize, "/tmp");
			*_inOutSize = 4;
			return true;
		}

		return false;
#endif // BX_PLATFORM_*
	}

	FilePath::FilePath()
	{
		set("");
	}

	FilePath::FilePath(Dir::Enum _dir)
	{
		set(_dir);
	}

	FilePath::FilePath(const char* _rhs)
	{
		set(_rhs);
	}

	FilePath::FilePath(const StringView& _filePath)
	{
		set(_filePath);
	}

	FilePath& FilePath::operator=(const StringView& _rhs)
	{
		set(_rhs);
		return *this;
	}

	void FilePath::set(Dir::Enum _dir)
	{
		char tmp[kMaxFilePath];
		uint32_t len = BX_COUNTOF(tmp);

		switch (_dir)
		{
		case Dir::Temp:
			getTempPath(tmp, &len);
			break;

		case Dir::Home:
			getHomePath(tmp, &len);
			break;

		default:
			len = 0;
			break;
		}

		set(StringView(tmp, len) );
	}

	void FilePath::set(const StringView& _filePath)
	{
		normalizeFilePath(
			  m_filePath
			, BX_COUNTOF(m_filePath)
			, _filePath.getPtr()
			, _filePath.getLength()
			);
	}

	void FilePath::join(const StringView& _str)
	{
		char tmp[kMaxFilePath];
		strCopy(tmp, BX_COUNTOF(tmp), m_filePath);
		strCat(tmp, BX_COUNTOF(tmp), "/");
		strCat(tmp, BX_COUNTOF(tmp), _str);
		set(tmp);
	}

	const char* FilePath::get() const
	{
		return m_filePath;
	}

	const StringView FilePath::getPath() const
	{
		const char* end = strRFind(m_filePath, '/');
		if (NULL != end)
		{
			return StringView(m_filePath, end+1);
		}

		return StringView();
	}

	const StringView FilePath::getFileName() const
	{
		const char* fileName = strRFind(m_filePath, '/');
		if (NULL != fileName)
		{
			return StringView(fileName+1);
		}

		return get();
	}

	const StringView FilePath::getBaseName() const
	{
		const StringView fileName = getFileName();
		if (!fileName.isEmpty() )
		{
			const char* ext = strFind(fileName, '.');
			if (ext != NULL)
			{
				return StringView(fileName.getPtr(), ext);
			}
		}

		return StringView();
	}

	const StringView FilePath::getExt() const
	{
		const StringView fileName = getFileName();
		if (!fileName.isEmpty() )
		{
			const char* ext = strFind(fileName, '.');
			return StringView(ext);
		}

		return StringView();
	}

	bool FilePath::isAbsolute() const
	{
		return  '/' == m_filePath[0] // no drive letter
			|| (':' == m_filePath[1] && '/' == m_filePath[2]) // with drive letter
			;
	}

} // namespace bx
<|endoftext|>


<commit_before>// all needed include files
#include <OpenSG/OSGGLUT.h>
#include <OpenSG/OSGConfig.h>
#include <OpenSG/OSGSimpleGeometry.h>
#include <OpenSG/OSGGLUTWindow.h>
#include <OpenSG/OSGSimpleSceneManager.h>

#include <OpenSG/OSGThreadManager.h>

OSG_USING_NAMESPACE

SimpleSceneManager *mgr;
NodeRecPtr          scene;

//we will store the transformation globally - this
//is not necessary, but comfortable
TransformRecPtr  trans;
Thread          *animationThread;
Thread          *applicationThread;
Barrier         *syncBarrier;

int setupGLUT(int *argc, char *argv[]);

NodeTransitPtr createScenegraph(void)
{
    // the scene must be created here
    NodeRecPtr n = makeTorus(.5,2,16,16);

    //add a simple Transformation
    trans = Transform::create();
    Matrix m;
    m.setIdentity();
    trans->setMatrix(m);

    NodeRecPtr transNode = Node::create();
    transNode->setCore(trans);
    transNode->addChild(n);

    return NodeTransitPtr(transNode);
}

//this function will run in a thread and simply will
//rotate the cube by setting a new transformation matrix
void rotate(void *args)
{
    // sync this thread to the main thread, i.e. pull in all changes done
    // during scene construction
    syncBarrier->enter(2);
    applicationThread->getChangeList()->applyAndClear();
    syncBarrier->enter(2);

    // we won't stop calculating new matrices....
    while(true)
    {
        Real32 time = glutGet(GLUT_ELAPSED_TIME);
        Matrix m;
        m.setIdentity();
        m.setRotate(Quaternion(Vec3f(0,1,0), time/1000));

        trans->setMatrix(m);
        // nothing unusual until here

        //well that's new...

        //wait until two threads are cought in the
        //same barrier
        syncBarrier->enter(2);    // barrier (1)

        //just the same again
        syncBarrier->enter(2);    // barrier (2)
    }
}

int main(int argc, char **argv)
{
    osgInit(argc,argv);

    {
        int winid = setupGLUT(&argc, argv);
        GLUTWindowRecPtr gwin = GLUTWindow::create();
        gwin->setGlutId(winid);
        gwin->init();

        scene = createScenegraph();

        //create the barrier, that will be used to
        //synchronize threads

        //instead of NULL you could provide a name
        syncBarrier = Barrier::get(NULL);

        mgr = new SimpleSceneManager;
        mgr->setWindow(gwin );
        mgr->setRoot  (scene);
        mgr->showAll();

        // store a pointer to the application thread
        applicationThread = dynamic_cast<Thread *>(ThreadManager::getAppThread());

        //create the thread that will run generation of new matrices
        animationThread = dynamic_cast<Thread *>(ThreadManager::the()->getThread("anim"));

        //do it...
        animationThread->runFunction(rotate, 1, NULL);

        // wait for animationThread to complete its sync
        syncBarrier->enter(2);
        syncBarrier->enter(2);

        commitChanges();
    }

    glutMainLoop();

    return 0;
}

void reshape(int w, int h)
{
    mgr->resize(w, h);
    glutPostRedisplay();
}

void display(void)
{
    // we wait here until the animation thread enters
    // barrier (1)
    syncBarrier->enter(2);

    //now we sync data
    animationThread->getChangeList()->applyAndClear();

    // now wait for animation thread to enter barrier (2)
    syncBarrier->enter(2);

    // !!!! Attention
    // you will find a more detailed description
    // of what's going on here in the documentation
    // itself!

    // now render...
    mgr->redraw();
}

void mouse(int button, int state, int x, int y)
{
    if (state)
        mgr->mouseButtonRelease(button, x, y);
    else
        mgr->mouseButtonPress(button, x, y);

    glutPostRedisplay();
}

void motion(int x, int y)
{
    mgr->mouseMove(x, y);
    glutPostRedisplay();
}

int setupGLUT(int *argc, char *argv[])
{
    glutInit(argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);

    int winid = glutCreateWindow("OpenSG First Application");

    glutDisplayFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutReshapeFunc(reshape);
    glutIdleFunc(display);

    return winid;
}
<commit_msg>fixed: modify aspect 1 in animationThread; use MTRecPtr and commitChanges        each iteration.<commit_after>// all needed include files
#include <OpenSG/OSGGLUT.h>
#include <OpenSG/OSGConfig.h>
#include <OpenSG/OSGSimpleGeometry.h>
#include <OpenSG/OSGGLUTWindow.h>
#include <OpenSG/OSGSimpleSceneManager.h>

#include <OpenSG/OSGThreadManager.h>

OSG_USING_NAMESPACE

SimpleSceneManager *mgr;

// we will store the transformation globally - this
// is not necessary, but comfortable
// Note that these global objects are accessed from different aspects,
// therefore you need to use MTRecPtr here, so that you get a pointer to the
// correct aspect copy of the object.

TransformMTRecPtr  trans;
NodeMTRecPtr       scene;
Thread            *animationThread;
Thread            *applicationThread;
Barrier           *syncBarrier;

int setupGLUT(int *argc, char *argv[]);

NodeTransitPtr createScenegraph(void)
{
    // the scene must be created here
    NodeRecPtr n = makeTorus(.5,2,16,16);

    //add a simple Transformation
    trans = Transform::create();
    Matrix m;
    m.setIdentity();
    trans->setMatrix(m);

    NodeRecPtr transNode = Node::create();
    transNode->setCore(trans);
    transNode->addChild(n);

    return NodeTransitPtr(transNode);
}

//this function will run in a thread and simply will
//rotate the cube by setting a new transformation matrix
void rotate(void *args)
{
    // sync this thread to the main thread, i.e. pull in all changes done
    // during scene construction
    syncBarrier->enter(2);
    applicationThread->getChangeList()->applyAndClear();
    syncBarrier->enter(2);

    // we won't stop calculating new matrices....
    while(true)
    {
        Real32 time = glutGet(GLUT_ELAPSED_TIME);
        Matrix m;
        m.setIdentity();
        m.setRotate(Quaternion(Vec3f(0,1,0), time/1000));

        trans->setMatrix(m);
        // nothing unusual until here

        // we are done with changing this aspect copy (for this iteration),
        // committing the changes makes sure they are being picked up when
        // the render thread syncronizes the next time.
        commitChanges();

        //well that's new...

        //wait until two threads are cought in the
        //same barrier
        syncBarrier->enter(2);    // barrier (1)

        //just the same again
        syncBarrier->enter(2);    // barrier (2)
    }
}

int main(int argc, char **argv)
{
    osgInit(argc,argv);

    {
        int winid = setupGLUT(&argc, argv);
        GLUTWindowRecPtr gwin = GLUTWindow::create();
        gwin->setGlutId(winid);
        gwin->init();

        scene = createScenegraph();

        //create the barrier, that will be used to
        //synchronize threads

        //instead of NULL you could provide a name
        syncBarrier = Barrier::get(NULL);

        mgr = new SimpleSceneManager;
        mgr->setWindow(gwin );
        mgr->setRoot  (scene);
        mgr->showAll();

        // store a pointer to the application thread
        applicationThread = dynamic_cast<Thread *>(ThreadManager::getAppThread());

        //create the thread that will run generation of new matrices
        animationThread = dynamic_cast<Thread *>(ThreadManager::the()->getThread("anim"));

        //do it...
        animationThread->runFunction(rotate, 1, NULL);

        // wait for animationThread to complete its sync
        syncBarrier->enter(2);
        syncBarrier->enter(2);

        commitChanges();
    }

    glutMainLoop();

    return 0;
}

void reshape(int w, int h)
{
    mgr->resize(w, h);
    glutPostRedisplay();
}

void display(void)
{
    // we wait here until the animation thread enters
    // barrier (1)
    syncBarrier->enter(2);

    //now we sync data
    animationThread->getChangeList()->applyAndClear();

    // now wait for animation thread to enter barrier (2)
    syncBarrier->enter(2);

    // !!!! Attention
    // you will find a more detailed description
    // of what's going on here in the documentation
    // itself!

    // now render...
    mgr->redraw();
}

void mouse(int button, int state, int x, int y)
{
    if (state)
        mgr->mouseButtonRelease(button, x, y);
    else
        mgr->mouseButtonPress(button, x, y);

    glutPostRedisplay();
}

void motion(int x, int y)
{
    mgr->mouseMove(x, y);
    glutPostRedisplay();
}

int setupGLUT(int *argc, char *argv[])
{
    glutInit(argc, argv);
    glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);

    int winid = glutCreateWindow("OpenSG First Application");

    glutDisplayFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(motion);
    glutReshapeFunc(reshape);
    glutIdleFunc(display);

    return winid;
}
<|endoftext|>


<commit_before>/*
 * File:   main.cpp
 * Author: moonlight83340
 *
 * Created on 11 septembre 2015, 21:11
 */

#include <iostream>
#include <fstream>

using namespace std;

namespace{
    void Binfile(){

        ifstream is;
        for(;;){
            string FileName;
            cout << "rentrer le nom du fichier à copier : ";
            cin >> FileName;
            cout << endl;
            is.open(FileName.c_str(), std::ios::in | std::ios::binary);
            if(is.good())break;
            cout << "nom de fichier incorrect" << endl;
        }

        ofstream of;
        for(;;){
            string FileNameDest;
            cout << "rentrer le nom du fichier destination : ";
            cin >> FileNameDest;
            cout << endl;
            of.open(FileNameDest.c_str(), std::ios::out | std::ios::binary);
            if(of.good())break;
            cout << "nom de fichier incorrect" << endl;
        }

        cout << "rentrer le nombre d'octet du fichier : " << endl;
        unsigned BlocSize;
        cin >> BlocSize;
        cout << endl;
        if(0 == BlocSize){
            is.seekg(0,is.end);
            BlocSize = is.tellg();
            cout << "taille : " << BlocSize << endl;
            is.seekg(0,is.beg);
        }
        char * Buffer = new char[BlocSize];
        for(streamsize Nb;Nb = (is.readsome(Buffer,BlocSize) ) > 0;)of.write(Buffer,BlocSize);
        delete [] Buffer;
        Buffer = 0;

    }

}

int main(int argc, char** argv) {

    return 0;
}

<commit_msg>ADD BinFile.cpp (exo bonus)<commit_after>/*
 * File:   main.cpp
 * Author: moonlight83340
 *
 * Created on 11 septembre 2015, 21:11
 */

#include <iostream>
#include <fstream>

using namespace std;

namespace{
    void Binfile(){

        ifstream is;
        for(;;){
            string FileName;
            cout << "rentrer le nom du fichier à copier : ";
            cin >> FileName;
            cout << endl;
            is.open(FileName.c_str(), std::ios::in | std::ios::binary);
            if(is.good())break;
            cout << "nom de fichier incorrect" << endl;
        }

        ofstream of;
        for(;;){
            string FileNameDest;
            cout << "rentrer le nom du fichier destination : ";
            cin >> FileNameDest;
            cout << endl;
            of.open(FileNameDest.c_str(), std::ios::out | std::ios::binary);
            if(of.good())break;
            cout << "nom de fichier incorrect" << endl;
        }

        cout << "rentrer le nombre d'octet du fichier : " << endl;
        unsigned BlocSize;
        cin >> BlocSize;
        cout << endl;
        if(0 == BlocSize){
            is.seekg(0,is.end);
            BlocSize = is.tellg();
            cout << "taille : " << BlocSize << endl;
            is.seekg(0,is.beg);
        }
        char * Buffer = new char[BlocSize];
        for(streamsize Nb;Nb = (is.readsome(Buffer,BlocSize) ) > 0;)of.write(Buffer,BlocSize);
        delete [] Buffer;
        Buffer = 0;

    }

}

int main(int argc, char** argv) {
    Binfile();
    return 0;
}

<|endoftext|>


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

#ifndef _XMLOFF_METAEXPORTCOMPONENT_HXX
#define _XMLOFF_METAEXPORTCOMPONENT_HXX

#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif

class XMLMetaExportComponent : public SvXMLExport
{
public:
    // #110680#
    // XMLMetaExportComponent();
    XMLMetaExportComponent(
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory
        );

    ~XMLMetaExportComponent();

protected:
    // export the events off all autotexts
    virtual sal_uInt32 exportDoc(
        enum ::xmloff::token::XMLTokenEnum eClass = xmloff::token::XML_TOKEN_INVALID );

    // methods without content:
    virtual void _ExportAutoStyles();
    virtual void _ExportMasterStyles();
    virtual void _ExportContent();
};

// global functions to support the component

::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
    XMLMetaExportComponent_getSupportedServiceNames()
    throw();

::rtl::OUString SAL_CALL XMLMetaExportComponent_getImplementationName()
    throw();

::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
    XMLMetaExportComponent_createInstance(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::lang::XMultiServiceFactory > & )
    throw( ::com::sun::star::uno::Exception );

#endif

<commit_msg>INTEGRATION: CWS oasis2 (1.4.64); FILE MERGED 2004/08/03 06:57:17 mib 1.4.64.1: #i32363#: StandoloneDocInfo is now recognizes OASIS file format<commit_after>/*************************************************************************
 *
 *  $RCSfile: MetaExportComponent.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2004-08-20 08:11:12 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLOFF_METAEXPORTCOMPONENT_HXX
#define _XMLOFF_METAEXPORTCOMPONENT_HXX

#ifndef _XMLOFF_XMLEXP_HXX
#include "xmlexp.hxx"
#endif

class XMLMetaExportComponent : public SvXMLExport
{
public:
    // #110680#
    // XMLMetaExportComponent();
    XMLMetaExportComponent(
        const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceFactory,
        sal_uInt16 nFlags
        );

    ~XMLMetaExportComponent();

protected:
    // export the events off all autotexts
    virtual sal_uInt32 exportDoc(
        enum ::xmloff::token::XMLTokenEnum eClass = xmloff::token::XML_TOKEN_INVALID );

    // methods without content:
    virtual void _ExportAutoStyles();
    virtual void _ExportMasterStyles();
    virtual void _ExportContent();
};

// global functions to support the component

::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL
    XMLMetaExportComponent_getSupportedServiceNames()
    throw();

::rtl::OUString SAL_CALL XMLMetaExportComponent_getImplementationName()
    throw();

::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
    XMLMetaExportComponent_createInstance(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::lang::XMultiServiceFactory > & )
    throw( ::com::sun::star::uno::Exception );

#endif

<|endoftext|>


<commit_before>/*
 * internal_rayshooter_multi.cpp
 *
 *  Created on: Jan 19, 2012
 *      Author: mpetkova, bmetcalf
 */

#include <slsimlib.h>

/** \ingroup DeflectionL2
 *
 * \brief This is the function that does the deflection calculation with multiple lens planes.
 *
 * The convergence, shear and rotation will be calculated if kappa_off == false
 *
 * Needs to be calculated before calling:
 *
 *
 * Dl[j = 0...Nplanes-1] - The angular size distance between the observer and the jth plane not counting the observer plane.
 * 	                    Dl[0] is the first plane with mass on it and Dl[Nplane-1] is the distance to the source plane.
 *
 * dDl[j = 0...Nplanes-1] - The angular size distance between the (j-1)th and jth planes counting the observer plane as j = -1.
 *                      dDl[0] = Dl[0], dDl[Nplane-1] is between the last plane with mass and the source plane.
 *
 * charge = 4*G*mass_scale/c^2 in units of Mpc
 *
 * i_points[].x[] is in angular units.
 *
 * Warning: Is not valid for a non-flat universe.
 */

void MultiLens::rayshooterInternal(unsigned long Npoints, Point *i_points, bool kappa_off){
	unsigned long i;
	int j;

	for(i = 0; i< Npoints; i++){

		double kappa,aa,bb,cc;
	    double alpha[2], gamma[2];
	    double xminus[2],xplus[2];
	    double kappa_minus,gamma_minus[3],kappa_plus,gamma_plus[3];

		// find position on first lens plane in physical units
		i_points[i].image->x[0] = i_points[i].x[0]*Dl[0];
       	i_points[i].image->x[1] = i_points[i].x[1]*Dl[0];

       	xminus[0] = 0;
		xminus[1] = 0;

		// Set magnification matrix on first plane.  Also the default if kappa_off == false
		kappa_minus = 0;
		gamma_minus[0] = 0;
		gamma_minus[1] = 0;
		gamma_minus[2] = 0;

		i_points[i].kappa = 1;  // This is actually 1-kappa until after the loop through the planes.
		i_points[i].gamma[0] = 0;
		i_points[i].gamma[1] = 0;
		i_points[i].gamma[2] = 0;

		for(j = 0; j < Nplanes-1 ; j++){  // each iteration leaves i_point[i].image on plane (j+1)

			if(flag_analens && j == flag_analens){
				analens->rayshooterInternal(i_points[i].image->x,&alpha[0],&gamma[0],&kappa,kappa_off);
				cc = dDl[j+1];
			}
			else{
				halo_tree[j]->force2D(i_points[i].image->x,&alpha[0],&kappa,&gamma[0],kappa_off);
				cc = charge*dDl[j+1];
			}

			aa = (dDl[j+1]+dDl[j])/dDl[j];
			bb = dDl[j+1]/dDl[j];

			xplus[0] = aa*i_points[i].image->x[0]
        				    - bb*xminus[0]
        		            - cc*alpha[0];
       		xplus[1] = aa*i_points[i].image->x[1]
        				    - bb*xminus[1]
        		            - cc*alpha[1];

			xminus[0] = i_points[i].image->x[0];
			xminus[1] = i_points[i].image->x[1];

			i_points[i].image->x[0] = xplus[0];
			i_points[i].image->x[1] = xplus[1];

			if(!kappa_off)
    		{

				aa = (dDl[j+1]+dDl[j])*Dl[j]/dDl[j]/Dl[j+1];

				bb = dDl[j+1]*Dl[ (j < 1) ? 0 : j-1]/dDl[j]/Dl[j+1];

				cc = charge*dDl[j+1]*Dl[j]/Dl[j+1];

				// still not positive about sign convention
				kappa_plus = aa*i_points[i].kappa - bb*kappa_minus
						- cc*(kappa*i_points[i].kappa - gamma[0]*i_points[i].gamma[0] - gamma[1]*i_points[i].gamma[1]);

				gamma_plus[0] = aa*i_points[i].gamma[0] - bb*gamma_minus[0]
						- cc*(kappa*i_points[i].gamma[0] - gamma[0]*i_points[i].kappa + gamma[1]*i_points[i].gamma[3]);

				gamma_plus[1] = aa*i_points[i].gamma[1] - bb*gamma_minus[1]
						- cc*(kappa*i_points[i].gamma[1] - gamma[1]*i_points[i].kappa - gamma[0]*i_points[i].gamma[3]);

				gamma_plus[2] = aa*i_points[i].gamma[2] - bb*gamma_minus[2]
						- cc*(kappa*i_points[i].gamma[2] - gamma[0]*i_points[i].gamma[1] + gamma[1]*i_points[i].gamma[0]);

				kappa_minus = i_points[i].kappa;
				gamma_minus[0] = i_points[i].gamma[0];
				gamma_minus[1] = i_points[i].gamma[1];
				gamma_minus[2] = i_points[i].gamma[2];

				i_points[i].kappa = kappa_plus;
				i_points[i].gamma[0] = gamma_plus[0];
				i_points[i].gamma[1] = gamma_plus[1];
				i_points[i].gamma[2] = gamma_plus[2];
    		}

		}
		// Convert units back to angles.

		i_points[i].image->x[0] /= Dl[Nplanes-1];
		i_points[i].image->x[1] /= Dl[Nplanes-1];

		i_points[i].kappa = 1 - i_points[i].kappa;
    }

    return;
}
<commit_msg>fixed some small things -- the cc for the magnification matrix does not contain charge -- the signs for samma_plus[2] were wrong -- added the calculation of the inverse magnification<commit_after>/*
 * internal_rayshooter_multi.cpp
 *
 *  Created on: Jan 19, 2012
 *      Author: mpetkova, bmetcalf
 */

#include <slsimlib.h>

/** \ingroup DeflectionL2
 *
 * \brief This is the function that does the deflection calculation with multiple lens planes.
 *
 * The convergence, shear and rotation will be calculated if kappa_off == false
 *
 * Needs to be calculated before calling:
 *
 *
 * Dl[j = 0...Nplanes-1] - The angular size distance between the observer and the jth plane not counting the observer plane.
 * 	                    Dl[0] is the first plane with mass on it and Dl[Nplane-1] is the distance to the source plane.
 *
 * dDl[j = 0...Nplanes-1] - The angular size distance between the (j-1)th and jth planes counting the observer plane as j = -1.
 *                      dDl[0] = Dl[0], dDl[Nplane-1] is between the last plane with mass and the source plane.
 *
 * charge = 4*G*mass_scale/c^2 in units of Mpc
 *
 * i_points[].x[] is in angular units.
 *
 * Warning: Is not valid for a non-flat universe.
 */

void MultiLens::rayshooterInternal(unsigned long Npoints, Point *i_points, bool kappa_off){
	unsigned long i;
	int j;

	for(i = 0; i< Npoints; i++){

		double kappa,aa,bb,cc;
	    double alpha[2], gamma[3];
	    double xminus[2],xplus[2];
	    double kappa_minus,gamma_minus[3],kappa_plus,gamma_plus[3];

		// find position on first lens plane in physical units
		i_points[i].image->x[0] = i_points[i].x[0]*Dl[0];
       	i_points[i].image->x[1] = i_points[i].x[1]*Dl[0];

       	xminus[0] = 0;
		xminus[1] = 0;

		// Set magnification matrix on first plane.  Also the default if kappa_off == false
		kappa_minus = 0;
		gamma_minus[0] = 0;
		gamma_minus[1] = 0;
		gamma_minus[2] = 0;

		i_points[i].kappa = 1;  // This is actually 1-kappa until after the loop through the planes.
		i_points[i].gamma[0] = 0;
		i_points[i].gamma[1] = 0;
		i_points[i].gamma[2] = 0;

		for(j = 0; j < Nplanes-1 ; j++){  // each iteration leaves i_point[i].image on plane (j+1)

			if(j == flag_analens && j > 0){
				analens->rayshooterInternal(i_points[i].image->x,&alpha[0],&gamma[0],&kappa,kappa_off);
				cc = dDl[j+1];
			}
			else{
				halo_tree[j]->force2D(i_points[i].image->x,&alpha[0],&kappa,&gamma[0],kappa_off);
				cc = charge*dDl[j+1];
			}

			aa = (dDl[j+1]+dDl[j])/dDl[j];
			bb = dDl[j+1]/dDl[j];

			xplus[0] = aa*i_points[i].image->x[0] - bb*xminus[0] + cc*alpha[0];
       		xplus[1] = aa*i_points[i].image->x[1] - bb*xminus[1] + cc*alpha[1];

			xminus[0] = i_points[i].image->x[0];
			xminus[1] = i_points[i].image->x[1];

			i_points[i].image->x[0] = xplus[0];
			i_points[i].image->x[1] = xplus[1];

			if(!kappa_off)
    		{

				aa = (dDl[j+1]+dDl[j])*Dl[j]/dDl[j]/Dl[j+1];

				bb = dDl[j+1]*Dl[ (j < 1) ? 0 : j-1]/dDl[j]/Dl[j+1];

				cc = - dDl[j+1]*Dl[j]/Dl[j+1];

				// still not positive about sign convention
				kappa_plus = aa*i_points[i].kappa - bb*kappa_minus
						- cc*(kappa*i_points[i].kappa - gamma[0]*i_points[i].gamma[0] - gamma[1]*i_points[i].gamma[1]);

				gamma_plus[0] = aa*i_points[i].gamma[0] - bb*gamma_minus[0]
						- cc*(kappa*i_points[i].gamma[0] - gamma[0]*i_points[i].kappa + gamma[1]*i_points[i].gamma[2]);

				gamma_plus[1] = aa*i_points[i].gamma[1] - bb*gamma_minus[1]
						- cc*(kappa*i_points[i].gamma[1] - gamma[1]*i_points[i].kappa - gamma[0]*i_points[i].gamma[2]);

				gamma_plus[2] = aa*i_points[i].gamma[2] - bb*gamma_minus[2]
						- cc*(gamma[1]*i_points[i].gamma[0] - kappa*i_points[i].gamma[2] - gamma[0]*i_points[i].gamma[1]);

				kappa_minus = i_points[i].kappa;
				gamma_minus[0] = i_points[i].gamma[0];
				gamma_minus[1] = i_points[i].gamma[1];
				gamma_minus[2] = i_points[i].gamma[2];

				i_points[i].kappa = kappa_plus;
				i_points[i].gamma[0] = gamma_plus[0];
				i_points[i].gamma[1] = gamma_plus[1];
				i_points[i].gamma[2] = gamma_plus[2];
    		}

		}
		// Convert units back to angles.

		i_points[i].image->x[0] /= Dl[Nplanes-1];
		i_points[i].image->x[1] /= Dl[Nplanes-1];

		i_points[i].kappa = 1 - i_points[i].kappa;

		i_points[i].invmag = (1-i_points[i].kappa)*(1-i_points[i].kappa)
		  	    - i_points[i].gamma[0]*i_points[i].gamma[0] - i_points[i].gamma[1]*i_points[i].gamma[1];

		if(i<10){
			cout << i_points[i].x[0] << " " << i_points[i].x[1] << " " << i_points[i].image->x[0] << " " << i_points[i].image->x[1] << " ";
			cout << i_points[i].invmag << " " << i_points[i].kappa << " " << i_points[i].gamma[0] << " " << i_points[i].gamma[1] << " " << i_points[i].gamma[2] << endl;
			}
    }

    return;
}
<|endoftext|>


<commit_before>#include <nan.h>
#include <iostream>
#include <sys/msg.h>

using v8::Function;
using v8::Local;
using v8::Number;
using v8::Value;
using Nan::AsyncQueueWorker;
using Nan::AsyncWorker;
using Nan::Callback;
using Nan::New;
using Nan::Null;

#ifndef MSGMAX
#define MSGMAX 4056
#endif

#ifndef linux
struct msgbuf {
  long mtype;
  char mtext[1];
};
#endif

const size_t bsize = sizeof(struct msgbuf);

const char *ConcatString(std::string one, const char *two) {
  return one.append(two).c_str();
}

Local<Value> CreateError(std::string message, int errcode) {
  message.append(": ");

  Nan::MaybeLocal<Value> val = Nan::Error(ConcatString(message, strerror(errcode)));

  return val.ToLocalChecked();
}

class SendMessageWorker : public AsyncWorker {

  public:
    SendMessageWorker(Callback *callback, int id, char *data, size_t dataLength, long type, int flags)
      : AsyncWorker(callback), id(id), data(data), dataLength(dataLength), type(type), flags(flags) { }
    ~SendMessageWorker() { }

    void Execute() {
      struct msgbuf* message =
        (struct msgbuf*)malloc(bsize + dataLength);

      message->mtype = type;
      memcpy(message->mtext, data, dataLength);

      ret = msgsnd(id, message, dataLength, flags);
      error = errno;

      free(message);
    }

    void HandleOKCallback () {
      Local<Value> argv[] = { Null() };

      if (ret == -1) {
        argv[0] = CreateError("Failed to send message", error);
      }

      callback->Call(1, argv);
    }

  private:
    int id;
    char *data;
    size_t dataLength;
    long type;
    int flags;
    int ret;
    int error;

};

class ReceiveMessageWorker : public AsyncWorker {

  public:
    ReceiveMessageWorker(Callback *callback, int id, size_t bufferLength, long type, int flags)
      : AsyncWorker(callback), id(id), bufferLength(bufferLength), type(type), flags(flags) { }
    ~ReceiveMessageWorker() { }

    void Execute() {
      message =
        (struct msgbuf*) malloc(bsize + bufferLength);

      bufferLength = msgrcv(id, message, bufferLength, type, flags);
      error = errno;
    }

    void HandleOKCallback () {
      Local<Value> argv[] = {
        Null(),
        Null()
      };

      if (bufferLength == (size_t) -1) {
        argv[0] = CreateError("Failed to receive message", error);
      } else {
        argv[1] = Nan::CopyBuffer(message->mtext, bufferLength).ToLocalChecked();
      }

      free(message);

      callback->Call(2, argv);
    }

  private:
    int id;
    struct msgbuf* message;
    size_t bufferLength;
    long type;
    int flags;
    int error;
};

NAN_METHOD(GetMessageQueue) {
  key_t key = (key_t) info[0]->Int32Value();
  int flags = info[1]->Int32Value();

  int queue = msgget(key, flags);

  if (queue == -1) {
    Nan::ThrowError(CreateError("Failed to get queue", errno));
  }

  info.GetReturnValue().Set(New(queue));
}

NAN_METHOD(ControlMessageQueue) {
  int id = info[0]->Int32Value();
  int cmd = info[1]->Int32Value();

  msqid_ds *buf;

  if (cmd != IPC_STAT && cmd != IPC_SET) {
    buf = nullptr;
  }
#ifdef linux
  else if (cmd != MSG_STAT) {
    buf = nullptr;
  }
#endif
  else {
    buf = new msqid_ds;
  }

  int ret = msgctl(id, cmd, buf);

  size_t bufSize = sizeof(msqid_ds);
  char rawBuf[bufSize];
  memcpy(rawBuf, buf, bufSize);

  if (ret == 0) {
    info.GetReturnValue().Set(Nan::NewBuffer(rawBuf, bufSize).ToLocalChecked());
  } else {
    info.GetReturnValue().Set(New(ret));
  }
}

NAN_METHOD(CloseMessageQueue) {
  int id = info[0]->Int32Value();

  int ret = msgctl(id, IPC_RMID, nullptr);

  if (ret != 0) {
    Nan::ThrowError(CreateError("Failed to close queue", errno));
  }

  info.GetReturnValue().Set(Nan::True());
}

NAN_METHOD(SendMessage) {
  int id = info[0]->Int32Value();
  char* bufferData = node::Buffer::Data(info[1]);
  size_t bufferLength = (size_t)  node::Buffer::Length(info[1]);
  long type = (long) info[2]->Int32Value();
  int flags = info[3]->Int32Value();
  Callback *callback = new Callback(info[4].As<Function>());

  AsyncQueueWorker(new SendMessageWorker(callback, id, bufferData, bufferLength, type, flags));
}

NAN_METHOD(ReceiveMessage) {
  int id = info[0]->Int32Value();
  size_t bufferLength = (size_t) info[1]->Int32Value();
  long type = (long) info[2]->Int32Value();
  int flags = info[3]->Int32Value();
  Callback *callback = new Callback(info[4].As<Function>());

  AsyncQueueWorker(new ReceiveMessageWorker(callback, id, bufferLength, type, flags));
}
<commit_msg>Fix deprecated Int32Value for node12<commit_after>#include <nan.h>
#include <iostream>
#include <sys/msg.h>

using v8::Function;
using v8::Local;
using v8::Number;
using v8::Value;
using Nan::AsyncQueueWorker;
using Nan::AsyncWorker;
using Nan::Callback;
using Nan::New;
using Nan::Null;

#ifndef MSGMAX
#define MSGMAX 4056
#endif

#ifndef linux
struct msgbuf {
  long mtype;
  char mtext[1];
};
#endif

const size_t bsize = sizeof(struct msgbuf);

const char *ConcatString(std::string one, const char *two) {
  return one.append(two).c_str();
}

Local<Value> CreateError(std::string message, int errcode) {
  message.append(": ");

  Nan::MaybeLocal<Value> val = Nan::Error(ConcatString(message, strerror(errcode)));

  return val.ToLocalChecked();
}

class SendMessageWorker : public AsyncWorker {

  public:
    SendMessageWorker(Callback *callback, int id, char *data, size_t dataLength, long type, int flags)
      : AsyncWorker(callback), id(id), data(data), dataLength(dataLength), type(type), flags(flags) { }
    ~SendMessageWorker() { }

    void Execute() {
      struct msgbuf* message =
        (struct msgbuf*)malloc(bsize + dataLength);

      message->mtype = type;
      memcpy(message->mtext, data, dataLength);

      ret = msgsnd(id, message, dataLength, flags);
      error = errno;

      free(message);
    }

    void HandleOKCallback () {
      Local<Value> argv[] = { Null() };

      if (ret == -1) {
        argv[0] = CreateError("Failed to send message", error);
      }

      callback->Call(1, argv);
    }

  private:
    int id;
    char *data;
    size_t dataLength;
    long type;
    int flags;
    int ret;
    int error;

};

class ReceiveMessageWorker : public AsyncWorker {

  public:
    ReceiveMessageWorker(Callback *callback, int id, size_t bufferLength, long type, int flags)
      : AsyncWorker(callback), id(id), bufferLength(bufferLength), type(type), flags(flags) { }
    ~ReceiveMessageWorker() { }

    void Execute() {
      message =
        (struct msgbuf*) malloc(bsize + bufferLength);

      bufferLength = msgrcv(id, message, bufferLength, type, flags);
      error = errno;
    }

    void HandleOKCallback () {
      Local<Value> argv[] = {
        Null(),
        Null()
      };

      if (bufferLength == (size_t) -1) {
        argv[0] = CreateError("Failed to receive message", error);
      } else {
        argv[1] = Nan::CopyBuffer(message->mtext, bufferLength).ToLocalChecked();
      }

      free(message);

      callback->Call(2, argv);
    }

  private:
    int id;
    struct msgbuf* message;
    size_t bufferLength;
    long type;
    int flags;
    int error;
};

NAN_METHOD(GetMessageQueue) {
  key_t key = (key_t) info[0]->Int32Value(Nan::GetCurrentContext()).FromJust();
  int flags = info[1]->Int32Value(Nan::GetCurrentContext()).FromJust();

  int queue = msgget(key, flags);

  if (queue == -1) {
    Nan::ThrowError(CreateError("Failed to get queue", errno));
  }

  info.GetReturnValue().Set(New(queue));
}

NAN_METHOD(ControlMessageQueue) {
  int id = info[0]->Int32Value(Nan::GetCurrentContext()).FromJust();
  int cmd = info[1]->Int32Value(Nan::GetCurrentContext()).FromJust();

  msqid_ds *buf;

  if (cmd != IPC_STAT && cmd != IPC_SET) {
    buf = nullptr;
  }
#ifdef linux
  else if (cmd != MSG_STAT) {
    buf = nullptr;
  }
#endif
  else {
    buf = new msqid_ds;
  }

  int ret = msgctl(id, cmd, buf);

  size_t bufSize = sizeof(msqid_ds);
  char rawBuf[bufSize];
  memcpy(rawBuf, buf, bufSize);

  if (ret == 0) {
    info.GetReturnValue().Set(Nan::NewBuffer(rawBuf, bufSize).ToLocalChecked());
  } else {
    info.GetReturnValue().Set(New(ret));
  }
}

NAN_METHOD(CloseMessageQueue) {
  int id = info[0]->Int32Value(Nan::GetCurrentContext()).FromJust();

  int ret = msgctl(id, IPC_RMID, nullptr);

  if (ret != 0) {
    Nan::ThrowError(CreateError("Failed to close queue", errno));
  }

  info.GetReturnValue().Set(Nan::True());
}

NAN_METHOD(SendMessage) {
  int id = info[0]->Int32Value(Nan::GetCurrentContext()).FromJust();
  char* bufferData = node::Buffer::Data(info[1]);
  size_t bufferLength = (size_t)  node::Buffer::Length(info[1]);
  long type = (long) info[2]->Int32Value(Nan::GetCurrentContext()).FromJust();
  int flags = info[3]->Int32Value(Nan::GetCurrentContext()).FromJust();
  Callback *callback = new Callback(info[4].As<Function>());

  AsyncQueueWorker(new SendMessageWorker(callback, id, bufferData, bufferLength, type, flags));
}

NAN_METHOD(ReceiveMessage) {
  int id = info[0]->Int32Value(Nan::GetCurrentContext()).FromJust();
  size_t bufferLength = (size_t) info[1]->Int32Value(Nan::GetCurrentContext()).FromJust();
  long type = (long) info[2]->Int32Value(Nan::GetCurrentContext()).FromJust();
  int flags = info[3]->Int32Value(Nan::GetCurrentContext()).FromJust();
  Callback *callback = new Callback(info[4].As<Function>());

  AsyncQueueWorker(new ReceiveMessageWorker(callback, id, bufferLength, type, flags));
}
<|endoftext|>


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

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

#ifndef _SD_XMLVIEWSETTINGSCONTEXT_HXX
#include "viewcontext.hxx"
#endif
#ifndef _SDXMLIMP_IMPL_HXX
#include "sdxmlimp_impl.hxx"
#endif

#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
#ifndef _XMLOFF_XMLNMSPE_HXX
#include "xmlnmspe.hxx"
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif
#ifndef _XMLOFF_VISAREACONTEXT_HXX
#include "VisAreaContext.hxx"
#endif

using namespace com::sun::star;
using namespace rtl;
using ::xmloff::token::IsXMLToken;

using ::xmloff::token::XML_EMBEDDED_VISIBLE_AREA;

//------------------------------------------------------------------

SdXMLViewSettingsContext::SdXMLViewSettingsContext( SdXMLImport& rImport, USHORT nPrfx, const OUString& rLName, const uno::Reference<xml::sax::XAttributeList>& ) :
    SvXMLImportContext( rImport, nPrfx, rLName )
{
}

SdXMLViewSettingsContext::~SdXMLViewSettingsContext()
{
}

SvXMLImportContext *SdXMLViewSettingsContext::CreateChildContext( USHORT nPrefix,
                                     const OUString& rLocalName,
                                     const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
    SvXMLImportContext *pContext = 0;

    if (nPrefix == XML_NAMESPACE_OFFICE)
    {
        if ( IsXMLToken( rLocalName, XML_EMBEDDED_VISIBLE_AREA ) )
        {
            sal_Int16 nMeasureUnit = 0;

            uno::Reference< beans::XPropertySet > xProps( GetImport().GetModel(), uno::UNO_QUERY );
            if( xProps.is() )
                xProps->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "MapUnit" ) ) ) >>= nMeasureUnit;

            pContext = new XMLVisAreaContext(GetImport(), nPrefix, rLocalName, xAttrList, maVisArea, nMeasureUnit);
        }
    }

    if( !pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );

    return pContext;
}

void SdXMLViewSettingsContext::EndElement()
{
    uno::Reference< beans::XPropertySet > xProps( GetImport().GetModel(), uno::UNO_QUERY );
    if( xProps.is() )
    {
        uno::Any aAny;
        aAny <<= maVisArea;

        xProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "VisibleArea" ) ), aAny );
    }
}
<commit_msg>INTEGRATION: CWS changefileheader (1.6.162); FILE MERGED 2008/04/01 13:04:45 thb 1.6.162.2: #i85898# Stripping all external header guards 2008/03/31 16:28:08 rt 1.6.162.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: viewcontext.cxx,v $
 * $Revision: 1.7 $
 *
 * 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_xmloff.hxx"
#include "viewcontext.hxx"
#include "sdxmlimp_impl.hxx"
#include <xmloff/xmltoken.hxx>
#include "xmlnmspe.hxx"
#include <xmloff/nmspmap.hxx>
#include "VisAreaContext.hxx"

using namespace com::sun::star;
using namespace rtl;
using ::xmloff::token::IsXMLToken;

using ::xmloff::token::XML_EMBEDDED_VISIBLE_AREA;

//------------------------------------------------------------------

SdXMLViewSettingsContext::SdXMLViewSettingsContext( SdXMLImport& rImport, USHORT nPrfx, const OUString& rLName, const uno::Reference<xml::sax::XAttributeList>& ) :
    SvXMLImportContext( rImport, nPrfx, rLName )
{
}

SdXMLViewSettingsContext::~SdXMLViewSettingsContext()
{
}

SvXMLImportContext *SdXMLViewSettingsContext::CreateChildContext( USHORT nPrefix,
                                     const OUString& rLocalName,
                                     const ::com::sun::star::uno::Reference<
                                          ::com::sun::star::xml::sax::XAttributeList>& xAttrList )
{
    SvXMLImportContext *pContext = 0;

    if (nPrefix == XML_NAMESPACE_OFFICE)
    {
        if ( IsXMLToken( rLocalName, XML_EMBEDDED_VISIBLE_AREA ) )
        {
            sal_Int16 nMeasureUnit = 0;

            uno::Reference< beans::XPropertySet > xProps( GetImport().GetModel(), uno::UNO_QUERY );
            if( xProps.is() )
                xProps->getPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "MapUnit" ) ) ) >>= nMeasureUnit;

            pContext = new XMLVisAreaContext(GetImport(), nPrefix, rLocalName, xAttrList, maVisArea, nMeasureUnit);
        }
    }

    if( !pContext )
        pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );

    return pContext;
}

void SdXMLViewSettingsContext::EndElement()
{
    uno::Reference< beans::XPropertySet > xProps( GetImport().GetModel(), uno::UNO_QUERY );
    if( xProps.is() )
    {
        uno::Any aAny;
        aAny <<= maVisArea;

        xProps->setPropertyValue( OUString( RTL_CONSTASCII_USTRINGPARAM( "VisibleArea" ) ), aAny );
    }
}
<|endoftext|>


<commit_before>#include <PCU.h>
#include "phRestart.h"
#include <apf.h>
#include "phIO.h"
#include "ph.h"
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <cassert>

namespace ph {

/* in_size is the number of dofs for the data array
   and out_size is the number of dofs in the field.
   they are unequal when we read a restart file
   and want to add more dofs for the next restart files */

void attachField(
    apf::Mesh* m,
    const char* fieldname,
    double* data,
    int in_size,
    int out_size)
{
  if (!(in_size <= out_size))
    fprintf(stderr, "field \"%s\" in_size %d out_size %d\n", fieldname, in_size, out_size);
  assert(in_size <= out_size);
  apf::Field* f = apf::createPackedField(m, fieldname, out_size);
  size_t n = m->count(0);
  apf::NewArray<double> c(out_size);
  apf::MeshEntity* e;
  size_t i = 0;
  apf::MeshIterator* it = m->begin(0);
  while ((e = m->iterate(it))) {
    for (int j = 0; j < in_size; ++j)
      c[j] = data[j * n + i];
    apf::setComponents(f, e, 0, &c[0]);
    ++i;
  }
  m->end(it);
  assert(i == n);
}

/* convenience wrapper, in most cases in_size=out_size */
void attachField(
    apf::Mesh* m,
    const char* fieldname,
    double* data,
    int size)
{
  attachField(m, fieldname, data, size, size);
}

void detachField(
    apf::Field* f,
    double*& data,
    int& size)
{
  apf::Mesh* m = apf::getMesh(f);
  size = apf::countComponents(f);
  size_t n = m->count(0);
  apf::NewArray<double> c(size);
  data = (double*)malloc(sizeof(double) * size * m->count(0));
  apf::MeshEntity* e;
  size_t i = 0;
  apf::MeshIterator* it = m->begin(0);
  while ((e = m->iterate(it))) {
    apf::getComponents(f, e, 0, &c[0]);
    for (int j = 0; j < size; ++j)
      data[j * n + i] = c[j];
    ++i;
  }
  m->end(it);
  assert(i == n);
  apf::destroyField(f);
}

void detachField(
    apf::Mesh* m,
    const char* fieldname,
    double*& data,
    int& size)
{
  apf::Field* f = m->findField(fieldname);
  detachField(f, data, size);
}

void readAndAttachField(
    Input& in,
    apf::Mesh* m,
    const char* filename,
    const char* fieldname,
    int out_size = -1)
{
  FILE* f = in.openfile_read(in, filename);
  if (!f) {
    fprintf(stderr,"failed to open \"%s\"!\n", filename);
    abort();
  }
  double* data;
  int nodes, vars, step;
  ph_read_field(f, fieldname, &data,
      &nodes, &vars, &step);
  fclose(f);
  assert(nodes == static_cast<int>(m->count(0)));
  assert(step == in.timeStepNumber);
  if (out_size == -1)
    out_size = vars;
  attachField(m, fieldname, data, vars, out_size);
  free(data);
}

void detachAndWriteField(
    Input& in,
    apf::Mesh* m,
    FILE* f,
    const char* fieldname)
{
  double* data;
  int size;
  detachField(m, fieldname, data, size);
  ph_write_field(f, fieldname, data, m->count(0), size, in.timeStepNumber);
  free(data);
}

/* silliest darn fields I ever did see */
static double* buildMappingPartId(apf::Mesh* m)
{
  int n = m->count(0);
  /* malloc instead of new[] for consistency with ph_read_field */
  double* data = (double*)malloc(sizeof(double) * n);
  int self = PCU_Comm_Self();
  for (int i = 0; i < n; ++i)
    data[i] = self;
  return data;
}
static double* buildMappingVtxId(apf::Mesh* m)
{
  int n = m->count(0);
  /* malloc instead of new[] for consistency with ph_read_field */
  double* data = (double*)malloc(sizeof(double) * n);
  for (int i = 0; i < n; ++i)
    data[i] = i;
  return data;
}

static std::string buildRestartFileName(std::string prefix, int step)
{
  std::stringstream ss;
  int rank = PCU_Comm_Self() + 1;
  ss << prefix << '.' << step << '.' << rank;
  return ss.str();
}

void readAndAttachSolution(Input& in, apf::Mesh* m)
{
  double t0 = PCU_Time();
  setupInputSubdir(in.restartFileName);
  std::string filename = buildRestartFileName(in.restartFileName, in.timeStepNumber);
  readAndAttachField(in, m, filename.c_str(), "solution", in.ensa_dof);
  if (in.displacementMigration)
    readAndAttachField(in, m, filename.c_str(), "displacement");
  if (in.dwalMigration)
    readAndAttachField(in, m, filename.c_str(), "dwal");
  if (in.adaptStrategy == 1)
    readAndAttachField(in, m, filename.c_str(), "errors");
  double t1 = PCU_Time();
  if (!PCU_Comm_Self())
    printf("solution read and attached in %f seconds\n", t1 - t0);
}

void buildMapping(apf::Mesh* m)
{
  double* mapping = buildMappingPartId(m);
  attachField(m, "mapping_partid", mapping, 1);
  free(mapping);
  mapping = buildMappingVtxId(m);
  attachField(m, "mapping_vtxid", mapping, 1);
  free(mapping);
}

void attachZeroSolution(Input& in, apf::Mesh* m)
{
  int vars = in.ensa_dof;
  int nodes = m->count(0);
  double* data = new double[nodes * vars]();
  attachField(m, "solution", data, vars);
  delete [] data;
}

void detachAndWriteSolution(Input& in, Output& out, apf::Mesh* m, std::string path)
{
  double t0 = PCU_Time();
  path += buildRestartFileName("restart", in.timeStepNumber);
  FILE* f = out.openfile_write(out, path.c_str());
  if (!f) {
    fprintf(stderr,"failed to open \"%s\"!\n", path.c_str());
    abort();
  }
  ph_write_preamble(f);
  int nodes = m->count(0);
  ph_write_header(f, "number of modes", 0, 1, &nodes);
  ph_write_header(f, "number of variables", 0, 1, &in.ensa_dof);
  if (m->findField("solution"))
    detachAndWriteField(in, m, f, "solution");
  if (in.displacementMigration)
    detachAndWriteField(in, m, f, "displacement");
  if (in.dwalMigration)
    detachAndWriteField(in, m, f, "dwal");
  if (in.buildMapping) {
    detachAndWriteField(in, m, f, "mapping_partid");
    detachAndWriteField(in, m, f, "mapping_vtxid");
  }
  fclose(f);
  double t1 = PCU_Time();
  if (!PCU_Comm_Self())
    printf("solution written in %f seconds\n", t1 - t0);
}

}
<commit_msg>destroy error field<commit_after>#include <PCU.h>
#include "phRestart.h"
#include <apf.h>
#include "phIO.h"
#include "ph.h"
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <cassert>

namespace ph {

/* in_size is the number of dofs for the data array
   and out_size is the number of dofs in the field.
   they are unequal when we read a restart file
   and want to add more dofs for the next restart files */

void attachField(
    apf::Mesh* m,
    const char* fieldname,
    double* data,
    int in_size,
    int out_size)
{
  if (!(in_size <= out_size))
    fprintf(stderr, "field \"%s\" in_size %d out_size %d\n", fieldname, in_size, out_size);
  assert(in_size <= out_size);
  apf::Field* f = apf::createPackedField(m, fieldname, out_size);
  size_t n = m->count(0);
  apf::NewArray<double> c(out_size);
  apf::MeshEntity* e;
  size_t i = 0;
  apf::MeshIterator* it = m->begin(0);
  while ((e = m->iterate(it))) {
    for (int j = 0; j < in_size; ++j)
      c[j] = data[j * n + i];
    apf::setComponents(f, e, 0, &c[0]);
    ++i;
  }
  m->end(it);
  assert(i == n);
}

/* convenience wrapper, in most cases in_size=out_size */
void attachField(
    apf::Mesh* m,
    const char* fieldname,
    double* data,
    int size)
{
  attachField(m, fieldname, data, size, size);
}

void detachField(
    apf::Field* f,
    double*& data,
    int& size)
{
  apf::Mesh* m = apf::getMesh(f);
  size = apf::countComponents(f);
  size_t n = m->count(0);
  apf::NewArray<double> c(size);
  data = (double*)malloc(sizeof(double) * size * m->count(0));
  apf::MeshEntity* e;
  size_t i = 0;
  apf::MeshIterator* it = m->begin(0);
  while ((e = m->iterate(it))) {
    apf::getComponents(f, e, 0, &c[0]);
    for (int j = 0; j < size; ++j)
      data[j * n + i] = c[j];
    ++i;
  }
  m->end(it);
  assert(i == n);
  apf::destroyField(f);
}

void detachField(
    apf::Mesh* m,
    const char* fieldname,
    double*& data,
    int& size)
{
  apf::Field* f = m->findField(fieldname);
  detachField(f, data, size);
}

void readAndAttachField(
    Input& in,
    apf::Mesh* m,
    const char* filename,
    const char* fieldname,
    int out_size = -1)
{
  FILE* f = in.openfile_read(in, filename);
  if (!f) {
    fprintf(stderr,"failed to open \"%s\"!\n", filename);
    abort();
  }
  double* data;
  int nodes, vars, step;
  ph_read_field(f, fieldname, &data,
      &nodes, &vars, &step);
  fclose(f);
  assert(nodes == static_cast<int>(m->count(0)));
  assert(step == in.timeStepNumber);
  if (out_size == -1)
    out_size = vars;
  attachField(m, fieldname, data, vars, out_size);
  free(data);
}

void detachAndWriteField(
    Input& in,
    apf::Mesh* m,
    FILE* f,
    const char* fieldname)
{
  double* data;
  int size;
  detachField(m, fieldname, data, size);
  ph_write_field(f, fieldname, data, m->count(0), size, in.timeStepNumber);
  free(data);
}

/* silliest darn fields I ever did see */
static double* buildMappingPartId(apf::Mesh* m)
{
  int n = m->count(0);
  /* malloc instead of new[] for consistency with ph_read_field */
  double* data = (double*)malloc(sizeof(double) * n);
  int self = PCU_Comm_Self();
  for (int i = 0; i < n; ++i)
    data[i] = self;
  return data;
}
static double* buildMappingVtxId(apf::Mesh* m)
{
  int n = m->count(0);
  /* malloc instead of new[] for consistency with ph_read_field */
  double* data = (double*)malloc(sizeof(double) * n);
  for (int i = 0; i < n; ++i)
    data[i] = i;
  return data;
}

static std::string buildRestartFileName(std::string prefix, int step)
{
  std::stringstream ss;
  int rank = PCU_Comm_Self() + 1;
  ss << prefix << '.' << step << '.' << rank;
  return ss.str();
}

void readAndAttachSolution(Input& in, apf::Mesh* m)
{
  double t0 = PCU_Time();
  setupInputSubdir(in.restartFileName);
  std::string filename = buildRestartFileName(in.restartFileName, in.timeStepNumber);
  readAndAttachField(in, m, filename.c_str(), "solution", in.ensa_dof);
  if (in.displacementMigration)
    readAndAttachField(in, m, filename.c_str(), "displacement");
  if (in.dwalMigration)
    readAndAttachField(in, m, filename.c_str(), "dwal");
  if (in.adaptStrategy == 1)
    readAndAttachField(in, m, filename.c_str(), "errors");
  double t1 = PCU_Time();
  if (!PCU_Comm_Self())
    printf("solution read and attached in %f seconds\n", t1 - t0);
}

void buildMapping(apf::Mesh* m)
{
  double* mapping = buildMappingPartId(m);
  attachField(m, "mapping_partid", mapping, 1);
  free(mapping);
  mapping = buildMappingVtxId(m);
  attachField(m, "mapping_vtxid", mapping, 1);
  free(mapping);
}

void attachZeroSolution(Input& in, apf::Mesh* m)
{
  int vars = in.ensa_dof;
  int nodes = m->count(0);
  double* data = new double[nodes * vars]();
  attachField(m, "solution", data, vars);
  delete [] data;
}

void detachAndWriteSolution(Input& in, Output& out, apf::Mesh* m, std::string path)
{
  double t0 = PCU_Time();
  path += buildRestartFileName("restart", in.timeStepNumber);
  FILE* f = out.openfile_write(out, path.c_str());
  if (!f) {
    fprintf(stderr,"failed to open \"%s\"!\n", path.c_str());
    abort();
  }
  ph_write_preamble(f);
  int nodes = m->count(0);
  ph_write_header(f, "number of modes", 0, 1, &nodes);
  ph_write_header(f, "number of variables", 0, 1, &in.ensa_dof);
  apf::Field* errField = m->findField("errors");
  if (errField)
    apf::destroyField(errField);
  if (m->findField("solution"))
    detachAndWriteField(in, m, f, "solution");
  if (in.displacementMigration)
    detachAndWriteField(in, m, f, "displacement");
  if (in.dwalMigration)
    detachAndWriteField(in, m, f, "dwal");
  if (in.buildMapping) {
    detachAndWriteField(in, m, f, "mapping_partid");
    detachAndWriteField(in, m, f, "mapping_vtxid");
  }
  fclose(f);
  double t1 = PCU_Time();
  if (!PCU_Comm_Self())
    printf("solution written in %f seconds\n", t1 - t0);
}

}
<|endoftext|>


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

#include "imageitm.hxx"

TYPEINIT1( SfxImageItem, SfxInt16Item );

struct SfxImageItem_Impl
{
    String  aURL;
    long    nAngle;
    BOOL    bMirrored;
    int     operator == ( const SfxImageItem_Impl& rOther ) const
            { return nAngle == rOther.nAngle && bMirrored == rOther.bMirrored; }
};

//---------------------------------------------------------

SfxImageItem::SfxImageItem( USHORT nWhich, UINT16 nImage )
    : SfxInt16Item( nWhich, nImage )
{
    pImp = new SfxImageItem_Impl;
    pImp->nAngle = 0;
    pImp->bMirrored = FALSE;
}

SfxImageItem::SfxImageItem( USHORT nWhich, const String& rURL )
    : SfxInt16Item( nWhich, 0 )
{
    pImp = new SfxImageItem_Impl;
    pImp->nAngle = 0;
    pImp->bMirrored = FALSE;
    pImp->aURL = rURL;
}

SfxImageItem::SfxImageItem( const SfxImageItem& rItem )
    : SfxInt16Item( rItem )
{
    pImp = new SfxImageItem_Impl( *(rItem.pImp) );
}

//---------------------------------------------------------

SfxPoolItem* SfxImageItem::Clone( SfxItemPool* pPool ) const
{
    return new SfxImageItem( *this );
}

//---------------------------------------------------------

int SfxImageItem::operator==( const SfxPoolItem& rItem ) const
{
    return( ((SfxImageItem&) rItem).GetValue() == GetValue() && (*pImp == *(((SfxImageItem&)rItem).pImp) ) );
}

BOOL SfxImageItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const
{
    return SfxInt16Item::QueryValue( rVal, 0 );
}

BOOL SfxImageItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId )
{
    return SfxInt16Item::PutValue( rVal, 0 );
}

void SfxImageItem::SetRotation( long nValue )
{
    pImp->nAngle = nValue;
}

long SfxImageItem::GetRotation() const
{
    return pImp->nAngle;
}

void SfxImageItem::SetMirrored( BOOL bSet )
{
    pImp->bMirrored = bSet;
}

BOOL SfxImageItem::IsMirrored() const
{
    return pImp->bMirrored;
}

String SfxImageItem::GetURL() const
{
    return pImp->aURL;
}

<commit_msg>INTEGRATION: CWS docking1 (1.1.494); FILE MERGED 2004/07/05 15:19:35 cd 1.1.494.2: #i30169# Fixed build problem with gcc 2004/07/05 12:06:16 cd 1.1.494.1: #i30169# Image item must transport all member via UNO any<commit_after>/*************************************************************************
 *
 *  $RCSfile: imageitm.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2004-07-06 12:12:59 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include "imageitm.hxx"

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

TYPEINIT1( SfxImageItem, SfxInt16Item );

struct SfxImageItem_Impl
{
    String  aURL;
    long    nAngle;
    BOOL    bMirrored;
    int     operator == ( const SfxImageItem_Impl& rOther ) const
            { return nAngle == rOther.nAngle && bMirrored == rOther.bMirrored; }
};

//---------------------------------------------------------

SfxImageItem::SfxImageItem( USHORT nWhich, UINT16 nImage )
    : SfxInt16Item( nWhich, nImage )
{
    pImp = new SfxImageItem_Impl;
    pImp->nAngle = 0;
    pImp->bMirrored = FALSE;
}

SfxImageItem::SfxImageItem( USHORT nWhich, const String& rURL )
    : SfxInt16Item( nWhich, 0 )
{
    pImp = new SfxImageItem_Impl;
    pImp->nAngle = 0;
    pImp->bMirrored = FALSE;
    pImp->aURL = rURL;
}

SfxImageItem::SfxImageItem( const SfxImageItem& rItem )
    : SfxInt16Item( rItem )
{
    pImp = new SfxImageItem_Impl( *(rItem.pImp) );
}

//---------------------------------------------------------

SfxPoolItem* SfxImageItem::Clone( SfxItemPool* pPool ) const
{
    return new SfxImageItem( *this );
}

//---------------------------------------------------------

int SfxImageItem::operator==( const SfxPoolItem& rItem ) const
{
    return( ((SfxImageItem&) rItem).GetValue() == GetValue() && (*pImp == *(((SfxImageItem&)rItem).pImp) ) );
}

BOOL SfxImageItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const
{
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > aSeq( 4 );
    aSeq[0] = ::com::sun::star::uno::makeAny( GetValue() );
    aSeq[1] = ::com::sun::star::uno::makeAny( pImp->nAngle );
    aSeq[2] = ::com::sun::star::uno::makeAny( pImp->bMirrored );
    aSeq[3] = ::com::sun::star::uno::makeAny( rtl::OUString( pImp->aURL ));

    rVal = ::com::sun::star::uno::makeAny( aSeq );
    return TRUE;
}

BOOL SfxImageItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId )
{
    ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > aSeq;
    if (( rVal >>= aSeq ) && ( aSeq.getLength() == 4 ))
    {
        sal_Int16     nVal;
        rtl::OUString aURL;
        if ( aSeq[0] >>= nVal )
            SetValue( nVal );
        aSeq[1] >>= pImp->nAngle;
        aSeq[2] >>= pImp->bMirrored;
        if ( aSeq[3] >>= aURL )
            pImp->aURL = aURL;
        return TRUE;
    }

    return FALSE;
}

void SfxImageItem::SetRotation( long nValue )
{
    pImp->nAngle = nValue;
}

long SfxImageItem::GetRotation() const
{
    return pImp->nAngle;
}

void SfxImageItem::SetMirrored( BOOL bSet )
{
    pImp->bMirrored = bSet;
}

BOOL SfxImageItem::IsMirrored() const
{
    return pImp->bMirrored;
}

String SfxImageItem::GetURL() const
{
    return pImp->aURL;
}

<|endoftext|>


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

#ifndef _SOT_FORMATS_HXX
#include <sot/formats.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif

#pragma hdrstop

#include "inetimg.hxx"

#define TOKEN_SEPARATOR '\001'

sal_Bool INetImage::Write( SvStream& rOStm, ULONG nFormat ) const
{
    sal_Bool bRet = sal_False;
    switch( nFormat )
    {
    case SOT_FORMATSTR_ID_INET_IMAGE:
        {
            String sString;
            (sString += aImageURL ) += TOKEN_SEPARATOR;
            (sString += aTargetURL ) += TOKEN_SEPARATOR;
            (sString += aTargetFrame ) += TOKEN_SEPARATOR;
            (sString += aAlternateText ) += TOKEN_SEPARATOR;
            sString += String::CreateFromInt32( aSizePixel.Width() );
            sString += TOKEN_SEPARATOR;
            sString += String::CreateFromInt32( aSizePixel.Height() );
            ByteString sOut( sString, RTL_TEXTENCODING_UTF8 );

            rOStm.Write( sOut.GetBuffer(), sOut.Len() );
            static const sal_Char aEndChar[2] = { 0 };
            rOStm.Write( aEndChar, sizeof( aEndChar ));
            bRet = 0 == rOStm.GetError();
        }
        break;

    case SOT_FORMATSTR_ID_NETSCAPE_IMAGE:
        break;
    }
    return bRet;
}

sal_Bool INetImage::Read( SvStream& rIStm, ULONG nFormat )
{
    sal_Bool bRet = sal_False;
    switch( nFormat )
    {
    case SOT_FORMATSTR_ID_INET_IMAGE:
        {
            String sINetImg;
            rIStm.ReadCString( sINetImg, RTL_TEXTENCODING_UTF8 );
            xub_StrLen nStart = 0;
            aImageURL = sINetImg.GetToken( 0, TOKEN_SEPARATOR, nStart );
            aTargetURL = sINetImg.GetToken( 0, TOKEN_SEPARATOR, nStart );
            aTargetFrame = sINetImg.GetToken( 0, TOKEN_SEPARATOR, nStart );
            aAlternateText = sINetImg.GetToken( 0, TOKEN_SEPARATOR, nStart );
            aSizePixel.Width() = sINetImg.GetToken( 0, TOKEN_SEPARATOR,
                                                    nStart ).ToInt32();
            aSizePixel.Height() = sINetImg.GetToken( 0, TOKEN_SEPARATOR,
                                                    nStart ).ToInt32();
            bRet = 0 != sINetImg.Len();
        }
        break;

    case SOT_FORMATSTR_ID_NETSCAPE_IMAGE:
        {
/*
    --> structure size  MUST - alignment of 4!
    int     iSize;              // size of all data, including variable length strings
    BOOL    bIsMap;             // For server side maps
    INT32   iWidth;             // Fixed size data correspond to fields in LO_ImageDataStruct
    INT32   iHeight;            //   and EDT_ImageData
    INT32   iHSpace;
    INT32   iVSpace;
    INT32   iBorder;
    int     iLowResOffset;      // Offsets into string_data. If 0, string is NULL (not used)
    int     iAltOffset;         // (alternate text?)
    int     iAnchorOffset;      // HREF in image
    int     iExtraHTML_Offset;  // Extra HTML (stored in CImageElement)
    sal_Char pImageURL[1];      // Append all variable-length strings starting here
*/
            rtl_TextEncoding eSysCSet = gsl_getSystemTextEncoding();
            sal_Int32 nVal, nAnchorOffset, nAltOffset, nFilePos;
            int nLen;
            ByteString sData;

            nFilePos = rIStm.Tell();
            // skip over iSize (int), bIsMao ( BOOL ) alignment of 4 !!!!
            rIStm.SeekRel( 8 );
            rIStm >> nVal;  aSizePixel.Width() = nVal;
            rIStm >> nVal;  aSizePixel.Height() = nVal;
            // skip over iHSpace, iVSpace, iBorder, iLowResOffset
            rIStm.SeekRel( 3 * sizeof( INT32 ) + sizeof( int ) );
            rIStm >> nAltOffset;
            rIStm >> nAnchorOffset;
            // skip over iExtraHTML_Offset
            rIStm.SeekRel( sizeof( int ) );

            rIStm.ReadCString( aImageURL, eSysCSet );
            if( nAltOffset )
            {
                rIStm.Seek( nFilePos + nAltOffset );
                rIStm.ReadCString( aAlternateText, eSysCSet );
            }
            else if( aAlternateText.Len() )
                aAlternateText.Erase();

            if( nAnchorOffset )
            {
                rIStm.Seek( nFilePos + nAnchorOffset );
                rIStm.ReadCString( aTargetURL, eSysCSet );
            }
            else if( aTargetURL.Len() )
                aTargetURL.Erase();

            bRet = 0 == rIStm.GetError();
        }
        break;
    }
    return bRet;
}

<commit_msg>INTEGRATION: CWS ooo20040509 (1.7.572); FILE MERGED 2004/05/06 12:00:16 waratah 1.7.572.1: #i1858# bracket the pragma's that gcc does not know about<commit_after>/*************************************************************************
 *
 *  $RCSfile: inetimg.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2004-06-16 10:31:17 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _SOT_FORMATS_HXX
#include <sot/formats.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif

#ifndef GCC
#pragma hdrstop
#endif

#include "inetimg.hxx"

#define TOKEN_SEPARATOR '\001'

sal_Bool INetImage::Write( SvStream& rOStm, ULONG nFormat ) const
{
    sal_Bool bRet = sal_False;
    switch( nFormat )
    {
    case SOT_FORMATSTR_ID_INET_IMAGE:
        {
            String sString;
            (sString += aImageURL ) += TOKEN_SEPARATOR;
            (sString += aTargetURL ) += TOKEN_SEPARATOR;
            (sString += aTargetFrame ) += TOKEN_SEPARATOR;
            (sString += aAlternateText ) += TOKEN_SEPARATOR;
            sString += String::CreateFromInt32( aSizePixel.Width() );
            sString += TOKEN_SEPARATOR;
            sString += String::CreateFromInt32( aSizePixel.Height() );
            ByteString sOut( sString, RTL_TEXTENCODING_UTF8 );

            rOStm.Write( sOut.GetBuffer(), sOut.Len() );
            static const sal_Char aEndChar[2] = { 0 };
            rOStm.Write( aEndChar, sizeof( aEndChar ));
            bRet = 0 == rOStm.GetError();
        }
        break;

    case SOT_FORMATSTR_ID_NETSCAPE_IMAGE:
        break;
    }
    return bRet;
}

sal_Bool INetImage::Read( SvStream& rIStm, ULONG nFormat )
{
    sal_Bool bRet = sal_False;
    switch( nFormat )
    {
    case SOT_FORMATSTR_ID_INET_IMAGE:
        {
            String sINetImg;
            rIStm.ReadCString( sINetImg, RTL_TEXTENCODING_UTF8 );
            xub_StrLen nStart = 0;
            aImageURL = sINetImg.GetToken( 0, TOKEN_SEPARATOR, nStart );
            aTargetURL = sINetImg.GetToken( 0, TOKEN_SEPARATOR, nStart );
            aTargetFrame = sINetImg.GetToken( 0, TOKEN_SEPARATOR, nStart );
            aAlternateText = sINetImg.GetToken( 0, TOKEN_SEPARATOR, nStart );
            aSizePixel.Width() = sINetImg.GetToken( 0, TOKEN_SEPARATOR,
                                                    nStart ).ToInt32();
            aSizePixel.Height() = sINetImg.GetToken( 0, TOKEN_SEPARATOR,
                                                    nStart ).ToInt32();
            bRet = 0 != sINetImg.Len();
        }
        break;

    case SOT_FORMATSTR_ID_NETSCAPE_IMAGE:
        {
/*
    --> structure size  MUST - alignment of 4!
    int     iSize;              // size of all data, including variable length strings
    BOOL    bIsMap;             // For server side maps
    INT32   iWidth;             // Fixed size data correspond to fields in LO_ImageDataStruct
    INT32   iHeight;            //   and EDT_ImageData
    INT32   iHSpace;
    INT32   iVSpace;
    INT32   iBorder;
    int     iLowResOffset;      // Offsets into string_data. If 0, string is NULL (not used)
    int     iAltOffset;         // (alternate text?)
    int     iAnchorOffset;      // HREF in image
    int     iExtraHTML_Offset;  // Extra HTML (stored in CImageElement)
    sal_Char pImageURL[1];      // Append all variable-length strings starting here
*/
            rtl_TextEncoding eSysCSet = gsl_getSystemTextEncoding();
            sal_Int32 nVal, nAnchorOffset, nAltOffset, nFilePos;
            ByteString sData;

            nFilePos = rIStm.Tell();
            // skip over iSize (int), bIsMao ( BOOL ) alignment of 4 !!!!
            rIStm.SeekRel( 8 );
            rIStm >> nVal;  aSizePixel.Width() = nVal;
            rIStm >> nVal;  aSizePixel.Height() = nVal;
            // skip over iHSpace, iVSpace, iBorder, iLowResOffset
            rIStm.SeekRel( 3 * sizeof( INT32 ) + sizeof( int ) );
            rIStm >> nAltOffset;
            rIStm >> nAnchorOffset;
            // skip over iExtraHTML_Offset
            rIStm.SeekRel( sizeof( int ) );

            rIStm.ReadCString( aImageURL, eSysCSet );
            if( nAltOffset )
            {
                rIStm.Seek( nFilePos + nAltOffset );
                rIStm.ReadCString( aAlternateText, eSysCSet );
            }
            else if( aAlternateText.Len() )
                aAlternateText.Erase();

            if( nAnchorOffset )
            {
                rIStm.Seek( nFilePos + nAnchorOffset );
                rIStm.ReadCString( aTargetURL, eSysCSet );
            }
            else if( aTargetURL.Len() )
                aTargetURL.Erase();

            bRet = 0 == rIStm.GetError();
        }
        break;
    }
    return bRet;
}

<|endoftext|>