<commit_before>/*
   This file is part of KDE Kontact.

   Copyright (c) 2001 Matthias Hoelzer-Kluepfel <mhk@kde.org>
   Copyright (c) 2002-2003 Daniel Molkentin <molkentin@kde.org>
   Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "core.h"

#include <kparts/part.h>
#include <kparts/componentfactory.h>
#include <kdebug.h>
#include <QTimer>
#include <klocale.h>

using namespace Kontact;

class Core::Private
{
public:
  QString lastErrorMessage;
};

Core::Core( QWidget *parent, const char *name )
  : KParts::MainWindow( parent, name )
{
  d = new Private;
  QTimer* timer = new QTimer( this );
  mLastDate = QDate::currentDate();
  connect(timer, SIGNAL( timeout() ), SLOT( checkNewDay() ) );
  timer->start( 1000*60 );
}

Core::~Core()
{
  delete d;
}

KParts::ReadOnlyPart *Core::createPart( const char *libname )
{
  kDebug(5601) << "Core::createPart(): " << libname << endl;

  QMap<QByteArray,KParts::ReadOnlyPart *>::ConstIterator it;
  it = mParts.find( libname );
  if ( it != mParts.end() ) return it.value();

  kDebug(5601) << "Creating new KPart" << endl;

  int error = 0;
  KParts::ReadOnlyPart *part =
      KParts::ComponentFactory::
          createPartInstanceFromLibrary<KParts::ReadOnlyPart>
              ( libname, this, this, QStringList(), &error );

  KParts::ReadOnlyPart *pimPart = dynamic_cast<KParts::ReadOnlyPart*>( part );
  if ( pimPart ) {
    mParts.insert( libname, pimPart );
    QObject::connect( pimPart, SIGNAL( destroyed( QObject * ) ),
                      SLOT( slotPartDestroyed( QObject * ) ) );
  } else {
    // TODO move to KParts::ComponentFactory
    switch( error ) {
    case KParts::ComponentFactory::ErrNoServiceFound:
      d->lastErrorMessage = i18n( "No service found" );
      break;
    case KParts::ComponentFactory::ErrServiceProvidesNoLibrary:
      d->lastErrorMessage = i18n( "Program error: the .desktop file for the service does not have a Library key." );
      break;
    case KParts::ComponentFactory::ErrNoLibrary:
      d->lastErrorMessage = KLibLoader::self()->lastErrorMessage();
      break;
    case KParts::ComponentFactory::ErrNoFactory:
      d->lastErrorMessage = i18n( "Program error: the library %1 does not provide a factory.", libname );
      break;
    case KParts::ComponentFactory::ErrNoComponent:
      d->lastErrorMessage = i18n( "Program error: the library %1 does not support creating components of the specified type", libname );
      break;
    }
    kWarning(5601) << d->lastErrorMessage << endl;
  }

  return pimPart;
}

void Core::slotPartDestroyed( QObject * obj )
{
  // the part was deleted, we need to remove it from the part map to not return
  // a dangling pointer in createPart
  QMap<QByteArray, KParts::ReadOnlyPart*>::Iterator end = mParts.end();
  QMap<QByteArray, KParts::ReadOnlyPart*>::Iterator it = mParts.begin();
  for ( ; it != end; ++it ) {
    if ( it.value() == obj ) {
      mParts.erase( it );
      return;
    }
  }
}

void Core::checkNewDay()
{
  if ( mLastDate != QDate::currentDate() )
    emit dayChanged( QDate::currentDate() );

  mLastDate = QDate::currentDate();
}

QString Core::lastErrorMessage() const
{
  return d->lastErrorMessage;
}

#include "core.moc"
// vim: sw=2 sts=2 et tw=80
<commit_msg>Minor port<commit_after>/*
   This file is part of KDE Kontact.

   Copyright (c) 2001 Matthias Hoelzer-Kluepfel <mhk@kde.org>
   Copyright (c) 2002-2003 Daniel Molkentin <molkentin@kde.org>
   Copyright (c) 2003 Cornelius Schumacher <schumacher@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110-1301, USA.
*/

#include "core.h"

#include <kparts/part.h>
#include <kparts/componentfactory.h>
#include <kdebug.h>
#include <QTimer>
#include <klocale.h>

using namespace Kontact;

class Core::Private
{
public:
  QString lastErrorMessage;
};

Core::Core( QWidget *parent, const char *name )
  : KParts::MainWindow( parent, name )
{
  d = new Private;
  QTimer* timer = new QTimer( this );
  mLastDate = QDate::currentDate();
  connect(timer, SIGNAL( timeout() ), SLOT( checkNewDay() ) );
  timer->start( 1000*60 );
}

Core::~Core()
{
  delete d;
}

KParts::ReadOnlyPart *Core::createPart( const char *libname )
{
  kDebug(5601) << "Core::createPart(): " << libname << endl;

  QMap<QByteArray,KParts::ReadOnlyPart *>::ConstIterator it;
  it = mParts.find( libname );
  if ( it != mParts.end() ) return it.value();

  kDebug(5601) << "Creating new KPart" << endl;

  int error = 0;
  KParts::ReadOnlyPart *part =
      KParts::ComponentFactory::
          createPartInstanceFromLibrary<KParts::ReadOnlyPart>
              ( libname, this, this, QStringList(), &error );

  KParts::ReadOnlyPart *pimPart = dynamic_cast<KParts::ReadOnlyPart*>( part );
  if ( pimPart ) {
    mParts.insert( libname, pimPart );
    QObject::connect( pimPart, SIGNAL( destroyed( QObject * ) ),
                      SLOT( slotPartDestroyed( QObject * ) ) );
  } else {
    // TODO move to KParts::ComponentFactory
    switch( error ) {
    case KLibLoader::ErrNoServiceFound:
      d->lastErrorMessage = i18n( "No service found" );
      break;
    case KLibLoader::ErrServiceProvidesNoLibrary:
      d->lastErrorMessage = i18n( "Program error: the .desktop file for the service does not have a Library key." );
      break;
    case KLibLoader::ErrNoLibrary:
      d->lastErrorMessage = KLibLoader::self()->lastErrorMessage();
      break;
    case KLibLoader::ErrNoFactory:
      d->lastErrorMessage = i18n( "Program error: the library %1 does not provide a factory.", libname );
      break;
    case KLibLoader::ErrNoComponent:
      d->lastErrorMessage = i18n( "Program error: the library %1 does not support creating components of the specified type", libname );
      break;
    }
    kWarning(5601) << d->lastErrorMessage << endl;
  }

  return pimPart;
}

void Core::slotPartDestroyed( QObject * obj )
{
  // the part was deleted, we need to remove it from the part map to not return
  // a dangling pointer in createPart
  QMap<QByteArray, KParts::ReadOnlyPart*>::Iterator end = mParts.end();
  QMap<QByteArray, KParts::ReadOnlyPart*>::Iterator it = mParts.begin();
  for ( ; it != end; ++it ) {
    if ( it.value() == obj ) {
      mParts.erase( it );
      return;
    }
  }
}

void Core::checkNewDay()
{
  if ( mLastDate != QDate::currentDate() )
    emit dayChanged( QDate::currentDate() );

  mLastDate = QDate::currentDate();
}

QString Core::lastErrorMessage() const
{
  return d->lastErrorMessage;
}

#include "core.moc"
// vim: sw=2 sts=2 et tw=80
<|endoftext|>


<commit_before>/*
  Copyright (C) 2015 Preet Desai (preet.desai@gmail.com)

  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.
*/

#ifndef KS_TEXT_GLYPH_DESC_HPP
#define KS_TEXT_GLYPH_DESC_HPP

#include <vector>
#include <ks/KsGlobal.hpp>

namespace ks
{
    namespace text
    {
        // Glyph Metrics
        // (horizontal layout)
        // =========================================================== //
        //
        //               xMin         xMax
        //            |    |           |
        //            |    |<- width ->|
        //            |    |           |
        //            +    +--.---.----+---+-------+--- yMax
        //            |    | / .'\ \   |   ^       ^
        //  bearingX -|--->| | |  | |  |   |       |
        //            |    | \ `-' /   | bearingY  |
        //            |    | /("'``    |   |       |
        // baseline---*----+-\-'---.-- +---+--*  height
        //           /|    |  /'""'.\  |      |    |
        //     origin |    | ||     || |      |    |
        //            |    | \'. __//  |      |    v
        //            |    +--`'---'---+------+----+--- yMin
        //            |                       |
        //            +------- advanceX ----->|
        //
        //
        // (vertical layout)
        // =========================================================== //
        //
        //                          origin
        //                         /
        //  baseline -+-----------*---------+------
        //            |          |    |         |
        //            | bearingX-|<---|      bearingY
        //            |          |    |         |
        //            |          |    |         v
        //            |          +--.-+-.----+--------- yMax
        //            |          | / .|\ \   |      ^
        //            |          | | || | |  |      |
        //            |          | \ `|' /   |      |
        //        advanceY       | /("|``    |      |
        //            |          | \ '|--.   |    height
        //            |          |  /'|"'.\  |      |
        //            |          | || |   || |      |
        //            |          | \'.|__//  |      v
        //            |          +--`'+--'---+--------- yMin
        //            v          |    |      |
        //            +----------+----*      |
        //                       |           |
        //                       |<- width ->|
        //                       |           |
        //                     xMin         xMax
        //
        // =========================================================== //

        // Generated by the Atlas. Contains glyph image
        // lookup information and metrics
        struct GlyphImageDesc
        {
            // index
            // * glyph index for given font's charmap
            // * we dont keep track of unicode codepoint
            //   because index <--> unicode codepoint
            //   isnt a one-to-one mapping
            uint index;
            u16 atlas;
            u16 font;

            // texture coords (pixels) for the top
            // left corner of the glyph tex in its atlas
            u16 tex_x;
            u16 tex_y;

            // sdf quad <--> glyph offset vector (pixels)
            u16 sdf_x;
            u16 sdf_y;

            // metrics (pixels)
            s16 bearing_x;
            s16 bearing_y;
            u16 width;
            u16 height;
        };

        // Generated by ShapeText. Contains the glyph
        // index lookups for freetype used by TextAtlas
        // to render and lookup corresponding glyphs
        struct GlyphInfo
        {
            // font glyph index
            // * the index for a given glyph used to
            //   lookup/render the glyph with freetype
            // * '0' indicates a missing glyph
            uint index;

            // cluster
            // * Let a character index be defined as an index
            //   in a UTF16 string: Then clusters are the remaining
            //   logical character indices after shaping has occured
            //   See:
            //   http://thread.gmane.org/gmane.comp.freedesktop.harfbuzz/1836/
            // * Cluster helps us map the final set of shaped glyphs
            //   back to their corresponding indices in the original
            //   text string
            uint cluster;

