<commit_before>// a layer of 3d clouds
//
// Written by Harald JOHNSEN, started April 2005.
//
// Copyright (C) 2005  Harald JOHNSEN - hjohnsen@evc.net
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//
//

#ifndef _CLOUDFIELD_HXX
#define _CLOUDFIELD_HXX

#include <plib/sg.h>
#include <simgear/compiler.h>
#include <vector>

#include <osgDB/ReaderWriter>

#include <osg/ref_ptr>
#include <osg/Array>
#include <osg/Geometry>
#include <osg/Group>
#include <osg/Switch>

namespace osg
{
        class Fog;
        class StateSet;
        class Vec4f;
}

#include <simgear/misc/sg_path.hxx>
#include <simgear/structure/Singleton.hxx>
#include <Simgear/math/SGMath.hxx>

using std::vector;

class SGNewCloud;

/**
 * A layer of 3D clouds.
 */
class SGCloudField {

private:
	class Cloud  {
	public:
		SGNewCloud	*aCloud;
		sgVec3		pos;
		bool		visible;
	};

        float Rnd(float);

        // We create a quadtree two levels deep
        static const int BRANCH_SIZE = 16;
        static const int QUADTREE_SIZE = 32;

	// this is a relative position only, with that we can move all clouds at once
	sgVec3 relative_position;
        //	double lon, lat;

        osg::ref_ptr<osg::Group> field_root;
        osg::ref_ptr<osg::MatrixTransform> field_transform;
        osg::ref_ptr<osg::PositionAttitudeTransform> altitude_transform;
        osg::ref_ptr<osg::Switch> field_group[QUADTREE_SIZE][QUADTREE_SIZE];
        osg::ref_ptr<osg::LOD> quad[BRANCH_SIZE][BRANCH_SIZE];

        osg::ref_ptr<osg::LOD> field_lod;

	double deltax, deltay, alt;
        double last_course;
        sgSphere field_sphere;
	float last_coverage;
        float coverage;
        SGGeoc cld_pos;
        int reposition_count;
        struct CloudFog : public simgear::Singleton<CloudFog>
        {
                CloudFog();
                osg::ref_ptr<osg::Fog> fog;
        };
public:

	SGCloudField();
	~SGCloudField();

	void clear(void);

	// add one cloud, data is not copied, ownership given
	void addCloud( SGVec3f& pos, SGNewCloud *cloud);

        /**
        * reposition the cloud layer at the specified origin and
        * orientation.
        * @param p position vector
        * @param up the local up vector
        * @param lon specifies a rotation about the Z axis
        * @param lat specifies a rotation about the new Y axis
        * @param dt the time elapsed since the last call
        * @param asl altitude of the layer
        */
        bool reposition( const SGVec3f& p, const SGVec3f& up,
                        double lon, double lat, double dt, int asl);

        osg::Group* getNode() { return field_root.get(); }

	// visibility distance for clouds in meters
	static float CloudVis;

	static sgVec3 view_vec, view_X, view_Y;

        static float view_distance;
        static double timer_dt;
	static float fieldSize;

        bool defined3D;

	float getCoverage(void) { return coverage; }
	void setCoverage(float c) { coverage = c; }

        static float getVisRange(void) { return view_distance; }
        static void setVisRange(float d) { view_distance = d; }

        void applyCoverage(void);
        void applyVisRange(void);

        static osg::Fog* getFog()
        {
                return CloudFog::instance()->fog.get();
        }
        static void updateFog(double visibility, const osg::Vec4f& color);
};

#endif // _CLOUDFIELD_HXX
<commit_msg>fix a typo<commit_after>// a layer of 3d clouds
//
// Written by Harald JOHNSEN, started April 2005.
//
// Copyright (C) 2005  Harald JOHNSEN - hjohnsen@evc.net
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
//
//

#ifndef _CLOUDFIELD_HXX
#define _CLOUDFIELD_HXX

#include <plib/sg.h>
#include <simgear/compiler.h>
#include <vector>

#include <osgDB/ReaderWriter>

#include <osg/ref_ptr>
#include <osg/Array>
#include <osg/Geometry>
#include <osg/Group>
#include <osg/Switch>

namespace osg
{
        class Fog;
        class StateSet;
        class Vec4f;
}

#include <simgear/misc/sg_path.hxx>
#include <simgear/structure/Singleton.hxx>
#include <simgear/math/SGMath.hxx>

using std::vector;

class SGNewCloud;

/**
 * A layer of 3D clouds.
 */
class SGCloudField {

private:
	class Cloud  {
	public:
		SGNewCloud	*aCloud;
		sgVec3		pos;
		bool		visible;
	};

        float Rnd(float);

        // We create a quadtree two levels deep
        static const int BRANCH_SIZE = 16;
        static const int QUADTREE_SIZE = 32;

	// this is a relative position only, with that we can move all clouds at once
	sgVec3 relative_position;
        //	double lon, lat;

        osg::ref_ptr<osg::Group> field_root;
        osg::ref_ptr<osg::MatrixTransform> field_transform;
        osg::ref_ptr<osg::PositionAttitudeTransform> altitude_transform;
        osg::ref_ptr<osg::Switch> field_group[QUADTREE_SIZE][QUADTREE_SIZE];
        osg::ref_ptr<osg::LOD> quad[BRANCH_SIZE][BRANCH_SIZE];

        osg::ref_ptr<osg::LOD> field_lod;

	double deltax, deltay, alt;
        double last_course;
        sgSphere field_sphere;
	float last_coverage;
        float coverage;
        SGGeoc cld_pos;
        int reposition_count;
        struct CloudFog : public simgear::Singleton<CloudFog>
        {
                CloudFog();
                osg::ref_ptr<osg::Fog> fog;
        };
public:

	SGCloudField();
	~SGCloudField();

	void clear(void);

	// add one cloud, data is not copied, ownership given
	void addCloud( SGVec3f& pos, SGNewCloud *cloud);

        /**
        * reposition the cloud layer at the specified origin and
        * orientation.
        * @param p position vector
        * @param up the local up vector
        * @param lon specifies a rotation about the Z axis
        * @param lat specifies a rotation about the new Y axis
        * @param dt the time elapsed since the last call
        * @param asl altitude of the layer
        */
        bool reposition( const SGVec3f& p, const SGVec3f& up,
                        double lon, double lat, double dt, int asl);

        osg::Group* getNode() { return field_root.get(); }

	// visibility distance for clouds in meters
	static float CloudVis;

	static sgVec3 view_vec, view_X, view_Y;

        static float view_distance;
        static double timer_dt;
	static float fieldSize;

        bool defined3D;

	float getCoverage(void) { return coverage; }
	void setCoverage(float c) { coverage = c; }

        static float getVisRange(void) { return view_distance; }
        static void setVisRange(float d) { view_distance = d; }

        void applyCoverage(void);
        void applyVisRange(void);

        static osg::Fog* getFog()
        {
                return CloudFog::instance()->fog.get();
        }
        static void updateFog(double visibility, const osg::Vec4f& color);
};

#endif // _CLOUDFIELD_HXX
<|endoftext|>


<commit_before>#include"all_defines.hpp"
#include"objects.hpp"
#include"heaps.hpp"
#include"types.hpp"

#include<cstdlib>
#include<stdint.h>

/*-----------------------------------------------------------------------------
Semispaces
-----------------------------------------------------------------------------*/

Semispace::Semispace(size_t nsz)
	: max(nsz) {
	mem = std::malloc(nsz);
	if(!mem) throw std::bad_alloc();

	allocpt = mem;
	// check alignment
	intptr_t tmp = reinterpret_cast<intptr_t>(allocpt);
	if(tmp & Object::tag_mask) {
		char* callocpt = allocpt;
		callocpt += Object::alignment - (tmp & Object::tag_mask);
		allocpt = callocpt;
	}
	allocstart = allocpt;

	char* cmem = mem;
	char* clifoallocpt = cmem + nsz;
	// adjust for alignment
	tmp = reinterpret_cast<intptr_t>(lifoallocpt);
	clifoallocpt -= (tmp & Object::tag_mask);

	lifoallocpt = clifoallocpt;
}

Semispace::~Semispace() {
	Generic* gp;
	size_t step;
	char* mvpt;
	char* endpt;

	/*TODO: consider refactoring*/
	/*----Delete normally-allocated memory----*/
	mvpt = allocstart;
	endpt = allocpt;

	while(mvpt < endpt) {
		gp = (Generic*)(void*) mvpt;
		step = gp->real_size();
		gp->~Generic();
		mvpt += step;
	}

	/*----Delete lifo-allocated memory----*/
	mvpt = lifoallocpt;
	endpt = lifoallocstart;

	while(mvpt < endpt) {
		gp = (Generic*)(void*) mvpt;
		step = gp->real_size();
		gp->~Generic();
		mvpt += step;
	}
}

/*
sz must be computed using the exact same
computation used in real_size() of the
object to be allocated.  This includes
alignment.
*/
void* Semispace::alloc(size_t sz) {
	prev_alloc = sz;
	void* tmp = allocpt;
	char* callocpt = allocpt;
	callocpt += sz;
	allocpt = callocpt;
	return tmp;
}

/*should be used only for most recent allocation
(i.e. should be used for freeing memory when the
constructor throws.)
*/
void Semispace::dealloc(void* pt) {
	#ifdef DEBUG
		char* callocpt = allocpt;
		callocpt -= prev_alloc;
		if(callocpt != pt) throw_DeallocError(pt);
	#endif
	allocpt = pt;
}

void* Semispace::lifo_alloc(size_t sz) {
	prevalloc = sz;
	char* clifoallocpt = lifoallocpt;
	clifoallocpt -= sz;
	lifoallocpt = clifoallocpt;
	return lifoallocpt;
}

void Semispace::lifo_dealloc(void* pt) {
	/*if we can't deallocate, just ignore*/
	if(pt != lifoallocpt) return;
	size_t sz = ((Generic*) pt)->real_size();
	((Generic*) pt)->~Generic();
	char* clifoallocpt = pt;
	clifoallocpt += sz;
	lifoallocpt = clifoallocpt;
}

/*This function should be used only when the
constructor for the object fails.  It does
*not* properly destroy the object.
*/
void Semispace::lifo_dealloc_abort(void* pt) {
	#ifdef DEBUG
		if(pt != lifoallocpt) throw_DeallocError(pt);
	#endif
	char* clifoallocpt = lifoallocpt;
	clifoallocpt += prev_alloc;
	lifoallocpt = clifoallocpt;
}

/*TODO*/
void Semispace::clone(boost::scoped_ptr<Semispace>& sp, Generic*& g);

/*-----------------------------------------------------------------------------
Heaps
-----------------------------------------------------------------------------*/

/*copy and modify GC class*/
class GCTraverser : public GenericTraverser {
	Semispace* nsp;
public:
	explicit GCTraverser(Semispace* nnsp) : nsp(nnsp) { }
	void traverse(Object::ref& r) {
		if(is_a<Generic*>(r)) {
			Generic* gp = as_a<Generic*>(r);
			BrokenHeart* bp = dynamic_cast<BrokenHeart*>(gp);
			if(bp) { //broken heart
				r = Object::to_ref(bp->to);
			} else { //unbroken
				Generic* ngp = gp->clone(nsp);
				gp->break_heart(ngp);
				r = Object::to_ref(ngp);
			}
		} else return;
	}
};

