<commit_before>#include <cassert>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <algorithm>

int detectorid(unsigned int wirepos, unsigned int gridpos) {
  // Should depend on the instance of a specific detector geomoetry,
  // and calibration data
  unsigned int wire = 128 * (wirepos - 0) / (1231);
  unsigned int grid =  96 * (gridpos - 0) / (1920);
  unsigned id;
  assert(wire >= 0);
  assert(wire <= 128);
  assert(grid >= 0);
  assert(grid <= 96);
  id = grid * 128 + wire;
  return id;
}

class DetMultiGrid {
public:
  enum class hdr { DAT = 0x00, HDR, END = 0x03 };

  typedef struct {
    unsigned int    n_words    : 12;
    unsigned int    adc_res    : 3;
    unsigned int    out_format : 1;
    unsigned int    module_id  : 8;
    unsigned int    sub_header : 6;
    unsigned int    header_sig : 2;
  } EventHeader;

typedef struct {
    unsigned int    adc_data   : 14;
    unsigned int    overflow   : 1;
    unsigned int    nop        : 1;
    unsigned int    channel    : 5;
    unsigned int    fix        : 9;
    unsigned int    data_sig   : 2;
  } DataWord;

  typedef struct {
    unsigned int    trigger    : 30;
    unsigned int    footer_sig : 2;
  } Footer;

  union {
    EventHeader eh;
    DataWord dw;
    Footer ef;
  } data;

  unsigned int wthresh{230}; // Current values from Anton
  unsigned int gthresh{170}; //          -=-

  const char * df[9]= {"w0 amp", "w1 amp", "w0 pos", "w1 pos", "g0 amp",
                       "g1 amp", "g0 pos", "g1 pos", "time  "};

  unsigned int readsz{sizeof data};
};

int main(int argc, char * argv[]) {
  DetMultiGrid det;
  char * filename;

  struct stat_t {
    int rx;      // file stats - Rx bytes
    int errors;  // event stat - header errors
    int events;  // event stat - number of events
    int noise;   //
    int multi;   // event stat - number of multi events
  } stat;

  unsigned int rxdata[9], maxdata[9], mindata[9];  // readout data

  if (argc == 2) {  // Filename only
    filename = argv[1];
  } else if (argc == 4) { // filename wthresh gthresh
    det.wthresh = atoi(argv[2]); // signed int to unsigned int
    det.gthresh = atoi(argv[3]);
    assert(det.wthresh < 16384); // check for negative numbers
    assert(det.gthresh < 16384);
    filename = argv[1];
  } else {
    printf("usage: %s filename [wire_thresh grid_thresh]\n", argv[0]);
    return -1;
  }

  bzero(&stat, sizeof(stat));
  memset(maxdata, 0x00, sizeof(maxdata));
  memset(mindata, 0xff, sizeof(mindata));

  printf("file: %s\n", filename);
  printf("wire thresh: %u\n", det.wthresh);
  printf("grid thresh: %u\n", det.gthresh);

  FILE *f = fopen(filename, "r");
  if (f == NULL) {
    printf("error: cannot open file \'%s\'\n", filename);
    return -1;
  }

  assert(det.readsz == 4);
  while (fread(&det.data, det.readsz, 1, f) > 0){
    stat.rx += det.readsz;

    if (det.data.eh.header_sig == (int)DetMultiGrid::hdr::HDR) { // Read Header
      int nread = det.data.eh.n_words;
      assert(nread == 9);

      bzero(rxdata, sizeof(rxdata));
      for (int j = 0; j < nread - 1; j++) {
        if (fread(&det.data, det.readsz, 1, f) > 0) {     // Read Data
          stat.rx += det.readsz;

          if (det.data.dw.data_sig != (int)DetMultiGrid::hdr::DAT) {
            stat.errors++;
            continue;
          }
          unsigned int ch  = det.data.dw.channel;
          unsigned int dat = det.data.dw.adc_data;
          rxdata[ch] = dat;
          maxdata[ch] = std::max(maxdata[ch], dat);
          mindata[ch] = std::min(mindata[ch], dat);
        }
      }

      // Read Footer
      if (fread(&det.data, det.readsz, 1, f) > 0) {
        stat.rx += det.readsz;

        if (det.data.ef.footer_sig != (int)DetMultiGrid::hdr::END) {
          stat.errors++;
          continue;
        }
        maxdata[8] = std::max(maxdata[8], det.data.ef.trigger);
        mindata[8] = std::min(mindata[8], det.data.ef.trigger);

        // We have data - Process event
        // Discard noisy data
        if ((rxdata[0] < det.wthresh) || (rxdata[4] < det.gthresh)) {
          stat.noise++;
          continue;
        }

        // Detect and discard double neutron event
        if ((rxdata[1] >= det.wthresh) && (rxdata[5] >= det.gthresh)) {
          stat.multi++;
          continue;
        }

        // Real event
        stat.events++;
        detectorid(rxdata[2], rxdata[6]);
      }
    }
  }

  printf("=======================\nStats\n");
  printf("Bytes read:    %d\n", stat.rx);
  printf("Total samples: %d\n", stat.multi + stat.noise + stat.events);
  printf("  events:      %d\n", stat.events);
  printf("  noise:       %d\n", stat.noise);
  printf("  double:      %d\n", stat.multi);
  printf("Errors:        %d\n", stat.errors);
  printf("-----------------------\n");
  printf("Name       Min     Max\n");
  for (int j = 0; j < 9; j++) {
    printf("%s  %5u  %8u\n", det.df[j], mindata[j], maxdata[j]);
  }
  printf("-----------------------\n");
  return 0;
}
<commit_msg>small edit<commit_after>#include <cassert>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <algorithm>

int detectorid(unsigned int wirepos, unsigned int gridpos) {
  // Should depend on the instance of a specific detector geomoetry,
  // and calibration data
  unsigned int wire = 128 * (wirepos - 0) / (1231);
  unsigned int grid =  96 * (gridpos - 0) / (1920);
  unsigned id;
  assert(wire >= 0);
  assert(wire <= 128);
  assert(grid >= 0);
  assert(grid <= 96);
  id = grid * 128 + wire;
  return id;
}

class DetMultiGrid {
public:
  enum class hdr { DAT = 0x00, HDR, END = 0x03 };

  typedef struct {
    unsigned int    n_words    : 12;
    unsigned int    adc_res    : 3;
    unsigned int    out_format : 1;
    unsigned int    module_id  : 8;
    unsigned int    sub_header : 6;
    unsigned int    header_sig : 2;
  } EventHeader;

typedef struct {
    unsigned int    adc_data   : 14;
    unsigned int    overflow   : 1;
    unsigned int    nop        : 1;
    unsigned int    channel    : 5;
    unsigned int    fix        : 9;
    unsigned int    data_sig   : 2;
  } DataWord;

  typedef struct {
    unsigned int    trigger    : 30;
    unsigned int    footer_sig : 2;
  } Footer;

  union {
    EventHeader eh;
    DataWord dw;
    Footer ef;
  } data;

  unsigned int wthresh{230}; // Current values from Anton
  unsigned int gthresh{170}; //          -=-

  const char * df[9]= {"w0 amp", "w1 amp", "w0 pos", "w1 pos", "g0 amp",
                       "g1 amp", "g0 pos", "g1 pos", "time  "};

  unsigned int readsz{sizeof data};
};

int main(int argc, char * argv[]) {
  DetMultiGrid det;
  char * filename;

  struct stat_t {
    int rx;      // file stats - Rx bytes
    int errors;  // event stat - header errors
    int events;  // event stat - number of events
    int noise;   //
    int multi;   // event stat - number of multi events
  } stat;

  unsigned int rxdata[9], maxdata[9], mindata[9];  // readout data

  if (argc == 2) {  // Filename only
    filename = argv[1];
  } else if (argc == 4) { // filename wthresh gthresh
    det.wthresh = atoi(argv[2]); // signed int to unsigned int
    det.gthresh = atoi(argv[3]);
    assert(det.wthresh < 16384); // check for negative numbers
    assert(det.gthresh < 16384);
    filename = argv[1];
  } else {
    printf("usage: %s filename [wire_thresh grid_thresh]\n", argv[0]);
    return -1;
  }

  bzero(&stat, sizeof(stat));
  memset(maxdata, 0x00, sizeof(maxdata));
  memset(mindata, 0xff, sizeof(mindata));

  printf("file: %s\n", filename);
  printf("wire thresh: %u\n", det.wthresh);
  printf("grid thresh: %u\n", det.gthresh);

  FILE *f = fopen(filename, "r");
  if (f == NULL) {
    printf("error: cannot open file \'%s\'\n", filename);
    return -1;
  }

  assert(det.readsz == 4);
  while (fread(&det.data, det.readsz, 1, f) > 0){
    stat.rx += det.readsz;

    if (det.data.eh.header_sig == (int)DetMultiGrid::hdr::HDR) { // Read Header
      int nread = det.data.eh.n_words;
      assert(nread == 9);

      bzero(rxdata, sizeof(rxdata));
      for (int j = 0; j < nread - 1; j++) {
        if (fread(&det.data, det.readsz, 1, f) > 0) {     // Read Data
          stat.rx += det.readsz;

          if (det.data.dw.data_sig != (int)DetMultiGrid::hdr::DAT) {
            stat.errors++;
            continue;
          }
          auto ch  = det.data.dw.channel;
          auto dat = det.data.dw.adc_data;
          rxdata[ch] = dat;
          maxdata[ch] = std::max(maxdata[ch], dat);
          mindata[ch] = std::min(mindata[ch], dat);
        }
      }

      // Read Footer
      if (fread(&det.data, det.readsz, 1, f) > 0) {
        stat.rx += det.readsz;

        if (det.data.ef.footer_sig != (int)DetMultiGrid::hdr::END) {
          stat.errors++;
          continue;
        }
        maxdata[8] = std::max(maxdata[8], det.data.ef.trigger);
        mindata[8] = std::min(mindata[8], det.data.ef.trigger);

        // We have data - Process event
        // Discard noisy data
        if ((rxdata[0] < det.wthresh) || (rxdata[4] < det.gthresh)) {
          stat.noise++;
          continue;
        }

        // Detect and discard double neutron event
        if ((rxdata[1] >= det.wthresh) && (rxdata[5] >= det.gthresh)) {
          stat.multi++;
          continue;
        }

        // Real event
        stat.events++;
        detectorid(rxdata[2], rxdata[6]);
      }
    }
  }

  printf("=======================\nStats\n");
  printf("Bytes read:    %d\n", stat.rx);
  printf("Total samples: %d\n", stat.multi + stat.noise + stat.events);
  printf("  events:      %d\n", stat.events);
  printf("  noise:       %d\n", stat.noise);
  printf("  double:      %d\n", stat.multi);
  printf("Errors:        %d\n", stat.errors);
  printf("-----------------------\n");
  printf("Name       Min     Max\n");
  for (int j = 0; j < 9; j++) {
    printf("%s  %5u  %8u\n", det.df[j], mindata[j], maxdata[j]);
  }
  printf("-----------------------\n");
  return 0;
}
<|endoftext|>


<commit_before><commit_msg>clang: Assigned value is garbage or undefined<commit_after><|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QProcess>
#include <QStringList>
#include <QObject>
#include <QDebug>

#include <MApplication>
#include <MApplicationService>
#ifdef HAVE_DBUS
#include <MApplicationIfAdaptor>
#endif //HAVE_DBUS
#include <MApplicationWindow>
#include <MApplicationPage>
#include <MAction>
#include <MLocale>
#include <MGConfItem>
#include <MSceneManager>
#include <MComponentCache>

#include "mainpage.h"
#include "timedemo.h"
#include "swaphook.h"
#include "widgetsgalleryretranslator.h"
#include "../../benchmarks/performancebenchmark/emptymainloophelper.h"

class MyApplicationService: public MApplicationService
{
public:
    MyApplicationService(QObject *parent = 0) :
        MApplicationService("com.nokia.widgetsgallery", parent) {
    }

    void launch() {
        launchAnotherWithQProcess();
    }

    void handleServiceRegistrationFailure() {
        qDebug() << "MyApplicationService::handleServiceRegistrationFailure()";

        incrementAndRegister();
    }
};