            // font index for TextAtlas
            // * '0' indicates an invalid font
            uint font;

            // Special case override of width so that this
            // character won't be rendered
            bool zero_width;
        };

        // Generated by ShapeText to help compute
        // final glyph positions
        struct GlyphOffset
        {
            s16 offset_x;
            s16 offset_y;
            s16 advance_x;
            s16 advance_y;
        };

        // TODO remove
        struct GlyphPosition
        {
            s32 x0;
            s32 y0;
            s32 x1; // x1 is to the right of x0
            s32 y1; // y1 is below y0
        };
    }
}

#endif // KS_TEXT_GLYPH_DESC_HPP
<commit_msg>Removed unused struct<commit_after>/*
  Copyright (C) 2015 Preet Desai (preet.desai@gmail.com)

  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.
*/

#ifndef KS_TEXT_GLYPH_DESC_HPP
#define KS_TEXT_GLYPH_DESC_HPP

#include <vector>
#include <ks/KsGlobal.hpp>

namespace ks
{
    namespace text
    {
        // Glyph Metrics
        // (horizontal layout)
        // =========================================================== //
        //
        //               xMin         xMax
        //            |    |           |
        //            |    |<- width ->|
        //            |    |           |
        //            +    +--.---.----+---+-------+--- yMax
        //            |    | / .'\ \   |   ^       ^
        //  bearingX -|--->| | |  | |  |   |       |
        //            |    | \ `-' /   | bearingY  |
        //            |    | /("'``    |   |       |
        // baseline---*----+-\-'---.-- +---+--*  height
        //           /|    |  /'""'.\  |      |    |
        //     origin |    | ||     || |      |    |
        //            |    | \'. __//  |      |    v
        //            |    +--`'---'---+------+----+--- yMin
        //            |                       |
        //            +------- advanceX ----->|
        //
        //
        // (vertical layout)
        // =========================================================== //
        //
        //                          origin
        //                         /
        //  baseline -+-----------*---------+------
        //            |          |    |         |
        //            | bearingX-|<---|      bearingY
        //            |          |    |         |
        //            |          |    |         v
        //            |          +--.-+-.----+--------- yMax
        //            |          | / .|\ \   |      ^
        //            |          | | || | |  |      |
        //            |          | \ `|' /   |      |
        //        advanceY       | /("|``    |      |
        //            |          | \ '|--.   |    height
        //            |          |  /'|"'.\  |      |
        //            |          | || |   || |      |
        //            |          | \'.|__//  |      v
        //            |          +--`'+--'---+--------- yMin
        //            v          |    |      |
        //            +----------+----*      |
        //                       |           |
        //                       |<- width ->|
        //                       |           |
        //                     xMin         xMax
        //
        // =========================================================== //

        // Generated by the Atlas. Contains glyph image
        // lookup information and metrics
        struct GlyphImageDesc
        {
            // index
            // * glyph index for given font's charmap
            // * we dont keep track of unicode codepoint
            //   because index <--> unicode codepoint
            //   isnt a one-to-one mapping
            uint index;
            u16 atlas;
            u16 font;

            // texture coords (pixels) for the top
            // left corner of the glyph tex in its atlas
            u16 tex_x;
            u16 tex_y;

            // sdf quad <--> glyph offset vector (pixels)
            u16 sdf_x;
            u16 sdf_y;

            // metrics (pixels)
            s16 bearing_x;
            s16 bearing_y;
            u16 width;
            u16 height;
        };

        // Generated by ShapeText. Contains the glyph
        // index lookups for freetype used by TextAtlas
        // to render and lookup corresponding glyphs
        struct GlyphInfo
        {
            // font glyph index
            // * the index for a given glyph used to
            //   lookup/render the glyph with freetype
            // * '0' indicates a missing glyph
            uint index;

            // cluster
            // * Let a character index be defined as an index
            //   in a UTF16 string: Then clusters are the remaining
            //   logical character indices after shaping has occured
            //   See:
            //   http://thread.gmane.org/gmane.comp.freedesktop.harfbuzz/1836/
            // * Cluster helps us map the final set of shaped glyphs
            //   back to their corresponding indices in the original
            //   text string
            uint cluster;

            // font index for TextAtlas
            // * '0' indicates an invalid font
            uint font;

            // Special case override of width so that this
            // character won't be rendered
            bool zero_width;
        };

        // Generated by ShapeText to help compute
        // final glyph positions
        struct GlyphOffset
        {
            s16 offset_x;
            s16 offset_y;
            s16 advance_x;
            s16 advance_y;
        };
    }
}

#endif // KS_TEXT_GLYPH_DESC_HPP
<|endoftext|>


<commit_before>#include "format_twobit.h"

// Fixme: Here for debugging
#define MAX_ALLOC 524288

enum {
	ACTION_DUMP,
	ACTION_INFO,
	ACTION_SHOW
};

int FormatTwoBit::dump(FILE *fp) {
	return helper(fp, ACTION_DUMP, 0);
}

int FormatTwoBit::info(FILE *fp, int verbose) {
	return helper(fp, ACTION_INFO, verbose);
}

int FormatTwoBit::show(FILE *fp) {
	return helper(fp, ACTION_SHOW, 0);
}

int FormatTwoBit::helper(FILE *fp, int action, int verbose) {
	char buf[256];

	// Fixme: Read header size only
	int n = fread(buf,1,sizeof(_2bit_header_t),fp);

	_2bit_header_t *header = (_2bit_header_t*)buf;

	if (
		(header->signature != 0x1a412743) &&
		(header->signature != 0x4327411a)
	) {
		printf("2bit: Error, not a 2bit file\n");
		return -1;
	}

	// Determine endian format.
	int endian_is_native = (*(uint32_t*)buf == 0x1a412743) ? 1 : 0;
	// Fixme, we care about big/little not native or swapped
	// Use htonl

	if (verbose >= 1) {
		printf("File format:    2bit\n");
		printf("Endian:         %s\n", endian_is_native ? "native" : "swapped");
		printf("Version:        %d\n", header->version); // Fixme, endians
		printf("Sequence Count: %d\n", header->sequenceCount); // Fixme, endians
		printf("Reserved:       %d\n", header->reserved); // Fixme, endians
		if (verbose == 1)
			return 0;
	}

	_2bit_index_t *index = (_2bit_index_t*)malloc(sizeof(_2bit_index_t)*header->sequenceCount);
	if (!index) {
		fprintf(stderr, "Error: Not enough memory to allocate %d index tables\n", header->sequenceCount);
		return -1;
	}

	for (unsigned i = 0; i < header->sequenceCount; i++) {
		_2bit_seq_hdr_t *seq_hdr = &index[i].seq_hdr;
		// Fixme: Excessive read calls
		n = fread(&seq_hdr->nameSize,1,1,fp);
		n = fread(&seq_hdr->name,1,seq_hdr->nameSize,fp);
		n = fread(&seq_hdr->offset,1,sizeof(uint32_t),fp);
		seq_hdr->name[seq_hdr->nameSize] = 0;
		// printf("Sequence #%d, \"%s\"\n", i, seq_hdr.name);
	}

	for (unsigned i = 0; i < header->sequenceCount; i++) {
		// Fixme: Excessive read calls
		n = fread(&index[i].dnaSize,    sizeof(uint32_t),1,fp);
		n = fread(&index[i].nBlockCount,sizeof(uint32_t),1,fp);
		if (index[i].nBlockCount) {
			if (index[i].nBlockCount > MAX_ALLOC)
				index[i].nBlockCount = MAX_ALLOC;

			index[i].nBlockStarts = (uint32_t*)malloc(sizeof(uint32_t)*index[i].nBlockCount);
			if (!index[i].nBlockStarts) {
				// Fixme: Convert to class to we can auto free.
				printf("Error, unable to allocate %d bytes.\n", sizeof(uint32_t)*index[i].nBlockCount);
				return -1;
			}

			index[i].nBlockSizes  = (uint32_t*)malloc(sizeof(uint32_t)*index[i].nBlockCount);
			if (!index[i].nBlockSizes) {
				// Fixme: Convert to class to we can auto free.
				printf("Error, unable to allocate %d bytes.\n", sizeof(uint32_t)*index[i].nBlockCount);
				return -1;
			}

			fread(index[i].nBlockStarts, sizeof(uint32_t), index[i].nBlockCount, fp);
			fread(index[i].nBlockSizes,  sizeof(uint32_t), index[i].nBlockCount, fp);

		} else {
			index[i].nBlockStarts =
			index[i].nBlockSizes = 0;
		}

		// Todo: Verify the blocks are in order
		// Related, how are these used?

		n = fread(&index[i].maskBlockCount,sizeof(uint32_t),1,fp);
		if (verbose >= 2) {
			printf(
				"Seq #%3d: %6d kbase, blocks %3d, masks %6d, \"%s\" \n",
				i,
				index[i].dnaSize / 1000,
				index[i].nBlockCount, index[i].maskBlockCount,
				index[i].seq_hdr.name
			);
		}

		if (verbose >= 3) {
			for (unsigned o = 0; o < index[i].nBlockCount; o++) {
				printf("   Block #%d: start: %d, size: %d\n",
					o, index[i].nBlockStarts[o], index[i].nBlockSizes[o]
				);
			}
		}

		if (!index[i].maskBlockCount) {
			index[i].maskBlockStarts = NULL;
			index[i].maskBlockSizes = NULL;
		} else {
			if (index[i].maskBlockCount > MAX_ALLOC)
				index[i].maskBlockCount = MAX_ALLOC;

			index[i].maskBlockStarts = (uint32_t*)malloc(sizeof(uint32_t)*index[i].maskBlockCount);
			index[i].maskBlockSizes  = (uint32_t*)malloc(sizeof(uint32_t)*index[i].maskBlockCount);

			n = fread(index[i].maskBlockStarts, sizeof(uint32_t), index[i].maskBlockCount, fp);
			if ((unsigned)n != index[i].maskBlockCount) {
				printf("Error: Unable to read mask block starts at index %d, short file?\n", i);
				return -1;
			}

			n = fread(index[i].maskBlockSizes,  sizeof(uint32_t), index[i].maskBlockCount, fp);
			if ((unsigned)n != index[i].maskBlockCount) {
				printf("Error: Unable to read mask block count at index %d, short file?\n", i);
				return -1;
			}

			if (verbose >= 3) {
				for (unsigned o = 0; o < index[i].maskBlockCount; o++) {
					printf("   Mask #%d: start: %d, size: %d\n",
						o, index[i].maskBlockStarts[o], index[i].maskBlockSizes[o]
					);
				}
			}

			// Todo: Walk the list of masks to ensure they are saved in alphabetical order
		}

		// Reserved
		n = fread(&index[i].reserved,sizeof(uint32_t),1,fp);

		/** Fixme: In some cases, we probably actually want to load this data. */
		index[i].packedDna_offset = ftell(fp);
		if (action == ACTION_INFO)
			fseek(fp,(index[i].dnaSize+3)/4,SEEK_CUR);
		else {
			unsigned cur_block_i = 0;      // Note: Requires the block list to be in order
			unsigned cur_mask_i = 0;       // Note: Requires the mask list to be in order
			unsigned cur_bp_pos = 0;       // Current base pair position.
			unsigned cur_print_width = 60; // Number of base pairs to print per line (for future show command)
			char buf[8192];
			int bpc = index[i].dnaSize;
			int len = (index[i].dnaSize+3)/4;
			while (len > 0) {
				int toread = len > sizeof(buf) ? sizeof(buf) : len;
				int available = index[i].dnaSize;
				// printf("ToRead :%d\n", toread);
				n = fread(&buf[0], 1, toread, fp);
				if (toread != n) {
					printf("Error: Unable to read DNA data\n");
					return -1;
				}
				for (unsigned i = 0; i < toread; i++) {
					const char c[4] = { 'T', 'C', 'A', 'G' };
					char ch = buf[i];
					for (unsigned o = 0; o < 4; o++) {
						if (available) {
							if (action == ACTION_SHOW)
								if (cur_bp_pos % cur_print_width == 0)
									printf("\n%9d: ", cur_bp_pos);
							// Fixme: Check blocks and masks as appropriate. And don't go over the end
							//if (cur_bp_pos >= index[i].nBlockStarts[cur_block_i]) {
							//	if (cur_bp_pos > index[i].nBlockStarts[cur_block_i]
							//} else {
								printf("%c", c[(ch >> 6) & 3]);
							//}
							ch <<= 2;
							available--;
							cur_bp_pos++;
						}
					}
				}
				len -= n;
			}
		}
	}

	// EOF Sanity Check
	if (1) {
		char buf[8192];
		n = fread(buf,1,sizeof(buf),fp);
		if (n != 0)
			printf("Warning: Additional data past where the end of file should be.\n");
	}

	return 0;
}
<commit_msg>Add in block masks to ggt show/ggt dump output. 'N' now appears in addition to 'TCAG'. Fixed my git email address, whoops.<commit_after>#include "format_twobit.h"