static void cheney_collection(Semispace* nsp) {
	GCTraverser gc(nsp);
	/*step 1: initial traverse*/
	scan_root_object(gc);
	/*step 2: non-root traverse*/
	/*notice that we traverse the new semispace
	this is a two-pointer Cheney collector, with mvpt
	being one pointer and nsp->allocpt the other one
	*/
	char* mvpt = nsp->allocstart;
	while(mvpt < ((char*) nsp->allocpt)) {
		Generic* gp = (Generic*)(void*) mvpt;
		size_t obsz = gp->real_size();
		gp->traverse_references(gc);
		mvpt += obsz;
	}
}

void Heap::GC(size_t insurance) {
	/*Determine the sizes of all semispaces*/
	size_t total = main->used() + insurance +
	(other_spaces) ?		other_spaces->used_total() :
	/*otherwise*/			0 ;

	if(tight) total *= 2;

	/*get a new Semispace*/
	boost::scoped_ptr<Semispace> nsp(new Semispace(total));

	/*traverse*/
	cheney_collection(&*nsp);

	/*replace*/
	main.swap(nsp);
	nsp.reset();
	other_spaces.reset();

	/*determine if resizing is appropriate*/
	if(main->used() + insurance <= total / 4) {
		/*semispace a bit large... make it smaller*/
		nsp.reset(new Semispace(total / 2));
		cheney_collection(&*nsp);
		main.swap(nsp);
		nsp.reset();
	} else if(main->used() + insurance >= (total / 4) * 3) {
		tight = 1;
	}
}

<commit_msg>src/heaps.cpp: Added proper casts<commit_after>#include"all_defines.hpp"
#include"objects.hpp"
#include"heaps.hpp"
#include"types.hpp"

#include<cstdlib>
#include<stdint.h>

/*-----------------------------------------------------------------------------
Semispaces
-----------------------------------------------------------------------------*/

Semispace::Semispace(size_t nsz)
	: max(nsz) {
	mem = std::malloc(nsz);
	if(!mem) throw std::bad_alloc();

	allocpt = mem;
	// check alignment
	intptr_t tmp = reinterpret_cast<intptr_t>(allocpt);
	if(tmp & Object::tag_mask) {
		char* callocpt = (char*)allocpt;
		callocpt += Object::alignment - (tmp & Object::tag_mask);
		allocpt = callocpt;
	}
	allocstart = allocpt;

	char* cmem = (char*)mem;
	char* clifoallocpt = cmem + nsz;
	// adjust for alignment
	tmp = reinterpret_cast<intptr_t>(lifoallocpt);
	clifoallocpt -= (tmp & Object::tag_mask);

	lifoallocpt = clifoallocpt;
}

Semispace::~Semispace() {
	Generic* gp;
	size_t step;
	char* mvpt;
	char* endpt;

	/*TODO: consider refactoring*/
	/*----Delete normally-allocated memory----*/
	mvpt = (char*) allocstart;
	endpt = (char*) allocpt;

	while(mvpt < endpt) {
		gp = (Generic*)(void*) mvpt;
		step = gp->real_size();
		gp->~Generic();
		mvpt += step;
	}

	/*----Delete lifo-allocated memory----*/
	mvpt = (char*) lifoallocpt;
	endpt = (char*) lifoallocstart;

	while(mvpt < endpt) {
		gp = (Generic*)(void*) mvpt;
		step = gp->real_size();
		gp->~Generic();
		mvpt += step;
	}
}

/*
sz must be computed using the exact same
computation used in real_size() of the
object to be allocated.  This includes
alignment.
*/
void* Semispace::alloc(size_t sz) {
	prev_alloc = sz;
	void* tmp = allocpt;
	char* callocpt = (char*) allocpt;
	callocpt += sz;
	allocpt = callocpt;
	return tmp;
}

/*should be used only for most recent allocation
(i.e. should be used for freeing memory when the
constructor throws.)
*/
void Semispace::dealloc(void* pt) {
	#ifdef DEBUG
		char* callocpt = allocpt;
		callocpt -= prev_alloc;
		if(callocpt != pt) throw_DeallocError(pt);
	#endif
	allocpt = pt;
}

void* Semispace::lifo_alloc(size_t sz) {
	prevalloc = sz;
	char* clifoallocpt = lifoallocpt;
	clifoallocpt -= sz;
	lifoallocpt = clifoallocpt;
	return lifoallocpt;
}

void Semispace::lifo_dealloc(void* pt) {
	/*if we can't deallocate, just ignore*/
	if(pt != lifoallocpt) return;
	size_t sz = ((Generic*) pt)->real_size();
	((Generic*) pt)->~Generic();
	char* clifoallocpt = pt;
	clifoallocpt += sz;
	lifoallocpt = clifoallocpt;
}

/*This function should be used only when the
constructor for the object fails.  It does
*not* properly destroy the object.
*/
void Semispace::lifo_dealloc_abort(void* pt) {
	#ifdef DEBUG
		if(pt != lifoallocpt) throw_DeallocError(pt);
	#endif
	char* clifoallocpt = lifoallocpt;
	clifoallocpt += prev_alloc;
	lifoallocpt = clifoallocpt;
}

/*TODO*/
void Semispace::clone(boost::scoped_ptr<Semispace>& sp, Generic*& g);

/*-----------------------------------------------------------------------------
Heaps
-----------------------------------------------------------------------------*/

/*copy and modify GC class*/
class GCTraverser : public GenericTraverser {
	Semispace* nsp;
public:
	explicit GCTraverser(Semispace* nnsp) : nsp(nnsp) { }
	void traverse(Object::ref& r) {
		if(is_a<Generic*>(r)) {
			Generic* gp = as_a<Generic*>(r);
			BrokenHeart* bp = dynamic_cast<BrokenHeart*>(gp);
			if(bp) { //broken heart
				r = Object::to_ref(bp->to);
			} else { //unbroken
				Generic* ngp = gp->clone(nsp);
				gp->break_heart(ngp);
				r = Object::to_ref(ngp);
			}
		} else return;
	}
};

static void cheney_collection(Semispace* nsp) {
	GCTraverser gc(nsp);
	/*step 1: initial traverse*/
	scan_root_object(gc);
	/*step 2: non-root traverse*/
	/*notice that we traverse the new semispace
	this is a two-pointer Cheney collector, with mvpt
	being one pointer and nsp->allocpt the other one
	*/
	char* mvpt = nsp->allocstart;
	while(mvpt < ((char*) nsp->allocpt)) {
		Generic* gp = (Generic*)(void*) mvpt;
		size_t obsz = gp->real_size();
		gp->traverse_references(gc);
		mvpt += obsz;
	}
}

void Heap::GC(size_t insurance) {
	/*Determine the sizes of all semispaces*/
	size_t total = main->used() + insurance +
	(other_spaces) ?		other_spaces->used_total() :
	/*otherwise*/			0 ;

	if(tight) total *= 2;

	/*get a new Semispace*/
	boost::scoped_ptr<Semispace> nsp(new Semispace(total));

	/*traverse*/
	cheney_collection(&*nsp);

	/*replace*/
	main.swap(nsp);
	nsp.reset();
	other_spaces.reset();

	/*determine if resizing is appropriate*/
	if(main->used() + insurance <= total / 4) {
		/*semispace a bit large... make it smaller*/
		nsp.reset(new Semispace(total / 2));
		cheney_collection(&*nsp);
		main.swap(nsp);
		nsp.reset();
	} else if(main->used() + insurance >= (total / 4) * 3) {
		tight = 1;
	}
}

<|endoftext|>


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

#include "appshell_extensions.h"
#include "client_handler.h"

#include <algorithm>
#include <CommDlg.h>
#include <ShlObj.h>
#include <Shlwapi.h>
#include <stdio.h>
#include <sys/stat.h>

#define CLOSING_PROP L"CLOSING"

extern CefRefPtr<ClientHandler> g_handler;

// Forward declarations for functions at the bottom of this file
void ConvertToNativePath(ExtensionString& filename);
void ConvertToUnixPath(ExtensionString& filename);
int ConvertErrnoCode(int errorCode, bool isReading = true);
int ConvertWinErrorCode(int errorCode, bool isReading = true);

static int CALLBACK SetInitialPathCallback(HWND hWnd, UINT uMsg, LPARAM lParam, LPARAM lpData)
{
    if (BFFM_INITIALIZED == uMsg && NULL != lpData)
    {
        SendMessage(hWnd, BFFM_SETSELECTION, TRUE, lpData);
    }

    return 0;
}

int32 ShowOpenDialog(bool allowMulitpleSelection,
                     bool chooseDirectory,
                     ExtensionString title,
                     ExtensionString initialDirectory,
                     ExtensionString fileTypes,
                     CefRefPtr<CefListValue>& selectedFiles)
{
    wchar_t szFile[MAX_PATH];
    szFile[0] = 0;

    // TODO (issue #64) - This method should be using IFileDialog instead of the
    /* outdated SHGetPathFromIDList and GetOpenFileName.

    Useful function to parse fileTypesStr:
    template<class T>
    int inline findAndReplaceString(T& source, const T& find, const T& replace)
    {
    int num=0;
    int fLen = find.size();
    int rLen = replace.size();
    for (int pos=0; (pos=source.find(find, pos))!=T::npos; pos+=rLen)
    {
    num++;
    source.replace(pos, fLen, replace);
    }
    return num;
    }
    */

    if (chooseDirectory) {
        BROWSEINFO bi = {0};
        bi.hwndOwner = GetActiveWindow();
        bi.lpszTitle = title.c_str();
        bi.ulFlags = BIF_NEWDIALOGSTYLE;
        bi.lpfn = SetInitialPathCallback;
        bi.lParam = (LPARAM)initialDirectory.c_str();

        LPITEMIDLIST pidl = SHBrowseForFolder(&bi);
        if (pidl != 0) {
            if (SHGetPathFromIDList(pidl, szFile)) {
                // Add directory path to the result
                selectedFiles->SetString(0, szFile);
            }
            IMalloc* pMalloc = NULL;
            SHGetMalloc(&pMalloc);
            if (pMalloc) {
                pMalloc->Free(pidl);
                pMalloc->Release();
            }
        }
    } else {
        OPENFILENAME ofn;

        ZeroMemory(&ofn, sizeof(ofn));
        ofn.hwndOwner = GetActiveWindow();
        ofn.lStructSize = sizeof(ofn);
        ofn.lpstrFile = szFile;
        ofn.nMaxFile = MAX_PATH;

        // TODO (issue #65) - Use passed in file types. Note, when fileTypesStr is null, all files should be shown
        /* findAndReplaceString( fileTypesStr, std::string(" "), std::string(";*."));
        LPCWSTR allFilesFilter = L"All Files\0*.*\0\0";*/

        ofn.lpstrFilter = L"All Files\0*.*\0Web Files\0*.js;*.css;*.htm;*.html\0\0";

        ofn.lpstrInitialDir = initialDirectory.c_str();
        ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_EXPLORER;
        if (allowMulitpleSelection)
            ofn.Flags |= OFN_ALLOWMULTISELECT;

        if (GetOpenFileName(&ofn)) {
            if (allowMulitpleSelection) {
                // Multiple selection encodes the files differently

                // If multiple files are selected, the first null terminator
                // signals end of directory that the files are all in
                std::wstring dir(szFile);

                // Check for two null terminators, which signal that only one file
                // was selected
                if (szFile[dir.length() + 1] == '\0') {
                    ExtensionString filePath(dir);
                    ConvertToUnixPath(filePath);
                    selectedFiles->SetString(0, filePath);
                } else {
                    // Multiple files are selected
                    wchar_t fullPath[MAX_PATH];
                    for (int i = (dir.length() + 1), fileIndex = 0; ; fileIndex++) {
                        // Get the next file name
                        std::wstring file(&szFile[i]);

                        // Two adjacent null characters signal the end of the files
                        if (file.length() == 0)
                            break;

                        // The filename is relative to the directory that was specified as
                        // the first string
                        if (PathCombine(fullPath, dir.c_str(), file.c_str()) != NULL) {
                            ExtensionString filePath(fullPath);
                            ConvertToUnixPath(filePath);
                            selectedFiles->SetString(fileIndex, filePath);
						}

                        // Go to the start of the next file name
                        i += file.length() + 1;
                    }
                }

            } else {
                // If multiple files are not allowed, add the single file
                selectedFiles->SetString(0, szFile);
            }
        }
    }

    return NO_ERROR;
}