#ifndef Q_OS_WIN
M_EXPORT
#endif
int main(int argc, char **argv)
{
#ifdef M_OS_MAEMO5
    QApplication::setGraphicsSystem(QLatin1String("native"));
#endif //M_OS_MAEMO5
    //MApplication application(argc, argv, "widgetsgallery", new MyApplicationService() );
    MApplication *application = MComponentCache::mApplication(argc, argv);

    WidgetsgalleryRetranslator widgetsgalleryRetranslator;
    QObject::connect(application, SIGNAL(localeSettingsChanged()), &widgetsgalleryRetranslator, SLOT(widgetsgalleryRetranslate()));

    MApplicationWindow* window = MComponentCache::mApplicationWindow();
    window->show();

    MainPage *mainPage = new MainPage;
    Timedemo *timedemo = 0;
    if (qApp->arguments().indexOf("-timedemo") >= 0) {
        QStringList demoPages;
        int idx = qApp->arguments().indexOf("-demopages");
        if (idx >= 0 && idx + 1 < qApp->arguments().count()) {
            demoPages = qApp->arguments()[idx + 1].split(',');
        }

        timedemo = new Timedemo(mainPage, demoPages);

        idx = qApp->arguments().indexOf("-outputcsv");
        if (idx >= 0 && idx + 1 < qApp->arguments().count()) {
            timedemo->setOutputCsv(qApp->arguments()[idx + 1]);
        }
        idx = qApp->arguments().indexOf("-framelog");
        if (idx >= 0 && idx + 1 < qApp->arguments().count()) {
            timedemo->setFramelog(qApp->arguments()[idx + 1]);
        }
    }

    int index = qApp->arguments().indexOf("-initialpage");
    if (index >= 0) {
      if (index + 1 < qApp->arguments().count()) {
          mainPage->setInitialPageToShow(qApp->arguments()[index + 1]);
      }
    }

    EmptyMainLoopHelper mainLoopHelper;
    // -quitimmediately will create fully the content of the main page
    // -exitimmediately will skip creating the content of the main page
    if (qApp->arguments().indexOf("-quitimmediately") >= 0 || qApp->arguments().indexOf("-exitimmediately") >= 0) {
        // terminate widgetsgallery as soon as the content is shown and main loop is idle
        mainPage->setMainLoopHelper(&mainLoopHelper);
        mainLoopHelper.triggerTermination(EmptyMainLoopHelper::QuitOnEmpty);
    }

    window->sceneManager()->appearSceneWindowNow(mainPage);

    int exitCode = application->exec();
    delete timedemo;
    delete mainPage;
    delete window;
    delete application;
    return exitCode;
}
<commit_msg>Changes: Show widgetsgallery window, after the content is ready for rendering.<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QProcess>
#include <QStringList>
#include <QObject>
#include <QDebug>

#include <MApplication>
#include <MApplicationService>
#ifdef HAVE_DBUS
#include <MApplicationIfAdaptor>
#endif //HAVE_DBUS
#include <MApplicationWindow>
#include <MApplicationPage>
#include <MAction>
#include <MLocale>
#include <MGConfItem>
#include <MSceneManager>
#include <MComponentCache>

#include "mainpage.h"
#include "timedemo.h"
#include "swaphook.h"
#include "widgetsgalleryretranslator.h"
#include "../../benchmarks/performancebenchmark/emptymainloophelper.h"

class MyApplicationService: public MApplicationService
{
public:
    MyApplicationService(QObject *parent = 0) :
        MApplicationService("com.nokia.widgetsgallery", parent) {
    }

    void launch() {
        launchAnotherWithQProcess();
    }

    void handleServiceRegistrationFailure() {
        qDebug() << "MyApplicationService::handleServiceRegistrationFailure()";

        incrementAndRegister();
    }
};

#ifndef Q_OS_WIN
M_EXPORT
#endif
int main(int argc, char **argv)
{
#ifdef M_OS_MAEMO5
    QApplication::setGraphicsSystem(QLatin1String("native"));
#endif //M_OS_MAEMO5
    //MApplication application(argc, argv, "widgetsgallery", new MyApplicationService() );
    MApplication *application = MComponentCache::mApplication(argc, argv);

    WidgetsgalleryRetranslator widgetsgalleryRetranslator;
    QObject::connect(application, SIGNAL(localeSettingsChanged()), &widgetsgalleryRetranslator, SLOT(widgetsgalleryRetranslate()));

    MApplicationWindow* window = MComponentCache::mApplicationWindow();

    MainPage *mainPage = new MainPage;
    Timedemo *timedemo = 0;
    if (qApp->arguments().indexOf("-timedemo") >= 0) {
        QStringList demoPages;
        int idx = qApp->arguments().indexOf("-demopages");
        if (idx >= 0 && idx + 1 < qApp->arguments().count()) {
            demoPages = qApp->arguments()[idx + 1].split(',');
        }

        timedemo = new Timedemo(mainPage, demoPages);

        idx = qApp->arguments().indexOf("-outputcsv");
        if (idx >= 0 && idx + 1 < qApp->arguments().count()) {
            timedemo->setOutputCsv(qApp->arguments()[idx + 1]);
        }
        idx = qApp->arguments().indexOf("-framelog");
        if (idx >= 0 && idx + 1 < qApp->arguments().count()) {
            timedemo->setFramelog(qApp->arguments()[idx + 1]);
        }
    }

    int index = qApp->arguments().indexOf("-initialpage");
    if (index >= 0) {
      if (index + 1 < qApp->arguments().count()) {
          mainPage->setInitialPageToShow(qApp->arguments()[index + 1]);
      }
    }

    EmptyMainLoopHelper mainLoopHelper;
    // -quitimmediately will create fully the content of the main page
    // -exitimmediately will skip creating the content of the main page
    if (qApp->arguments().indexOf("-quitimmediately") >= 0 || qApp->arguments().indexOf("-exitimmediately") >= 0) {
        // terminate widgetsgallery as soon as the content is shown and main loop is idle
        mainPage->setMainLoopHelper(&mainLoopHelper);
        mainLoopHelper.triggerTermination(EmptyMainLoopHelper::QuitOnEmpty);
    }

    window->sceneManager()->appearSceneWindowNow(mainPage);
    window->show();

    int exitCode = application->exec();
    delete timedemo;
    delete mainPage;
    delete window;
    delete application;
    return exitCode;
}
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------
// Copyright 2011 Ciaran McHale.
//
// 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 "SchemaTypeTable.h"
#include "Common.h"

namespace CONFIG4CPP_NAMESPACE {

void
SchemaTypeTable::checkRule(
	const SchemaValidator *		sv,
	const Configuration *		cfg,
	const char *				typeName,
	const StringVector &		typeArgs,
	const char *				rule) const throw(ConfigurationException)
{
    unused(cfg);

	StringBuffer				msg;
	int							i;
	const char *				columnType;
	SchemaType *				typeDef;

	//--------
	// Check there is at least one pair of column-type, column-name
	// arguments.
	//--------
	int len = typeArgs.length();
	if ((len == 0) || (len % 2 != 0)) {
		msg << "the '" << typeName << "' type requires pairs of column-type "
			<< "and column-name arguments in " << "rule '" << rule << "'";
		throw ConfigurationException(msg.c_str());
	}

	//--------
	// Check that all the column-type arguments are valid types.
	//--------
	for (i = 0; i < len; i+=2) {
		columnType = typeArgs[i+0];
		typeDef = findType(sv, columnType);
		if (typeDef == 0) {
			msg << "unknown type '" << columnType << "' in rule '"
				<< rule << "'";
			throw ConfigurationException(msg.c_str());
		}
		switch (typeDef->cfgType()) {
		case Configuration::CFG_STRING:
			break;
		case Configuration::CFG_LIST:
			msg << "you cannot embed a list type ('" << columnType
				<< "') inside a table in rule '" << rule << "'";
			throw ConfigurationException(msg.c_str());
		case Configuration::CFG_SCOPE:
			msg << "you cannot embed a scope type ('" << columnType
				<< "') inside a table in rule '" << rule << "'";
			throw ConfigurationException(msg.c_str());
		default:
			assert(0); // Bug!
		}
	}
}

void
SchemaTypeTable::validate(
	const SchemaValidator *		sv,
	const Configuration *		cfg,
	const char *				scope,
	const char *				name,
	const char *				typeName,
	const char *				origTypeName,
	const StringVector &		typeArgs,
	int							indentLevel) const
											throw(ConfigurationException)
{
    unused(origTypeName);

	StringBuffer				msg;
	StringBuffer				errSuffix;
	StringBuffer				fullyScopedName;
	const char **				list;
	const char *				colValue;
	const char *				colTypeName;
	int							i;
	int							listSize;
	int							typeArgsSize;
	int							colNameIndex;
	int							typeIndex;
	int							rowNum;
	int							numColumns;
	SchemaType *				colTypeDef;
	StringVector				emptyArgs;
	bool						ok;
	const char *				sep;

	//--------
	// Check that the length of the list is a multiple of the number
	// of columns in the table.
	//--------
	typeArgsSize = typeArgs.length();
	assert(typeArgsSize != 0);
	assert(typeArgsSize % 2 == 0);
	numColumns = typeArgsSize / 2;
	cfg->lookupList(scope, name, list, listSize);
	if (listSize % numColumns != 0) {
		cfg->mergeNames(scope, name, fullyScopedName);
		msg << cfg->fileName() << ": the number of entries in the '"
			<< fullyScopedName << "' " << typeName
			<< " is not a multiple of " << numColumns;
		throw ConfigurationException(msg.c_str());
	}

	//--------
	// Check each item in the list is of the type specified for its column
	//--------
	for (i = 0; i < listSize; i++) {
		typeIndex    = (i * 2 + 0) % typeArgsSize;
		colNameIndex = (i * 2 + 1) % typeArgsSize;
		rowNum = (i / numColumns) + 1;
		colValue = list[i];
		colTypeName = typeArgs[typeIndex];
		colTypeDef = findType(sv, colTypeName);
		ok = callIsA(colTypeDef, sv, cfg, colValue, colTypeName, emptyArgs,
					 indentLevel + 1, errSuffix);
		if (!ok) {
			if (errSuffix.length() == 0) {
				sep = "";
			} else {
				sep = "; ";
			}
			cfg->mergeNames(scope, name, fullyScopedName);
			msg << cfg->fileName() << ": bad " << colTypeName << " value ('"
				<< colValue << "') for the '" << typeArgs[colNameIndex]
				<< "' column in row " << rowNum << " of the '"
				<< fullyScopedName << "' " << typeName << sep << errSuffix;
			throw ConfigurationException(msg.c_str());
		}
	}
}

} // namespace CONFIG4CPP_NAMESPACE
<commit_msg>Fixes.<commit_after>//-----------------------------------------------------------------------
// Copyright 2011 Ciaran McHale.
//
// 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 "SchemaTypeTable.h"
#include "Common.h"