// Fixme: Here for debugging
#define MAX_ALLOC 524288

enum {
	ACTION_DUMP,
	ACTION_INFO,
	ACTION_SHOW
};

int FormatTwoBit::dump(FILE *fp) {
	return helper(fp, ACTION_DUMP, 0);
}

int FormatTwoBit::info(FILE *fp, int verbose) {
	return helper(fp, ACTION_INFO, verbose);
}

int FormatTwoBit::show(FILE *fp) {
	return helper(fp, ACTION_SHOW, 0);
}

int FormatTwoBit::helper(FILE *fp, int action, int verbose) {
	char buf[256];

	// Fixme: Read header size only
	int n = fread(buf,1,sizeof(_2bit_header_t),fp);

	_2bit_header_t *header = (_2bit_header_t*)buf;

	if (
		(header->signature != 0x1a412743) &&
		(header->signature != 0x4327411a)
	) {
		printf("2bit: Error, not a 2bit file\n");
		return -1;
	}

	// Determine endian format.
	int endian_is_native = (*(uint32_t*)buf == 0x1a412743) ? 1 : 0;
	// Fixme, we care about big/little not native or swapped
	// Use htonl

	if (verbose >= 1) {
		printf("File format:    2bit\n");
		printf("Endian:         %s\n", endian_is_native ? "native" : "swapped");
		printf("Version:        %d\n", header->version); // Fixme, endians
		printf("Sequence Count: %d\n", header->sequenceCount); // Fixme, endians
		printf("Reserved:       %d\n", header->reserved); // Fixme, endians
		if (verbose == 1)
			return 0;
	}

	_2bit_index_t *index = (_2bit_index_t*)malloc(sizeof(_2bit_index_t)*header->sequenceCount);
	if (!index) {
		fprintf(stderr, "Error: Not enough memory to allocate %d index tables\n", header->sequenceCount);
		return -1;
	}

	for (unsigned i = 0; i < header->sequenceCount; i++) {
		_2bit_seq_hdr_t *seq_hdr = &index[i].seq_hdr;
		// Fixme: Excessive read calls
		n = fread(&seq_hdr->nameSize,1,1,fp);
		n = fread(&seq_hdr->name,1,seq_hdr->nameSize,fp);
		n = fread(&seq_hdr->offset,1,sizeof(uint32_t),fp);
		seq_hdr->name[seq_hdr->nameSize] = 0;
		// printf("Sequence #%d, \"%s\"\n", i, seq_hdr.name);
	}

	for (unsigned i = 0; i < header->sequenceCount; i++) {
		// Fixme: Excessive read calls
		n = fread(&index[i].dnaSize,    sizeof(uint32_t),1,fp);
		n = fread(&index[i].nBlockCount,sizeof(uint32_t),1,fp);
		if (index[i].nBlockCount) {
			if (index[i].nBlockCount > MAX_ALLOC)
				index[i].nBlockCount = MAX_ALLOC;

			index[i].nBlockStarts = (uint32_t*)malloc(sizeof(uint32_t)*index[i].nBlockCount);
			if (!index[i].nBlockStarts) {
				// Fixme: Convert to class to we can auto free.
				printf("Error, unable to allocate %d bytes.\n", sizeof(uint32_t)*index[i].nBlockCount);
				return -1;
			}

			index[i].nBlockSizes  = (uint32_t*)malloc(sizeof(uint32_t)*index[i].nBlockCount);
			if (!index[i].nBlockSizes) {
				// Fixme: Convert to class to we can auto free.
				printf("Error, unable to allocate %d bytes.\n", sizeof(uint32_t)*index[i].nBlockCount);
				return -1;
			}

			fread(index[i].nBlockStarts, sizeof(uint32_t), index[i].nBlockCount, fp);
			fread(index[i].nBlockSizes,  sizeof(uint32_t), index[i].nBlockCount, fp);

		} else {
			index[i].nBlockStarts =
			index[i].nBlockSizes = 0;
		}

		// Todo: Verify the blocks are in order
		// Related, how are these used?

		n = fread(&index[i].maskBlockCount,sizeof(uint32_t),1,fp);
		if (verbose >= 2) {
			printf(
				"Seq #%3d: %6d kbase, blocks %3d, masks %6d, \"%s\" \n",
				i,
				index[i].dnaSize / 1000,
				index[i].nBlockCount, index[i].maskBlockCount,
				index[i].seq_hdr.name
			);
		}

		if (verbose >= 3) {
			for (unsigned o = 0; o < index[i].nBlockCount; o++) {
				printf("   Block #%d: start: %d, size: %d\n",
					o, index[i].nBlockStarts[o], index[i].nBlockSizes[o]
				);
			}
		}

		if (!index[i].maskBlockCount) {
			index[i].maskBlockStarts = NULL;
			index[i].maskBlockSizes = NULL;
		} else {
			if (index[i].maskBlockCount > MAX_ALLOC)
				index[i].maskBlockCount = MAX_ALLOC;

			index[i].maskBlockStarts = (uint32_t*)malloc(sizeof(uint32_t)*index[i].maskBlockCount);
			index[i].maskBlockSizes  = (uint32_t*)malloc(sizeof(uint32_t)*index[i].maskBlockCount);

			n = fread(index[i].maskBlockStarts, sizeof(uint32_t), index[i].maskBlockCount, fp);
			if ((unsigned)n != index[i].maskBlockCount) {
				printf("Error: Unable to read mask block starts at index %d, short file?\n", i);
				return -1;
			}

			n = fread(index[i].maskBlockSizes,  sizeof(uint32_t), index[i].maskBlockCount, fp);
			if ((unsigned)n != index[i].maskBlockCount) {
				printf("Error: Unable to read mask block count at index %d, short file?\n", i);
				return -1;
			}

			if (verbose >= 3) {
				for (unsigned o = 0; o < index[i].maskBlockCount; o++) {
					printf("   Mask #%d: start: %d, size: %d\n",
						o, index[i].maskBlockStarts[o], index[i].maskBlockSizes[o]
					);
				}
			}

			// Todo: Walk the list of masks to ensure they are saved in alphabetical order
		}

		// Reserved
		n = fread(&index[i].reserved,sizeof(uint32_t),1,fp);

		/** Fixme: In some cases, we probably actually want to load this data. */
		index[i].packedDna_offset = ftell(fp);
		if (action == ACTION_INFO)
			fseek(fp,(index[i].dnaSize+3)/4,SEEK_CUR);
		else {
			unsigned cur_block_i = 0;      // Note: Requires the block list to be in order
			unsigned cur_mask_i = 0;       // Note: Requires the mask list to be in order
			unsigned cur_bp_pos = 0;       // Current base pair position.
			unsigned cur_print_width = 60; // Number of base pairs to print per line (for future show command)
			char buf[8192];
			int bpc = index[i].dnaSize;
			int len = (index[i].dnaSize+3)/4;
			while (len > 0) {
				int toread = len > sizeof(buf) ? sizeof(buf) : len;
				int available = index[i].dnaSize;
				// printf("ToRead :%d\n", toread);
				n = fread(&buf[0], 1, toread, fp);
				if (toread != n) {
					printf("Error: Unable to read DNA data\n");
					return -1;
				}
				for (unsigned print_pos = 0; print_pos < toread; print_pos++) {
					const char c[4] = { 'T', 'C', 'A', 'G' };
					char ch = buf[print_pos];
					for (unsigned o = 0; o < 4; o++) {
						if (available) {
							if (action == ACTION_SHOW)
								if (cur_bp_pos % cur_print_width == 0)
									printf("\n%9d: ", cur_bp_pos);
							// Fixme: Check blocks and masks as appropriate. And don't go over the end
						test_again:
							if (cur_block_i < index[i].nBlockCount) {
								if (cur_bp_pos >= index[i].nBlockStarts[cur_block_i]) {
									if (cur_bp_pos > index[i].nBlockStarts[cur_block_i] + index[i].nBlockSizes[cur_block_i]) {
										cur_block_i++;
										goto test_again;
									}
									printf("N");
								} else {
									printf("%c", c[(ch >> 6) & 3]);
								}
							} else {
								printf("%c", c[(ch >> 6) & 3]);
							}
							ch <<= 2;
							available--;
							cur_bp_pos++;
						}
					}
				}
				len -= n;
			}
		}
	}

	// EOF Sanity Check
	if (1) {
		char buf[8192];
		n = fread(buf,1,sizeof(buf),fp);
		if (n != 0)
			printf("Warning: Additional data past where the end of file should be.\n");
	}

	return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ids.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 23:01:04 $
 *
 *  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
 *
 ************************************************************************/

#include "ids.hxx"

IMPLEMENT_IMPLEMENTATIONID_HELPER(frm, OImplementationIds)

<commit_msg>INTEGRATION: CWS pchfix02 (1.2.112); FILE MERGED 2006/09/01 17:27:41 kaib 1.2.112.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ids.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 23:57:39 $
 *
 *  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_forms.hxx"

#include "ids.hxx"

IMPLEMENT_IMPLEMENTATIONID_HELPER(frm, OImplementationIds)

<|endoftext|>


<commit_before>#include "execute.h"
#include "Command.h"
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <sstream>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost;

Execute::Execute(){
    this->index = 0;
}

void Execute::parsecmd(string text, vector<string>&parse) //this function converts the command into individual words
{
    parse.clear(); // clears the vector of any previous instructions
    boost::split(parse, text, boost::is_any_of(" "));
}

char* Execute::to_char(const string &token)// this function converts the individual words from parsecmd into char** so we can use execvp
{
	char* temp = new char[token.size() + 1];
	strcpy(temp, token.c_str());
	return temp;
}
int Execute::forking(const vector<char*>&convert)//this function takes care of executing commands and forking
{
    vector<char*>temp = convert;
    int termstat;
    char** arg = &temp.at(0);
    pid_t pid = fork();

    if(pid < 0)
    {
        perror("$ Error: fork failed");
        _exit(-127);
    }

    if(pid == 0) //child process
    {
        int check = execvp(arg[0],arg);
        if(check < 0)
        {
            cout << "$ Error: " << arg[0] <<" command not found" << endl;
            _exit(-127);
        }

        _exit(0);
    }

    waitpid(pid, &termstat, 0);
    return WEXITSTATUS(termstat);

}

void Execute::runtest(Command* test)
{
    if(test->tokenCheck().at(0) == '[' && test->tokenCheck().at(test->tokenCheck().size()-1) == ']') // we will remove the brackets
    {
        string temp = test->tokenCheck();
        temp.erase(temp.begin(), temp.begin()+1);
        temp.erase(temp.end()-1, temp.end());
        test->addtoken(temp);
    }

    if(test->tokenCheck().substr(0,4) == "test")
    {
        string temp = test->tokenCheck();
        temp.erase(temp.begin(), temp.begin()+4);
        test->addtoken(temp);
    }

    if(test->tokenCheck().at(0) == ' ')  //removing any preceding whitespace
    {
        string temp = test->tokenCheck();
        temp.erase(temp.begin(), temp.begin()+1);
        test->addtoken(temp);
     }

    if(test->tokenCheck().at(test->tokenCheck().size()-1) == ' ')  //removing any proceeding whitespace
    {
        string temp = test->tokenCheck();
        temp.erase(temp.end()-1, temp.end());
        test->addtoken(temp);
    }

    //now we will be checking for the flags since we removed all unnecessary syntax
    struct stat buf;
    int check;         //tells us which flag it is 1 = -e, 2 = -f, 3 = -d

    if(test->tokenCheck().substr(0,2) == "-e") //check if the file/directory exists
    {
        check = 1;
    }

    else if(test->tokenCheck().substr(0,2) == "-f") //check if the file/directory exists and is a regular file
    {
        check = 2;
    }

    else if(test->tokenCheck().substr(0,2) == "-d") //check if the file/directory exists and is a directory
    {
        check = 3;
    }
    else
    {
        check = 1;
    }

    string temp = test->tokenCheck();

    if(test->tokenCheck().substr(0,2) == "-e" || test->tokenCheck().substr(0,2) == "-f" || test->tokenCheck().substr(0,2) == "-d")  //remove the flag from the token/commmand
    {
        temp.erase(temp.begin(), temp.begin()+2);
        test->addtoken(temp);
    }

    if(test->tokenCheck().at(0) == ' ')  //removing any preceding whitespace
    {
        string temp = test->tokenCheck();
        temp.erase(temp.begin(), temp.begin()+1);
        test->addtoken(temp);
     }

    if(test->tokenCheck().at(test->tokenCheck().size()-1) == ' ')  //removing any proceeding whitespace
    {
        string temp = test->tokenCheck();
        temp.erase(temp.end()-1, temp.end());
        test->addtoken(temp);
    }

    string flag = test->tokenCheck();

    if(check == 1)
    {
        int sign = stat(flag.c_str(), &buf);

        if(sign == 0)
        {
            test->addstatus(true);
        }
        else
        {
            test->addstatus(false);
        }
    }

    if(check == 2)
    {
        int sign = stat(flag.c_str(), &buf);

        if(sign == 0 && S_ISREG(buf.st_mode))
        {
            test->addstatus(true);
        }
        else
        {
            test->addstatus(false);
        }
    }

    if(check == 3)
    {
        int sign = stat(flag.c_str(), &buf);

        if(sign == 0 && S_ISDIR(buf.st_mode))
        {
            test->addstatus(true);
        }
        else
        {
            test->addstatus(false);
        }
    }

    string status;
    if(test->statusCheck())
    {
        status = "(true)";
    }
    else
    {
        status = "(false)";
    }

    cout << status << endl;
}

void Execute::terminal(const vector<Command*>& tokens) //this function will run the commands
{
    int check;
    vector<char*>convert;
    vector<string> parse;
    string text;
    // ; = next command is always executed
    // && = next command only executes if previous command succesfully executed
    // || = next command only executes if previous command didnt
    // # = comment
    // [] or test = test

    bool percon = false;
    int counter = 0;
    int idex;
    bool allTrue = false;
    for(unsigned x = 0; x < tokens.size(); x++)
    {

        convert.resize(0);
        text = tokens.at(x)->tokenCheck();
        parsecmd(text,parse);

        for(unsigned i = 0; i < parse.size(); i++)
        {
            convert.push_back(to_char(parse[i]));
        }

        //check = forking(convert);
        if(tokens.at(index)->getprec() >= 2)
        {

            percon = true;
            allTrue = true;
            idex = index;
            counter = tokens.at(index)->getprec();
        }
        if(tokens.at(index)->signCheck() == 0)  //comment - delete this token
            {
                tokens.at(index)->addstatus(true);
            }

        if(tokens.at(index)->signCheck() == 1)  // ; always runs
            {
                check = forking(convert);
                if(check == 0)
                {
                    tokens.at(index)->addstatus(true);
                }

                else
                {
                    tokens.at(index)->addstatus(false);
                    allTrue = false;

                }

            }

        if(tokens.at(index)->signCheck() == 2)  // || runs only if first fails
            {

                if(tokens.at(index-1)->statusCheck() == false)
                    {

                        check = forking(convert);
                        if(check == 0)
                            {
                                tokens.at(index)->addstatus(true);
                            }
                         else
                            {
                                tokens.at(index)->addstatus(false);
                                allTrue = false;
                            }
                    }
            }

        if(tokens.at(index)->signCheck() == 3)  // && runs only if first passes
            {
                if(index >= 2 && tokens.at(index-1)->signCheck() == 2)  // have to deal with precedence issues due to multiple parameters
                {
                    if(tokens.at(index-1)->statusCheck() == true || tokens.at(index-2)->statusCheck() == true)
                    {
                         check = forking(convert);
                        if(check == 0)
                        {
                            tokens.at(index)->addstatus(true);

                        }
                        else
                        {
                            tokens.at(index)->addstatus(false);
                            allTrue = false;
                        }
                    }
                }

                else
                {
                    if(tokens.at(index-1)->statusCheck() == true)
                    {
                        check = forking(convert);
                        if(check == 0)
                        {
                            tokens.at(index)->addstatus(true);

                        }
                        else
                        {
                            tokens.at(index)->addstatus(false);
                            allTrue = false;

                        }
                    }
                }
            }

        if(tokens.at(index)->signCheck() == 4) // test or [], will run the test command via our functionality
        {
            //call test function
            Command* tst = tokens.at(index);
            runtest(tst);
        }
        counter --;

	//skips the next token or tokens depending on whether or not there are parenthesis

        if(allTrue == false && percon == true && counter == 0)
        {
            if(unsigned(idex + tokens.at(idex)->getprec()) != tokens.size()-1)
            {
                x+= tokens.at(idex)->getprec();
                index += tokens.at(idex)->getprec();
            }
        }

        this->index++;      // keeps track of which command is being executed

    }

}

<commit_msg>Delete execute.cpp<commit_after><|endoftext|>


<commit_before>/*
 * Copyright 2014-present Facebook, Inc.
 *
 * 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 <folly/Benchmark.h>
#include <folly/executors/InlineExecutor.h>
#include <folly/futures/Future.h>
#include <folly/futures/Promise.h>
#include <folly/portability/GFlags.h>
#include <folly/portability/Semaphore.h>
#include <folly/synchronization/Baton.h>

#include <vector>

using namespace folly;

namespace {

template <class T>
T incr(Try<T>&& t) {
  return t.value() + 1;
}

void someThens(size_t n) {
  auto f = makeFuture<int>(42);
  for (size_t i = 0; i < n; i++) {
    f = std::move(f).then(incr<int>);
  }
}

} // namespace

BENCHMARK(constantFuture) {
  makeFuture(42);
}

BENCHMARK_RELATIVE(promiseAndFuture) {
  Promise<int> p;
  Future<int> f = p.getFuture();
  p.setValue(42);
  f.value();
}

BENCHMARK_RELATIVE(withThen) {
  Promise<int> p;
  Future<int> f = p.getFuture().then(incr<int>);
  p.setValue(42);
  f.value();
}

// thens
BENCHMARK_DRAW_LINE();

BENCHMARK(oneThen) {
  someThens(1);
}

// look for >= 50% relative
BENCHMARK_RELATIVE(twoThens) {
  someThens(2);
}

// look for >= 25% relative
BENCHMARK_RELATIVE(fourThens) {
  someThens(4);
}

// look for >= 1% relative
BENCHMARK_RELATIVE(hundredThens) {
  someThens(100);
}

// Lock contention. Although in practice fulfills tend to be temporally
// separate from then()s, still sometimes they will be concurrent. So the
// higher this number is, the better.
BENCHMARK_DRAW_LINE();

BENCHMARK(no_contention) {
  std::vector<Promise<int>> promises(10000);
  std::vector<Future<int>> futures;
  std::thread producer, consumer;

  BENCHMARK_SUSPEND {
    folly::Baton<> b1, b2;
    for (auto& p : promises) {
      futures.push_back(p.getFuture());
    }

    consumer = std::thread([&] {
      b1.post();
      for (auto& f : futures) {
        std::move(f).then(incr<int>);
      }
    });
    consumer.join();

    producer = std::thread([&] {
      b2.post();
      for (auto& p : promises) {
        p.setValue(42);
      }
    });

    b1.wait();
    b2.wait();
  }

  // The only thing we are measuring is how long fulfill + callbacks take
  producer.join();
}

BENCHMARK_RELATIVE(contention) {
  std::vector<Promise<int>> promises(10000);
  std::vector<Future<int>> futures;
  std::thread producer, consumer;
  sem_t sem;
  sem_init(&sem, 0, 0);

  BENCHMARK_SUSPEND {
    folly::Baton<> b1, b2;
    for (auto& p : promises) {
      futures.push_back(p.getFuture());
    }

    consumer = std::thread([&] {
      b1.post();
      for (auto& f : futures) {
        sem_wait(&sem);
        std::move(f).then(incr<int>);
      }
    });

    producer = std::thread([&] {
      b2.post();
      for (auto& p : promises) {
        sem_post(&sem);
        p.setValue(42);
      }
    });

    b1.wait();
    b2.wait();
  }

  // The astute reader will notice that we're not *precisely* comparing apples
  // to apples here. Well, maybe it's like comparing Granny Smith to
  // Braeburn or something. In the serial version, we waited for the futures
  // to be all set up, but here we are probably still doing that work
  // (although in parallel). But even though there is more work (on the order
  // of 2x), it is being done by two threads. Hopefully most of the difference
  // we see is due to lock contention and not false parallelism.
  //
  // Be warned that if the box is under heavy load, this will greatly skew
  // these results (scheduling overhead will begin to dwarf lock contention).
  // I'm not sure but I'd guess in Windtunnel this will mean large variance,
  // because I expect they load the boxes as much as they can?
  consumer.join();
  producer.join();
}

BENCHMARK_DRAW_LINE();

// The old way. Throw an exception, and rethrow to access it upstream.
void throwAndCatchImpl() {
  makeFuture()
      .then([](Try<Unit>&&) { throw std::runtime_error("oh no"); })
      .then([](Try<Unit>&& t) {
        try {
          t.value();
        } catch (const std::runtime_error& e) {
          // ...
          return;
        }
        CHECK(false);
      });
}

// Not much better. Throw an exception, and access it via the wrapper upstream.
// Actually a little worse due to wrapper overhead. then() won't know that the
// exception is a runtime_error, so will have to store it as an exception_ptr
// anyways. withException will therefore have to rethrow. Note that if we threw
// std::exception instead, we would see some wins, as that's the type then()
// will try to wrap, so no exception_ptrs/rethrows are necessary.
void throwAndCatchWrappedImpl() {
  makeFuture()
      .then([](Try<Unit>&&) { throw std::runtime_error("oh no"); })
      .then([](Try<Unit>&& t) {
        auto caught = t.withException<std::runtime_error>(
            [](const std::runtime_error& /* e */) {
              // ...
            });
        CHECK(caught);
      });
}