int32 ReadDir(ExtensionString path, CefRefPtr<CefListValue>& directoryContents)
{
    if (path.length() && path[path.length() - 1] != '/')
        path += '/';

    path += '*';

    WIN32_FIND_DATA ffd;
    HANDLE hFind = FindFirstFile(path.c_str(), &ffd);

    std::vector<ExtensionString> resultFiles;
    std::vector<ExtensionString> resultDirs;

    if (hFind != INVALID_HANDLE_VALUE) {
        do {
            // Ignore '.' and '..'
            if (!wcscmp(ffd.cFileName, L".") || !wcscmp(ffd.cFileName, L".."))
                continue;

            // Collect file and directory names separately
            if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
                resultDirs.push_back(ExtensionString(ffd.cFileName));
            } else {
                resultFiles.push_back(ExtensionString(ffd.cFileName));
            }
        }
        while (FindNextFile(hFind, &ffd) != 0);

        FindClose(hFind);
    }
    else {
        return ConvertWinErrorCode(GetLastError());
    }

    // On Windows, list directories first, then files
    size_t i, total = 0;
    for (i = 0; i < resultDirs.size(); i++)
        directoryContents->SetString(total++, resultDirs[i]);
    for (i = 0; i < resultFiles.size(); i++)
        directoryContents->SetString(total++, resultFiles[i]);

    return NO_ERROR;
}

int32 GetFileModificationTime(ExtensionString filename, uint32& modtime, bool& isDir)
{
    DWORD dwAttr = GetFileAttributes(filename.c_str());

    if (dwAttr == INVALID_FILE_ATTRIBUTES) {
        return ConvertWinErrorCode(GetLastError());
    }

    isDir = ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) != 0);

    // Remove trailing "/", if present. _wstat will fail with a "file not found"
    // error if a directory has a trailing '/' in the name.
    if (filename[filename.length() - 1] == '/')
        filename[filename.length() - 1] = 0;

    struct _stat buffer;
    if(_wstat(filename.c_str(), &buffer) == -1) {
        return ConvertErrnoCode(errno);
    }

    modtime = buffer.st_mtime;

    return NO_ERROR;
}

int32 ReadFile(ExtensionString filename, ExtensionString encoding, std::string& contents)
{
    if (encoding != L"utf8")
        return ERR_UNSUPPORTED_ENCODING;

    DWORD dwAttr;
    dwAttr = GetFileAttributes(filename.c_str());
    if (INVALID_FILE_ATTRIBUTES == dwAttr)
        return ConvertWinErrorCode(GetLastError());

    if (dwAttr & FILE_ATTRIBUTE_DIRECTORY)
        return ERR_CANT_READ;

    HANDLE hFile = CreateFile(filename.c_str(), GENERIC_READ,
        0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    int32 error = NO_ERROR;

    if (INVALID_HANDLE_VALUE == hFile)
        return ConvertWinErrorCode(GetLastError());

    DWORD dwFileSize = GetFileSize(hFile, NULL);
    DWORD dwBytesRead;
    char* buffer = (char*)malloc(dwFileSize);
    if (buffer && ReadFile(hFile, buffer, dwFileSize, &dwBytesRead, NULL)) {
        contents = std::string(buffer, dwFileSize);
    }
    else {
        if (!buffer)
            error = ERR_UNKNOWN;
        else
            error = ConvertWinErrorCode(GetLastError());
    }
    CloseHandle(hFile);
    if (buffer)
        free(buffer);

    return error;
}

int32 WriteFile(ExtensionString filename, std::string contents, ExtensionString encoding)
{
    if (encoding != L"utf8")
        return ERR_UNSUPPORTED_ENCODING;

    HANDLE hFile = CreateFile(filename.c_str(), GENERIC_WRITE,
        0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    DWORD dwBytesWritten;
    int error = NO_ERROR;

    if (INVALID_HANDLE_VALUE == hFile)
        return ConvertWinErrorCode(GetLastError(), false);

    // TODO (issue 67) -  Should write to temp file and handle encoding
    if (!WriteFile(hFile, contents.c_str(), contents.length(), &dwBytesWritten, NULL)) {
        error = ConvertWinErrorCode(GetLastError(), false);
    }

    CloseHandle(hFile);
    return error;
}

int32 SetPosixPermissions(ExtensionString filename, int32 mode)
{
    DWORD dwAttr = GetFileAttributes(filename.c_str());

    if (dwAttr == INVALID_FILE_ATTRIBUTES)
        return ERR_NOT_FOUND;

    if ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) != 0)
        return NO_ERROR;

    bool write = (mode & 0200) != 0;
    bool read = (mode & 0400) != 0;
    int mask = (write ? _S_IWRITE : 0) | (read ? _S_IREAD : 0);

    if (_wchmod(filename.c_str(), mask) == -1) {
        return ConvertErrnoCode(errno);
    }

    return NO_ERROR;
}

int32 DeleteFileOrDirectory(ExtensionString filename)
{
    DWORD dwAttr = GetFileAttributes(filename.c_str());

    if ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) != 0)
        return ERR_NOT_FILE;

    if (!DeleteFile(filename.c_str()))
        return ConvertWinErrorCode(GetLastError());

    return NO_ERROR;
}

void CloseWindow(CefRefPtr<CefBrowser> browser)
{
    if (browser.get() && g_handler.get()) {
		HWND browserHwnd = browser->GetHost()->GetWindowHandle();
		SetProp(browserHwnd, CLOSING_PROP, (HANDLE)1);
	    browser->GetHost()->CloseBrowser();
	}
}

void BringBrowserWindowToFront(CefRefPtr<CefBrowser> browser)
{
    if (browser.get()) {
        HWND hwnd = browser->GetHost()->GetWindowHandle();
        if (hwnd)
            ::BringWindowToTop(hwnd);
    }
}

void ConvertToNativePath(ExtensionString& filename)
{
    // Convert '/' to '\'
    replace(filename.begin(), filename.end(), '/', '\\');
}

void ConvertToUnixPath(ExtensionString& filename)
{
    // Convert '\\' to '/'
    replace(filename.begin(), filename.end(), '\\', '/');
}

// Maps errors from errno.h to the brackets error codes
// found in brackets_extensions.js
int ConvertErrnoCode(int errorCode, bool isReading)
{
    switch (errorCode) {
    case NO_ERROR:
        return NO_ERROR;
    case EINVAL:
        return ERR_INVALID_PARAMS;
    case ENOENT:
        return ERR_NOT_FOUND;
    default:
        return ERR_UNKNOWN;
    }
}

// Maps errors from  WinError.h to the brackets error codes
// found in brackets_extensions.js
int ConvertWinErrorCode(int errorCode, bool isReading)
{
    switch (errorCode) {
    case NO_ERROR:
        return NO_ERROR;
    case ERROR_PATH_NOT_FOUND:
    case ERROR_FILE_NOT_FOUND:
        return ERR_NOT_FOUND;
    case ERROR_ACCESS_DENIED:
        return isReading ? ERR_CANT_READ : ERR_CANT_WRITE;
    case ERROR_WRITE_PROTECT:
        return ERR_CANT_WRITE;
    case ERROR_HANDLE_DISK_FULL:
        return ERR_OUT_OF_SPACE;
    default:
        return ERR_UNKNOWN;
    }
}

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

#include "appshell_extensions.h"
#include "client_handler.h"

#include <algorithm>
#include <CommDlg.h>
#include <ShlObj.h>
#include <Shlwapi.h>
#include <stdio.h>
#include <sys/stat.h>

#define CLOSING_PROP L"CLOSING"

extern CefRefPtr<ClientHandler> g_handler;

// Forward declarations for functions at the bottom of this file
void ConvertToNativePath(ExtensionString& filename);
void ConvertToUnixPath(ExtensionString& filename);
int ConvertErrnoCode(int errorCode, bool isReading = true);
int ConvertWinErrorCode(int errorCode, bool isReading = true);

static int CALLBACK SetInitialPathCallback(HWND hWnd, UINT uMsg, LPARAM lParam, LPARAM lpData)
{
    if (BFFM_INITIALIZED == uMsg && NULL != lpData)
    {
        SendMessage(hWnd, BFFM_SETSELECTION, TRUE, lpData);
    }

    return 0;
}