namespace CONFIG4CPP_NAMESPACE {

void
SchemaTypeTable::checkRule(
	const SchemaValidator *		sv,
	const Configuration *		cfg,
	const char *				typeName,
	const StringVector &		typeArgs,
	const char *				rule) const throw(ConfigurationException)
{
    unused(cfg);

	StringBuffer				msg;

	//--------
	// Check there is at least one pair of column-type, column-name
	// arguments.
	//--------
	int len = typeArgs.length();
	if ((len == 0) || (len % 2 != 0)) {
		msg << "the '" << typeName << "' type requires pairs of column-type "
			<< "and column-name arguments in " << "rule '" << rule << "'";
		throw ConfigurationException(msg.c_str());
	}

	//--------
	// Check that all the column-type arguments are valid types.
	//--------
	for (int i = 0; i < len; i+=2) {
		const char* columnType = typeArgs[i+0];
		SchemaType* typeDef = findType(sv, columnType);
		if (typeDef == 0) {
			msg << "unknown type '" << columnType << "' in rule '"
				<< rule << "'";
			throw ConfigurationException(msg.c_str());
		}
		switch (typeDef->cfgType()) {
		case Configuration::CFG_STRING:
			break;
		case Configuration::CFG_LIST:
			msg << "you cannot embed a list type ('" << columnType
				<< "') inside a table in rule '" << rule << "'";
			throw ConfigurationException(msg.c_str());
		case Configuration::CFG_SCOPE:
			msg << "you cannot embed a scope type ('" << columnType
				<< "') inside a table in rule '" << rule << "'";
			throw ConfigurationException(msg.c_str());
		default:
			assert(0); // Bug!
		}
	}
}

void
SchemaTypeTable::validate(
	const SchemaValidator *		sv,
	const Configuration *		cfg,
	const char *				scope,
	const char *				name,
	const char *				typeName,
	const char *				origTypeName,
	const StringVector &		typeArgs,
	int							indentLevel) const
											throw(ConfigurationException)
{
    unused(origTypeName);

	StringBuffer				msg;
	StringBuffer				errSuffix;
	StringBuffer				fullyScopedName;
	const char **				list;
	int							listSize;
	StringVector				emptyArgs;

	//--------
	// Check that the length of the list is a multiple of the number
	// of columns in the table.
	//--------
	int typeArgsSize = typeArgs.length();
	assert(typeArgsSize != 0);
	assert(typeArgsSize % 2 == 0);
	int numColumns = typeArgsSize / 2;
	cfg->lookupList(scope, name, list, listSize);
	if (listSize % numColumns != 0) {
		cfg->mergeNames(scope, name, fullyScopedName);
		msg << cfg->fileName() << ": the number of entries in the '"
			<< fullyScopedName << "' " << typeName
			<< " is not a multiple of " << numColumns;
		throw ConfigurationException(msg.c_str());
	}

	//--------
	// Check each item in the list is of the type specified for its column
	//--------
	for (int i = 0; i < listSize; i++) {
		int typeIndex    = (i * 2 + 0) % typeArgsSize;
		int colNameIndex = (i * 2 + 1) % typeArgsSize;
		int rowNum = (i / numColumns) + 1;
		const char* colValue = list[i];
		const char* colTypeName = typeArgs[typeIndex];
		SchemaType* colTypeDef = findType(sv, colTypeName);
		bool ok = callIsA(colTypeDef, sv, cfg, colValue, colTypeName, emptyArgs,
					 indentLevel + 1, errSuffix);
		if (!ok) {
            const char* sep;
			if (errSuffix.length() == 0) {
				sep = "";
			} else {
				sep = "; ";
			}
			cfg->mergeNames(scope, name, fullyScopedName);
			msg << cfg->fileName() << ": bad " << colTypeName << " value ('"
				<< colValue << "') for the '" << typeArgs[colNameIndex]
				<< "' column in row " << rowNum << " of the '"
				<< fullyScopedName << "' " << typeName << sep << errSuffix;
			throw ConfigurationException(msg.c_str());
		}
	}
}

} // namespace CONFIG4CPP_NAMESPACE
<|endoftext|>


<commit_before>// SetWorkspaceName.cc for Fluxbox
// Copyright (c) 2003 Henrik Kinnunen (fluxgen(at)users.sourceforge.net)
//
// 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.

// $Id: SetWorkspaceName.cc,v 1.2 2003/08/27 18:05:12 fluxgen Exp $

#include "SetWorkspaceName.hh"

#include "Screen.hh"
#include "Workspace.hh"
#include "WinClient.hh"
#include "FbWinFrameTheme.hh"

#include "FbTk/EventManager.hh"
#include "FbTk/App.hh"

#include <X11/keysym.h>
#include <X11/Xutil.h>

#include <iostream>
using namespace std;

SetWorkspaceName::SetWorkspaceName(BScreen &screen):
    FbWindow(screen.rootWindow().screenNumber(),
             0, 0, 1, 1, 0),
    m_textbox(*this, m_font, screen.currentWorkspace()->name()),
    m_label(*this, m_font, "Set workspace name:"),
    m_font("fixed"),
    m_gc(m_textbox),
    m_screen(screen),
    m_move_x(0),
    m_move_y(0) {

    m_label.setGC(screen.winFrameTheme().labelTextFocusGC());
    m_label.setBackgroundColor(screen.winFrameTheme().labelFocusTexture().color());
    m_label.moveResize(0, 0,
                       200, m_font.height() + 2);
    m_label.setEventMask(m_label.eventMask() | ButtonPressMask | ButtonMotionMask); // we listen to motion notify too
    m_label.show();

    m_textbox.setBackgroundColor(FbTk::Color("white", m_textbox.screenNumber()));

    FbTk::Color black("black", m_textbox.screenNumber());
    m_gc.setForeground(black);

    m_textbox.setGC(m_gc.gc());

    m_textbox.moveResize(0, m_label.height(),
                         200, m_font.height() + 2);
    m_textbox.show();

    resize(200, m_textbox.height() + m_label.height());

    // move to center of the screen
    move((screen.width() - width())/2, (screen.height() - height())/2);

    // we need ConfigureNotify from children
    FbTk::EventManager::instance()->addParent(*this, *this);
}

SetWorkspaceName::~SetWorkspaceName() {
    FbTk::EventManager::instance()->remove(*this);
    hide();
}

void SetWorkspaceName::show() {
    FbTk::FbWindow::show();
    m_textbox.setInputFocus();
    m_textbox.setText(m_screen.currentWorkspace()->name());
    m_textbox.clear();
    m_label.clear();
}

void SetWorkspaceName::hide() {
    FbTk::FbWindow::hide();

    // return focus to fluxbox window
    if (Fluxbox::instance()->getFocusedWindow() &&
        Fluxbox::instance()->getFocusedWindow()->fbwindow())
        Fluxbox::instance()->getFocusedWindow()->fbwindow()->setInputFocus();

}

void SetWorkspaceName::buttonPressEvent(XButtonEvent &event) {
    m_textbox.setInputFocus();
    m_move_x = event.x_root - x();
    m_move_y = event.y_root - y();
}

void SetWorkspaceName::handleEvent(XEvent &event) {
    if (event.type == ConfigureNotify && event.xconfigure.window != window()) {
        moveResize(event.xconfigure.x, event.xconfigure.y,
                   event.xconfigure.width, event.xconfigure.height);
    } else if (event.type == DestroyNotify)
        delete this;
}

void SetWorkspaceName::motionNotifyEvent(XMotionEvent &event) {
    int new_x = event.x_root - m_move_x;
    int new_y = event.y_root - m_move_y;
    move(new_x, new_y);
}

void SetWorkspaceName::keyPressEvent(XKeyEvent &event) {
    if (event.state)
        return;

    KeySym ks;
    char keychar[1];
    XLookupString(&event, keychar, 1, &ks, 0);

    if (ks == XK_Return) {
        m_screen.currentWorkspace()->setName(m_textbox.text());
        m_screen.updateWorkspaceNamesAtom();
        Fluxbox::instance()->save_rc();
        delete this; // end this
    } else if (ks == XK_Escape)
        delete this; // end this
}
<commit_msg>minor fix<commit_after>// SetWorkspaceName.cc for Fluxbox
// Copyright (c) 2003 Henrik Kinnunen (fluxgen(at)users.sourceforge.net)
//
// 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.

// $Id: SetWorkspaceName.cc,v 1.3 2003/12/19 00:47:55 fluxgen Exp $

#include "SetWorkspaceName.hh"

#include "Screen.hh"
#include "Workspace.hh"
#include "WinClient.hh"
#include "FbWinFrameTheme.hh"
#include "fluxbox.hh"

#include "FbTk/EventManager.hh"
#include "FbTk/App.hh"

#include <X11/keysym.h>
#include <X11/Xutil.h>

#include <iostream>
using namespace std;

SetWorkspaceName::SetWorkspaceName(BScreen &screen):
    FbWindow(screen.rootWindow().screenNumber(),
             0, 0, 1, 1, 0),
    m_textbox(*this, m_font, screen.currentWorkspace()->name()),
    m_label(*this, m_font, "Set workspace name:"),
    m_font("fixed"),
    m_gc(m_textbox),
    m_screen(screen),
    m_move_x(0),
    m_move_y(0) {

    m_label.setGC(screen.winFrameTheme().labelTextFocusGC());
    m_label.setBackgroundColor(screen.winFrameTheme().labelFocusTexture().color());
    m_label.moveResize(0, 0,
                       200, m_font.height() + 2);
    m_label.setEventMask(m_label.eventMask() | ButtonPressMask | ButtonMotionMask); // we listen to motion notify too
    m_label.show();

    m_textbox.setBackgroundColor(FbTk::Color("white", m_textbox.screenNumber()));

    FbTk::Color black("black", m_textbox.screenNumber());
    m_gc.setForeground(black);

    m_textbox.setGC(m_gc.gc());

    m_textbox.moveResize(0, m_label.height(),
                         200, m_font.height() + 2);
    m_textbox.show();

    resize(200, m_textbox.height() + m_label.height());

    // move to center of the screen
    move((screen.width() - width())/2, (screen.height() - height())/2);

    // we need ConfigureNotify from children
    FbTk::EventManager::instance()->addParent(*this, *this);
}

SetWorkspaceName::~SetWorkspaceName() {
    FbTk::EventManager::instance()->remove(*this);
    hide();
}

void SetWorkspaceName::show() {
    FbTk::FbWindow::show();
    m_textbox.setInputFocus();
    m_textbox.setText(m_screen.currentWorkspace()->name());
    m_textbox.clear();
    m_label.clear();
}

void SetWorkspaceName::hide() {
    FbTk::FbWindow::hide();

    // return focus to fluxbox window
    if (Fluxbox::instance()->getFocusedWindow() &&
        Fluxbox::instance()->getFocusedWindow()->fbwindow())
        Fluxbox::instance()->getFocusedWindow()->fbwindow()->setInputFocus();

}

void SetWorkspaceName::buttonPressEvent(XButtonEvent &event) {
    m_textbox.setInputFocus();
    m_move_x = event.x_root - x();
    m_move_y = event.y_root - y();
}

void SetWorkspaceName::handleEvent(XEvent &event) {
    if (event.type == ConfigureNotify && event.xconfigure.window != window()) {
        moveResize(event.xconfigure.x, event.xconfigure.y,
                   event.xconfigure.width, event.xconfigure.height);
    } else if (event.type == DestroyNotify)
        delete this;
}

void SetWorkspaceName::motionNotifyEvent(XMotionEvent &event) {
    int new_x = event.x_root - m_move_x;
    int new_y = event.y_root - m_move_y;
    move(new_x, new_y);
}

void SetWorkspaceName::keyPressEvent(XKeyEvent &event) {
    if (event.state)
        return;

    KeySym ks;
    char keychar[1];
    XLookupString(&event, keychar, 1, &ks, 0);

    if (ks == XK_Return) {
        m_screen.currentWorkspace()->setName(m_textbox.text());
        m_screen.updateWorkspaceNamesAtom();
        Fluxbox::instance()->save_rc();
        delete this; // end this
    } else if (ks == XK_Escape)
        delete this; // end this
}
<|endoftext|>


<commit_before>/*
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef BENG_PROXY_SLICE_FIFO_BUFFER_HXX
#define BENG_PROXY_SLICE_FIFO_BUFFER_HXX

#include "socket_wrapper.hxx"
#include "util/ForeignFifoBuffer.hxx"

#include <stdint.h>

struct SlicePool;
struct SliceArea;

class SliceFifoBuffer : public ForeignFifoBuffer<uint8_t> {
    SliceArea *area;

public:
    SliceFifoBuffer():ForeignFifoBuffer<uint8_t>(nullptr) {}

    SliceFifoBuffer(SlicePool &pool)
        :ForeignFifoBuffer<uint8_t>(nullptr) {
        Allocate(pool);
    }

    void Swap(SliceFifoBuffer &other) {
        ForeignFifoBuffer<uint8_t>::Swap(other);
        std::swap(area, other.area);
    }

    void Allocate(SlicePool &pool);
    void Free(SlicePool &pool);

    bool IsDefinedAndFull() const {
        return IsDefined() && IsFull();
    }

    void AllocateIfNull(SlicePool &pool) {
        if (IsNull())
            Allocate(pool);
    }

    void FreeIfDefined(SlicePool &pool) {
        if (IsDefined())
            Free(pool);
    }

    void FreeIfEmpty(SlicePool &pool) {
        if (IsEmpty())
            FreeIfDefined(pool);
    }

    /**
     * Move as much data as possible from the specified buffer.  If
     * the destination buffer is empty, the buffers are swapped.  Care
     * is taken that neither buffer suddenly becomes nulled
     * afterwards, because some callers may not be prepared for this.
     */
    void MoveFrom(SliceFifoBuffer &src) {
        if (IsEmpty() && !IsNull() && !src.IsNull())
            /* optimized special case: swap buffer pointers instead of
               copying data */
            Swap(src);
        else
            ForeignFifoBuffer<uint8_t>::MoveFrom(src);
    }

    /**
     * Like MoveFrom(), but allow the destination to be nulled.  This
     * is useful when #src can be freed, but this object cannot.
     */
    void MoveFromAllowNull(SliceFifoBuffer &src) {
        if (IsEmpty() && (!src.IsEmpty() || !IsNull()))
            /* optimized special case: swap buffer pointers instead of
               copying data */
            Swap(src);
        else
            ForeignFifoBuffer<uint8_t>::MoveFrom(src);
    }

    /**
     * Swaps the two buffers if #src is nulled.  This is useful when
     * #src can be freed, but this object cannot.
     */
    void SwapIfNull(SliceFifoBuffer &src) {
        if (src.IsNull() && IsEmpty() && !IsNull())
            Swap(src);
    }
};