// Better. Wrap an exception, and rethrow to access it upstream.
void throwWrappedAndCatchImpl() {
  makeFuture()
      .then([](Try<Unit>&&) {
        return makeFuture<Unit>(std::runtime_error("oh no"));
      })
      .then([](Try<Unit>&& t) {
        try {
          t.value();
        } catch (const std::runtime_error& e) {
          // ...
          return;
        }
        CHECK(false);
      });
}

// The new way. Wrap an exception, and access it via the wrapper upstream
void throwWrappedAndCatchWrappedImpl() {
  makeFuture()
      .then([](Try<Unit>&&) {
        return makeFuture<Unit>(std::runtime_error("oh no"));
      })
      .then([](Try<Unit>&& t) {
        auto caught = t.withException<std::runtime_error>(
            [](const std::runtime_error& /* e */) {
              // ...
            });
        CHECK(caught);
      });
}

// Simulate heavy contention on func
void contend(void (*func)()) {
  folly::BenchmarkSuspender s;
  const int N = 100;
  const int iters = 1000;
  pthread_barrier_t barrier;
  pthread_barrier_init(&barrier, nullptr, N + 1);
  std::vector<std::thread> threads;
  for (int i = 0; i < N; i++) {
    threads.push_back(std::thread([&]() {
      pthread_barrier_wait(&barrier);
      for (int j = 0; j < iters; j++) {
        func();
      }
    }));
  }
  pthread_barrier_wait(&barrier);
  s.dismiss();
  for (auto& t : threads) {
    t.join();
  }
  s.rehire();
  pthread_barrier_destroy(&barrier);
}