int32 ShowOpenDialog(bool allowMulitpleSelection,
                     bool chooseDirectory,
                     ExtensionString title,
                     ExtensionString initialDirectory,
                     ExtensionString fileTypes,
                     CefRefPtr<CefListValue>& selectedFiles)
{
    wchar_t szFile[MAX_PATH];
    szFile[0] = 0;

    // TODO (issue #64) - This method should be using IFileDialog instead of the
    /* outdated SHGetPathFromIDList and GetOpenFileName.

    Useful function to parse fileTypesStr:
    template<class T>
    int inline findAndReplaceString(T& source, const T& find, const T& replace)
    {
    int num=0;
    int fLen = find.size();
    int rLen = replace.size();
    for (int pos=0; (pos=source.find(find, pos))!=T::npos; pos+=rLen)
    {
    num++;
    source.replace(pos, fLen, replace);
    }
    return num;
    }
    */

    if (chooseDirectory) {
        BROWSEINFO bi = {0};
        bi.hwndOwner = GetActiveWindow();
        bi.lpszTitle = title.c_str();
        bi.ulFlags = BIF_NEWDIALOGSTYLE;
        bi.lpfn = SetInitialPathCallback;
        bi.lParam = (LPARAM)initialDirectory.c_str();

        LPITEMIDLIST pidl = SHBrowseForFolder(&bi);
        if (pidl != 0) {
            if (SHGetPathFromIDList(pidl, szFile)) {
                // Add directory path to the result
                ExtensionString pathName(szFile);
                ConvertToUnixPath(pathName);
                selectedFiles->SetString(0, pathName);
            }
            IMalloc* pMalloc = NULL;
            SHGetMalloc(&pMalloc);
            if (pMalloc) {
                pMalloc->Free(pidl);
                pMalloc->Release();
            }
        }
    } else {
        OPENFILENAME ofn;

        ZeroMemory(&ofn, sizeof(ofn));
        ofn.hwndOwner = GetActiveWindow();
        ofn.lStructSize = sizeof(ofn);
        ofn.lpstrFile = szFile;
        ofn.nMaxFile = MAX_PATH;

        // TODO (issue #65) - Use passed in file types. Note, when fileTypesStr is null, all files should be shown
        /* findAndReplaceString( fileTypesStr, std::string(" "), std::string(";*."));
        LPCWSTR allFilesFilter = L"All Files\0*.*\0\0";*/

        ofn.lpstrFilter = L"All Files\0*.*\0Web Files\0*.js;*.css;*.htm;*.html\0\0";

        ofn.lpstrInitialDir = initialDirectory.c_str();
        ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_EXPLORER;
        if (allowMulitpleSelection)
            ofn.Flags |= OFN_ALLOWMULTISELECT;

        if (GetOpenFileName(&ofn)) {
            if (allowMulitpleSelection) {
                // Multiple selection encodes the files differently

                // If multiple files are selected, the first null terminator
                // signals end of directory that the files are all in
                std::wstring dir(szFile);

                // Check for two null terminators, which signal that only one file
                // was selected
                if (szFile[dir.length() + 1] == '\0') {
                    ExtensionString filePath(dir);
                    ConvertToUnixPath(filePath);
                    selectedFiles->SetString(0, filePath);
                } else {
                    // Multiple files are selected
                    wchar_t fullPath[MAX_PATH];
                    for (int i = (dir.length() + 1), fileIndex = 0; ; fileIndex++) {
                        // Get the next file name
                        std::wstring file(&szFile[i]);

                        // Two adjacent null characters signal the end of the files
                        if (file.length() == 0)
                            break;

                        // The filename is relative to the directory that was specified as
                        // the first string
                        if (PathCombine(fullPath, dir.c_str(), file.c_str()) != NULL) {
                            ExtensionString filePath(fullPath);
                            ConvertToUnixPath(filePath);
                            selectedFiles->SetString(fileIndex, filePath);
                        }

                        // Go to the start of the next file name
                        i += file.length() + 1;
                    }
                }

            } else {
                // If multiple files are not allowed, add the single file
                selectedFiles->SetString(0, szFile);
            }
        }
    }

    return NO_ERROR;
}

int32 ReadDir(ExtensionString path, CefRefPtr<CefListValue>& directoryContents)
{
    if (path.length() && path[path.length() - 1] != '/')
        path += '/';

    path += '*';

    WIN32_FIND_DATA ffd;
    HANDLE hFind = FindFirstFile(path.c_str(), &ffd);

    std::vector<ExtensionString> resultFiles;
    std::vector<ExtensionString> resultDirs;

    if (hFind != INVALID_HANDLE_VALUE) {
        do {
            // Ignore '.' and '..'
            if (!wcscmp(ffd.cFileName, L".") || !wcscmp(ffd.cFileName, L".."))
                continue;

            // Collect file and directory names separately
            if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
                resultDirs.push_back(ExtensionString(ffd.cFileName));
            } else {
                resultFiles.push_back(ExtensionString(ffd.cFileName));
            }
        }
        while (FindNextFile(hFind, &ffd) != 0);

        FindClose(hFind);
    }
    else {
        return ConvertWinErrorCode(GetLastError());
    }

    // On Windows, list directories first, then files
    size_t i, total = 0;
    for (i = 0; i < resultDirs.size(); i++)
        directoryContents->SetString(total++, resultDirs[i]);
    for (i = 0; i < resultFiles.size(); i++)
        directoryContents->SetString(total++, resultFiles[i]);

    return NO_ERROR;
}

int32 GetFileModificationTime(ExtensionString filename, uint32& modtime, bool& isDir)
{
    DWORD dwAttr = GetFileAttributes(filename.c_str());

    if (dwAttr == INVALID_FILE_ATTRIBUTES) {
        return ConvertWinErrorCode(GetLastError());
    }

    isDir = ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) != 0);

    // Remove trailing "/", if present. _wstat will fail with a "file not found"
    // error if a directory has a trailing '/' in the name.
    if (filename[filename.length() - 1] == '/')
        filename[filename.length() - 1] = 0;

    struct _stat buffer;
    if(_wstat(filename.c_str(), &buffer) == -1) {
        return ConvertErrnoCode(errno);
    }

    modtime = buffer.st_mtime;

    return NO_ERROR;
}

int32 ReadFile(ExtensionString filename, ExtensionString encoding, std::string& contents)
{
    if (encoding != L"utf8")
        return ERR_UNSUPPORTED_ENCODING;

    DWORD dwAttr;
    dwAttr = GetFileAttributes(filename.c_str());
    if (INVALID_FILE_ATTRIBUTES == dwAttr)
        return ConvertWinErrorCode(GetLastError());

    if (dwAttr & FILE_ATTRIBUTE_DIRECTORY)
        return ERR_CANT_READ;

    HANDLE hFile = CreateFile(filename.c_str(), GENERIC_READ,
        0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    int32 error = NO_ERROR;

    if (INVALID_HANDLE_VALUE == hFile)
        return ConvertWinErrorCode(GetLastError());

    DWORD dwFileSize = GetFileSize(hFile, NULL);
    DWORD dwBytesRead;
    char* buffer = (char*)malloc(dwFileSize);
    if (buffer && ReadFile(hFile, buffer, dwFileSize, &dwBytesRead, NULL)) {
        contents = std::string(buffer, dwFileSize);
    }
    else {
        if (!buffer)
            error = ERR_UNKNOWN;
        else
            error = ConvertWinErrorCode(GetLastError());
    }
    CloseHandle(hFile);
    if (buffer)
        free(buffer);

    return error;
}

int32 WriteFile(ExtensionString filename, std::string contents, ExtensionString encoding)
{
    if (encoding != L"utf8")
        return ERR_UNSUPPORTED_ENCODING;

    HANDLE hFile = CreateFile(filename.c_str(), GENERIC_WRITE,
        0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    DWORD dwBytesWritten;
    int error = NO_ERROR;

    if (INVALID_HANDLE_VALUE == hFile)
        return ConvertWinErrorCode(GetLastError(), false);

    // TODO (issue 67) -  Should write to temp file and handle encoding
    if (!WriteFile(hFile, contents.c_str(), contents.length(), &dwBytesWritten, NULL)) {
        error = ConvertWinErrorCode(GetLastError(), false);
    }

    CloseHandle(hFile);
    return error;
}

int32 SetPosixPermissions(ExtensionString filename, int32 mode)
{
    DWORD dwAttr = GetFileAttributes(filename.c_str());

    if (dwAttr == INVALID_FILE_ATTRIBUTES)
        return ERR_NOT_FOUND;

    if ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) != 0)
        return NO_ERROR;

    bool write = (mode & 0200) != 0;
    bool read = (mode & 0400) != 0;
    int mask = (write ? _S_IWRITE : 0) | (read ? _S_IREAD : 0);

    if (_wchmod(filename.c_str(), mask) == -1) {
        return ConvertErrnoCode(errno);
    }

    return NO_ERROR;
}

int32 DeleteFileOrDirectory(ExtensionString filename)
{
    DWORD dwAttr = GetFileAttributes(filename.c_str());

    if (dwAttr == INVALID_FILE_ATTRIBUTES)
        return ERR_NOT_FOUND;

    if ((dwAttr & FILE_ATTRIBUTE_DIRECTORY) != 0)
        return ERR_NOT_FILE;

    if (!DeleteFile(filename.c_str()))
        return ConvertWinErrorCode(GetLastError());

    return NO_ERROR;
}

void CloseWindow(CefRefPtr<CefBrowser> browser)
{
    if (browser.get() && g_handler.get()) {
        HWND browserHwnd = browser->GetHost()->GetWindowHandle();
        SetProp(browserHwnd, CLOSING_PROP, (HANDLE)1);
        browser->GetHost()->CloseBrowser();
    }
}

void BringBrowserWindowToFront(CefRefPtr<CefBrowser> browser)
{
    if (browser.get()) {
        HWND hwnd = browser->GetHost()->GetWindowHandle();
        if (hwnd)
            ::BringWindowToTop(hwnd);
    }
}

void ConvertToNativePath(ExtensionString& filename)
{
    // Convert '/' to '\'
    replace(filename.begin(), filename.end(), '/', '\\');
}

void ConvertToUnixPath(ExtensionString& filename)
{
    // Convert '\\' to '/'
    replace(filename.begin(), filename.end(), '\\', '/');
}

// Maps errors from errno.h to the brackets error codes
// found in brackets_extensions.js
int ConvertErrnoCode(int errorCode, bool isReading)
{
    switch (errorCode) {
    case NO_ERROR:
        return NO_ERROR;
    case EINVAL:
        return ERR_INVALID_PARAMS;
    case ENOENT:
        return ERR_NOT_FOUND;
    default:
        return ERR_UNKNOWN;
    }
}

// Maps errors from  WinError.h to the brackets error codes
// found in brackets_extensions.js
int ConvertWinErrorCode(int errorCode, bool isReading)
{
    switch (errorCode) {
    case NO_ERROR:
        return NO_ERROR;
    case ERROR_PATH_NOT_FOUND:
    case ERROR_FILE_NOT_FOUND:
        return ERR_NOT_FOUND;
    case ERROR_ACCESS_DENIED:
        return isReading ? ERR_CANT_READ : ERR_CANT_WRITE;
    case ERROR_WRITE_PROTECT:
        return ERR_CANT_WRITE;
    case ERROR_HANDLE_DISK_FULL:
        return ERR_OUT_OF_SPACE;
    default:
        return ERR_UNKNOWN;
    }
}

<|endoftext|>


<commit_before>#include "input.h"

InputHandler::InputHandler(sf::Window* Window, Player* Player, Renderer* Renderer) : app(Window), player(Player), renderer(Renderer) {
    app->ShowMouseCursor(false);
}

bool fullscreen = false;
void InputHandler::handleEvent(sf::Event Event) {
    // Close window : exit
    if (Event.Type == sf::Event::Closed)
        app->Close();

    // Escape key : exit
    if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape))
        app->Close();

    // Spacebar : jump
    if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Space))
        player->Jump();

    // F5 : regenerate terrain
    if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::F5))
        renderer->terrain.Regenerate();

    // F11 : toggle fullscreen
    if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::F11)) {
        fullscreen = !fullscreen;
        app->Close();
        app->Create(sf::VideoMode(800, 600, 32), "MineCube", (fullscreen ? sf::Style::Fullscreen : sf::Style::Resize|sf::Style::Close));

        renderer->InitGraphics();
        app->ShowMouseCursor(false);
    }

    // Resize event : adjust viewport
    if (Event.Type == sf::Event::Resized)
        glViewport(0, 0, Event.Size.Width, Event.Size.Height);
}

float ElapsedTime;
float mouseDeltaX, mouseDeltaY;