#endif
<commit_msg>SliceFifoBuffer: add method CycleIfEmpty()<commit_after>/*
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef BENG_PROXY_SLICE_FIFO_BUFFER_HXX
#define BENG_PROXY_SLICE_FIFO_BUFFER_HXX

#include "socket_wrapper.hxx"
#include "util/ForeignFifoBuffer.hxx"

#include <stdint.h>

struct SlicePool;
struct SliceArea;

class SliceFifoBuffer : public ForeignFifoBuffer<uint8_t> {
    SliceArea *area;

public:
    SliceFifoBuffer():ForeignFifoBuffer<uint8_t>(nullptr) {}

    SliceFifoBuffer(SlicePool &pool)
        :ForeignFifoBuffer<uint8_t>(nullptr) {
        Allocate(pool);
    }

    void Swap(SliceFifoBuffer &other) {
        ForeignFifoBuffer<uint8_t>::Swap(other);
        std::swap(area, other.area);
    }

    void Allocate(SlicePool &pool);
    void Free(SlicePool &pool);

    bool IsDefinedAndFull() const {
        return IsDefined() && IsFull();
    }

    void AllocateIfNull(SlicePool &pool) {
        if (IsNull())
            Allocate(pool);
    }

    void FreeIfDefined(SlicePool &pool) {
        if (IsDefined())
            Free(pool);
    }

    void FreeIfEmpty(SlicePool &pool) {
        if (IsEmpty())
            FreeIfDefined(pool);
    }

    /**
     * If this buffer is empty, free the buffer and reallocate a new
     * one.  This is useful to work around #SliceArea fragmentation.
     */
    void CycleIfEmpty(SlicePool &pool) {
        if (IsDefined() && IsEmpty()) {
            Free(pool);
            Allocate(pool);
        }
    }

    /**
     * Move as much data as possible from the specified buffer.  If
     * the destination buffer is empty, the buffers are swapped.  Care
     * is taken that neither buffer suddenly becomes nulled
     * afterwards, because some callers may not be prepared for this.
     */
    void MoveFrom(SliceFifoBuffer &src) {
        if (IsEmpty() && !IsNull() && !src.IsNull())
            /* optimized special case: swap buffer pointers instead of
               copying data */
            Swap(src);
        else
            ForeignFifoBuffer<uint8_t>::MoveFrom(src);
    }

    /**
     * Like MoveFrom(), but allow the destination to be nulled.  This
     * is useful when #src can be freed, but this object cannot.
     */
    void MoveFromAllowNull(SliceFifoBuffer &src) {
        if (IsEmpty() && (!src.IsEmpty() || !IsNull()))
            /* optimized special case: swap buffer pointers instead of
               copying data */
            Swap(src);
        else
            ForeignFifoBuffer<uint8_t>::MoveFrom(src);
    }

    /**
     * Swaps the two buffers if #src is nulled.  This is useful when
     * #src can be freed, but this object cannot.
     */
    void SwapIfNull(SliceFifoBuffer &src) {
        if (src.IsNull() && IsEmpty() && !IsNull())
            Swap(src);
    }
};

#endif
<|endoftext|>


<commit_before>/*
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef BENG_PROXY_SLICE_FIFO_BUFFER_HXX
#define BENG_PROXY_SLICE_FIFO_BUFFER_HXX

#include "socket_wrapper.hxx"
#include "util/ForeignFifoBuffer.hxx"

#include <stdint.h>

class SliceFifoBuffer : public ForeignFifoBuffer<uint8_t> {
    struct slice_area *area;

public:
    SliceFifoBuffer():ForeignFifoBuffer<uint8_t>(nullptr) {}

    SliceFifoBuffer(struct slice_pool &pool)
        :ForeignFifoBuffer<uint8_t>(nullptr) {
        Allocate(pool);
    }

    void Allocate(struct slice_pool &pool);
    void Free(struct slice_pool &pool);

    bool IsDefinedAndFull() const {
        return IsDefined() && IsFull();
    }

    void AllocateIfNull(struct slice_pool &pool) {
        if (IsNull())
            Allocate(pool);
    }

    void FreeIfDefined(struct slice_pool &pool) {
        if (IsDefined())
            Free(pool);
    }

    void FreeIfEmpty(struct slice_pool &pool) {
        if (IsEmpty())
            FreeIfDefined(pool);
    }
};

#endif
<commit_msg>SliceFifoBuffer: add method Swap()<commit_after>/*
 * author: Max Kellermann <mk@cm4all.com>
 */

#ifndef BENG_PROXY_SLICE_FIFO_BUFFER_HXX
#define BENG_PROXY_SLICE_FIFO_BUFFER_HXX

#include "socket_wrapper.hxx"
#include "util/ForeignFifoBuffer.hxx"

#include <stdint.h>

class SliceFifoBuffer : public ForeignFifoBuffer<uint8_t> {
    struct slice_area *area;

public:
    SliceFifoBuffer():ForeignFifoBuffer<uint8_t>(nullptr) {}

    SliceFifoBuffer(struct slice_pool &pool)
        :ForeignFifoBuffer<uint8_t>(nullptr) {
        Allocate(pool);
    }

    void Swap(SliceFifoBuffer &other) {
        ForeignFifoBuffer<uint8_t>::Swap(other);
        std::swap(area, other.area);
    }

    void Allocate(struct slice_pool &pool);
    void Free(struct slice_pool &pool);

    bool IsDefinedAndFull() const {
        return IsDefined() && IsFull();
    }

    void AllocateIfNull(struct slice_pool &pool) {
        if (IsNull())
            Allocate(pool);
    }

    void FreeIfDefined(struct slice_pool &pool) {
        if (IsDefined())
            Free(pool);
    }

    void FreeIfEmpty(struct slice_pool &pool) {
        if (IsEmpty())
            FreeIfDefined(pool);
    }
};

#endif
<|endoftext|>


<commit_before>#pragma once

#include "../StandardInclude.hpp"
#include "../EntityInclude.hpp"

#include "../StateInterface.hpp"

class GameTitle : public StateInterface
{
public: static GameTitle &GetInstance(void) { static auto instance = GameTitle(); return instance; }
private: GameTitle() { }

private:
	bool IsInitial = true;
	int logoHandle;

public:
	// 場面名を取得します
	string StateName()
	{
		return "Title";
	}

	// 更新(ターゲット時のみ)
	void Update()
	{
		if (IsInitial)
		{
			IsInitial = false;

			logoHandle = LoadGraph("Image/logo.png", 1);
		}
	}

	// 描画(常時)
	void Draw()
	{
		if (Core::GetInstance().GetNowStateName() == StateName())
		{
			int temp[2];
			GetGraphSize(logoHandle, &temp[0], &temp[1]);
			Point imageRightBottom = Point(temp[0], temp[1]);

			Size screenSize = Core::GetInstance().ScreenSize;
			Point screenRightBottom = Point(screenSize.GetWidth(), screenSize.GetHeight());

			Point location = screenRightBottom / 2 - imageRightBottom / 2;
			location.AddY(-150);

			DrawGraph(location.GetX(), location.GetY(), logoHandle, 1);
		}
	}
};<commit_msg>Fix to cast Size to Point<commit_after>#pragma once

#include "../StandardInclude.hpp"
#include "../EntityInclude.hpp"

#include "../StateInterface.hpp"

class GameTitle : public StateInterface
{
public: static GameTitle &GetInstance(void) { static auto instance = GameTitle(); return instance; }
private: GameTitle() { }

private:
	bool IsInitial = true;
	int logoHandle;

public:
	// 場面名を取得します
	string StateName()
	{
		return "Title";
	}

	// 更新(ターゲット時のみ)
	void Update()
	{
		if (IsInitial)
		{
			IsInitial = false;

			logoHandle = LoadGraph("Image/logo.png", 1);
		}
	}

	// 描画(常時)
	void Draw()
	{
		if (Core::GetInstance().GetNowStateName() == StateName())
		{
			int temp[2];
			GetGraphSize(logoHandle, &temp[0], &temp[1]);
			Point imageRightBottom = Point(temp[0], temp[1]);

			Point screenRightBottom = (Point)Core::GetInstance().ScreenSize;

			Point location = screenRightBottom / 2 - imageRightBottom / 2;
			location.AddY(-150);

			DrawGraph(location.GetX(), location.GetY(), logoHandle, 1);
		}
	}
};<|endoftext|>


<commit_before>/*
 * System_fileSync.cpp
 *
 *  Created on: Jun 24, 2014
 *      Author: Pimenta
 */

// this
#include "System.hpp"

// local
#include "Defines.hpp"
#include "FD8Protocol.hpp"
#include "FileSystem.hpp"

using namespace std;
using namespace helpers;
using namespace concurrency;
using namespace network;
using namespace fd8protocol;

void System::send_createFile(const string& fullPath, const ByteQueue& info) {
  Thread([this, fullPath, info]() {
    set<uint32_t> peers;

    for (auto& kv : users) {
      peers.insert(kv.first);

      if (kv.first == localAddress.ip)
        continue;
      TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
      conn.send(char(MTYPE_CREATE_FILE));
      conn.send(fullPath);
      conn.send(uint32_t(info.size()));
      conn.send(info);
    }

    FileSystem::initTmpFileSystem();
    list<FileSystem::Command*> cmds = FileSystem::calculateDuplications(peers);
    list<FileSystem::Command*> balCmds = FileSystem::calculateBalance(peers);
    for (auto& cmd : balCmds)
      cmds.push_back(cmd);
    ByteQueue data = FileSystem::Command::serialize(cmds);
    for (auto& kv : users) {
      if (kv.first == localAddress.ip)
        continue;
      TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
      conn.send(char(MTYPE_COMMANDS));
      conn.send(uint32_t(data.size()));
      conn.send(data);
    }

    send_files(cmds);
    FileSystem::processCommands(cmds);

    for (auto& cmd : cmds)
      delete cmd;
  }).start();
}

void System::send_updateFile(const string& fullPath, const string& newName) {
  Thread([this, fullPath, newName]() {
    for (auto& kv : users) {
      if (kv.first == localAddress.ip)
        continue;
      TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
      conn.send(char(MTYPE_UPDATE_FILE));
      conn.send(fullPath);
      conn.send(newName);
    }
  }).start();
}

void System::send_deleteFile(const string& fullPath) {
  Thread([this, fullPath]() {
    set<uint32_t> peers;

    for (auto& kv : users) {
      peers.insert(kv.first);

      if (kv.first == localAddress.ip)
        continue;
      TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
      conn.send(char(MTYPE_DELETE_FILE));
      conn.send(fullPath);
    }

    FileSystem::initTmpFileSystem();
    list<FileSystem::Command*> cmds = FileSystem::calculateBalance(peers);
    ByteQueue data = FileSystem::Command::serialize(cmds);
    for (auto& kv : users) {
      if (kv.first == localAddress.ip)
        continue;
      TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
      conn.send(char(MTYPE_COMMANDS));
      conn.send(uint32_t(data.size()));
      conn.send(data);
    }

    send_files(cmds);
    FileSystem::processCommands(cmds);

    for (auto& cmd : cmds)
      delete cmd;
  }).start();
}

void System::recv_createFile(const string& fullPath, ByteQueue& info) {
  FileSystem::createFile(fullPath, info);
}

void System::recv_updateFile(const string& fullPath, const string& newName) {
  FileSystem::updateFile(fullPath, newName);
}

void System::recv_deleteFile(const string& fullPath) {
  FileSystem::deleteFile(fullPath);
}