BENCHMARK(throwAndCatch) {
  throwAndCatchImpl();
}

BENCHMARK_RELATIVE(throwAndCatchWrapped) {
  throwAndCatchWrappedImpl();
}

BENCHMARK_RELATIVE(throwWrappedAndCatch) {
  throwWrappedAndCatchImpl();
}

BENCHMARK_RELATIVE(throwWrappedAndCatchWrapped) {
  throwWrappedAndCatchWrappedImpl();
}

BENCHMARK_DRAW_LINE();

BENCHMARK(throwAndCatchContended) {
  contend(throwAndCatchImpl);
}

BENCHMARK_RELATIVE(throwAndCatchWrappedContended) {
  contend(throwAndCatchWrappedImpl);
}

BENCHMARK_RELATIVE(throwWrappedAndCatchContended) {
  contend(throwWrappedAndCatchImpl);
}

BENCHMARK_RELATIVE(throwWrappedAndCatchWrappedContended) {
  contend(throwWrappedAndCatchWrappedImpl);
}

BENCHMARK_DRAW_LINE();

namespace {
struct Bulky {
  explicit Bulky(std::string message) : message_(message) {}
  std::string message() & {
    return message_;
  }
  std::string&& message() && {
    return std::move(message_);
  }

 private:
  std::string message_;
  std::array<int, 1024> ints_;
};
} // anonymous namespace

BENCHMARK(lvalue_get) {
  BenchmarkSuspender suspender;
  Optional<Future<Bulky>> future;
  future = makeFuture(Bulky("Hello"));
  suspender.dismissing([&] {
    std::string message = std::move(future.value()).get().message();
    doNotOptimizeAway(message);
  });
}

BENCHMARK_RELATIVE(rvalue_get) {
  BenchmarkSuspender suspender;
  Optional<Future<Bulky>> future;
  future = makeFuture(Bulky("Hello"));
  suspender.dismissing([&] {
    std::string message = std::move(future.value()).get().message();
    doNotOptimizeAway(message);
  });
}

InlineExecutor exe;

template <class T>
Future<T> fGen() {
  Promise<T> p;
  auto f = p.getFuture()
               .thenValue([](T&& t) { return std::move(t); })
               .thenValue([](T&& t) { return makeFuture(std::move(t)); })
               .via(&exe)
               .thenValue([](T&& t) { return std::move(t); })
               .thenValue([](T&& t) { return makeFuture(std::move(t)); });
  p.setValue(T());
  return f;
}

template <class T>
std::vector<Future<T>> fsGen() {
  std::vector<Future<T>> fs;
  for (auto i = 0; i < 10; i++) {
    fs.push_back(fGen<T>());
  }
  return fs;
}

template <class T>
void complexBenchmark() {
  collect(fsGen<T>());
  collectAll(fsGen<T>());
  collectAny(fsGen<T>());
  futures::mapValue(fsGen<T>(), [](const T& t) { return t; });
  futures::mapValue(fsGen<T>(), [](const T& t) { return makeFuture(T(t)); });
}

BENCHMARK_DRAW_LINE();

template <size_t S>
struct Blob {
  char buf[S];
};

BENCHMARK(complexUnit) {
  complexBenchmark<Unit>();
}

BENCHMARK_RELATIVE(complexBlob4) {
  complexBenchmark<Blob<4>>();
}

BENCHMARK_RELATIVE(complexBlob8) {
  complexBenchmark<Blob<8>>();
}

BENCHMARK_RELATIVE(complexBlob64) {
  complexBenchmark<Blob<64>>();
}

BENCHMARK_RELATIVE(complexBlob128) {
  complexBenchmark<Blob<128>>();
}

BENCHMARK_RELATIVE(complexBlob256) {
  complexBenchmark<Blob<256>>();
}

BENCHMARK_RELATIVE(complexBlob512) {
  complexBenchmark<Blob<512>>();
}

BENCHMARK_RELATIVE(complexBlob1024) {
  complexBenchmark<Blob<1024>>();
}

BENCHMARK_RELATIVE(complexBlob2048) {
  complexBenchmark<Blob<2048>>();
}

BENCHMARK_RELATIVE(complexBlob4096) {
  complexBenchmark<Blob<4096>>();
}