void InputHandler::handleEvents() {
    const sf::Input& Input = app->GetInput();

    // Constant movement speed
    ElapsedTime = Clock.GetElapsedTime();
    Clock.Reset();

    // Handle held keys
    if ((Input.IsKeyDown(sf::Key::S))) player->Forward(-ElapsedTime);
    if ((Input.IsKeyDown(sf::Key::W))) player->Forward( ElapsedTime);
    if ((Input.IsKeyDown(sf::Key::D))) player->Strafe(-ElapsedTime);
    if ((Input.IsKeyDown(sf::Key::A))) player->Strafe( ElapsedTime);
    if ((Input.IsKeyDown(sf::Key::Z))) player->Speed++;
    if ((Input.IsKeyDown(sf::Key::X))) player->Speed--;

    // Handle other events
    sf::Event Event;
    while (app->GetEvent(Event))
    {
        handleEvent(Event);
    }

    // Rotate view based on mouse movement
    mouseDeltaX = Input.GetMouseX() - 100;
    mouseDeltaY = Input.GetMouseY() - 100;
    app->SetCursorPosition(100, 100);

    if (!(mouseDeltaX == -100 && mouseDeltaY == -100) && !(mouseDeltaX == 0 && mouseDeltaY == 0))
        player->ChangeRotation((mouseDeltaY/10), (mouseDeltaX/10));

    player->DoStep(ElapsedTime);
}

<commit_msg>Don't need to close the window, as of 2008<commit_after>#include "input.h"

InputHandler::InputHandler(sf::Window* Window, Player* Player, Renderer* Renderer) : app(Window), player(Player), renderer(Renderer) {
    app->ShowMouseCursor(false);
}

bool fullscreen = false;
void InputHandler::handleEvent(sf::Event Event) {
    // Close window : exit
    if (Event.Type == sf::Event::Closed)
        app->Close();

    // Escape key : exit
    if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape))
        app->Close();

    // Spacebar : jump
    if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Space))
        player->Jump();

    // F5 : regenerate terrain
    if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::F5))
        renderer->terrain.Regenerate();

    // F11 : toggle fullscreen
    if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::F11)) {
        fullscreen = !fullscreen;
        app->Create(sf::VideoMode(800, 600, 32), "MineCube", (fullscreen ? sf::Style::Fullscreen : sf::Style::Resize|sf::Style::Close));

        renderer->InitGraphics();
        app->ShowMouseCursor(false);
    }

    // Resize event : adjust viewport
    if (Event.Type == sf::Event::Resized)
        glViewport(0, 0, Event.Size.Width, Event.Size.Height);
}

float ElapsedTime;
float mouseDeltaX, mouseDeltaY;

void InputHandler::handleEvents() {
    const sf::Input& Input = app->GetInput();

    // Constant movement speed
    ElapsedTime = Clock.GetElapsedTime();
    Clock.Reset();

    // Handle held keys
    if ((Input.IsKeyDown(sf::Key::S))) player->Forward(-ElapsedTime);
    if ((Input.IsKeyDown(sf::Key::W))) player->Forward( ElapsedTime);
    if ((Input.IsKeyDown(sf::Key::D))) player->Strafe(-ElapsedTime);
    if ((Input.IsKeyDown(sf::Key::A))) player->Strafe( ElapsedTime);
    if ((Input.IsKeyDown(sf::Key::Z))) player->Speed++;
    if ((Input.IsKeyDown(sf::Key::X))) player->Speed--;

    // Handle other events
    sf::Event Event;
    while (app->GetEvent(Event))
    {
        handleEvent(Event);
    }

    // Rotate view based on mouse movement
    mouseDeltaX = Input.GetMouseX() - 100;
    mouseDeltaY = Input.GetMouseY() - 100;
    app->SetCursorPosition(100, 100);

    if (!(mouseDeltaX == -100 && mouseDeltaY == -100) && !(mouseDeltaX == 0 && mouseDeltaY == 0))
        player->ChangeRotation((mouseDeltaY/10), (mouseDeltaX/10));

    player->DoStep(ElapsedTime);
}

<|endoftext|>


<commit_before>#include <errno.h>
#include <sys/ioctl.h>
#include "nan.h"

using namespace v8;
using namespace node;

NAN_METHOD(Ioctl) {
    NanScope();
    Local<Object> buf;
    int length = args.Length();

    assert((length == 2) || (length == 3));

    void* argp = NULL;

    if (!args[0]->IsInt32()) {
		NanThrowTypeError("Argument 0 Must be an Integer");
    }

    if (!args[1]->IsUint32()) {
		NanThrowTypeError("Argument 1 Must be an Integer");
    }

    if (length == 3) {
        if (args[2]->IsInt32()) {
            argp = reinterpret_cast<void*>(args[2]->Int32Value());
        } else {
            buf = args[2]->ToObject();
            if (!Buffer::HasInstance(buf)) {
                NanThrowTypeError("Argument 2 Must be an Integer or a Buffer");
            }

            argp = Buffer::Data(buf);
        }
    }

    int fd = args[0]->Int32Value();
    unsigned long request = args[1]->IntegerValue();
    int res = ioctl(fd, request, argp);
    if (res == -1) {
        res = -errno;
    }

    NanReturnValue(NanNew(res));
}

void InitAll(Handle<Object> exports) {
    exports->Set(NanNew("ioctl"),
                 NanNew<FunctionTemplate>(Ioctl)->GetFunction());
}

NODE_MODULE(ioctl, InitAll)

<commit_msg>src: fix the case when no ioctl third ioctl param<commit_after>#include <errno.h>
#include <sys/ioctl.h>
#include "nan.h"

using namespace v8;
using namespace node;

NAN_METHOD(Ioctl) {
    NanScope();
    Local<Object> buf;
    int length = args.Length();

    assert(length == 3);

    void* argp = NULL;

    if (!args[0]->IsInt32()) {
		NanThrowTypeError("Argument 0 Must be an Integer");
    }

    if (!args[1]->IsUint32()) {
		NanThrowTypeError("Argument 1 Must be an Integer");
    }

    if (!args[2]->IsUndefined()) {
        if (args[2]->IsInt32()) {
            argp = reinterpret_cast<void*>(args[2]->Int32Value());
        } else {
            buf = args[2]->ToObject();
            if (!Buffer::HasInstance(buf)) {
                NanThrowTypeError("Argument 2 Must be an Integer or a Buffer");
            }

            argp = Buffer::Data(buf);
        }
    }

    int fd = args[0]->Int32Value();
    unsigned long request = args[1]->IntegerValue();
    int res = ioctl(fd, request, argp);
    if (res == -1) {
        res = -errno;
    }

    NanReturnValue(NanNew(res));
}

void InitAll(Handle<Object> exports) {
    exports->Set(NanNew("ioctl"),
                 NanNew<FunctionTemplate>(Ioctl)->GetFunction());
}

NODE_MODULE(ioctl, InitAll)

<|endoftext|>