void System::send_files(const list<FileSystem::Command*>& cmds) {
  for (auto& cmd : cmds) {
    if(cmd->type() == MTYPE_CMD_DUPLICATION && ((FileSystem::DuplicationCommand*)cmd)->srcPeer == localAddress.ip) {
      FileSystem::DuplicationCommand dupCmd = *((FileSystem::DuplicationCommand*)cmd);
      Thread([this, dupCmd]() {
        char tmp[25];
        char buf[SIZE_FILEBUFFER_MAXLEN];
        TCPConnection conn(Address(dupCmd.dstPeer, Address("", TCPUDP_MAIN).port));
        sprintf(tmp, "www/files/%08x", dupCmd.fileID);
        FILE* fp = fopen(tmp, "rb");
        fseek(fp, 0, SEEK_END);
        conn.send(char(fd8protocol::MTYPE_FILE));
        conn.send(uint32_t(dupCmd.fileID));
        conn.send(uint32_t(ftell(fp)));
        fclose(fp);
        fp = fopen(tmp, "rb");
        for (
          size_t readBytes;
          (readBytes = fread(buf, 1, SIZE_FILEBUFFER_MAXLEN, fp)) > 0 && state == STATE_IDLE;
          conn.send(buf, readBytes)
        );
        fclose(fp);
      }).start();
    }
    else if(cmd->type() == MTYPE_CMD_BALANCING && ((FileSystem::BalancingCommand*)cmd)->srcPeer == localAddress.ip) {
      FileSystem::BalancingCommand& balCmd = *((FileSystem::BalancingCommand*)cmd);
      string zuera;
      FileSystem::File file = *FileSystem::retrieveFolder("/", zuera)->findFile(balCmd.fileID);
      Thread([this, balCmd, file]() {
        char buf[SIZE_FILEBUFFER_MAXLEN];

        // getting file name
        char tmp[25];
        sprintf(tmp, "www/files/%08x", balCmd.fileID);

        // getting file size
        FILE* fp = fopen(tmp, "rb");
        fseek(fp, 0, SEEK_END);
        uint32_t fileSize = ftell(fp);
        fclose(fp);

        // sending to peer 1
        if (balCmd.peer1 != file.peer1 && balCmd.peer1 != file.peer2) {
          TCPConnection conn(Address(balCmd.peer1, Address("", TCPUDP_MAIN).port));
          conn.send(char(fd8protocol::MTYPE_FILE));
          conn.send(uint32_t(balCmd.fileID));
          conn.send(fileSize);
          fp = fopen(tmp, "rb");
          for (
            size_t readBytes;
            (readBytes = fread(buf, 1, SIZE_FILEBUFFER_MAXLEN, fp)) > 0 && state == STATE_IDLE;
            conn.send(buf, readBytes)
          );
          fclose(fp);
        }

        // sending to peer 2
        if (balCmd.peer2 != file.peer1 && balCmd.peer2 != file.peer2) {
          TCPConnection conn(Address(balCmd.peer2, Address("", TCPUDP_MAIN).port));
          conn.send(char(fd8protocol::MTYPE_FILE));
          conn.send(uint32_t(balCmd.fileID));
          conn.send(fileSize);
          fp = fopen(tmp, "rb");
          for (
            size_t readBytes;
            (readBytes = fread(buf, 1, SIZE_FILEBUFFER_MAXLEN, fp)) > 0 && state == STATE_IDLE;
            conn.send(buf, readBytes)
          );
          fclose(fp);
        }

        remove(tmp);
      }).start();
    }
  }
}
<commit_msg>Fixing bug<commit_after>/*
 * System_fileSync.cpp
 *
 *  Created on: Jun 24, 2014
 *      Author: Pimenta
 */

// this
#include "System.hpp"

// local
#include "Defines.hpp"
#include "FD8Protocol.hpp"
#include "FileSystem.hpp"

using namespace std;
using namespace helpers;
using namespace concurrency;
using namespace network;
using namespace fd8protocol;

void System::send_createFile(const string& fullPath, const ByteQueue& info) {
  Thread([this, fullPath, info]() {
    set<uint32_t> peers;

    for (auto& kv : users) {
      peers.insert(kv.first);

      if (kv.first == localAddress.ip)
        continue;
      TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
      conn.send(char(MTYPE_CREATE_FILE));
      conn.send(fullPath);
      conn.send(uint32_t(info.size()));
      conn.send(info);
    }

    FileSystem::initTmpFileSystem();
    list<FileSystem::Command*> cmds = FileSystem::calculateDuplications(peers);
    list<FileSystem::Command*> balCmds = FileSystem::calculateBalance(peers);
    for (auto& cmd : balCmds)
      cmds.push_back(cmd);
    ByteQueue data = FileSystem::Command::serialize(cmds);
    for (auto& kv : users) {
      if (kv.first == localAddress.ip)
        continue;
      TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
      conn.send(char(MTYPE_COMMANDS));
      conn.send(uint32_t(data.size()));
      conn.send(data);
    }

    send_files(cmds);
    FileSystem::processCommands(cmds);

    for (auto& cmd : cmds)
      delete cmd;
  }).start();
}

void System::send_updateFile(const string& fullPath, const string& newName) {
  Thread([this, fullPath, newName]() {
    for (auto& kv : users) {
      if (kv.first == localAddress.ip)
        continue;
      TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
      conn.send(char(MTYPE_UPDATE_FILE));
      conn.send(fullPath);
      conn.send(newName);
    }
  }).start();
}

void System::send_deleteFile(const string& fullPath) {
  Thread([this, fullPath]() {
    set<uint32_t> peers;

    for (auto& kv : users) {
      peers.insert(kv.first);

      if (kv.first == localAddress.ip)
        continue;
      TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
      conn.send(char(MTYPE_DELETE_FILE));
      conn.send(fullPath);
    }

    FileSystem::initTmpFileSystem();
    list<FileSystem::Command*> cmds = FileSystem::calculateBalance(peers);
    ByteQueue data = FileSystem::Command::serialize(cmds);
    for (auto& kv : users) {
      if (kv.first == localAddress.ip)
        continue;
      TCPConnection conn(Address(kv.first, Address("", TCPUDP_MAIN).port));
      conn.send(char(MTYPE_COMMANDS));
      conn.send(uint32_t(data.size()));
      conn.send(data);
    }

    send_files(cmds);
    FileSystem::processCommands(cmds);

    for (auto& cmd : cmds)
      delete cmd;
  }).start();
}

void System::recv_createFile(const string& fullPath, ByteQueue& info) {
  FileSystem::createFile(fullPath, info);
}

void System::recv_updateFile(const string& fullPath, const string& newName) {
  FileSystem::updateFile(fullPath, newName);
}

void System::recv_deleteFile(const string& fullPath) {
  FileSystem::deleteFile(fullPath);
}

void System::send_files(const list<FileSystem::Command*>& cmds) {
  for (auto& cmd : cmds) {
    if(cmd->type() == MTYPE_CMD_DUPLICATION && ((FileSystem::DuplicationCommand*)cmd)->srcPeer == localAddress.ip) {
      FileSystem::DuplicationCommand dupCmd = *((FileSystem::DuplicationCommand*)cmd);
      Thread([this, dupCmd]() {
        char tmp[25];
        char buf[SIZE_FILEBUFFER_MAXLEN];
        TCPConnection conn(Address(dupCmd.dstPeer, Address("", TCPUDP_MAIN).port));
        sprintf(tmp, "www/files/%08x", dupCmd.fileID);
        FILE* fp = fopen(tmp, "rb");
        fseek(fp, 0, SEEK_END);
        conn.send(char(fd8protocol::MTYPE_FILE));
        conn.send(uint32_t(dupCmd.fileID));
        conn.send(uint32_t(ftell(fp)));
        fclose(fp);
        fp = fopen(tmp, "rb");
        for (
          size_t readBytes;
          (readBytes = fread(buf, 1, SIZE_FILEBUFFER_MAXLEN, fp)) > 0 && state == STATE_IDLE;
          conn.send(buf, readBytes)
        );
        fclose(fp);
      }).start();
    }
    else if (cmd->type() == MTYPE_CMD_BALANCING) {
      FileSystem::BalancingCommand& balCmd = *((FileSystem::BalancingCommand*)cmd);
      string zuera;
      FileSystem::File file = *FileSystem::retrieveFolder("/", zuera)->findFile(balCmd.fileID);
      if (balCmd.srcPeer == localAddress.ip) {
        Thread([this, balCmd, file]() {
          char buf[SIZE_FILEBUFFER_MAXLEN];

          // getting file name
          char tmp[25];
          sprintf(tmp, "www/files/%08x", balCmd.fileID);

          // getting file size
          FILE* fp = fopen(tmp, "rb");
          fseek(fp, 0, SEEK_END);
          uint32_t fileSize = ftell(fp);
          fclose(fp);

          // sending to peer 1
          if (balCmd.peer1 != file.peer1 && balCmd.peer1 != file.peer2) {
            TCPConnection conn(Address(balCmd.peer1, Address("", TCPUDP_MAIN).port));
            conn.send(char(fd8protocol::MTYPE_FILE));
            conn.send(uint32_t(balCmd.fileID));
            conn.send(fileSize);
            fp = fopen(tmp, "rb");
            for (
              size_t readBytes;
              (readBytes = fread(buf, 1, SIZE_FILEBUFFER_MAXLEN, fp)) > 0 && state == STATE_IDLE;
              conn.send(buf, readBytes)
            );
            fclose(fp);
          }

          // sending to peer 2
          if (balCmd.peer2 != file.peer1 && balCmd.peer2 != file.peer2) {
            TCPConnection conn(Address(balCmd.peer2, Address("", TCPUDP_MAIN).port));
            conn.send(char(fd8protocol::MTYPE_FILE));
            conn.send(uint32_t(balCmd.fileID));
            conn.send(fileSize);
            fp = fopen(tmp, "rb");
            for (
              size_t readBytes;
              (readBytes = fread(buf, 1, SIZE_FILEBUFFER_MAXLEN, fp)) > 0 && state == STATE_IDLE;
              conn.send(buf, readBytes)
            );
            fclose(fp);
          }

          remove(tmp);
        }).start();
      }
      else if ((file.peer1 == localAddress.ip || file.peer2 == localAddress.ip) && balCmd.peer1 != localAddress.ip && balCmd.peer2 != localAddress.ip) {
        char tmp[25];
        sprintf(tmp, "www/files/%08x", balCmd.fileID);
        remove(tmp);
      }
    }
  }
}
<|endoftext|>


<commit_before>#include "ImageRenderer.hpp"
#include "FAST/Exception.hpp"
#include "FAST/DeviceManager.hpp"
#include "FAST/Utility.hpp"
#include "FAST/SceneGraph.hpp"
#if defined(__APPLE__) || defined(__MACOSX)
#include <OpenCL/cl_gl.h>
#include <OpenGL/gl.h>
#include <OpenGL/OpenGL.h>
#else
#if _WIN32
#include <GL/gl.h>
#include <CL/cl_gl.h>
#else
#include <GL/glx.h>
#include <CL/cl_gl.h>
#endif
#endif
#include <boost/thread/lock_guard.hpp>

using namespace fast;

#ifndef GL_RGBA32F // this is missing on windows and mac for some reason
#define GL_RGBA32F 0x8814
#endif

void ImageRenderer::execute() {
    boost::lock_guard<boost::mutex> lock(mMutex);

    // This simply gets the input data for each connection and puts it into a data structure
    for(uint inputNr = 0; inputNr < getNrOfInputData(); inputNr++) {
        Image::pointer input = getStaticInputData<Image>(inputNr);

        mImagesToRender[inputNr] = input;
    }
}

void ImageRenderer::addInputConnection(ProcessObjectPort port) {
    uint nr = getNrOfInputData();
    if(nr > 0)
        createInputPort<Image>(nr);
    releaseInputAfterExecute(nr, false);
    setInputConnection(nr, port);
}

ImageRenderer::ImageRenderer() : Renderer() {
    createInputPort<Image>(0, false);
    createOpenCLProgram(std::string(FAST_SOURCE_DIR) + "/Visualization/ImageRenderer/ImageRenderer.cl", "3D");
    createOpenCLProgram(std::string(FAST_SOURCE_DIR) + "/Visualization/ImageRenderer/ImageRenderer2D.cl", "2D");
    mIsModified = false;
}