int main(int argc, char** argv) {
  gflags::ParseCommandLineFlags(&argc, &argv, true);
  folly::runBenchmarks();
  return 0;
}
<commit_msg>Add benchmark for inline continuations:<commit_after>/*
 * Copyright 2014-present Facebook, Inc.
 *
 * 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 <folly/Benchmark.h>
#include <folly/executors/InlineExecutor.h>
#include <folly/futures/Future.h>
#include <folly/futures/Promise.h>
#include <folly/futures/test/TestExecutor.h>
#include <folly/portability/GFlags.h>
#include <folly/portability/Semaphore.h>
#include <folly/synchronization/Baton.h>

#include <vector>

using namespace folly;

namespace {

template <class T>
T incr(Try<T>&& t) {
  return t.value() + 1;
}

Future<int> thens(Future<int> f, size_t n, bool runInline = false) {
  for (size_t i = 0; i < n; i++) {
    if (runInline) {
      f = std::move(f).thenInline(incr<int>);
    } else {
      f = std::move(f).then(incr<int>);
    }
  }
  return f;
}

void someThens(size_t n) {
  auto f = makeFuture<int>(42);
  f = thens(std::move(f), n);
}

void someThensOnThread(size_t n, bool runInline = false) {
  auto executor = std::make_unique<TestExecutor>(1);
  auto f = makeFuture<int>(42).via(executor.get());
  f = thens(std::move(f), n / 2, runInline);
  f = thens(std::move(f), 1, false);
  f = thens(std::move(f), n / 2, runInline);
  f.wait();
}

} // namespace

BENCHMARK(constantFuture) {
  makeFuture(42);
}

BENCHMARK_RELATIVE(promiseAndFuture) {
  Promise<int> p;
  Future<int> f = p.getFuture();
  p.setValue(42);
  f.value();
}

BENCHMARK_RELATIVE(withThen) {
  Promise<int> p;
  Future<int> f = p.getFuture().then(incr<int>);
  p.setValue(42);
  f.value();
}

// thens
BENCHMARK_DRAW_LINE();

BENCHMARK(oneThen) {
  someThens(1);
}

// look for >= 50% relative
BENCHMARK_RELATIVE(twoThens) {
  someThens(2);
}

// look for >= 25% relative
BENCHMARK_RELATIVE(fourThens) {
  someThens(4);
}

// look for >= 1% relative
BENCHMARK_RELATIVE(hundredThens) {
  someThens(100);
}

BENCHMARK_DRAW_LINE();

// look for >= 25% relative
BENCHMARK_RELATIVE(fourThensOnThread) {
  someThensOnThread(4);
}

// look for >= 25% relative
BENCHMARK_RELATIVE(fourThensOnThreadInline) {
  someThensOnThread(4, true);
}

// look for >= 1% relative
BENCHMARK_RELATIVE(hundredThensOnThread) {
  someThensOnThread(100);
}

// look for >= 1% relative
BENCHMARK_RELATIVE(hundredThensOnThreadInline) {
  someThensOnThread(100, true);
}

// Lock contention. Although in practice fulfills tend to be temporally
// separate from then()s, still sometimes they will be concurrent. So the
// higher this number is, the better.
BENCHMARK_DRAW_LINE();

BENCHMARK(no_contention) {
  std::vector<Promise<int>> promises(10000);
  std::vector<Future<int>> futures;
  std::thread producer, consumer;

  BENCHMARK_SUSPEND {
    folly::Baton<> b1, b2;
    for (auto& p : promises) {
      futures.push_back(p.getFuture());
    }

    consumer = std::thread([&] {
      b1.post();
      for (auto& f : futures) {
        std::move(f).then(incr<int>);
      }
    });
    consumer.join();

    producer = std::thread([&] {
      b2.post();
      for (auto& p : promises) {
        p.setValue(42);
      }
    });

    b1.wait();
    b2.wait();
  }

  // The only thing we are measuring is how long fulfill + callbacks take
  producer.join();
}

BENCHMARK_RELATIVE(contention) {
  std::vector<Promise<int>> promises(10000);
  std::vector<Future<int>> futures;
  std::thread producer, consumer;
  sem_t sem;
  sem_init(&sem, 0, 0);

  BENCHMARK_SUSPEND {
    folly::Baton<> b1, b2;
    for (auto& p : promises) {
      futures.push_back(p.getFuture());
    }

    consumer = std::thread([&] {
      b1.post();
      for (auto& f : futures) {
        sem_wait(&sem);
        std::move(f).then(incr<int>);
      }
    });

    producer = std::thread([&] {
      b2.post();
      for (auto& p : promises) {
        sem_post(&sem);
        p.setValue(42);
      }
    });

    b1.wait();
    b2.wait();
  }

  // The astute reader will notice that we're not *precisely* comparing apples
  // to apples here. Well, maybe it's like comparing Granny Smith to
  // Braeburn or something. In the serial version, we waited for the futures
  // to be all set up, but here we are probably still doing that work
  // (although in parallel). But even though there is more work (on the order
  // of 2x), it is being done by two threads. Hopefully most of the difference
  // we see is due to lock contention and not false parallelism.
  //
  // Be warned that if the box is under heavy load, this will greatly skew
  // these results (scheduling overhead will begin to dwarf lock contention).
  // I'm not sure but I'd guess in Windtunnel this will mean large variance,
  // because I expect they load the boxes as much as they can?
  consumer.join();
  producer.join();
}

BENCHMARK_DRAW_LINE();

// The old way. Throw an exception, and rethrow to access it upstream.
void throwAndCatchImpl() {
  makeFuture()
      .then([](Try<Unit>&&) { throw std::runtime_error("oh no"); })
      .then([](Try<Unit>&& t) {
        try {
          t.value();
        } catch (const std::runtime_error& e) {
          // ...
          return;
        }
        CHECK(false);
      });
}

// Not much better. Throw an exception, and access it via the wrapper upstream.
// Actually a little worse due to wrapper overhead. then() won't know that the
// exception is a runtime_error, so will have to store it as an exception_ptr
// anyways. withException will therefore have to rethrow. Note that if we threw
// std::exception instead, we would see some wins, as that's the type then()
// will try to wrap, so no exception_ptrs/rethrows are necessary.
void throwAndCatchWrappedImpl() {
  makeFuture()
      .then([](Try<Unit>&&) { throw std::runtime_error("oh no"); })
      .then([](Try<Unit>&& t) {
        auto caught = t.withException<std::runtime_error>(
            [](const std::runtime_error& /* e */) {
              // ...
            });
        CHECK(caught);
      });
}

// Better. Wrap an exception, and rethrow to access it upstream.
void throwWrappedAndCatchImpl() {
  makeFuture()
      .then([](Try<Unit>&&) {
        return makeFuture<Unit>(std::runtime_error("oh no"));
      })
      .then([](Try<Unit>&& t) {
        try {
          t.value();
        } catch (const std::runtime_error& e) {
          // ...
          return;
        }
        CHECK(false);
      });
}

// The new way. Wrap an exception, and access it via the wrapper upstream
void throwWrappedAndCatchWrappedImpl() {
  makeFuture()
      .then([](Try<Unit>&&) {
        return makeFuture<Unit>(std::runtime_error("oh no"));
      })
      .then([](Try<Unit>&& t) {
        auto caught = t.withException<std::runtime_error>(
            [](const std::runtime_error& /* e */) {
              // ...
            });
        CHECK(caught);
      });
}

// Simulate heavy contention on func
void contend(void (*func)()) {
  folly::BenchmarkSuspender s;
  const int N = 100;
  const int iters = 1000;
  pthread_barrier_t barrier;
  pthread_barrier_init(&barrier, nullptr, N + 1);
  std::vector<std::thread> threads;
  for (int i = 0; i < N; i++) {
    threads.push_back(std::thread([&]() {
      pthread_barrier_wait(&barrier);
      for (int j = 0; j < iters; j++) {
        func();
      }
    }));
  }
  pthread_barrier_wait(&barrier);
  s.dismiss();
  for (auto& t : threads) {
    t.join();
  }
  s.rehire();
  pthread_barrier_destroy(&barrier);
}

BENCHMARK(throwAndCatch) {
  throwAndCatchImpl();
}

BENCHMARK_RELATIVE(throwAndCatchWrapped) {
  throwAndCatchWrappedImpl();
}

BENCHMARK_RELATIVE(throwWrappedAndCatch) {
  throwWrappedAndCatchImpl();
}

BENCHMARK_RELATIVE(throwWrappedAndCatchWrapped) {
  throwWrappedAndCatchWrappedImpl();
}

BENCHMARK_DRAW_LINE();

BENCHMARK(throwAndCatchContended) {
  contend(throwAndCatchImpl);
}

BENCHMARK_RELATIVE(throwAndCatchWrappedContended) {
  contend(throwAndCatchWrappedImpl);
}

BENCHMARK_RELATIVE(throwWrappedAndCatchContended) {
  contend(throwWrappedAndCatchImpl);
}

BENCHMARK_RELATIVE(throwWrappedAndCatchWrappedContended) {
  contend(throwWrappedAndCatchWrappedImpl);
}

BENCHMARK_DRAW_LINE();

namespace {
struct Bulky {
  explicit Bulky(std::string message) : message_(message) {}
  std::string message() & {
    return message_;
  }
  std::string&& message() && {
    return std::move(message_);
  }

 private:
  std::string message_;
  std::array<int, 1024> ints_;
};
} // anonymous namespace

BENCHMARK(lvalue_get) {
  BenchmarkSuspender suspender;
  Optional<Future<Bulky>> future;
  future = makeFuture(Bulky("Hello"));
  suspender.dismissing([&] {
    std::string message = std::move(future.value()).get().message();
    doNotOptimizeAway(message);
  });
}

BENCHMARK_RELATIVE(rvalue_get) {
  BenchmarkSuspender suspender;
  Optional<Future<Bulky>> future;
  future = makeFuture(Bulky("Hello"));
  suspender.dismissing([&] {
    std::string message = std::move(future.value()).get().message();
    doNotOptimizeAway(message);
  });
}

InlineExecutor exe;

template <class T>
Future<T> fGen() {
  Promise<T> p;
  auto f = p.getFuture()
               .thenValue([](T&& t) { return std::move(t); })
               .thenValue([](T&& t) { return makeFuture(std::move(t)); })
               .via(&exe)
               .thenValue([](T&& t) { return std::move(t); })
               .thenValue([](T&& t) { return makeFuture(std::move(t)); });
  p.setValue(T());
  return f;
}

template <class T>
std::vector<Future<T>> fsGen() {
  std::vector<Future<T>> fs;
  for (auto i = 0; i < 10; i++) {
    fs.push_back(fGen<T>());
  }
  return fs;
}

template <class T>
void complexBenchmark() {
  collect(fsGen<T>());
  collectAll(fsGen<T>());
  collectAny(fsGen<T>());
  futures::mapValue(fsGen<T>(), [](const T& t) { return t; });
  futures::mapValue(fsGen<T>(), [](const T& t) { return makeFuture(T(t)); });
}

BENCHMARK_DRAW_LINE();

template <size_t S>
struct Blob {
  char buf[S];
};

BENCHMARK(complexUnit) {
  complexBenchmark<Unit>();
}

BENCHMARK_RELATIVE(complexBlob4) {
  complexBenchmark<Blob<4>>();
}

BENCHMARK_RELATIVE(complexBlob8) {
  complexBenchmark<Blob<8>>();
}

BENCHMARK_RELATIVE(complexBlob64) {
  complexBenchmark<Blob<64>>();
}

BENCHMARK_RELATIVE(complexBlob128) {
  complexBenchmark<Blob<128>>();
}

BENCHMARK_RELATIVE(complexBlob256) {
  complexBenchmark<Blob<256>>();
}

BENCHMARK_RELATIVE(complexBlob512) {
  complexBenchmark<Blob<512>>();
}

BENCHMARK_RELATIVE(complexBlob1024) {
  complexBenchmark<Blob<1024>>();
}

BENCHMARK_RELATIVE(complexBlob2048) {
  complexBenchmark<Blob<2048>>();
}

BENCHMARK_RELATIVE(complexBlob4096) {
  complexBenchmark<Blob<4096>>();
}

int main(int argc, char** argv) {
  gflags::ParseCommandLineFlags(&argc, &argv, true);
  folly::runBenchmarks();
  return 0;
}
<|endoftext|>


<commit_before>#include <MT2D/MT2D_Terminal_Define.h>

#ifdef SDL_USE
#include <MT2D/SDL/MT2D_SDL_Redefine.h>
#include <MT2D/SDL/MT2D_SDL_Event_Handler.h>
#include <MT2D/MT2D_Debug.h>