<commit_before>/*
 *
 * Copyright 2017 Asylo authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <arpa/inet.h>

#include "asylo/platform/arch/include/trusted/host_calls.h"

#ifdef __cplusplus
extern "C" {
#endif

static inline uint32_t flip_endian_32(uint32_t u32_in) {
  const char *in = reinterpret_cast<const char *>(&u32_in);
  char out[4];
  out[0] = in[3];
  out[1] = in[2];
  out[2] = in[1];
  out[3] = in[0];
  return *reinterpret_cast<uint32_t *>(out);
}

static inline uint16_t flip_endian_16(uint16_t u16_in) {
  const char *in = reinterpret_cast<const char *>(&u16_in);
  char out[2];
  out[0] = in[1];
  out[1] = in[0];
  return *reinterpret_cast<uint16_t *>(out);
}

uint32_t htonl(uint32_t hostlong) {
#ifdef __LITTLE_ENDIAN
  return flip_endian_32(hostlong);
#endif
  return hostlong;
}

uint16_t htons(uint16_t hostshort) {
#ifdef __LITTLE_ENDIAN
  return flip_endian_16(hostshort);
#endif
  return hostshort;
}

uint32_t ntohl(uint32_t netlong) {
#ifdef __LITTLE_ENDIAN
  return flip_endian_32(netlong);
#endif
  return netlong;
}

uint16_t ntohs(uint16_t netshort) {
#ifdef __LITTLE_ENDIAN
  return flip_endian_16(netshort);
#endif
  return netshort;
}

const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) {
  return enc_untrusted_inet_ntop(af, src, dst, size);
}

int inet_pton(int af, const char *src, void *dst) {
  return enc_untrusted_inet_pton(af, src, dst);
}

#ifdef __cplusplus
}  // extern "C"
#endif
<commit_msg>Update endianness swaps to use byteswap intrinsics<commit_after>/*
 *
 * Copyright 2017 Asylo authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#include <arpa/inet.h>
#include <byteswap.h>

#include "asylo/platform/arch/include/trusted/host_calls.h"

extern "C" {

uint32_t htonl(uint32_t hostlong) {
#ifdef __LITTLE_ENDIAN
  return bswap_32(hostlong);
#else
  return hostlong;
#endif
}

uint16_t htons(uint16_t hostshort) {
#ifdef __LITTLE_ENDIAN
  return bswap_16(hostshort);
#else
  return hostshort;
#endif
}

uint32_t ntohl(uint32_t netlong) {
#ifdef __LITTLE_ENDIAN
  return bswap_32(netlong);
#else
  return netlong;
#endif
}

uint16_t ntohs(uint16_t netshort) {
#ifdef __LITTLE_ENDIAN
  return bswap_16(netshort);
#else
  return netshort;
#endif
}

const char *inet_ntop(int af, const void *src, char *dst, socklen_t size) {
  return enc_untrusted_inet_ntop(af, src, dst, size);
}

int inet_pton(int af, const char *src, void *dst) {
  return enc_untrusted_inet_pton(af, src, dst);
}

}  // extern "C"
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include "gomory_lex.h"

GomoryLex::GomoryLex(const rapidjson::Value& root) : GomoryNaive(root) {
	original_obj_coeffs = (double*)malloc(num_vars*sizeof(double));
	del_lex_constr_ids = (int*)malloc(num_vars*sizeof(int));
	grb_error = GRBgetdblattrlist(model, GRB_DBL_ATTR_OBJ, num_vars,
	                              cut_coeff_ids, original_obj_coeffs);
	grb_error = GRBgetintattr(model, "NumConstrs", &original_num_constrs);
}

GomoryLex::~GomoryLex(void) {
	free(del_lex_constr_ids);
	free(original_obj_coeffs);
}

void GomoryLex::LexSimplex(void) {
	grb_error = GRBgetintattr(model, "NumConstrs", &num_constrs);

	double sol_i;
	grb_error = GRBgetdblattrelement(model, "X", 0, &sol_i);

	int id[1] = {0};
	double vid[1] = {1.0};
	grb_error = GRBaddconstr(model, 1, id, vid, GRB_EQUAL, sol_i, NULL);
	del_lex_constr_ids[0] = num_constrs;

	for (unsigned int j = 1; j < num_vars; j++) {
		for (unsigned int k = 0; k < num_vars; k++) {
			if (k == j) {
				grb_error = GRBsetdblattrelement(model, GRB_DBL_ATTR_OBJ, k, 1.0);
			} else {
				grb_error = GRBsetdblattrelement(model, GRB_DBL_ATTR_OBJ, k, 0.0);
			}
		}

		grb_error = GRBoptimize(model);

		int id[1] = {j};
		double vid[1] = {1.0};

		double sol_j;
		grb_error = GRBgetdblattrelement(model, "X", j, &sol_j);
		grb_error = GRBaddconstr(model, 1, id, vid, GRB_EQUAL, sol_j, NULL);
		del_lex_constr_ids[j] = num_constrs + j;
	}

	grb_error = GRBoptimize(model);

	// Restore the objective to that of the original problem.
	for (unsigned int j = 0; j < num_vars; j++) {
		grb_error = GRBsetdblattrelement(model, GRB_DBL_ATTR_OBJ, j, original_obj_coeffs[j]);
	}

	grb_error = GRBdelconstrs(model, num_vars, del_lex_constr_ids);
	grb_error = GRBoptimize(model);
}

int GomoryLex::PurgeCuts(void) {
	grb_error = GRBgetintattr(model, "NumConstrs", &num_constrs);
	std::vector<int> purge_cut_ids;

	for (int i = original_num_constrs; i < num_constrs; i++) {
		double constraint_slack;
		grb_error = GRBgetdblattrelement(model, "Slack", i, &constraint_slack);

		if (fabs(constraint_slack) > 1.0e-6) {
			purge_cut_ids.push_back(i);
		}
	}

	grb_error = GRBdelconstrs(model, (int)purge_cut_ids.size(), purge_cut_ids.data());
	grb_error = GRBoptimize(model);
	return purge_cut_ids.size();
}

int GomoryLex::Step(void) {
	if (objective_value != old_objective_value || iter_since_purge >= 1000) {
		iter_since_purge = 0;
		int num_constrs_purged = PurgeCuts();
		old_objective_value = objective_value;
	}

	UpdateBasisData();
	//int cut_id = GetLeastFractionalIndex();
	//int cut_id = GetMostFractionalIndex();
	int cut_id = GetRandomIndex();
	//int cut_id = *frac_int_vars.begin();

	if (num_vars == num_int_vars) {
		// If all of the variables were integer, use the pure integer cut.
		LexSimplex();
		num_cuts += AddPureCut(cut_id);
	} else {
		// Otherwise, use the mixed-integer cut.
		LexSimplex();
		num_cuts += AddMixedCut(cut_id);
	}

	grb_error = GRBoptimize(model);
	grb_error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objective_value);
	iter_since_purge++;

	return UpdateVariableData();
}

void GomoryLex::Run(void) {
	grb_error = GRBoptimize(model);
	grb_error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objective_value);
	old_objective_value = objective_value;
	int num_frac_vars = UpdateVariableData();
	iter_since_purge = 0;

	while (num_frac_vars > 0) {
		num_frac_vars = Step();
		PrintStep();
	}

	grb_error = GRBwrite(model, solution_path.c_str());
}
<commit_msg>Updating lexicographic method.<commit_after>#include <iostream>
#include <vector>
#include "gomory_lex.h"

GomoryLex::GomoryLex(const rapidjson::Value& root) : GomoryNaive(root) {
	original_obj_coeffs = (double*)malloc(num_vars*sizeof(double));
	del_lex_constr_ids = (int*)malloc(num_vars*sizeof(int));
	grb_error = GRBgetdblattrlist(model, GRB_DBL_ATTR_OBJ, num_vars,
	                              cut_coeff_ids, original_obj_coeffs);
	grb_error = GRBgetintattr(model, "NumConstrs", &original_num_constrs);
}

GomoryLex::~GomoryLex(void) {
	free(del_lex_constr_ids);
	free(original_obj_coeffs);
}

void GomoryLex::LexSimplex(void) {
	grb_error = GRBgetintattr(model, "NumConstrs", &num_constrs);

	double sol_i;
	grb_error = GRBgetdblattrelement(model, "X", 0, &sol_i);

	int id[1] = {0};
	double vid[1] = {1.0};
	grb_error = GRBaddconstr(model, 1, id, vid, GRB_EQUAL, sol_i, NULL);
	del_lex_constr_ids[0] = num_constrs;

	for (unsigned int j = 1; j < num_vars; j++) {
		for (unsigned int k = 0; k < num_vars; k++) {
			if (k == j) {
				grb_error = GRBsetdblattrelement(model, GRB_DBL_ATTR_OBJ, k, 1.0);
			} else {
				grb_error = GRBsetdblattrelement(model, GRB_DBL_ATTR_OBJ, k, 0.0);
			}
		}

		grb_error = GRBoptimize(model);

		int id[1] = {j};
		double vid[1] = {1.0};

		double sol_j;
		grb_error = GRBgetdblattrelement(model, "X", j, &sol_j);
		grb_error = GRBaddconstr(model, 1, id, vid, GRB_EQUAL, sol_j, NULL);
		del_lex_constr_ids[j] = num_constrs + j;
	}

	grb_error = GRBoptimize(model);

	// Restore the objective to that of the original problem.
	for (unsigned int j = 0; j < num_vars; j++) {
		grb_error = GRBsetdblattrelement(model, GRB_DBL_ATTR_OBJ, j, original_obj_coeffs[j]);
	}

	grb_error = GRBdelconstrs(model, num_vars, del_lex_constr_ids);
	grb_error = GRBoptimize(model);
}

int GomoryLex::PurgeCuts(void) {
	grb_error = GRBgetintattr(model, "NumConstrs", &num_constrs);
	std::vector<int> purge_cut_ids;

	for (int i = original_num_constrs; i < num_constrs; i++) {
		double constraint_slack;
		grb_error = GRBgetdblattrelement(model, "Slack", i, &constraint_slack);

		if (fabs(constraint_slack) > 1.0e-6) {
			purge_cut_ids.push_back(i);
		}
	}

	grb_error = GRBdelconstrs(model, (int)purge_cut_ids.size(), purge_cut_ids.data());
	grb_error = GRBoptimize(model);
	return purge_cut_ids.size();
}

int GomoryLex::Step(void) {
	if (objective_value != old_objective_value || iter_since_purge >= original_num_constrs * 10) {
		iter_since_purge = 0;
		int num_constrs_purged = PurgeCuts();
		old_objective_value = objective_value;
	}

	UpdateBasisData();
	//int cut_id = GetLeastFractionalIndex();
	//int cut_id = GetMostFractionalIndex();
	int cut_id = GetRandomIndex();
	//int cut_id = *frac_int_vars.begin();

	if (num_vars == num_int_vars) {
		// If all of the variables were integer, use the pure integer cut.
		LexSimplex();
		num_cuts += AddPureCut(cut_id);
	} else {
		// Otherwise, use the mixed-integer cut.
		LexSimplex();
		num_cuts += AddMixedCut(cut_id);
	}

	grb_error = GRBoptimize(model);
	grb_error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objective_value);
	iter_since_purge++;

	return UpdateVariableData();
}

void GomoryLex::Run(void) {
	grb_error = GRBoptimize(model);
	grb_error = GRBgetdblattr(model, GRB_DBL_ATTR_OBJVAL, &objective_value);
	old_objective_value = objective_value;
	int num_frac_vars = UpdateVariableData();
	iter_since_purge = 0;

	while (num_frac_vars > 0) {
		num_frac_vars = Step();
		PrintStep();
	}

	grb_error = GRBwrite(model, solution_path.c_str());
}
<|endoftext|>


<commit_before>#include "atlas/hlr/LoadLibrary.hpp"

#include <atlas/core/Platform.hpp>
#include <fmt/printf.h>

#if defined(ATLAS_PLATFORM_WINDOWS)
#    define WIN32_LEAN_AND_MEAN
#    include <windows.h>
#endif

namespace atlas::hlr
{
#if defined(ATLAS_PLATFORM_WINDOWS)
    void* loadLibraryHandle(std::string const& libraryName)
    {
        void* handle = LoadLibrary(libraryName.c_str());
        if (handle == nullptr)
        {
            auto errorCode = GetLastError();
            fmt::print(stderr, "error: LoadLibrary returned error code {}\n",
                       errorCode);
        }

        return handle;
    }

    void* loadRawFunctionPtr(void* handle, std::string const& functionName)
    {
        if (handle == nullptr)
        {
            fmt::print(stderr, "error: null library handle\n");
            return nullptr;
        }

        HMODULE h = reinterpret_cast<HMODULE>(handle);

        FARPROC procAddress = GetProcAddress(h, functionName.c_str());
        if (procAddress == nullptr)
        {
            auto errorCode = GetLastError();
            fmt::print(stderr, "error: GetProcAddress returned error code {}\n",
                       errorCode);
        }

        return procAddress;
    }

    void unloadLibraryHandle(void* handle)
    {
        HMODULE h = reinterpret_cast<HMODULE>(handle);
        FreeLibrary(h);
    }
#else
#endif
} // namespace atlas::hlr
<commit_msg>[brief] Tidies up HLR module.<commit_after>#include "atlas/hlr/LoadLibrary.hpp"

#include <atlas/core/Platform.hpp>
#include <fmt/printf.h>

#if defined(ATLAS_PLATFORM_WINDOWS)
#    define WIN32_LEAN_AND_MEAN
#    include <windows.h>
#endif

namespace atlas::hlr
{
#if defined(ATLAS_PLATFORM_WINDOWS)
    void* loadLibraryHandle(std::string const& libraryName)
    {
        void* handle = LoadLibrary(libraryName.c_str());
        if (handle == nullptr)
        {
            auto errorCode = GetLastError();
            fmt::print(stderr, "error: LoadLibrary returned error code {}\n",
                       errorCode);
        }

        return handle;
    }

    void* loadRawFunctionPtr(void* handle, std::string const& functionName)
    {
        if (handle == nullptr)
        {
            fmt::print(stderr, "error: null library handle\n");
            return nullptr;
        }

        auto h = reinterpret_cast<HMODULE>(handle);

        FARPROC procAddress = GetProcAddress(h, functionName.c_str());
        if (procAddress == nullptr)
        {
            auto errorCode = GetLastError();
            fmt::print(stderr, "error: GetProcAddress returned error code {}\n",
                       errorCode);
        }

        return procAddress;
    }

    void unloadLibraryHandle(void* handle)
    {
        auto h = reinterpret_cast<HMODULE>(handle);
        FreeLibrary(h);
    }
#else
#endif
} // namespace atlas::hlr
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ik_exception.hxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: np $ $Date: 2002-11-01 17:11: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 ARY_IDL_IK_EXCEPTION_HXX
#define ARY_IDL_IK_EXCEPTION_HXX

// USED SERVICES
    // BASE CLASSES
#include <ary/idl/ik_ce.hxx>
    // COMPONENTS
    // PARAMETERS

namespace ary
{
namespace idl
{

namespace ifc_exception
{

using ifc_ce::Dyn_CeIterator;
using ifc_ce::DocText;

struct attr: public ifc_ce::attr
{
    static Type_id      Base(
                            const CodeEntity &  i_ce );
    static void         Get_Elements(
                            Dyn_CeIterator &    o_result,
                            const CodeEntity &  i_ce );
};

struct xref : public ifc_ce::xref
{
    static void         Get_Derivations(
                            Dyn_CeIterator &    o_result,
                            const CodeEntity &  i_ce );
    static void         Get_RaisingFunctions(
                            Dyn_CeIterator &    o_result,
                            const CodeEntity &  i_ce );
};

struct doc : public ifc_ce::doc
{
};

}   // namespace ifc_exception

}   // namespace idl
}   // namespace ary

#endif

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

#ifndef ARY_IDL_IK_EXCEPTION_HXX
#define ARY_IDL_IK_EXCEPTION_HXX

// USED SERVICES
    // BASE CLASSES
#include <ary/idl/ik_ce.hxx>
    // COMPONENTS
    // PARAMETERS

namespace ary
{
namespace idl
{

namespace ifc_exception
{

using ifc_ce::Dyn_CeIterator;
using ifc_ce::DocText;

struct attr: public ifc_ce::attr
{
    static Type_id      Base(
                            const CodeEntity &  i_ce );
    static void         Get_Elements(
                            Dyn_CeIterator &    o_result,
                            const CodeEntity &  i_ce );
};

struct xref : public ifc_ce::xref
{
    static void         Get_Derivations(
                            Dyn_CeIterator &    o_result,
                            const CodeEntity &  i_ce );
    static void         Get_RaisingFunctions(
                            Dyn_CeIterator &    o_result,
                            const CodeEntity &  i_ce );
};

struct doc : public ifc_ce::doc
{
};

}   // namespace ifc_exception

}   // namespace idl
}   // namespace ary

#endif

<|endoftext|>


<commit_before>extern "C" void kmain(void* /*mbd*/, u32 magic)
{
   if ( magic != 0x2BADB002 )
   {
      /* Something went not according to specs. Print an error */
      /* message and halt, but do *not* rely on the multiboot */
      /* data structure. */
   }

   /* You could either use multiboot.h */
   /* (http://www.gnu.org/software/grub/manual/multiboot/multiboot.html#multiboot_002eh) */
   /* or do your offsets yourself. The following is merely an example. */
   //char * boot_loader_name =(char*) ((long*)mbd)[16];

   /* Print a letter to screen to see everything is working: */
   unsigned char *videoram = (unsigned char *) 0xb8000;
   int arr[5] = {0, 2, 4, 6, 8};
   for(int x : arr) {
      videoram[x] = 65; /* character 'A' */
      videoram[x+1] = 0x07; /* light grey (7) on black (0). */
   }
}