void ImageRenderer::draw() {
    boost::lock_guard<boost::mutex> lock(mMutex);

    boost::unordered_map<uint, Image::pointer>::iterator it;
    for(it = mImagesToRender.begin(); it != mImagesToRender.end(); it++) {
        Image::pointer input = it->second;
        uint inputNr = it->first;

        // Check if a texture has already been created for this image
        if(mTexturesToRender.count(inputNr) > 0 && mImageUsed[inputNr] == input)
            continue; // If it has already been created, skip it

        // If it has not been created, create the texture

        // Determine level and window
        float window = mWindow;
        float level = mLevel;
        // If mWindow/mLevel is equal to -1 use default level/window values
        if(window == -1) {
            window = getDefaultIntensityWindow(input->getDataType());
        }
        if(level == -1) {
            level = getDefaultIntensityLevel(input->getDataType());
        }

        OpenCLDevice::pointer device = getMainDevice();

        OpenCLImageAccess::pointer access = input->getOpenCLImageAccess(ACCESS_READ, device);
        cl::Image2D* clImage = access->get2DImage();

        glEnable(GL_TEXTURE_2D);
        if(mTexturesToRender.count(inputNr) > 0) {
            // Delete old texture
            glDeleteTextures(1, &mTexturesToRender[inputNr]);
            mTexturesToRender.erase(inputNr);
        }

        // Create OpenGL texture
        GLuint textureID;
        glGenTextures(1, &textureID);
        glBindTexture(GL_TEXTURE_2D, textureID);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, clImage->getImageInfo<CL_IMAGE_WIDTH>(), clImage->getImageInfo<CL_IMAGE_HEIGHT>(), 0, GL_RGBA, GL_FLOAT, 0);
        glBindTexture(GL_TEXTURE_2D, 0);
        glFinish();

        mTexturesToRender[inputNr] = textureID;
        mImageUsed[inputNr] = input;

        // Create CL-GL image
        #if defined(CL_VERSION_1_2)
            cl::ImageGL mImageGL = cl::ImageGL(
                    device->getContext(),
                    CL_MEM_READ_WRITE,
                    GL_TEXTURE_2D,
                    0,
                    textureID
            );
        #else
            cl::Image2DGL mImageGL = cl::Image2DGL(
                    device->getContext(),
                    CL_MEM_READ_WRITE,
                    GL_TEXTURE_2D,
                    0,
                    textureID
            );
        #endif

        std::string kernelName = "renderToTextureInt";
        if(input->getDataType() == TYPE_FLOAT) {
            kernelName = "renderToTextureFloat";
        } else if(input->getDataType() == TYPE_UINT8 || input->getDataType() == TYPE_UINT16) {
            kernelName = "renderToTextureUint";
        }

        mKernel = cl::Kernel(getOpenCLProgram(device, "3D"), kernelName.c_str());
        // Run kernel to fill the texture
        cl::CommandQueue queue = device->getCommandQueue();
        std::vector<cl::Memory> v;
        v.push_back(mImageGL);
        queue.enqueueAcquireGLObjects(&v);

        mKernel.setArg(0, *clImage);
        mKernel.setArg(1, mImageGL);
        mKernel.setArg(2, level);
        mKernel.setArg(3, window);
        queue.enqueueNDRangeKernel(
                mKernel,
                cl::NullRange,
                cl::NDRange(clImage->getImageInfo<CL_IMAGE_WIDTH>(), clImage->getImageInfo<CL_IMAGE_HEIGHT>()),
                cl::NullRange
        );

        queue.enqueueReleaseGLObjects(&v);
        queue.finish();
    }

    // This is the actual rendering
    for(it = mImageUsed.begin(); it != mImageUsed.end(); it++) {
        glPushMatrix();

        AffineTransformation transform = SceneGraph::getAffineTransformationFromData(it->second);
        transform.scale(it->second->getSpacing()); // Apply image spacing
        glMultMatrixf(transform.data());

        glBindTexture(GL_TEXTURE_2D, mTexturesToRender[it->first]);
        uint width = it->second->getWidth();
        uint height = it->second->getHeight();

        glColor3f(1,1,1); // black white texture
        glBegin(GL_QUADS);
            glTexCoord2i(0, 0);
            glVertex3f(0, height, 0.0f);
            glTexCoord2i(1, 0);
            glVertex3f(width, height, 0.0f);
            glTexCoord2i(1, 1);
            glVertex3f(width, 0, 0.0f);
            glTexCoord2i(0, 1);
            glVertex3f(0, 0, 0.0f);
        glEnd();

        glBindTexture(GL_TEXTURE_2D, 0);
        glPopMatrix();
    }
}

void ImageRenderer::draw2D(cl::BufferGL PBO, uint width, uint height, Eigen::Transform<float, 3, Eigen::Affine> pixelToViewportTransform, float PBOspacing, Vector2f translation) {
    boost::lock_guard<boost::mutex> lock(mMutex);

    OpenCLDevice::pointer device = getMainDevice();
    cl::CommandQueue queue = device->getCommandQueue();
    std::vector<cl::Memory> v;
    v.push_back(PBO);
    queue.enqueueAcquireGLObjects(&v);

    // Create an aux PBO
    cl::Buffer PBO2(
            device->getContext(),
            CL_MEM_READ_WRITE,
            sizeof(float)*width*height*4
    );

    boost::unordered_map<uint, Image::pointer>::iterator it;
    for(it = mImagesToRender.begin(); it != mImagesToRender.end(); it++) {
        Image::pointer input = it->second;
        // Determine level and window
        float window = mWindow;
        float level = mLevel;
        // If mWindow/mLevel is equal to -1 use default level/window values
        if(window == -1) {
            window = getDefaultIntensityWindow(input->getDataType());
        }
        if(level == -1) {
            level = getDefaultIntensityLevel(input->getDataType());
        }

        if(input->getDimensions() == 2) {
            cl::Kernel kernel(getOpenCLProgram(device, "2D"), "render2Dimage");
            // Run kernel to fill the texture

            OpenCLImageAccess::pointer access = input->getOpenCLImageAccess(ACCESS_READ, device);
            cl::Image2D* clImage = access->get2DImage();
            kernel.setArg(0, *clImage);
            kernel.setArg(1, PBO); // Read from this
            kernel.setArg(2, PBO2); // Write to this
            kernel.setArg(3, input->getSpacing().x());
            kernel.setArg(4, input->getSpacing().y());
            kernel.setArg(5, PBOspacing);
            kernel.setArg(6, level);
            kernel.setArg(7, window);
            kernel.setArg(8, translation.x());
            kernel.setArg(9, translation.y());

            // Run the draw 2D kernel
            device->getCommandQueue().enqueueNDRangeKernel(
                    kernel,
                    cl::NullRange,
                    cl::NDRange(width, height),
                    cl::NullRange
            );
        } else {

            // Get transform of the image
            AffineTransformation dataTransform = SceneGraph::getAffineTransformationFromData(input);
            dataTransform.scale(it->second->getSpacing()); // Apply image spacing

            // Transfer transformations
            Eigen::Affine3f transform = dataTransform.inverse()*pixelToViewportTransform;

            cl::Buffer transformBuffer(
                    device->getContext(),
                    CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
                    16*sizeof(float),
                    transform.data()
            );

             cl::Kernel kernel(getOpenCLProgram(device, "2D"), "render3Dimage");
            // Run kernel to fill the texture

            OpenCLImageAccess::pointer access = input->getOpenCLImageAccess(ACCESS_READ, device);
            cl::Image3D* clImage = access->get3DImage();
            kernel.setArg(0, *clImage);
            kernel.setArg(1, PBO); // Read from this
            kernel.setArg(2, PBO2); // Write to this
            kernel.setArg(3, transformBuffer);
            kernel.setArg(4, level);
            kernel.setArg(5, window);

            // Run the draw 3D image kernel
            device->getCommandQueue().enqueueNDRangeKernel(
                    kernel,
                    cl::NullRange,
                    cl::NDRange(width, height),
                    cl::NullRange
            );
        }

        // Copy PBO2 to PBO
        queue.enqueueCopyBuffer(PBO2, PBO, 0, 0, sizeof(float)*width*height*4);
    }
    queue.enqueueReleaseGLObjects(&v);
    queue.finish();
}

BoundingBox ImageRenderer::getBoundingBox() {
    std::vector<Vector3f> coordinates;

    boost::unordered_map<uint, Image::pointer>::iterator it;
    for(it = mImagesToRender.begin(); it != mImagesToRender.end(); it++) {
        BoundingBox transformedBoundingBox;
        transformedBoundingBox = it->second->getTransformedBoundingBox();

        MatrixXf corners = transformedBoundingBox.getCorners();
        for(uint j = 0; j < 8; j++) {
            coordinates.push_back((Vector3f)corners.row(j));
        }
    }
    return BoundingBox(coordinates);
}
<commit_msg>fixed image spacing issue in image renderer<commit_after>#include "ImageRenderer.hpp"
#include "FAST/Exception.hpp"
#include "FAST/DeviceManager.hpp"
#include "FAST/Utility.hpp"
#include "FAST/SceneGraph.hpp"
#if defined(__APPLE__) || defined(__MACOSX)
#include <OpenCL/cl_gl.h>
#include <OpenGL/gl.h>
#include <OpenGL/OpenGL.h>
#else
#if _WIN32
#include <GL/gl.h>
#include <CL/cl_gl.h>
#else
#include <GL/glx.h>
#include <CL/cl_gl.h>
#endif
#endif
#include <boost/thread/lock_guard.hpp>

using namespace fast;

#ifndef GL_RGBA32F // this is missing on windows and mac for some reason
#define GL_RGBA32F 0x8814
#endif

void ImageRenderer::execute() {
    boost::lock_guard<boost::mutex> lock(mMutex);

    // This simply gets the input data for each connection and puts it into a data structure
    for(uint inputNr = 0; inputNr < getNrOfInputData(); inputNr++) {
        Image::pointer input = getStaticInputData<Image>(inputNr);

        mImagesToRender[inputNr] = input;
    }
}

void ImageRenderer::addInputConnection(ProcessObjectPort port) {
    uint nr = getNrOfInputData();
    if(nr > 0)
        createInputPort<Image>(nr);
    releaseInputAfterExecute(nr, false);
    setInputConnection(nr, port);
}

ImageRenderer::ImageRenderer() : Renderer() {
    createInputPort<Image>(0, false);
    createOpenCLProgram(std::string(FAST_SOURCE_DIR) + "/Visualization/ImageRenderer/ImageRenderer.cl", "3D");
    createOpenCLProgram(std::string(FAST_SOURCE_DIR) + "/Visualization/ImageRenderer/ImageRenderer2D.cl", "2D");
    mIsModified = false;
}