/*GLOBAL VARS*/
int FRAMEBUFFER[MAX_VER][MAX_HOR]; //used to store what was draw under the screen, (it should avoid overdrawn)
SDL_DisplayMode mode;
//The actual hardware texture
MT2D_SDL_Texture* mTexture;
//The window we'll be rendering to
MT2D_SDL_Window* gWindow = NULL;
//Scene sprites
MT2D_SDL_Rect gSpriteClips[256];
SDL_Surface* NEWloadedSurface;
MT2D_SDL_Texture *CharSprite[256] = { NULL };;
MT2D_SDL_Texture *CharSpriteRotated[256] = { NULL };
MT2D_SDL_Rect ScreenBuffer_Size;
MT2D_SDL_Texture *OffscrBuff[2];
bool fullscreen = false;
SDL_Surface *surface;
extern MT2D_SDL_Events MainEvents;

#pragma region SDL_stbimage_adapted_code

void SDL_Render();
#ifdef SDL_stbimage;
SDL_Surface *IMG_Load(const char *file) {
	return STBIMG_Load(file);
}

void IMG_Quit() {}  // not required

int IMG_Init(int flags) { return true; }

#define IMG_INIT_PNG true

#endif
#pragma endregion

void free_Texture() {
	//Free texture if it exists
	if (mTexture != NULL)
	{
		MT2D_SDL_DestroyTexture(mTexture);
		mTexture = NULL;
	}
}

bool NewLoadFromFile(char *string) {
	//Get rid of preexisting texture
	int mWidth;
	int mHeight;
	free_Texture();
	int TAccess = SDL_TEXTUREACCESS_STREAMING;
	MT2D_SDL_Rect RotateClip;

	RotateClip.h = FONT_SIZEY;
	RotateClip.w = FONT_SIZEX;
	RotateClip.x = 0;
	RotateClip.y = 0;

	//The final texture
	MT2D_SDL_Texture* newTexture = NULL;
	SDL_Surface *tmpSurface = NULL;

	//Load image at specified path
	NEWloadedSurface = IMG_Load(string);
	if (NEWloadedSurface == NULL)
	{
		//printf( "Unable to load image %s! SDL_image Error: %s\n", string, IMG_GetError() );
	}
	else
	{
		//Color key image
		SDL_SetColorKey(NEWloadedSurface, SDL_RLEACCEL, SDL_MapRGB(NEWloadedSurface->format, 0, 0xFF, 0xFF));

		//Create texture from surface pixels
		//SDL_TEXTUREACCESS_STREAMING
		newTexture = MT2D_SDL_CreateTextureFromSurface(MainEvents.Render, NEWloadedSurface);
		if (newTexture == NULL)
		{
			//printf( "Unable to create texture from %s! SDL Error: %s\n", string, SDL_GetError() );
		}
		else
		{
			//Get image dimensions
			mWidth = NEWloadedSurface->w;
			mHeight = NEWloadedSurface->h;
		}
		int hor = 0, ver = 0;

		ScreenBuffer_Size.x = 0;
		ScreenBuffer_Size.y = 0;
		ScreenBuffer_Size.w = mode.w;
		ScreenBuffer_Size.h = mode.h;
		OffscrBuff[1]= SDL_CreateTexture(MainEvents.Render, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, FONT_SIZEY*MAX_VER, FONT_SIZEX*MAX_HOR);
		OffscrBuff[0] = SDL_CreateTexture(MainEvents.Render, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, FONT_SIZEX*MAX_HOR, FONT_SIZEY*MAX_VER);
		for (int i = 0; i<256; i++) {
			if (hor>256 - 8) {
				hor = 0;
				ver += 8;
			}
			gSpriteClips[i].x = hor;//posicao x
			gSpriteClips[i].y = ver;//posicao y
			gSpriteClips[i].w = FONT_SIZEX;// tamanho x
			gSpriteClips[i].h = FONT_SIZEY;// tamanho y
			hor += 8;
			tmpSurface = SDL_CreateRGBSurface(0, FONT_SIZEX, FONT_SIZEY, 24, 0, 0, 0, 0);
			MT2D_SDL_BlitSurface(NEWloadedSurface, &gSpriteClips[i], tmpSurface, NULL);
			CharSprite[i] = MT2D_SDL_CreateTextureFromSurface(MainEvents.Render, tmpSurface);
			CharSpriteRotated[i] = SDL_CreateTexture(MainEvents.Render, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, FONT_SIZEY, FONT_SIZEX);
			//			CharSpriteRotated[i] = SDL_CreateTextureFromSurface(gRenderer, tmpSurface);
			//			SDL_SetTextureBlendMode(CharSpriteRotated[i], SDL_BLENDMODE_BLEND);
			MT2D_SDL_SetRenderTarget(MainEvents.Render, CharSpriteRotated[i]);
			MT2D_SDL_RenderCopyEx(MainEvents.Render, CharSprite[i], &RotateClip, &RotateClip, 90, NULL, SDL_FLIP_NONE);
			MT2D_SDL_SetRenderTarget(MainEvents.Render, NULL);
			MT2D_SDL_RenderCopy(MainEvents.Render, CharSpriteRotated[i], NULL, &RotateClip);
		}
		//Get rid of old loaded surface
		SDL_FreeSurface(NEWloadedSurface);

	}
	//Return success

	mTexture = newTexture;
	return mTexture != NULL;

}

bool loadMedia()
{
	SDL_Surface *tmpSurface = 0;
	SDL_Rect R;
	int ver = 0;
	int hor = 0;
	int dif = 0;
	//Loading success flag
	bool success = true;
	MT2D_Ide_Printf("MT2D: SDL Load tilemap char - ");
	success = NewLoadFromFile("./msdos_fnt.png");
	//Load sprite sheet texture
	if (!success) {
		success = NewLoadFromFile("../../MT2D/SDL_MT2D/msdos_fnt.png");
	}
	if (success)
	{
		R.h = 0;
		R.w = 0;
		R.x = FONT_SIZEX;
		R.y = FONT_SIZEY;
		tmpSurface = SDL_CreateRGBSurface(0, FONT_SIZEX, FONT_SIZEY, 24, 0, 0, 0, 0);
		for (int i = 0; i<256; i++) {
			if (hor>256 - 8) {
				hor = 0;
				ver += 8;
			}
			gSpriteClips[i].x = hor;//posicao x
			gSpriteClips[i].y = ver;//posicao y
			gSpriteClips[i].w = FONT_SIZEX;// tamanho x
			gSpriteClips[i].h = FONT_SIZEY;// tamanho y
			hor += 8;

		}
		MT2D_Ide_Printf("Success\n");
	}
	else {
		MT2D_Ide_Printf("Failed\n");
	}
	return success;
}

void MT2D_SDL_Init()
{
	//Initialization flag
	bool success = true;
	int i = 0, j = 0;
	MainEvents.RequestRender = false;
	MainEvents.Keyboard;
	MainEvents.Keyboard_Pressed = false;
	MainEvents.Window_Started = false;
	MainEvents.Window_Resized = false;
	MainEvents.Close_Program = false;

	MT2D_Ide_Printf("MT2D: Starting SDL\n");

	//Initialize SDL
	if(SDL_Init(SDL_INIT_VIDEO) != 0)
	{
		//printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() );
		success = false;
	}
    else
	{
//		SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
//		SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
//		SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);

//		SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 0);
//		SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

		//Get screen resolution
		if (SDL_GetCurrentDisplayMode(0, &mode) != 0) {
			return;
		}
		#if  !defined(MT2D_WINDOWED_MODE) || defined(MT2D_SCREEN_RESIZE) //set the screen size as the size of the screen in case of fullscreen.
//            SCREEN_WIDTH = mode.w;
 //           SCREEN_HEIGHT = mode.h;
		#endif

		//Set texture filtering to linear
		if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "0" ) )
		{
			//printf( "Warning: Linear texture filtering not enabled!" );
		}

		//Create a window display
		#ifdef MT2D_WINDOWED_MODE
            gWindow = MT2D_SDL_CreateWindow( "MT2D SDL", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT,  SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
		#else
            gWindow = MT2D_SDL_CreateWindow( "MT2D SDL", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_FULLSCREEN);
		#endif
			MainEvents.Render = MT2D_SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED);
		if( gWindow == NULL )
		{
			//printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() );
			success = false;
		}
		else //load the image from the testing MT2D directory or from the actual exe folder
		{
			surface = IMG_Load("../../MT2D/SDL_MT2D/msdos.ico");
			if (!surface) {
				surface = IMG_Load("./msdos.ico");
			}
			MT2D_SDL_SetWindowIcon(gWindow,surface);
			// ...and the surface containing the icon pixel data is no longer required.
			//SDL_FreeSurface(surface);

			if(MainEvents.Render == NULL )
			{
				//printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
				success = false;
			}
			else
			{
				//Initialize renderer color
				MT2D_SDL_SetRenderDrawColor(MainEvents.Render, 0, 0, 0, 0 );

				//Initialize PNG loading
				int imgFlags = IMG_INIT_PNG;
				if( !( IMG_Init( imgFlags ) & imgFlags ) )
				{
					//printf( "SDL_image could not initialize! SDL_mage Error: %s\n", IMG_GetError() );
					success = false;
				}
			}
		}
	}

	if(success){
		success=loadMedia();
		SDL_GetWindowSize(gWindow, &mode.w, &mode.h);//get the window size
		for (i = 0; i < MAX_HOR; i++) {
			for (j = 0; j < MAX_VER; j++) {
				FRAMEBUFFER[j][i] = -1;
			}
		}
//#ifdef  SDL_stbimage
        #ifndef MT2D_WINDOWED_MODE
		if (mode.w > mode.h) {
			FONT_RESIZEX = (mode.w / 80) - FONT_SIZEX;
			FONT_RESIZEY = (mode.h / 25) - FONT_SIZEY;
		}
		else {

			FONT_RESIZEX = (mode.w / 25);
			FONT_RESIZEY = (mode.h / 80);
			SCREEN_MISSING_WIDTH = mode.w - FONT_RESIZEX * 25;
			SCREEN_MISSING_HEIGHT = mode.h - FONT_RESIZEY * 80;

		}
		#endif
//#endif //  SDL_stbimage
    }
}

void close()
{
	free_Texture();

	//Destroy window
	MT2D_SDL_DestroyRenderer(MainEvents.Render);
	SDL_DestroyWindow( gWindow );
	gWindow = NULL;
	MainEvents.Render = NULL;

	//Quit SDL subsystems
	IMG_Quit();
	SDL_Quit();
}

void SDL_MT2DDelay(int Milliseconds) {
	SDL_Delay((Uint32)Milliseconds);
}

#else
#warning You must define "SDL_USE" to use the SDL code
#endif

<commit_msg>ehm, extra line space...<commit_after>#include <MT2D/MT2D_Terminal_Define.h>

#ifdef SDL_USE
#include <MT2D/SDL/MT2D_SDL_Redefine.h>
#include <MT2D/SDL/MT2D_SDL_Event_Handler.h>
#include <MT2D/MT2D_Debug.h>