<commit_msg>Add barebones VGA text-mode display driver.<commit_after>const int console_width = 80;
const int console_height = 25;
const u8 color = 0x07; /* light grey (7) on black (0). */

u16 volatile* videoram = (u16 volatile*) 0xb8000;

void clear_screen() {
   for(int i = 0; i < console_height * console_width; i++)
      videoram[i] = (color << 8) | ' ';
}

void put_char_at(char c, int row, int col) {
   videoram[row * console_width + col] = (color << 8) | c;
}

int position = 0;
void put_char(char c) {
   put_char_at(c, 0, position); // TODO Handle end of line wrapping.
   position++;
}

void put_string(const char* str) {
   for(int i = 0; str[i]; i++)
      put_char(str[i]);
}

extern "C" void kmain(void* /*mbd*/, u32 magic)
{
   if ( magic != 0x2BADB002 )
   {
      /* Something went not according to specs. Print an error */
      /* message and halt, but do *not* rely on the multiboot */
      /* data structure. */
   }

   /* You could either use multiboot.h */
   /* (http://www.gnu.org/software/grub/manual/multiboot/multiboot.html#multiboot_002eh) */
   /* or do your offsets yourself. The following is merely an example. */
   //char * boot_loader_name =(char*) ((long*)mbd)[16];

   /* Print a string to screen to see everything is working: */
   clear_screen();
   put_string("This is a test!");
}

<|endoftext|>


<commit_before>/******************************************************************************
*   Copyright (C) 2010 by Robert Tolliver                                     *
*   Robb.Tolli@gmail.com                                                      *
*                                                                             *
*   This file is part of Birthstone.                                          *
*                                                                             *
*   Birthstone is free software: you can redistribute it and/or modify        *
*   it under the terms of the GNU General Public License as published by      *
*   the Free Software Foundation, either version 3 of the License, or         *
*  (at your option) any later version.                                        *
*                                                                             *
*   Birthstone is distributed in the hope that it will be useful,             *
*   but WITHOUT ANY WARRANTY; without even the implied warranty of            *
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             *
*   GNU General Public License for more details.                              *
*                                                                             *
*   You should have received a copy of the GNU General Public License         *
*   along with Birthstone.  If not, see <http://www.gnu.org/licenses/>.       *
*                                                                             *
******************************************************************************/

#include "lexer.h"
#include <ostream>
#include <cctype>
#include <cstdlib>
#include <iostream>
#include <sstream>

std::map <std::string, Token> Lexer::sKeywords;

Lexer::Lexer(std::istream &input)
   : mInput(&input), mLineNum(1), mToken(Sym::END)
{
	 setupKeywords();
}

Lexer::Lexer(const Lexer &lexer)
	: mInput(lexer.mInput), mLineNum(1), mToken(Sym::END)
{}

Lexer::~Lexer() {}

void Lexer::setupKeywords()
{
	if (sKeywords.empty())
	{
		sKeywords["if"]       =	Sym::IF;
		sKeywords["elif"]     = Sym::ELIF;
		sKeywords["else"]     =	Sym::ELSE;
		sKeywords["while"]    =	Sym::WHILE;
		sKeywords["until"]    =	Sym::UNTIL;
		sKeywords["for"]      =	Sym::FOR;
		sKeywords["in"]       =	Sym::IN;
		sKeywords["break"]    =	Sym::BREAK;
		sKeywords["continue"] =	Sym::CONT;
		sKeywords["read"] 	 =	Sym::READ;
		sKeywords["write"] 	 =	Sym::WRITE;
		sKeywords["print"] 	 =	Sym::PRINT;
		sKeywords["def"] 		 =	Sym::DEF;
		sKeywords["class"] 	 = Sym::CLASS;

      sKeywords["and"]		 = Sym::AND;
		sKeywords["or"]		 =	Sym::OR;
		sKeywords["not"]		 =	Sym::NOT;

		sKeywords["true"]     = Token(Sym::BOOL, true);
		sKeywords["false"]    = Token(Sym::BOOL, false);

		sKeywords["exit"]     = Sym::QUIT;
		sKeywords["quit"]     = Sym::QUIT;
	}
}

const Token &Lexer::getNext()
{

	char ch = mInput->peek();

	if (mInput->eof())
		mToken = Token(Sym::END);
	else if (ch == '#')
	{
		do
		{
			mInput->get();
			ch = mInput->peek();
		} while (!(mInput->eof()) && (ch != '\n'));
		++mLineNum;
		mInput->get();
		return getNext();
	}
	else if (ch == ' ' || ch == '\t')
	{
		mInput->get();
		return getNext();
	}
	else if (ch == '\n')
	{
		++mLineNum;
		mInput->get();
		return getNext();
	}

	else if (ch == '(')
	{
		mInput->get();
		mToken = Sym::O_PARAN;
	}
	else if (ch == ')')
	{
		mInput->get();
		mToken = Sym::C_PARAN;
	}
	else if (ch == '[')
	{
		mInput->get();
		mToken = Sym::O_BRACKET;
	}
	else if (ch == ']')
	{
		mInput->get();
		mToken = Sym::C_BRACKET;
	}
	else if (ch == '{')
	{
		mInput->get();
		mToken = Sym::O_BRACE;
	}
	else if (ch == '}')
	{
		mInput->get();
		mToken = Sym::C_BRACE;
	}
	else if (ch == ';')
	{
		mInput->get();
		mToken = Sym::SC;
	}
	else if (ch == ',')
	{
		mInput->get();
		mToken = Sym::COMMA;
	}
	else if (isalpha(ch) || ch == '_')
	{
		std::string mTokenStr;
		mTokenStr.reserve(20);
		do
		{
			mTokenStr += ch;
			mInput->get();
			ch = mInput->peek();
		} while (!(mInput->eof()) && (isalnum(ch) || ch == '_'));

		std::map <std::string, Token>::iterator it = sKeywords.find(mTokenStr);
		if (it != sKeywords.end()) // keyword
			mToken = it->second;
		else //identifier
			mToken = Token(Sym::ID, mTokenStr);
	}
   else if ((ch == '"') || (ch == '\''))
	{
      char quote = ch;
		std::string mTokenStr;
		mTokenStr.reserve(20);

		mInput->get();
		ch = mInput->peek();

      while (!(mInput->eof()) && (ch != quote))
		{
			if (ch == '\\')
			{
				mInput->get();
				ch = mInput->peek();
				switch (ch)
				{
					case 't':
						ch = '\t';
						break;
					case 'n':
						ch = '\n';
						break;
					// \\, \', \" will work because we just want to add the
					//     character after the \ to the string
				}
			}
			mTokenStr += ch;
			mInput->get();
			ch = mInput->peek();

		}
		mInput->get();
		mToken = Token(Sym::STR, mTokenStr);
	}
	else if (ch == '+')
	{
		mInput->get();
		ch = mInput->peek();
		if (ch == '=')
		{
			mInput->get();
			mToken = Sym::PLUS_EQ;
		}
		else
			mToken = Sym::PLUS;
	}
	else if (ch == '*')
	{
		mInput->get();
		mToken = Sym::TIMES;
	}
	else if (ch == '/')
	{
		mInput->get();
		mToken = Sym::DIVIDE;
	}
	else if ((ch == '-') || (ch == '.') || isdigit(ch))
	{
		bool minus    = false;
		std::string mTokenStr;
		mTokenStr.reserve(10);

		if (ch == '-')
		{
			mInput->get();
			ch = mInput->peek();
			if ((!isdigit(ch) && (ch != '.'))
				|| (mToken.getType() == Sym::NUM) || (mToken.getType() == Sym::ID)
				|| (mToken.getType() == Sym::STR))
				minus = true;
			else
				mTokenStr += '-';
		}
		if (minus)
			mToken = Token(Sym::MINUS);
		else
		{
			bool foundPoint = false;
			do
			{
				foundPoint = (ch == '.') || foundPoint;
				mTokenStr += ch;
				mInput->get();
				ch = mInput->peek();
			} while(!(mInput->eof()) && (isdigit(ch) || (!foundPoint && (ch == '.'))));
			mToken = Token(Sym::NUM, atof(mTokenStr.c_str()));
		}
	}
	else if (ch == '<')
	{
		mInput->get();
		ch = mInput->peek();
		if (ch == '=')
		{
			mInput->get();
			mToken = Token(Sym::LESS_EQ);
		}
		else
			mToken = Token(Sym::LESS);
	}
	else if (ch == '>')
	{
		mInput->get();
		ch = mInput->peek();
		if (ch == '=')
		{
			mInput->get();
			mToken = Token(Sym::GREATER_EQ);
		}
		else
			mToken = Token(Sym::GREATER);
	}
	else if (ch == '=')
	{
		mInput->get();
		ch = mInput->peek();
		if (ch == '=')
		{
			mInput->get();
			mToken = Token(Sym::EQ);
		}
		else
			mToken = Token(Sym::ASSIGN);
	}
	else if (ch == '&')
	{
		mInput->get();
		ch = mInput->peek();
		if (ch == '&')
		{
			mInput->get();
			mToken = Token(Sym::AND);
		}
		else
			mToken = Token(Sym::FAIL, std::string("expected: \"&&\" found \"&") + ch + "\"");
	}

	else if (ch == '|')
	{
		mInput->get();
		ch = mInput->peek();
		if (ch == '|')
		{
			mInput->get();
			mToken = Token(Sym::OR);
		}
		else
			mToken = Token(Sym::FAIL, std::string("expected: \"||\" found \"|") + ch + "\"");
	}
	else if (ch == '!')
	{
		mInput->get();
		ch = mInput->peek();
		if (ch == '=')
		{
			mInput->get();
			mToken = Token(Sym::NOT_EQ);
		}
		else
			mToken = Token(Sym::NOT);
	}
	else if (ch == ':')
	{
		mInput->get();
		ch = mInput->peek();
		if (ch == '=')
		{
			mInput->get();
			mToken = Token(Sym::INIT);
		}
		else
			mToken = Token(Sym::FAIL, std::string("expected: ':=' found ':") + ch + "'");
	}
	else
	{
		mInput->get();
		mToken = Token(Sym::FAIL, std::string("Invalid mToken: '") + ch + '\'');
	}

	return mToken;
}