void ImageRenderer::draw() {
    boost::lock_guard<boost::mutex> lock(mMutex);

    boost::unordered_map<uint, Image::pointer>::iterator it;
    for(it = mImagesToRender.begin(); it != mImagesToRender.end(); it++) {
        Image::pointer input = it->second;
        uint inputNr = it->first;

        // Check if a texture has already been created for this image
        if(mTexturesToRender.count(inputNr) > 0 && mImageUsed[inputNr] == input)
            continue; // If it has already been created, skip it

        // If it has not been created, create the texture

        // Determine level and window
        float window = mWindow;
        float level = mLevel;
        // If mWindow/mLevel is equal to -1 use default level/window values
        if(window == -1) {
            window = getDefaultIntensityWindow(input->getDataType());
        }
        if(level == -1) {
            level = getDefaultIntensityLevel(input->getDataType());
        }

        OpenCLDevice::pointer device = getMainDevice();

        OpenCLImageAccess::pointer access = input->getOpenCLImageAccess(ACCESS_READ, device);
        cl::Image2D* clImage = access->get2DImage();

        glEnable(GL_TEXTURE_2D);
        if(mTexturesToRender.count(inputNr) > 0) {
            // Delete old texture
            glDeleteTextures(1, &mTexturesToRender[inputNr]);
            mTexturesToRender.erase(inputNr);
        }

        // Create OpenGL texture
        GLuint textureID;
        glGenTextures(1, &textureID);
        glBindTexture(GL_TEXTURE_2D, textureID);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, clImage->getImageInfo<CL_IMAGE_WIDTH>(), clImage->getImageInfo<CL_IMAGE_HEIGHT>(), 0, GL_RGBA, GL_FLOAT, 0);
        glBindTexture(GL_TEXTURE_2D, 0);
        glFinish();

        mTexturesToRender[inputNr] = textureID;
        mImageUsed[inputNr] = input;

        // Create CL-GL image
        #if defined(CL_VERSION_1_2)
            cl::ImageGL mImageGL = cl::ImageGL(
                    device->getContext(),
                    CL_MEM_READ_WRITE,
                    GL_TEXTURE_2D,
                    0,
                    textureID
            );
        #else
            cl::Image2DGL mImageGL = cl::Image2DGL(
                    device->getContext(),
                    CL_MEM_READ_WRITE,
                    GL_TEXTURE_2D,
                    0,
                    textureID
            );
        #endif

        std::string kernelName = "renderToTextureInt";
        if(input->getDataType() == TYPE_FLOAT) {
            kernelName = "renderToTextureFloat";
        } else if(input->getDataType() == TYPE_UINT8 || input->getDataType() == TYPE_UINT16) {
            kernelName = "renderToTextureUint";
        }

        mKernel = cl::Kernel(getOpenCLProgram(device, "3D"), kernelName.c_str());
        // Run kernel to fill the texture
        cl::CommandQueue queue = device->getCommandQueue();
        std::vector<cl::Memory> v;
        v.push_back(mImageGL);
        queue.enqueueAcquireGLObjects(&v);

        mKernel.setArg(0, *clImage);
        mKernel.setArg(1, mImageGL);
        mKernel.setArg(2, level);
        mKernel.setArg(3, window);
        queue.enqueueNDRangeKernel(
                mKernel,
                cl::NullRange,
                cl::NDRange(clImage->getImageInfo<CL_IMAGE_WIDTH>(), clImage->getImageInfo<CL_IMAGE_HEIGHT>()),
                cl::NullRange
        );

        queue.enqueueReleaseGLObjects(&v);
        queue.finish();
    }

    // This is the actual rendering
    for(it = mImageUsed.begin(); it != mImageUsed.end(); it++) {
        glPushMatrix();

        AffineTransformation transform = SceneGraph::getAffineTransformationFromData(it->second);
        glMultMatrixf(transform.data());

        glBindTexture(GL_TEXTURE_2D, mTexturesToRender[it->first]);

        // Get width and height in mm
        float width = it->second->getWidth()*it->second->getSpacing().x();
        float height = it->second->getHeight()*it->second->getSpacing().y();

        glColor3f(1,1,1); // black white texture
        glBegin(GL_QUADS);
            glTexCoord2i(0, 0);
            glVertex3f(0, height, 0.0f);
            glTexCoord2i(1, 0);
            glVertex3f(width, height, 0.0f);
            glTexCoord2i(1, 1);
            glVertex3f(width, 0, 0.0f);
            glTexCoord2i(0, 1);
            glVertex3f(0, 0, 0.0f);
        glEnd();

        glBindTexture(GL_TEXTURE_2D, 0);
        glPopMatrix();
    }
}

void ImageRenderer::draw2D(cl::BufferGL PBO, uint width, uint height, Eigen::Transform<float, 3, Eigen::Affine> pixelToViewportTransform, float PBOspacing, Vector2f translation) {
    boost::lock_guard<boost::mutex> lock(mMutex);

    OpenCLDevice::pointer device = getMainDevice();
    cl::CommandQueue queue = device->getCommandQueue();
    std::vector<cl::Memory> v;
    v.push_back(PBO);
    queue.enqueueAcquireGLObjects(&v);

    // Create an aux PBO
    cl::Buffer PBO2(
            device->getContext(),
            CL_MEM_READ_WRITE,
            sizeof(float)*width*height*4
    );

    boost::unordered_map<uint, Image::pointer>::iterator it;
    for(it = mImagesToRender.begin(); it != mImagesToRender.end(); it++) {
        Image::pointer input = it->second;
        // Determine level and window
        float window = mWindow;
        float level = mLevel;
        // If mWindow/mLevel is equal to -1 use default level/window values
        if(window == -1) {
            window = getDefaultIntensityWindow(input->getDataType());
        }
        if(level == -1) {
            level = getDefaultIntensityLevel(input->getDataType());
        }

        if(input->getDimensions() == 2) {
            cl::Kernel kernel(getOpenCLProgram(device, "2D"), "render2Dimage");
            // Run kernel to fill the texture

            OpenCLImageAccess::pointer access = input->getOpenCLImageAccess(ACCESS_READ, device);
            cl::Image2D* clImage = access->get2DImage();
            kernel.setArg(0, *clImage);
            kernel.setArg(1, PBO); // Read from this
            kernel.setArg(2, PBO2); // Write to this
            kernel.setArg(3, input->getSpacing().x());
            kernel.setArg(4, input->getSpacing().y());
            kernel.setArg(5, PBOspacing);
            kernel.setArg(6, level);
            kernel.setArg(7, window);
            kernel.setArg(8, translation.x());
            kernel.setArg(9, translation.y());

            // Run the draw 2D kernel
            device->getCommandQueue().enqueueNDRangeKernel(
                    kernel,
                    cl::NullRange,
                    cl::NDRange(width, height),
                    cl::NullRange
            );
        } else {

            // Get transform of the image
            AffineTransformation dataTransform = SceneGraph::getAffineTransformationFromData(input);
            dataTransform.scale(it->second->getSpacing()); // Apply image spacing

            // Transfer transformations
            Eigen::Affine3f transform = dataTransform.inverse()*pixelToViewportTransform;

            cl::Buffer transformBuffer(
                    device->getContext(),
                    CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
                    16*sizeof(float),
                    transform.data()
            );

             cl::Kernel kernel(getOpenCLProgram(device, "2D"), "render3Dimage");
            // Run kernel to fill the texture

            OpenCLImageAccess::pointer access = input->getOpenCLImageAccess(ACCESS_READ, device);
            cl::Image3D* clImage = access->get3DImage();
            kernel.setArg(0, *clImage);
            kernel.setArg(1, PBO); // Read from this
            kernel.setArg(2, PBO2); // Write to this
            kernel.setArg(3, transformBuffer);
            kernel.setArg(4, level);
            kernel.setArg(5, window);

            // Run the draw 3D image kernel
            device->getCommandQueue().enqueueNDRangeKernel(
                    kernel,
                    cl::NullRange,
                    cl::NDRange(width, height),
                    cl::NullRange
            );
        }

        // Copy PBO2 to PBO
        queue.enqueueCopyBuffer(PBO2, PBO, 0, 0, sizeof(float)*width*height*4);
    }
    queue.enqueueReleaseGLObjects(&v);
    queue.finish();
}

BoundingBox ImageRenderer::getBoundingBox() {
    std::vector<Vector3f> coordinates;

    boost::unordered_map<uint, Image::pointer>::iterator it;
    for(it = mImagesToRender.begin(); it != mImagesToRender.end(); it++) {
        BoundingBox transformedBoundingBox;
        transformedBoundingBox = it->second->getTransformedBoundingBox();

        MatrixXf corners = transformedBoundingBox.getCorners();
        for(uint j = 0; j < 8; j++) {
            coordinates.push_back((Vector3f)corners.row(j));
        }
    }
    return BoundingBox(coordinates);
}
<|endoftext|>


<commit_before>// Copyright (c) 2020 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list ofconditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <functional>
#include <iostream>
#include <vector>
#include "lexer.hh"
#include "value.hh"
#include "chunk.hh"
#include "vm.hh"
#include "compiler.hh"

namespace tadpole {

enum class Precedence {
  NONE,

  ASSIGN, // =
  TERM,   // - +
  FACTOR, // / *
  CALL,   // ()

  PRIMARY,
};

template <typename T> inline Precedence operator+(Precedence a, T b) noexcept {
  return as_type<Precedence>(as_type<int>(a) + as_type<int>(b));
}

struct ParseRule {
  using ParseFn = std::function<void (GlobalParser&, bool)>;

  ParseFn prefix;
  ParseFn infix;
  Precedence precedence;
};

struct LocalVar {
  Token name;
  int depth{};
  bool is_upvalue{};

  LocalVar(const Token& arg_name, int arg_depth = -1, bool arg_upvalue = false) noexcept
    : name(arg_name), depth(arg_depth), is_upvalue(arg_upvalue) {
  }
};

struct Upvalue {
  u8_t index{};
  bool is_local{};

  Upvalue(u8_t arg_index = 0, bool arg_local = false) noexcept
    : index(arg_index), is_local(arg_local) {
  }

  inline bool operator==(Upvalue r) const noexcept {
    return index == r.index && is_local == r.is_local;
  }

  inline bool operator!=(Upvalue r) const noexcept {
    return !(*this == r);
  }

  inline bool is_equal(u8_t arg_index, bool arg_local) const noexcept {
    return index == arg_index && is_local == arg_local;
  }
};

FunctionObject* GlobalCompiler::compile(VM& vm, const str_t& source_bytes) {
  return nullptr;
}

void GlobalCompiler::mark_compiler() {
}

}
<commit_msg>:construction: chore(compiler): add basic compiler for function<commit_after>// Copyright (c) 2020 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list ofconditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <functional>
#include <iostream>
#include <vector>
#include "lexer.hh"
#include "value.hh"
#include "chunk.hh"
#include "vm.hh"
#include "compiler.hh"

namespace tadpole {

enum class Precedence {
  NONE,

  ASSIGN, // =
  TERM,   // - +
  FACTOR, // / *
  CALL,   // ()

  PRIMARY,
};

template <typename T> inline Precedence operator+(Precedence a, T b) noexcept {
  return as_type<Precedence>(as_type<int>(a) + as_type<int>(b));
}

struct ParseRule {
  using ParseFn = std::function<void (GlobalParser&, bool)>;

  ParseFn prefix;
  ParseFn infix;
  Precedence precedence;
};

struct LocalVar {
  Token name;
  int depth{};
  bool is_upvalue{};

  LocalVar(const Token& arg_name, int arg_depth = -1, bool arg_upvalue = false) noexcept
    : name(arg_name), depth(arg_depth), is_upvalue(arg_upvalue) {
  }
};

struct Upvalue {
  u8_t index{};
  bool is_local{};

  Upvalue(u8_t arg_index = 0, bool arg_local = false) noexcept
    : index(arg_index), is_local(arg_local) {
  }

  inline bool operator==(Upvalue r) const noexcept {
    return index == r.index && is_local == r.is_local;
  }

  inline bool operator!=(Upvalue r) const noexcept {
    return !(*this == r);
  }

  inline bool is_equal(u8_t arg_index, bool arg_local) const noexcept {
    return index == arg_index && is_local == arg_local;
  }
};

enum class FunType {
  FUNCTION,
  TOPLEVEL,
};

class Compiler final : private UnCopyable {
  using ErrorFn = std::function<void (const str_t&)>;

  Compiler* enclosing_{};
  FunctionObject* fn_{};
  FunType fn_type_{};

  int scope_depth_{};

  std::vector<LocalVar> locals_;
  std::vector<Upvalue> upvalues_;
public:
  Compiler() noexcept {}

  Compiler(Compiler* enclosing,
      FunctionObject* fn, FunType fn_type, int scope_depth = 0) noexcept
    : enclosing_(enclosing), fn_(fn), fn_type_(fn_type), scope_depth_(scope_depth) {
  }

  inline void set_compiler(Compiler* enclosing,
      FunctionObject* fn, FunType fn_type, int scope_depth = 0) noexcept {
    enclosing_ = enclosing;
    fn_ = fn;
    fn_type_ = fn_type;
    scope_depth_ = scope_depth;
  }

  inline Compiler* enclosing() const noexcept { return enclosing_; }
  inline FunctionObject* fn() const noexcept { return fn_; }
  inline FunType fn_type() const noexcept { return fn_type_; }
  inline int scope_depth() const noexcept { return scope_depth_; }
  inline void set_scope_depth(int depth) noexcept { scope_depth_ = depth; }
  inline int locals_count() const noexcept { return as_type<int>(locals_.size()); }
  inline LocalVar& get_local(sz_t i) noexcept { return locals_[i]; }
  inline const LocalVar& get_local(sz_t i) const noexcept { return locals_[i]; }
  inline LocalVar& peek_local() noexcept { return locals_.back(); }
  inline const LocalVar& peek_local() const noexcept { return locals_.back(); }
  inline void append_local(const LocalVar& var) noexcept { return locals_.push_back(var); }
  inline Upvalue& get_upvalue(sz_t i) noexcept { return upvalues_[i]; }
  inline const Upvalue& get_upvalue(sz_t i) const noexcept { return upvalues_[i]; }
  inline void append_upvalue(const Upvalue& u) noexcept { upvalues_.push_back(u); }
};

FunctionObject* GlobalCompiler::compile(VM& vm, const str_t& source_bytes) {
  return nullptr;
}

void GlobalCompiler::mark_compiler() {
}

}
<|endoftext|>