/*GLOBAL VARS*/
int FRAMEBUFFER[MAX_VER][MAX_HOR]; //used to store what was draw under the screen, (it should avoid overdrawn)
SDL_DisplayMode mode;
//The actual hardware texture
MT2D_SDL_Texture* mTexture;
//The window we'll be rendering to
MT2D_SDL_Window* gWindow = NULL;
//Scene sprites
MT2D_SDL_Rect gSpriteClips[256];
SDL_Surface* NEWloadedSurface;
MT2D_SDL_Texture *CharSprite[256] = { NULL };;
MT2D_SDL_Texture *CharSpriteRotated[256] = { NULL };
MT2D_SDL_Rect ScreenBuffer_Size;
MT2D_SDL_Texture *OffscrBuff[2];
bool fullscreen = false;
SDL_Surface *surface;
extern MT2D_SDL_Events MainEvents;

#pragma region SDL_stbimage_adapted_code

void SDL_Render();
#ifdef SDL_stbimage;
SDL_Surface *IMG_Load(const char *file) {
	return STBIMG_Load(file);
}

void IMG_Quit() {}  // not required

int IMG_Init(int flags) { return true; }

#define IMG_INIT_PNG true

#endif
#pragma endregion

void free_Texture() {
	//Free texture if it exists
	if (mTexture != NULL)
	{
		MT2D_SDL_DestroyTexture(mTexture);
		mTexture = NULL;
	}
}

bool NewLoadFromFile(char *string) {
	//Get rid of preexisting texture
	int mWidth;
	int mHeight;
	free_Texture();
	int TAccess = SDL_TEXTUREACCESS_STREAMING;
	MT2D_SDL_Rect RotateClip;

	RotateClip.h = FONT_SIZEY;
	RotateClip.w = FONT_SIZEX;
	RotateClip.x = 0;
	RotateClip.y = 0;

	//The final texture
	MT2D_SDL_Texture* newTexture = NULL;
	SDL_Surface *tmpSurface = NULL;

	//Load image at specified path
	NEWloadedSurface = IMG_Load(string);
	if (NEWloadedSurface == NULL)
	{
		//printf( "Unable to load image %s! SDL_image Error: %s\n", string, IMG_GetError() );
	}
	else
	{
		//Color key image
		SDL_SetColorKey(NEWloadedSurface, SDL_RLEACCEL, SDL_MapRGB(NEWloadedSurface->format, 0, 0xFF, 0xFF));

		//Create texture from surface pixels
		//SDL_TEXTUREACCESS_STREAMING
		newTexture = MT2D_SDL_CreateTextureFromSurface(MainEvents.Render, NEWloadedSurface);
		if (newTexture == NULL)
		{
			//printf( "Unable to create texture from %s! SDL Error: %s\n", string, SDL_GetError() );
		}
		else
		{
			//Get image dimensions
			mWidth = NEWloadedSurface->w;
			mHeight = NEWloadedSurface->h;
		}
		int hor = 0, ver = 0;

		ScreenBuffer_Size.x = 0;
		ScreenBuffer_Size.y = 0;
		ScreenBuffer_Size.w = mode.w;
		ScreenBuffer_Size.h = mode.h;
		OffscrBuff[1]= SDL_CreateTexture(MainEvents.Render, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, FONT_SIZEY*MAX_VER, FONT_SIZEX*MAX_HOR);
		OffscrBuff[0] = SDL_CreateTexture(MainEvents.Render, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, FONT_SIZEX*MAX_HOR, FONT_SIZEY*MAX_VER);
		for (int i = 0; i<256; i++) {
			if (hor>256 - 8) {
				hor = 0;
				ver += 8;
			}
			gSpriteClips[i].x = hor;//posicao x
			gSpriteClips[i].y = ver;//posicao y
			gSpriteClips[i].w = FONT_SIZEX;// tamanho x
			gSpriteClips[i].h = FONT_SIZEY;// tamanho y
			hor += 8;
			tmpSurface = SDL_CreateRGBSurface(0, FONT_SIZEX, FONT_SIZEY, 24, 0, 0, 0, 0);
			MT2D_SDL_BlitSurface(NEWloadedSurface, &gSpriteClips[i], tmpSurface, NULL);
			CharSprite[i] = MT2D_SDL_CreateTextureFromSurface(MainEvents.Render, tmpSurface);
			CharSpriteRotated[i] = SDL_CreateTexture(MainEvents.Render, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, FONT_SIZEY, FONT_SIZEX);
			//			CharSpriteRotated[i] = SDL_CreateTextureFromSurface(gRenderer, tmpSurface);
			//			SDL_SetTextureBlendMode(CharSpriteRotated[i], SDL_BLENDMODE_BLEND);
			MT2D_SDL_SetRenderTarget(MainEvents.Render, CharSpriteRotated[i]);
			MT2D_SDL_RenderCopyEx(MainEvents.Render, CharSprite[i], &RotateClip, &RotateClip, 90, NULL, SDL_FLIP_NONE);
			MT2D_SDL_SetRenderTarget(MainEvents.Render, NULL);
			MT2D_SDL_RenderCopy(MainEvents.Render, CharSpriteRotated[i], NULL, &RotateClip);
		}
		//Get rid of old loaded surface
		SDL_FreeSurface(NEWloadedSurface);

	}
	//Return success

	mTexture = newTexture;
	return mTexture != NULL;

}

bool loadMedia()
{
	SDL_Surface *tmpSurface = 0;
	SDL_Rect R;
	int ver = 0;
	int hor = 0;
	int dif = 0;
	//Loading success flag
	bool success = true;
	MT2D_Ide_Printf("MT2D: SDL Load tilemap char - ");
	success = NewLoadFromFile("./msdos_fnt.png");
	//Load sprite sheet texture
	if (!success) {
		success = NewLoadFromFile("../../MT2D/SDL_MT2D/msdos_fnt.png");
	}
	if (success)
	{
		R.h = 0;
		R.w = 0;
		R.x = FONT_SIZEX;
		R.y = FONT_SIZEY;
		tmpSurface = SDL_CreateRGBSurface(0, FONT_SIZEX, FONT_SIZEY, 24, 0, 0, 0, 0);
		for (int i = 0; i<256; i++) {
			if (hor>256 - 8) {
				hor = 0;
				ver += 8;
			}
			gSpriteClips[i].x = hor;//posicao x
			gSpriteClips[i].y = ver;//posicao y
			gSpriteClips[i].w = FONT_SIZEX;// tamanho x
			gSpriteClips[i].h = FONT_SIZEY;// tamanho y
			hor += 8;

		}
		MT2D_Ide_Printf("Success\n");
	}
	else {
		MT2D_Ide_Printf("Failed\n");
	}
	return success;
}

void MT2D_SDL_Init()
{
	//Initialization flag
	bool success = true;
	int i = 0, j = 0;
	MainEvents.RequestRender = false;
	MainEvents.Keyboard;
	MainEvents.Keyboard_Pressed = false;
	MainEvents.Window_Started = false;
	MainEvents.Window_Resized = false;
	MainEvents.Close_Program = false;

	MT2D_Ide_Printf("MT2D: Starting SDL\n");

	//Initialize SDL
	if(SDL_Init(SDL_INIT_VIDEO) != 0)
	{
		//printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() );
		success = false;
	}
    else
	{
//		SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
//		SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
//		SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
		SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 0);
//		SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 0);
//		SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

		//Get screen resolution
		if (SDL_GetCurrentDisplayMode(0, &mode) != 0) {
			return;
		}
		#if  !defined(MT2D_WINDOWED_MODE) || defined(MT2D_SCREEN_RESIZE) //set the screen size as the size of the screen in case of fullscreen.
//            SCREEN_WIDTH = mode.w;
 //           SCREEN_HEIGHT = mode.h;
		#endif

		//Set texture filtering to linear
		if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "0" ) )
		{
			//printf( "Warning: Linear texture filtering not enabled!" );
		}

		//Create a window display
		#ifdef MT2D_WINDOWED_MODE
            gWindow = MT2D_SDL_CreateWindow( "MT2D SDL", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT,  SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
		#else
            gWindow = MT2D_SDL_CreateWindow( "MT2D SDL", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_FULLSCREEN);
		#endif
			MainEvents.Render = MT2D_SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED);
		if( gWindow == NULL )
		{
			//printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() );
			success = false;
		}
		else //load the image from the testing MT2D directory or from the actual exe folder
		{
			surface = IMG_Load("../../MT2D/SDL_MT2D/msdos.ico");
			if (!surface) {
				surface = IMG_Load("./msdos.ico");
			}
			MT2D_SDL_SetWindowIcon(gWindow,surface);
			// ...and the surface containing the icon pixel data is no longer required.
			//SDL_FreeSurface(surface);

			if(MainEvents.Render == NULL )
			{
				//printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
				success = false;
			}
			else
			{
				//Initialize renderer color
				MT2D_SDL_SetRenderDrawColor(MainEvents.Render, 0, 0, 0, 0 );

				//Initialize PNG loading
				int imgFlags = IMG_INIT_PNG;
				if( !( IMG_Init( imgFlags ) & imgFlags ) )
				{
					//printf( "SDL_image could not initialize! SDL_mage Error: %s\n", IMG_GetError() );
					success = false;
				}
			}
		}
	}

	if(success){
		success=loadMedia();
		SDL_GetWindowSize(gWindow, &mode.w, &mode.h);//get the window size
		for (i = 0; i < MAX_HOR; i++) {
			for (j = 0; j < MAX_VER; j++) {
				FRAMEBUFFER[j][i] = -1;
			}
		}
//#ifdef  SDL_stbimage
        #ifndef MT2D_WINDOWED_MODE
		if (mode.w > mode.h) {
			FONT_RESIZEX = (mode.w / 80) - FONT_SIZEX;
			FONT_RESIZEY = (mode.h / 25) - FONT_SIZEY;
		}
		else {

			FONT_RESIZEX = (mode.w / 25);
			FONT_RESIZEY = (mode.h / 80);
			SCREEN_MISSING_WIDTH = mode.w - FONT_RESIZEX * 25;
			SCREEN_MISSING_HEIGHT = mode.h - FONT_RESIZEY * 80;

		}
		#endif
//#endif //  SDL_stbimage
    }
}

void close()
{
	free_Texture();

	//Destroy window
	MT2D_SDL_DestroyRenderer(MainEvents.Render);
	SDL_DestroyWindow( gWindow );
	gWindow = NULL;
	MainEvents.Render = NULL;

	//Quit SDL subsystems
	IMG_Quit();
	SDL_Quit();
}

void SDL_MT2DDelay(int Milliseconds) {
	SDL_Delay((Uint32)Milliseconds);
}

#else
#warning You must define "SDL_USE" to use the SDL code
#endif

<|endoftext|>