unsigned int Lexer::getLine() const { return mLineNum; }

Lexer &Lexer::operator=(const Lexer &lexer)
{
		mInput = lexer.mInput;
}

#ifdef BS_LEXER_DEBUG

#include <iostream>
#include <sstream>
	int main ()
	{

		while (true)
		{
			std::string str;
			std::stringstream stream;
			std::cout << "Type some commands (Ctrl-C to exit): ";
			std::getline(std::cin, str);
			stream.str(str);
			Lexer lex(stream);
			Token token = lex.getNext();

			std::cout << "   ";
			while ((token.getType() != Sym::END) /*&& (token.getType() != FAIL)*/)
			{
 				std::cout << token << ' ';
				token = lex.getNext();
			}
			// 			std::cFAIL << token; // show the <END> token
			std::cout << std::endl;
		}
	}

#endif // BS_LEXER_DEBUG

<commit_msg>added escaped newlines in strings<commit_after>/******************************************************************************
*   Copyright (C) 2010 by Robert Tolliver                                     *
*   Robb.Tolli@gmail.com                                                      *
*                                                                             *
*   This file is part of Birthstone.                                          *
*                                                                             *
*   Birthstone is free software: you can redistribute it and/or modify        *
*   it under the terms of the GNU General Public License as published by      *
*   the Free Software Foundation, either version 3 of the License, or         *
*  (at your option) any later version.                                        *
*                                                                             *
*   Birthstone is distributed in the hope that it will be useful,             *
*   but WITHOUT ANY WARRANTY; without even the implied warranty of            *
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             *
*   GNU General Public License for more details.                              *
*                                                                             *
*   You should have received a copy of the GNU General Public License         *
*   along with Birthstone.  If not, see <http://www.gnu.org/licenses/>.       *
*                                                                             *
******************************************************************************/

#include "lexer.h"
#include <ostream>
#include <cctype>
#include <cstdlib>
#include <iostream>
#include <sstream>

std::map <std::string, Token> Lexer::sKeywords;

Lexer::Lexer(std::istream &input)
   : mInput(&input), mLineNum(1), mToken(Sym::END)
{
	 setupKeywords();
}

Lexer::Lexer(const Lexer &lexer)
	: mInput(lexer.mInput), mLineNum(1), mToken(Sym::END)
{}

Lexer::~Lexer() {}

void Lexer::setupKeywords()
{
	if (sKeywords.empty())
	{
		sKeywords["if"]       =	Sym::IF;
		sKeywords["elif"]     = Sym::ELIF;
		sKeywords["else"]     =	Sym::ELSE;
		sKeywords["while"]    =	Sym::WHILE;
		sKeywords["until"]    =	Sym::UNTIL;
		sKeywords["for"]      =	Sym::FOR;
		sKeywords["in"]       =	Sym::IN;
		sKeywords["break"]    =	Sym::BREAK;
		sKeywords["continue"] =	Sym::CONT;
		sKeywords["read"] 	 =	Sym::READ;
		sKeywords["write"] 	 =	Sym::WRITE;
		sKeywords["print"] 	 =	Sym::PRINT;
		sKeywords["def"] 		 =	Sym::DEF;
		sKeywords["class"] 	 = Sym::CLASS;

      sKeywords["and"]		 = Sym::AND;
		sKeywords["or"]		 =	Sym::OR;
		sKeywords["not"]		 =	Sym::NOT;

		sKeywords["true"]     = Token(Sym::BOOL, true);
		sKeywords["false"]    = Token(Sym::BOOL, false);

		sKeywords["exit"]     = Sym::QUIT;
		sKeywords["quit"]     = Sym::QUIT;
	}
}

const Token &Lexer::getNext()
{

	char ch = mInput->peek();

	if (mInput->eof())
		mToken = Token(Sym::END);
	else if (ch == '#')
	{
		do
		{
			mInput->get();
			ch = mInput->peek();
		} while (!(mInput->eof()) && (ch != '\n'));
		++mLineNum;
		mInput->get();
		return getNext();
	}
	else if (ch == ' ' || ch == '\t')
	{
		mInput->get();
		return getNext();
	}
	else if (ch == '\n')
	{
		++mLineNum;
		mInput->get();
		return getNext();
	}

	else if (ch == '(')
	{
		mInput->get();
		mToken = Sym::O_PARAN;
	}
	else if (ch == ')')
	{
		mInput->get();
		mToken = Sym::C_PARAN;
	}
	else if (ch == '[')
	{
		mInput->get();
		mToken = Sym::O_BRACKET;
	}
	else if (ch == ']')
	{
		mInput->get();
		mToken = Sym::C_BRACKET;
	}
	else if (ch == '{')
	{
		mInput->get();
		mToken = Sym::O_BRACE;
	}
	else if (ch == '}')
	{
		mInput->get();
		mToken = Sym::C_BRACE;
	}
	else if (ch == ';')
	{
		mInput->get();
		mToken = Sym::SC;
	}
	else if (ch == ',')
	{
		mInput->get();
		mToken = Sym::COMMA;
	}
	else if (isalpha(ch) || ch == '_')
	{
		std::string mTokenStr;
		mTokenStr.reserve(20);
		do
		{
			mTokenStr += ch;
			mInput->get();
			ch = mInput->peek();
		} while (!(mInput->eof()) && (isalnum(ch) || ch == '_'));

		std::map <std::string, Token>::iterator it = sKeywords.find(mTokenStr);
		if (it != sKeywords.end()) // keyword
			mToken = it->second;
		else //identifier
			mToken = Token(Sym::ID, mTokenStr);
	}
   else if ((ch == '"') || (ch == '\''))
	{
      char quote = ch;
		std::string mTokenStr;
		mTokenStr.reserve(20);

		mInput->get();
		ch = mInput->peek();

      while (!(mInput->eof()) && (ch != quote))
		{
			if (ch == '\\')
			{
				mInput->get();
				ch = mInput->peek();
				switch (ch)
				{
					case '\n':
						ch = mInput->peek();
						break;
					case '\r':
						ch = mInput->peek();
						if (ch == '\n')
							ch = mInput->peek();
						break;
					case 't':
						ch = '\t';
						break;
					case 'n':
						ch = '\n';
						break;
					// \\, \', \" will work because we just want to add the
					//     character after the \ to the string
				}
			}
			mTokenStr += ch;
			mInput->get();
			ch = mInput->peek();

		}
		mInput->get();
		mToken = Token(Sym::STR, mTokenStr);
	}
	else if (ch == '+')
	{
		mInput->get();
		ch = mInput->peek();
		if (ch == '=')
		{
			mInput->get();
			mToken = Sym::PLUS_EQ;
		}
		else
			mToken = Sym::PLUS;
	}
	else if (ch == '*')
	{
		mInput->get();
		mToken = Sym::TIMES;
	}
	else if (ch == '/')
	{
		mInput->get();
		mToken = Sym::DIVIDE;
	}
	else if ((ch == '-') || (ch == '.') || isdigit(ch))
	{
		bool minus    = false;
		std::string mTokenStr;
		mTokenStr.reserve(10);

		if (ch == '-')
		{
			mInput->get();
			ch = mInput->peek();
			if ((!isdigit(ch) && (ch != '.'))
				|| (mToken.getType() == Sym::NUM) || (mToken.getType() == Sym::ID)
				|| (mToken.getType() == Sym::STR))
				minus = true;
			else
				mTokenStr += '-';
		}
		if (minus)
			mToken = Token(Sym::MINUS);
		else
		{
			bool foundPoint = false;
			do
			{
				foundPoint = (ch == '.') || foundPoint;
				mTokenStr += ch;
				mInput->get();
				ch = mInput->peek();
			} while(!(mInput->eof()) && (isdigit(ch) || (!foundPoint && (ch == '.'))));
			mToken = Token(Sym::NUM, atof(mTokenStr.c_str()));
		}
	}
	else if (ch == '<')
	{
		mInput->get();
		ch = mInput->peek();
		if (ch == '=')
		{
			mInput->get();
			mToken = Token(Sym::LESS_EQ);
		}
		else
			mToken = Token(Sym::LESS);
	}
	else if (ch == '>')
	{
		mInput->get();
		ch = mInput->peek();
		if (ch == '=')
		{
			mInput->get();
			mToken = Token(Sym::GREATER_EQ);
		}
		else
			mToken = Token(Sym::GREATER);
	}
	else if (ch == '=')
	{
		mInput->get();
		ch = mInput->peek();
		if (ch == '=')
		{
			mInput->get();
			mToken = Token(Sym::EQ);
		}
		else
			mToken = Token(Sym::ASSIGN);
	}
	else if (ch == '&')
	{
		mInput->get();
		ch = mInput->peek();
		if (ch == '&')
		{
			mInput->get();
			mToken = Token(Sym::AND);
		}
		else
			mToken = Token(Sym::FAIL, std::string("expected: \"&&\" found \"&") + ch + "\"");
	}

	else if (ch == '|')
	{
		mInput->get();
		ch = mInput->peek();
		if (ch == '|')
		{
			mInput->get();
			mToken = Token(Sym::OR);
		}
		else
			mToken = Token(Sym::FAIL, std::string("expected: \"||\" found \"|") + ch + "\"");
	}
	else if (ch == '!')
	{
		mInput->get();
		ch = mInput->peek();
		if (ch == '=')
		{
			mInput->get();
			mToken = Token(Sym::NOT_EQ);
		}
		else
			mToken = Token(Sym::NOT);
	}
	else if (ch == ':')
	{
		mInput->get();
		ch = mInput->peek();
		if (ch == '=')
		{
			mInput->get();
			mToken = Token(Sym::INIT);
		}
		else
			mToken = Token(Sym::FAIL, std::string("expected: ':=' found ':") + ch + "'");
	}
	else
	{
		mInput->get();
		mToken = Token(Sym::FAIL, std::string("Invalid mToken: '") + ch + '\'');
	}

	return mToken;
}

unsigned int Lexer::getLine() const { return mLineNum; }

Lexer &Lexer::operator=(const Lexer &lexer)
{
		mInput = lexer.mInput;
}

#ifdef BS_LEXER_DEBUG

#include <iostream>
#include <sstream>
	int main ()
	{

		while (true)
		{
			std::string str;
			std::stringstream stream;
			std::cout << "Type some commands (Ctrl-C to exit): ";
			std::getline(std::cin, str);
			stream.str(str);
			Lexer lex(stream);
			Token token = lex.getNext();

			std::cout << "   ";
			while ((token.getType() != Sym::END) /*&& (token.getType() != FAIL)*/)
			{
 				std::cout << token << ' ';
				token = lex.getNext();
			}
			// 			std::cFAIL << token; // show the <END> token
			std::cout << std::endl;
		}
	}

#endif // BS_LEXER_DEBUG

<|endoftext|>