<commit_before><commit_msg>fix scissor override<commit_after><|endoftext|>


<commit_before>#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <srt/srt.h>

#define DEBUG

#ifdef DEBUG
#include <android/log.h>
#define LOG_TAG "SRT-JNI"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
#else
#define LOGI(...)
#define LOGD(...)
#define LOGE(...)
#define LOGW(...)
#endif

/**
* JNI のパッケージ名、クラス名を定義.
*/
#define JNI_METHOD_NAME(name) Java_org_deviceconnect_android_libsrt_NdkHelper_##name

#ifdef __cplusplus
extern "C" {
#endif

JNIEXPORT void JNICALL
JNI_METHOD_NAME(startup)(JNIEnv *env, jclass clazz) {
    LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_startup()");
    srt_startup();
}

JNIEXPORT void JNICALL
JNI_METHOD_NAME(cleanup)(JNIEnv *env, jclass clazz) {
    LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_cleanup()");
    srt_cleanup();
}

JNIEXPORT jlong JNICALL
JNI_METHOD_NAME(createSrtSocket)(JNIEnv *env, jclass clazz, jstring address, jint port, jint backlog) {
    LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_createSrtSocket()");

    int yes = 1;
    int st;
    int ss = srt_create_socket();
    if (ss == SRT_ERROR) {
        LOGE("srt_socket: %s", srt_getlasterror_str());
        return -1;
    }

    const char *addressString = env->GetStringUTFChars(address, nullptr);
    struct sockaddr_in sa;
    sa.sin_family = AF_INET;
    sa.sin_port = htons(port);
    if (inet_pton(AF_INET, addressString, &sa.sin_addr) != 1) {
        LOGE("inet_pton error.");
        env->ReleaseStringUTFChars(address, addressString);
        return -1;
    }
    env->ReleaseStringUTFChars(address, addressString);

    srt_setsockflag(ss, SRTO_RCVSYN, &yes, sizeof yes);

    st = srt_bind(ss, (struct sockaddr*)&sa, sizeof sa);
    if (st == SRT_ERROR) {
        LOGE("srt_bind: %s", srt_getlasterror_str());
        return -1;
    }

    st = srt_listen(ss, backlog);
    if (st == SRT_ERROR) {
        LOGE("srt_listen: %s\n", srt_getlasterror_str());
        return -1;
    }

    return ss;
}

JNIEXPORT void JNICALL
JNI_METHOD_NAME(closeSrtSocket)(JNIEnv *env, jclass clazz, jlong ptr) {
    LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_closeSrtSocket()");

    int st = srt_close((int) ptr);
    if (st == SRT_ERROR) {
        LOGE("srt_close: %s\n", srt_getlasterror_str());
    }
}

JNIEXPORT jlong JNICALL
JNI_METHOD_NAME(accept)(JNIEnv *env, jclass clazz, jlong ptr, jobject socket) {
    LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_accept()");

    struct sockaddr addr;
    int addrlen;
    int st = srt_accept((int) ptr, &addr, &addrlen);
    if (st == SRT_ERROR) {
        LOGE("srt_accept: %s\n", srt_getlasterror_str());
        return -1;
    }

    // クライアント側のソケットへのポインタ
    jclass socketCls = env->FindClass("org/deviceconnect/android/libsrt/SRTSocket");
    jfieldID socketPtr = env->GetFieldID(socketCls, "mNativePtr", "J");
    env->SetLongField(socket, socketPtr, st);

    // クライアントのIPアドレス
    char format[] = "%d.%d.%d.%d";
    char buf[15];
    sprintf(buf, format, addr.sa_data[2], addr.sa_data[3], addr.sa_data[4], addr.sa_data[5]);
    jstring address = env->NewStringUTF(buf);
    jfieldID addressField = env->GetFieldID(socketCls, "mSocketAddress", "Ljava/lang/String;");
    env->SetObjectField(socket, addressField, address);

    return st;
}

JNIEXPORT int JNICALL
JNI_METHOD_NAME(sendMessage)(JNIEnv *env, jclass clazz, jlong ptr, jbyteArray byteArray, jint offset, jint length) {
    jboolean isCopy;
    jbyte* data = env->GetByteArrayElements(byteArray, &isCopy);
    if (data == nullptr) {
        return -1;
    }

    int result = srt_sendmsg((int) ptr, (const char *) &data[offset], length, -1, 0);
    if (result < SRT_ERROR) {
        LOGE("srt_send: %s\n", srt_getlasterror_str());
    }
    env->ReleaseByteArrayElements(byteArray, data, 0);
    return result;
}

JNIEXPORT int JNICALL
JNI_METHOD_NAME(recvMessage)(JNIEnv *env, jclass clazz, jlong ptr, jbyteArray byteArray, jint length) {
    jboolean isCopy;
    jbyte* data = env->GetByteArrayElements(byteArray, &isCopy);
    if (data == nullptr) {
        return -1;
    }

    int result = srt_recvmsg((int) ptr, (char *) data, length);
    if (result < SRT_ERROR) {
        LOGE("srt_send: %s\n", srt_getlasterror_str());
    }
    env->ReleaseByteArrayElements(byteArray, data, 0);
    return result;
}

JNIEXPORT void JNICALL
JNI_METHOD_NAME(dumpStats)(JNIEnv *env, jclass clazz, jlong ptr) {
    LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_dumpStats(): ptr=%d", ptr);

    SRT_TRACEBSTATS stats;
    int result = srt_bstats((int) ptr, &stats, 0);
    if (result == SRT_ERROR) {
        return;
    }
    LOGD("dumpStats: pktSentTotal=%ld, pktRetransTotal=%d, pktSndLossTotal=%d", stats.pktSentTotal, stats.pktRetransTotal, stats.pktSndLossTotal);
    LOGD("dumpStats: mbpsBandwidth=%f, mbpsMaxBW=%f, byteAvailSndBuf=%d", stats.mbpsBandwidth, stats.mbpsMaxBW, stats.byteAvailSndBuf);
}

#ifdef __cplusplus
}
#endif
<commit_msg>NdkHelper.accept() と NDK の返り値が一致していなかったので修正<commit_after>#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <srt/srt.h>

#define DEBUG

#ifdef DEBUG
#include <android/log.h>
#define LOG_TAG "SRT-JNI"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__)
#else
#define LOGI(...)
#define LOGD(...)
#define LOGE(...)
#define LOGW(...)
#endif

/**
* JNI のパッケージ名、クラス名を定義.
*/
#define JNI_METHOD_NAME(name) Java_org_deviceconnect_android_libsrt_NdkHelper_##name

#ifdef __cplusplus
extern "C" {
#endif

JNIEXPORT void JNICALL
JNI_METHOD_NAME(startup)(JNIEnv *env, jclass clazz) {
    LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_startup()");
    srt_startup();
}

JNIEXPORT void JNICALL
JNI_METHOD_NAME(cleanup)(JNIEnv *env, jclass clazz) {
    LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_cleanup()");
    srt_cleanup();
}

JNIEXPORT jlong JNICALL
JNI_METHOD_NAME(createSrtSocket)(JNIEnv *env, jclass clazz, jstring address, jint port, jint backlog) {
    LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_createSrtSocket()");

    int yes = 1;
    int st;
    int ss = srt_create_socket();
    if (ss == SRT_ERROR) {
        LOGE("srt_socket: %s", srt_getlasterror_str());
        return -1;
    }

    const char *addressString = env->GetStringUTFChars(address, nullptr);
    struct sockaddr_in sa;
    sa.sin_family = AF_INET;
    sa.sin_port = htons(port);
    if (inet_pton(AF_INET, addressString, &sa.sin_addr) != 1) {
        LOGE("inet_pton error.");
        env->ReleaseStringUTFChars(address, addressString);
        return -1;
    }
    env->ReleaseStringUTFChars(address, addressString);

    srt_setsockflag(ss, SRTO_RCVSYN, &yes, sizeof yes);

    st = srt_bind(ss, (struct sockaddr*)&sa, sizeof sa);
    if (st == SRT_ERROR) {
        LOGE("srt_bind: %s", srt_getlasterror_str());
        return -1;
    }

    st = srt_listen(ss, backlog);
    if (st == SRT_ERROR) {
        LOGE("srt_listen: %s\n", srt_getlasterror_str());
        return -1;
    }

    return ss;
}

JNIEXPORT void JNICALL
JNI_METHOD_NAME(closeSrtSocket)(JNIEnv *env, jclass clazz, jlong ptr) {
    LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_closeSrtSocket()");

    int st = srt_close((int) ptr);
    if (st == SRT_ERROR) {
        LOGE("srt_close: %s\n", srt_getlasterror_str());
    }
}

JNIEXPORT void JNICALL
JNI_METHOD_NAME(accept)(JNIEnv *env, jclass clazz, jlong ptr, jobject socket) {
    LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_accept()");

    struct sockaddr addr;
    int addrlen;
    int st = srt_accept((int) ptr, &addr, &addrlen);
    if (st == SRT_ERROR) {
        LOGE("srt_accept: %s\n", srt_getlasterror_str());
        return;
    }

    // クライアント側のソケットへのポインタ
    jclass socketCls = env->FindClass("org/deviceconnect/android/libsrt/SRTSocket");
    jfieldID socketPtr = env->GetFieldID(socketCls, "mNativePtr", "J");
    env->SetLongField(socket, socketPtr, st);

    // クライアントのIPアドレス
    char format[] = "%d.%d.%d.%d";
    char buf[15];
    sprintf(buf, format, addr.sa_data[2], addr.sa_data[3], addr.sa_data[4], addr.sa_data[5]);
    jstring address = env->NewStringUTF(buf);
    jfieldID addressField = env->GetFieldID(socketCls, "mSocketAddress", "Ljava/lang/String;");
    env->SetObjectField(socket, addressField, address);
}

JNIEXPORT int JNICALL
JNI_METHOD_NAME(sendMessage)(JNIEnv *env, jclass clazz, jlong ptr, jbyteArray byteArray, jint offset, jint length) {
    jboolean isCopy;
    jbyte* data = env->GetByteArrayElements(byteArray, &isCopy);
    if (data == nullptr) {
        return -1;
    }

    int result = srt_sendmsg((int) ptr, (const char *) &data[offset], length, -1, 0);
    if (result < SRT_ERROR) {
        LOGE("srt_send: %s\n", srt_getlasterror_str());
    }
    env->ReleaseByteArrayElements(byteArray, data, 0);
    return result;
}

JNIEXPORT int JNICALL
JNI_METHOD_NAME(recvMessage)(JNIEnv *env, jclass clazz, jlong ptr, jbyteArray byteArray, jint length) {
    jboolean isCopy;
    jbyte* data = env->GetByteArrayElements(byteArray, &isCopy);
    if (data == nullptr) {
        return -1;
    }

    int result = srt_recvmsg((int) ptr, (char *) data, length);
    if (result < SRT_ERROR) {
        LOGE("srt_send: %s\n", srt_getlasterror_str());
    }
    env->ReleaseByteArrayElements(byteArray, data, 0);
    return result;
}

JNIEXPORT void JNICALL
JNI_METHOD_NAME(dumpStats)(JNIEnv *env, jclass clazz, jlong ptr) {
    LOGI("Java_org_deviceconnect_android_libsrt_NdkHelper_dumpStats(): ptr=%d", ptr);

    SRT_TRACEBSTATS stats;
    int result = srt_bstats((int) ptr, &stats, 0);
    if (result == SRT_ERROR) {
        return;
    }
    LOGD("dumpStats: pktSentTotal=%ld, pktRetransTotal=%d, pktSndLossTotal=%d", stats.pktSentTotal, stats.pktRetransTotal, stats.pktSndLossTotal);
    LOGD("dumpStats: mbpsBandwidth=%f, mbpsMaxBW=%f, byteAvailSndBuf=%d", stats.mbpsBandwidth, stats.mbpsMaxBW, stats.byteAvailSndBuf);
}

#ifdef __cplusplus
}
#endif
<|endoftext|>