<commit_before>#if (RASPBERRY_PI)
#include <led-matrix.h>
#include <threaded-canvas-manipulator.h>
#endif
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <bass.h>

#define SPECWIDTH 64 // display width (should be multiple of 4)
#define SPECHEIGHT 32  // height (changing requires palette adjustments too)
#define BANDS 64

#define CHAIN 4
#define ROWS 32
#define REFRESH_RATE 30

#define MAX(x,y) ((x > y) ? x : y)

#pragma pack(1)
typedef struct {
  BYTE rgbRed,rgbGreen,rgbBlue;
} RGB;
#pragma pack()
#if (RASPBERRY_PI)
using namespace rgb_matrix;
#endif
DWORD chan;

RGB palette[] = {
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {250, 100, 0},
  {250, 100, 0},
  {250, 100, 0},
  {250, 100, 0},
  {250, 100, 0},
  {250, 100, 0},
  {200, 0, 0},
  {200, 0, 0},
  {200, 0, 0},
  {200, 0, 0},
  {200, 0, 0}
};
#if (RASPBERRY_PI)
class VolumeBars : public ThreadedCanvasManipulator {
public:
  VolumeBars(Canvas *m, int delay_ms=50)
    : ThreadedCanvasManipulator(m), delay_ms_(delay_ms),
      numBars_(BANDS), t_(0) {
  }

  void Run() {
    int x,y,y1,y2;
    y1 = 0;
    height_ = canvas()->height();
    barWidth_ = 2; //width/numBars_;

    // Start the loop
    while (running()) {
      float fft[1024];
      BASS_ChannelGetData(chan,fft,BASS_DATA_FFT2048); // get the FFT data
      for (x=0;x<SPECWIDTH;x++) {
        y=sqrt(fft[x+1])*3*SPECHEIGHT-4; // scale it (sqrt to make low values more visible)
        if (y>SPECHEIGHT) y=SPECHEIGHT; // cap it
        y2 = SPECHEIGHT + 1;
        while (--y2>MAX(y,y1)) drawBarRow(x, y2, {0,0,0});
        if (x && (y1=(y+y1)/2)) // interpolate from previous to make the display smoother
          while (--y1>=0) drawBarRow(x, y1, palette[y1]);
        y1=y;
        while (--y>=0) drawBarRow(x, y, palette[y]); // draw level
      }
      usleep(delay_ms_ * 1000);
    }
  }

private:
  void drawBarRow(int bar, uint8_t y, RGB color) {
    for (uint8_t x=bar*barWidth_; x<(bar+1)*barWidth_; ++x) {
      canvas()->SetPixel(x, height_-1-y, color.rgbRed, color.rgbGreen, color.rgbBlue);
    }
  }

  int delay_ms_;
  int numBars_;
  int barWidth_;
  int height_;
  int heightGreen_;
  int heightYellow_;
  int heightOrange_;
  int heightRed_;
  int t_;
};
#endif
int main(int argc, char *argv[])
{
#if (RASPBERRY_PI)
  if (getuid() != 0) {
    fprintf(stderr, "Must run as root to be able to access /dev/mem\n"
            "Prepend 'sudo' to the command:\n\tsudo %s ...\n", argv[0]);
    return 1;
  }

  // Need to be root for this
  GPIO io;
  if (!io.Init())
    return 1;

  RGBMatrix *matrix = new RGBMatrix(&io, ROWS, CHAIN);

  Canvas *canvas = matrix;

  ThreadedCanvasManipulator *image_gen = image_gen = new VolumeBars(canvas, REFRESH_RATE);
#endif
  // initialize BASS
  if (!BASS_Init(-1,44100,0,NULL,NULL)) {
    printf("Can't initialize device\n");
    return 0;
  }

  BASS_SetConfig(BASS_CONFIG_NET_PLAYLIST,1); // enable playlist processing
  BASS_SetConfig(BASS_CONFIG_NET_PREBUF,0); // minimize automatic pre-buffering, so we can do it (and display it) instead

  BASS_PluginLoad("libbass_aac.so",0); // load BASS_AAC (if present) for AAC support
#if (RASPBERRY_PI)
  image_gen->Start();
#endif
  char url[1000];
  DWORD r;
  while (true)
  {
    fgets(url, sizeof(url), stdin);
    url[strcspn(url, "\n")] = 0;
    BASS_StreamFree(chan); // close old stream
    if (!(chan=BASS_StreamCreateURL(url,0,BASS_STREAM_BLOCK|BASS_STREAM_STATUS|BASS_STREAM_AUTOFREE,NULL,(void*)r))) {
      printf("BASS Error: %d\n", BASS_ErrorGetCode());
      break; //TODO add proper error handling here
    } else {
      BASS_ChannelPlay(chan,FALSE);
    }
  }

  BASS_Free();
#if(RASPBERRY_PI)
  // Stop image generating thread.
  delete image_gen;
  delete canvas;
#endif
  return 0;
}
<commit_msg>Play command implemented<commit_after>#if (RASPBERRY_PI)
#include <led-matrix.h>
#include <threaded-canvas-manipulator.h>
#endif
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <bass.h>

#define SPECWIDTH 64 // display width (should be multiple of 4)
#define SPECHEIGHT 32  // height (changing requires palette adjustments too)
#define BANDS 64

#define CHAIN 4
#define ROWS 32
#define REFRESH_RATE 30

#define MAX(x,y) ((x > y) ? x : y)

#pragma pack(1)
typedef struct {
  BYTE rgbRed,rgbGreen,rgbBlue;
} RGB;
#pragma pack()
#if (RASPBERRY_PI)
using namespace rgb_matrix;
#endif
DWORD chan;

RGB palette[] = {
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {0, 200, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {150, 150, 0},
  {250, 100, 0},
  {250, 100, 0},
  {250, 100, 0},
  {250, 100, 0},
  {250, 100, 0},
  {250, 100, 0},
  {200, 0, 0},
  {200, 0, 0},
  {200, 0, 0},
  {200, 0, 0},
  {200, 0, 0}
};
#if (RASPBERRY_PI)
class VolumeBars : public ThreadedCanvasManipulator {
public:
  VolumeBars(Canvas *m, int delay_ms=50)
    : ThreadedCanvasManipulator(m), delay_ms_(delay_ms),
      numBars_(BANDS), t_(0) {
  }

  void Run() {
    int x,y,y1,y2;
    y1 = 0;
    height_ = canvas()->height();
    barWidth_ = 2; //width/numBars_;

    // Start the loop
    while (running()) {
      float fft[1024];
      BASS_ChannelGetData(chan,fft,BASS_DATA_FFT2048); // get the FFT data
      for (x=0;x<SPECWIDTH;x++) {
        y=sqrt(fft[x+1])*3*SPECHEIGHT-4; // scale it (sqrt to make low values more visible)
        if (y>SPECHEIGHT) y=SPECHEIGHT; // cap it
        y2 = SPECHEIGHT + 1;
        while (--y2>MAX(y,y1)) drawBarRow(x, y2, {0,0,0});
        if (x && (y1=(y+y1)/2)) // interpolate from previous to make the display smoother
          while (--y1>=0) drawBarRow(x, y1, palette[y1]);
        y1=y;
        while (--y>=0) drawBarRow(x, y, palette[y]); // draw level
      }
      usleep(delay_ms_ * 1000);
    }
  }

private:
  void drawBarRow(int bar, uint8_t y, RGB color) {
    for (uint8_t x=bar*barWidth_; x<(bar+1)*barWidth_; ++x) {
      canvas()->SetPixel(x, height_-1-y, color.rgbRed, color.rgbGreen, color.rgbBlue);
    }
  }

  int delay_ms_;
  int numBars_;
  int barWidth_;
  int height_;
  int heightGreen_;
  int heightYellow_;
  int heightOrange_;
  int heightRed_;
  int t_;
};
#endif

void handle_play(char* str)
{
    DWORD r;
    BASS_StreamFree(chan); // close old stream
    if (!(chan=BASS_StreamCreateURL(str+5,0,BASS_STREAM_BLOCK|BASS_STREAM_STATUS|BASS_STREAM_AUTOFREE,NULL,(void*)r))) {
      printf("BASS Error: %d\n", BASS_ErrorGetCode());
    } else {
      BASS_ChannelPlay(chan,FALSE);
    }
}

int main(int argc, char *argv[])
{
#if (RASPBERRY_PI)
  if (getuid() != 0) {
    fprintf(stderr, "Must run as root to be able to access /dev/mem\n"
            "Prepend 'sudo' to the command:\n\tsudo %s ...\n", argv[0]);
    return 1;
  }

  // Need to be root for this
  GPIO io;
  if (!io.Init())
    return 1;

  RGBMatrix *matrix = new RGBMatrix(&io, ROWS, CHAIN);

  Canvas *canvas = matrix;

  ThreadedCanvasManipulator *image_gen = image_gen = new VolumeBars(canvas, REFRESH_RATE);
#endif
  // initialize BASS
  if (!BASS_Init(-1,44100,0,NULL,NULL)) {
    printf("Can't initialize device\n");
    return 0;
  }

  BASS_SetConfig(BASS_CONFIG_NET_PLAYLIST,1); // enable playlist processing
  BASS_SetConfig(BASS_CONFIG_NET_PREBUF,0); // minimize automatic pre-buffering, so we can do it (and display it) instead

  BASS_PluginLoad("libbass_aac.so",0); // load BASS_AAC (if present) for AAC support
#if (RASPBERRY_PI)
  image_gen->Start();
#endif
  char url[1000];
  while (true)
  {
    fgets(url, sizeof(url), stdin);
    url[strcspn(url, "\n")] = 0;
    if (strncmp(url, "play", 4) == 0)
    {
      handle_play(url);
    }
  }

  BASS_Free();
#if(RASPBERRY_PI)
  // Stop image generating thread.
  delete image_gen;
  delete canvas;
#endif
  return 0;
}
<|endoftext|>


<commit_before>58fc949e-ad5c-11e7-8f1a-ac87a332f658<commit_msg>The previous fix has been fixed<commit_after>598cabc5-ad5c-11e7-862c-ac87a332f658<|endoftext|>


<commit_before>/*
 * Copyright (C) 2004-2008  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include "znc.h"
#include <getopt.h>

static struct option g_LongOpts[] = {
	{ "help",			no_argument,	0,	'h' },
	{ "version",			no_argument,	0,	'v' },
	{ "no-color",			no_argument,	0,	'n' },
	{ "allow-root",			no_argument,	0,	'r' },
	{ "makeconf",			no_argument,	0,	'c' },
	{ "makepass",			no_argument,	0,	's' },
#ifdef HAVE_LIBSSL
	{ "makepem",			no_argument,	0,	'p' },
	{ "encrypt-pem",		no_argument,	0, 	'e' },
#endif /* HAVE_LIBSSL */
	{ "datadir",                    required_argument,	0,   'd' },
	{ 0, 0, 0, 0 }
};

static void GenerateHelp(const char *appname) {
	CUtils::PrintMessage("USAGE: " + CString(appname) + " [options] [config]");
	CUtils::PrintMessage("Options are:");
	CUtils::PrintMessage("\t-h, --help         List available command line options (this page)");
	CUtils::PrintMessage("\t-v, --version      Output version information and exit");
	CUtils::PrintMessage("\t-n, --no-color     Don't use escape sequences in the output");
	CUtils::PrintMessage("\t-r, --allow-root   Don't complain if ZNC is run as root");
	CUtils::PrintMessage("\t-c, --makeconf     Interactively create a new config");
	CUtils::PrintMessage("\t-s, --makepass     Generates a password for use in config");
#ifdef HAVE_LIBSSL
	CUtils::PrintMessage("\t-p, --makepem      Generates a pemfile for use with SSL");
	CUtils::PrintMessage("\t-e, --encrypt-pem  when used along with --makepem, encrypts the private key in the pemfile");
#endif /* HAVE_LIBSSL */
	CUtils::PrintMessage("\t-d, --datadir      Set a different znc repository (default is ~/.znc)");
}

static void die(int sig) {
	signal(SIGPIPE, SIG_DFL);

#ifdef _DEBUG
	CUtils::PrintMessage("Exiting on SIG [" + CString(sig) + "]");
	if ((sig == SIGABRT) || (sig == SIGSEGV)) {
		abort();
	}
#endif /* _DEBUG */

	delete &CZNC::Get();
	exit(sig);
}

static void rehash(int sig) {
	CZNC::Get().SetNeedRehash(true);
}

static bool isRoot() {
	// User root? If one of these were root, we could switch the others to root, too
	if (geteuid() == 0 || getuid() == 0)
		return true;

	return false;
}

int main(int argc, char** argv) {
	CString sConfig;
	CString sDataDir = "";

	srand(time(NULL));
	CUtils::SetStdoutIsTTY(isatty(1));

#ifdef HAVE_LIBSSL
	InitSSL();
#endif /* HAVE_LIBSSL */

	int iArg, iOptIndex = -1;
	bool bMakeConf = false;
	bool bMakePass = false;
	bool bAllowRoot = false;
#ifdef HAVE_LIBSSL
	bool bMakePem = false;
	bool bEncPem = false;

	while ((iArg = getopt_long(argc, argv, "hvnrcsped:", g_LongOpts, &iOptIndex)) != -1) {
#else
	while ((iArg = getopt_long(argc, argv, "hvnrcsd:", g_LongOpts, &iOptIndex)) != -1) {
#endif /* HAVE_LIBSSL */
	    switch (iArg) {
		case 'h':
			GenerateHelp(argv[0]);
			return 0;
		case 'v':
			cout << CZNC::GetTag() << endl;
			return 0;
		case 'n':
			CUtils::SetStdoutIsTTY(false);
			break;
		case 'r':
			bAllowRoot = true;
			break;
		case 'c':
			bMakeConf = true;
			break;
		case 's':
			bMakePass = true;
			break;
#ifdef HAVE_LIBSSL
		case 'p':
			bMakePem = true;
			break;
		case 'e':
			bEncPem = true;
			break;
#endif /* HAVE_LIBSSL */
		case 'd':
			sDataDir = CString(optarg);
			break;
		case '?':
		default:
			GenerateHelp(argv[0]);
			return 1;
	    }
	}

	if (optind < argc) {
		sConfig = argv[optind];
	} else {
		sConfig = "znc.conf";
	}

	CZNC* pZNC = &CZNC::Get();
	pZNC->InitDirs(((argc) ? argv[0] : ""), sDataDir);

#ifdef HAVE_LIBSSL
	if (bMakePem) {
		pZNC->WritePemFile(bEncPem);

		delete pZNC;
		return 0;
	}

	if (bEncPem && !bMakePem) {
		CUtils::PrintError("--encrypt-pem should be used along with --makepem.");
		delete pZNC;
		return 1;
	}
#endif /* HAVE_LIBSSL */

	if (bMakePass) {
		CString sSalt;
		CString sHash = CUtils::GetSaltedHashPass(sSalt);
		CUtils::PrintMessage("Use this in the <User> section of your config:");
		CUtils::PrintMessage("Pass = md5#" + sHash + "#" + sSalt + "#");

		delete pZNC;
		return 0;
	}

	if (bMakeConf) {
		if (!pZNC->WriteNewConfig(sConfig)) {
			delete pZNC;
			return 0;
		}
		/* Fall through to normal bootup */
	}

	if (!pZNC->ParseConfig(sConfig)) {
		CUtils::PrintError("Unrecoverable config error.");
		delete pZNC;
		return 1;
	}

	if (!pZNC->OnBoot()) {
		CUtils::PrintError("Exiting due to module boot errors.");
		delete pZNC;
		return 1;
	}

	if (isRoot()) {
		CUtils::PrintError("You are running ZNC as root! Don't do that! There are not many valid");
		CUtils::PrintError("reasons for this and it can, in theory, cause great damage!");
		if (!bAllowRoot) {
			delete pZNC;
			return 1;
		}
		CUtils::PrintError("You have been warned.");
		CUtils::PrintError("Hit CTRL+C now if you don't want to run ZNC as root.");
		CUtils::PrintError("ZNC will start in 30 seconds.");
		sleep(30);
	}

#ifdef _DEBUG
	int iPid = getpid();
	CUtils::PrintMessage("Staying open for debugging [pid: " + CString(iPid) + "]");

	pZNC->WritePidFile(iPid);
	CUtils::PrintMessage(CZNC::GetTag());
#else
	CUtils::PrintAction("Forking into the background");

	int iPid = fork();

	if (iPid == -1) {
		CUtils::PrintStatus(false, strerror(errno));
		delete pZNC;
		return 1;
	}

	if (iPid > 0) {
		// We are the parent. We are done and will go to bed.
		CUtils::PrintStatus(true, "[pid: " + CString(iPid) + "]");

		pZNC->WritePidFile(iPid);
		CUtils::PrintMessage(CZNC::GetTag());
		/* Don't destroy pZNC here or it will delete the pid file. */
		return 0;
	}

	// Redirect std in/out/err to /dev/null
	close(0); open("/dev/null", O_RDONLY);
	close(1); open("/dev/null", O_WRONLY);
	close(2); open("/dev/null", O_WRONLY);

	CUtils::SetStdoutIsTTY(false);

	// We are the child. There is no way we can be a process group
	// leader, thus setsid() must succeed.
	setsid();
	// Now we are in our own process group and session (no controlling
	// terminal). We are independent!
#endif

	struct sigaction sa;
	sa.sa_flags = 0;
	sigemptyset(&sa.sa_mask);

	sa.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &sa, (struct sigaction*) NULL);

	sa.sa_handler = rehash;
	sigaction(SIGHUP,  &sa, (struct sigaction*) NULL);

	// Once this signal is caught, the signal handler is reset
	// to SIG_DFL. This avoids endless loop with signals.
	sa.sa_flags = SA_RESETHAND;
	sa.sa_handler = die;
	sigaction(SIGINT,  &sa, (struct sigaction*) NULL);
	sigaction(SIGILL,  &sa, (struct sigaction*) NULL);
	sigaction(SIGQUIT, &sa, (struct sigaction*) NULL);
	sigaction(SIGBUS,  &sa, (struct sigaction*) NULL);
	sigaction(SIGSEGV, &sa, (struct sigaction*) NULL);
	sigaction(SIGTERM, &sa, (struct sigaction*) NULL);

	int iRet = 0;

	try {
		iRet = pZNC->Loop();
	} catch (CException e) {
		switch (e.GetType()) {
			case CException::EX_Shutdown:
				iRet = 0;
				break;
			case CException::EX_Restart: {
				// strdup() because GCC is stupid
				char *args[] = {
					strdup(argv[0]),
					strdup("--datadir"),
					strdup(pZNC->GetZNCPath().c_str()),
					strdup(pZNC->GetConfigFile().c_str()),
					NULL
				};
				execvp(args[0], args);
				CUtils::PrintError("Unable to restart znc [" + CString(strerror(errno)) + "]");
			} /* Fall through */
			default:
				iRet = 1;
		}
	}

	delete pZNC;

	return iRet;
}
<commit_msg>Print a message when SIGHUP is caught<commit_after>/*
 * Copyright (C) 2004-2008  See the AUTHORS file for details.
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 as published
 * by the Free Software Foundation.
 */

#include "znc.h"
#include <getopt.h>

static struct option g_LongOpts[] = {
	{ "help",			no_argument,	0,	'h' },
	{ "version",			no_argument,	0,	'v' },
	{ "no-color",			no_argument,	0,	'n' },
	{ "allow-root",			no_argument,	0,	'r' },
	{ "makeconf",			no_argument,	0,	'c' },
	{ "makepass",			no_argument,	0,	's' },
#ifdef HAVE_LIBSSL
	{ "makepem",			no_argument,	0,	'p' },
	{ "encrypt-pem",		no_argument,	0, 	'e' },
#endif /* HAVE_LIBSSL */
	{ "datadir",                    required_argument,	0,   'd' },
	{ 0, 0, 0, 0 }
};

static void GenerateHelp(const char *appname) {
	CUtils::PrintMessage("USAGE: " + CString(appname) + " [options] [config]");
	CUtils::PrintMessage("Options are:");
	CUtils::PrintMessage("\t-h, --help         List available command line options (this page)");
	CUtils::PrintMessage("\t-v, --version      Output version information and exit");
	CUtils::PrintMessage("\t-n, --no-color     Don't use escape sequences in the output");
	CUtils::PrintMessage("\t-r, --allow-root   Don't complain if ZNC is run as root");
	CUtils::PrintMessage("\t-c, --makeconf     Interactively create a new config");
	CUtils::PrintMessage("\t-s, --makepass     Generates a password for use in config");
#ifdef HAVE_LIBSSL
	CUtils::PrintMessage("\t-p, --makepem      Generates a pemfile for use with SSL");
	CUtils::PrintMessage("\t-e, --encrypt-pem  when used along with --makepem, encrypts the private key in the pemfile");
#endif /* HAVE_LIBSSL */
	CUtils::PrintMessage("\t-d, --datadir      Set a different znc repository (default is ~/.znc)");
}

static void die(int sig) {
	signal(SIGPIPE, SIG_DFL);

#ifdef _DEBUG
	CUtils::PrintMessage("Exiting on SIG [" + CString(sig) + "]");
	if ((sig == SIGABRT) || (sig == SIGSEGV)) {
		abort();
	}
#endif /* _DEBUG */

	delete &CZNC::Get();
	exit(sig);
}

static void rehash(int sig) {
	CUtils::PrintMessage("Caught SIGHUP");
	CZNC::Get().SetNeedRehash(true);
}

static bool isRoot() {
	// User root? If one of these were root, we could switch the others to root, too
	if (geteuid() == 0 || getuid() == 0)
		return true;

	return false;
}

int main(int argc, char** argv) {
	CString sConfig;
	CString sDataDir = "";

	srand(time(NULL));
	CUtils::SetStdoutIsTTY(isatty(1));

#ifdef HAVE_LIBSSL
	InitSSL();
#endif /* HAVE_LIBSSL */

	int iArg, iOptIndex = -1;
	bool bMakeConf = false;
	bool bMakePass = false;
	bool bAllowRoot = false;
#ifdef HAVE_LIBSSL
	bool bMakePem = false;
	bool bEncPem = false;

	while ((iArg = getopt_long(argc, argv, "hvnrcsped:", g_LongOpts, &iOptIndex)) != -1) {
#else
	while ((iArg = getopt_long(argc, argv, "hvnrcsd:", g_LongOpts, &iOptIndex)) != -1) {
#endif /* HAVE_LIBSSL */
	    switch (iArg) {
		case 'h':
			GenerateHelp(argv[0]);
			return 0;
		case 'v':
			cout << CZNC::GetTag() << endl;
			return 0;
		case 'n':
			CUtils::SetStdoutIsTTY(false);
			break;
		case 'r':
			bAllowRoot = true;
			break;
		case 'c':
			bMakeConf = true;
			break;
		case 's':
			bMakePass = true;
			break;
#ifdef HAVE_LIBSSL
		case 'p':
			bMakePem = true;
			break;
		case 'e':
			bEncPem = true;
			break;
#endif /* HAVE_LIBSSL */
		case 'd':
			sDataDir = CString(optarg);
			break;
		case '?':
		default:
			GenerateHelp(argv[0]);
			return 1;
	    }
	}

	if (optind < argc) {
		sConfig = argv[optind];
	} else {
		sConfig = "znc.conf";
	}

	CZNC* pZNC = &CZNC::Get();
	pZNC->InitDirs(((argc) ? argv[0] : ""), sDataDir);

#ifdef HAVE_LIBSSL
	if (bMakePem) {
		pZNC->WritePemFile(bEncPem);

		delete pZNC;
		return 0;
	}

	if (bEncPem && !bMakePem) {
		CUtils::PrintError("--encrypt-pem should be used along with --makepem.");
		delete pZNC;
		return 1;
	}
#endif /* HAVE_LIBSSL */

	if (bMakePass) {
		CString sSalt;
		CString sHash = CUtils::GetSaltedHashPass(sSalt);
		CUtils::PrintMessage("Use this in the <User> section of your config:");
		CUtils::PrintMessage("Pass = md5#" + sHash + "#" + sSalt + "#");

		delete pZNC;
		return 0;
	}

	if (bMakeConf) {
		if (!pZNC->WriteNewConfig(sConfig)) {
			delete pZNC;
			return 0;
		}
		/* Fall through to normal bootup */
	}

	if (!pZNC->ParseConfig(sConfig)) {
		CUtils::PrintError("Unrecoverable config error.");
		delete pZNC;
		return 1;
	}

	if (!pZNC->OnBoot()) {
		CUtils::PrintError("Exiting due to module boot errors.");
		delete pZNC;
		return 1;
	}

	if (isRoot()) {
		CUtils::PrintError("You are running ZNC as root! Don't do that! There are not many valid");
		CUtils::PrintError("reasons for this and it can, in theory, cause great damage!");
		if (!bAllowRoot) {
			delete pZNC;
			return 1;
		}
		CUtils::PrintError("You have been warned.");
		CUtils::PrintError("Hit CTRL+C now if you don't want to run ZNC as root.");
		CUtils::PrintError("ZNC will start in 30 seconds.");
		sleep(30);
	}

#ifdef _DEBUG
	int iPid = getpid();
	CUtils::PrintMessage("Staying open for debugging [pid: " + CString(iPid) + "]");

	pZNC->WritePidFile(iPid);
	CUtils::PrintMessage(CZNC::GetTag());
#else
	CUtils::PrintAction("Forking into the background");

	int iPid = fork();

	if (iPid == -1) {
		CUtils::PrintStatus(false, strerror(errno));
		delete pZNC;
		return 1;
	}

	if (iPid > 0) {
		// We are the parent. We are done and will go to bed.
		CUtils::PrintStatus(true, "[pid: " + CString(iPid) + "]");

		pZNC->WritePidFile(iPid);
		CUtils::PrintMessage(CZNC::GetTag());
		/* Don't destroy pZNC here or it will delete the pid file. */
		return 0;
	}

	// Redirect std in/out/err to /dev/null
	close(0); open("/dev/null", O_RDONLY);
	close(1); open("/dev/null", O_WRONLY);
	close(2); open("/dev/null", O_WRONLY);

	CUtils::SetStdoutIsTTY(false);

	// We are the child. There is no way we can be a process group
	// leader, thus setsid() must succeed.
	setsid();
	// Now we are in our own process group and session (no controlling
	// terminal). We are independent!
#endif

	struct sigaction sa;
	sa.sa_flags = 0;
	sigemptyset(&sa.sa_mask);

	sa.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &sa, (struct sigaction*) NULL);

	sa.sa_handler = rehash;
	sigaction(SIGHUP,  &sa, (struct sigaction*) NULL);

	// Once this signal is caught, the signal handler is reset
	// to SIG_DFL. This avoids endless loop with signals.
	sa.sa_flags = SA_RESETHAND;
	sa.sa_handler = die;
	sigaction(SIGINT,  &sa, (struct sigaction*) NULL);
	sigaction(SIGILL,  &sa, (struct sigaction*) NULL);
	sigaction(SIGQUIT, &sa, (struct sigaction*) NULL);
	sigaction(SIGBUS,  &sa, (struct sigaction*) NULL);
	sigaction(SIGSEGV, &sa, (struct sigaction*) NULL);
	sigaction(SIGTERM, &sa, (struct sigaction*) NULL);

	int iRet = 0;

	try {
		iRet = pZNC->Loop();
	} catch (CException e) {
		switch (e.GetType()) {
			case CException::EX_Shutdown:
				iRet = 0;
				break;
			case CException::EX_Restart: {
				// strdup() because GCC is stupid
				char *args[] = {
					strdup(argv[0]),
					strdup("--datadir"),
					strdup(pZNC->GetZNCPath().c_str()),
					strdup(pZNC->GetConfigFile().c_str()),
					NULL
				};
				execvp(args[0], args);
				CUtils::PrintError("Unable to restart znc [" + CString(strerror(errno)) + "]");
			} /* Fall through */
			default:
				iRet = 1;
		}
	}

	delete pZNC;

	return iRet;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <opencv2/opencv.hpp>

#include "clicker.hpp"

using namespace cv;
using namespace std;

string window_title = "Join-Robockets Clientside Software";

//HSV filter variables
int h_lower = 0, s_lower = 0, v_lower = 0;
int h_upper = 180, s_upper = 255, v_upper = 255;
Scalar hsv_lower(h_lower, s_lower, v_lower);
Scalar hsv_upper(h_upper, s_upper, v_upper);

//Camera settings
int exposure = 50;
VideoCapture cap(CV_CAP_ANY);

/*
 * Callback for exposure trackbar. Sets camera exposure.
 */
void exposure_callback(int, void*) {
    cap.set(CV_CAP_PROP_EXPOSURE, exposure);
}

/*
 * Callback for the HSV trackbars. Update the hsv_upper and hsv_lower scalars
 * with new values.
 */
void filter_callback(int, void*) {
    hsv_lower = Scalar(h_lower, s_lower, v_lower);
    hsv_upper = Scalar(h_upper, s_upper, v_upper);
}

int main() {
    //Check if camera works
    if(!cap.isOpened()) {
        cerr << "Could not open image capture device!" << endl;
        exit(EXIT_FAILURE);
    }

    Mat frame, hsv, filtered;
    namedWindow(window_title);
    createTrackbar("H Lower", window_title, &h_lower, 180, filter_callback);
    createTrackbar("H Upper", window_title, &h_upper, 180, filter_callback);
    createTrackbar("S Lower", window_title, &s_lower, 255, filter_callback);
    createTrackbar("S Upper", window_title, &s_upper, 255, filter_callback);
    createTrackbar("V Lower", window_title, &v_lower, 255, filter_callback);
    createTrackbar("V Upper", window_title, &v_upper, 255, filter_callback);
    createTrackbar("Exposure", window_title, &exposure, 255, exposure_callback);

    while(1) {
        //Capture and show image.
        cap >> frame;
        cvtColor(frame, hsv, CV_BGR2HSV);
        inRange(hsv, hsv_lower, hsv_upper, filtered);
        imshow(window_title, filtered);

        //Quit if any key has been pressed.
        if(waitKey(30) >= 0) {
            break;
        }
    }
    //VideoCapture is closed automatically.
    return 0;
}<commit_msg>Make window resizable<commit_after>#include <iostream>
#include <opencv2/opencv.hpp>

#include "clicker.hpp"

using namespace cv;
using namespace std;

string window_title = "Join-Robockets Clientside Software";

//HSV filter variables
int h_lower = 0, s_lower = 0, v_lower = 0;
int h_upper = 180, s_upper = 255, v_upper = 255;
Scalar hsv_lower(h_lower, s_lower, v_lower);
Scalar hsv_upper(h_upper, s_upper, v_upper);

//Camera settings
int exposure = 50;
VideoCapture cap(CV_CAP_ANY);

/*
 * Callback for exposure trackbar. Sets camera exposure.
 */
void exposure_callback(int, void*) {
    cap.set(CV_CAP_PROP_EXPOSURE, exposure);
}

/*
 * Callback for the HSV trackbars. Update the hsv_upper and hsv_lower scalars
 * with new values.
 */
void filter_callback(int, void*) {
    hsv_lower = Scalar(h_lower, s_lower, v_lower);
    hsv_upper = Scalar(h_upper, s_upper, v_upper);
}

int main() {
    //Check if camera works
    if(!cap.isOpened()) {
        cerr << "Could not open image capture device!" << endl;
        exit(EXIT_FAILURE);
    }

    Mat frame, hsv, filtered;
    namedWindow(window_title, WINDOW_NORMAL);
    createTrackbar("H Lower", window_title, &h_lower, 180, filter_callback);
    createTrackbar("H Upper", window_title, &h_upper, 180, filter_callback);
    createTrackbar("S Lower", window_title, &s_lower, 255, filter_callback);
    createTrackbar("S Upper", window_title, &s_upper, 255, filter_callback);
    createTrackbar("V Lower", window_title, &v_lower, 255, filter_callback);
    createTrackbar("V Upper", window_title, &v_upper, 255, filter_callback);
    createTrackbar("Exposure", window_title, &exposure, 255, exposure_callback);

    while(1) {
        //Capture and show image.
        cap >> frame;
        cvtColor(frame, hsv, CV_BGR2HSV);
        inRange(hsv, hsv_lower, hsv_upper, filtered);
        imshow(window_title, filtered);

        //Quit if any key has been pressed.
        if(waitKey(30) >= 0) {
            break;
        }
    }
    //VideoCapture is closed automatically.
    return 0;
}<|endoftext|>


<commit_before>44cf7773-2748-11e6-8853-e0f84713e7b8<commit_msg>Did a thing<commit_after>44e36105-2748-11e6-a9a0-e0f84713e7b8<|endoftext|>


<commit_before>8d1586a1-4b02-11e5-9fd5-28cfe9171a43<commit_msg>updated some files<commit_after>8d258730-4b02-11e5-821f-28cfe9171a43<|endoftext|>


<commit_before>7e2a4f87-4b02-11e5-9b41-28cfe9171a43<commit_msg>new flies<commit_after>7e36f74c-4b02-11e5-9e79-28cfe9171a43<|endoftext|>


<commit_before>/*
Copyright (c) 2010, Pieter Beyens
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 of conditions 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 materials provided with the distribution.
Neither the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
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 <FL/Fl.H>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Text_Editor.H>
#include <FL/Fl_Text_Buffer.H>
#include <FL/Fl_Button.H>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <list>
#include <signal.h>
#include <argp.h>

#include "flgoban.h"
#include "sgf.h"
#include "goban.h"

using namespace std;

static Fl_Double_Window *win = NULL;
static Fl_Goban *flgoban = NULL;
//static Fl_Text_Buffer *textbuffer = NULL;
//static Fl_Text_Editor *comment = NULL;
static list<int> fds;
static struct goban *g = NULL;
static char broadcast_msg[10000];

struct settings
{
	int width, height, port, nogui, expand;
};
static struct settings setts;

static void handler_sigpipe(int)
{
	return;
}

static void broadcast(const char *cmd)
{
	list<int>::const_iterator cit = fds.begin();
	while(cit!=fds.end()) {
		send(*cit, cmd, strlen(cmd),0);
		++cit;
	}
	printf("%s",cmd);
}

static void read_cb(int fd, void *data)
{
	int n;
	char rd_cmd[10000];
	memset(rd_cmd, '\0', sizeof(rd_cmd));
	memset(broadcast_msg, '\0', sizeof(rd_cmd));
	n = read(fd, rd_cmd, sizeof(rd_cmd));
	if(n <= 0) {
		Fl::remove_fd(fd);
		fds.remove(fd);
		/* if not a gui and not listening then exit */
		if(setts.nogui && !setts.port && !fds.size())
			exit(0);
		return;
	}
	//printf("Received: %s\n",rd_cmd);
	sgf_parse_fast(rd_cmd);
	broadcast(broadcast_msg);
	flgoban->redraw();
}

static void listen_cb(int fd, void *s)
{
	int a = accept(*(int*)s, NULL, 0);
	if(0 > a)
		perror("accept()");
	else {
		Fl::add_fd(a, read_cb, NULL);
		fds.push_back(a);
	}
}

/* GOBAN */
static void goban_ab(struct goban *gob, int x, int y)
{
	char msg[10];
	flgoban->set_stone(x,y,black);
	if(setts.expand) {
		sprintf(msg, "AB[%c%c]", int2sgf(x),int2sgf(y));
		strcat(broadcast_msg, msg);
	}
}

static void goban_aw(struct goban *gob, int x, int y)
{
	char msg[10];
	flgoban->set_stone(x,y,white);
	if(setts.expand) {
		sprintf(msg, "AW[%c%c]", int2sgf(x),int2sgf(y));
		strcat(broadcast_msg, msg);
	}
}

static void goban_ae(struct goban *gob, int x, int y)
{
	char msg[10];
	flgoban->set_stone(x,y,empty);
	if(setts.expand) {
		sprintf(msg, "AE[%c%c]", int2sgf(x),int2sgf(y));
		strcat(broadcast_msg, msg);
	}
}

static const struct goban_cb gcb = { goban_ab, goban_aw, goban_ae };

/* SGF */
static void sgf_node_new(void)
{
	strcat(broadcast_msg, ";");
}

static void sgf_node_end(void)
{
	strcat(broadcast_msg, "\n");
}

static void sgf_sz(int s)
{
	char msg[10];
	goban_free(g);
	g = goban_alloc(s, &gcb);
	flgoban->flresize(s);
	sprintf(msg, "SZ[%d]", s);
	strcat(broadcast_msg, msg);
}

static void sgf_b(char cx, char cy)
{
	char msg[20];
	goban_play(g, sgf2int(cx), sgf2int(cy), black);
	flgoban->set_mark(sgf2int(cx),sgf2int(cy),circle);

	if(!setts.expand) {
		sprintf(msg, "B[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
}

static void sgf_w(char cx, char cy)
{
	char msg[20];

	goban_play(g, sgf2int(cx), sgf2int(cy), white);
	flgoban->set_mark(sgf2int(cx),sgf2int(cy),circle);

	if(!setts.expand) {
		sprintf(msg, "W[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
}

static void sgf_ab(char cx, char cy)
{
	char msg[10];
	goban_set(g, sgf2int(cx), sgf2int(cy), black);
	if(!setts.expand) {
		sprintf(msg, "AB[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
}

static void sgf_aw(char cx, char cy)
{
	char msg[10];
	goban_set(g, sgf2int(cx), sgf2int(cy), white);
	if(!setts.expand) {
		sprintf(msg, "AW[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
}

static void sgf_ae(char cx, char cy)
{
	char msg[10];
	goban_set(g, sgf2int(cx), sgf2int(cy), empty);
	if(!setts.expand) {
		sprintf(msg, "AE[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
}

static void sgf_pw(const char *prop, int size)
{
	strcat(broadcast_msg, "PW[");
	strncat(broadcast_msg, prop, size);
	strcat(broadcast_msg, "]");
}

static void sgf_pb(const char *prop, int size)
{
	strcat(broadcast_msg, "PB[");
	strncat(broadcast_msg, prop, size);
	strcat(broadcast_msg, "]");
}

static void sgf_cr(char cx, char cy)
{
	char msg[10];
	flgoban->set_mark(sgf2int(cx),sgf2int(cy),circle);
	sprintf(msg, "CR[%c%c]", cx,cy);
	strcat(broadcast_msg, msg);
}

static void sgf_me(char cx, char cy)
{
	char msg[10];
	flgoban->set_mark(sgf2int(cx),sgf2int(cy),empty);
	sprintf(msg, "ME[%c%c]", cx,cy);
	strcat(broadcast_msg, msg);
}

static void sgf_prop_unknown(const char *prop, int size)
{
	strncat(broadcast_msg, prop, size);
}

static const struct sgf_cb scb = { \
	sgf_node_new, sgf_node_end, \
	sgf_sz, \
	sgf_b, sgf_w, sgf_ab, sgf_aw, sgf_ae, \
	sgf_pw, sgf_pb, \
	sgf_cr, sgf_me, \
	sgf_prop_unknown };

/* EVENTS */

static void ev_key(char k)
{
	char e[100];
	sprintf(e, ";KEY[%c]\n", k);
	broadcast(e);
}

static void ev_mou(int x, int y)
{
	char e[100];
	sprintf(e, ";MOU[%c%c]\n", int2sgf(x),int2sgf(y));
	broadcast(e);
}

/* ARGP */
const char *argp_program_version = "flgoban 0.1";
const char *argp_program_bug_address = "<pieter.beyens@gmail.com>";
static char doc[] = "flgoban -- reads, displays and broadcasts sgf";
static char args_doc[] = "";
static struct argp_option options[] = {
	{"width", 'w', "WIDTH", 0, "window width (defaults to 600)" },
	{"height", 'h', "HEIGHT", 0, "window height (defaults to 600)" },
	{"port", 'p', "PORT", 0, "listening port (if set to zero then only read from stdin - defaults to 5000)" },
	{"nogui",'g', 0, 0, "text-only interface (reads and broadcasts sgf)"},
	{"expand",'e', 0, 0, "expand sgf"},
	{ 0 }
};
static error_t parse_opt (int key, char *arg, struct argp_state *state)
{
	switch (key)
	{
		case 'w':
			if(!arg || 1!=sscanf(arg, "%d", &setts.width)) {
				perror("width must be an integer");
				exit(1);
			}
			break;
		case 'h':
			if(!arg || 1!=sscanf(arg, "%d", &setts.height)) {
				perror("height must be an integer");
				exit(1);
			}
			break;
		case 'p':
			if(!arg || 1!=sscanf(arg, "%d", &setts.port)) {
				perror("port must be an integer");
				exit(1);
			}
			break;
		case 'g':
			setts.nogui = 1;
			break;
		case 'e':
			setts.expand = 1;
			break;
		default:
			return ARGP_ERR_UNKNOWN;
	}
	return 0;
}
static struct argp argp = { options, parse_opt, args_doc, doc };

int main(int argc, char **argv) {
	int s;
	struct sockaddr_in addr;

	memset(&setts,'\0', sizeof(setts));
	setts.width = 600;
	setts.height = 600;
	setts.port = 5000;

	argp_parse (&argp, argc, argv, 0, 0, 0);

	if(setts.port) {
		s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
		if(s < 0) {
			perror("socket()");
			return -1;
		}

		bzero(&addr, sizeof(addr));
		addr.sin_family = AF_INET;
		addr.sin_addr.s_addr = htonl(INADDR_ANY);
		addr.sin_port = htons(setts.port);

		int tr=1;
		if (setsockopt(s,SOL_SOCKET,SO_REUSEADDR,&tr,sizeof(int)) == -1) {
			perror("setsockopt");
			exit(1);
		}

		if(0 > bind(s,(struct sockaddr*)&addr,sizeof(addr))) {
			perror("bind()");
			return -1;
		}

		if(0 > listen(s,1)) {
			perror("listen()");
			return -1;
		}
		Fl::add_fd(s, listen_cb, &s);
	}

	Fl::add_fd(STDIN_FILENO, read_cb, NULL);

	win = new Fl_Double_Window(setts.width,setts.height);
	win->begin();
	flgoban = new Fl_Goban(0,0,setts.width,setts.height, ev_key, ev_mou);
	//textbuffer = new Fl_Text_Buffer();
	//comment = new Fl_Text_Editor(10,650,WINDOW_WIDTH-20,90,0);
	//comment->buffer(textbuffer);
	win->end();
	win->resizable(flgoban);
	if(!setts.nogui)
		win->show();

	g = goban_alloc(19, &gcb);
	sgf_init(&scb);

	signal(SIGPIPE,handler_sigpipe);

	if(setts.nogui)
		while(1)
			Fl::check();
	else
		Fl::run();

	if(setts.port)
		close(s);
	goban_free(g);
}
<commit_msg>bug fix marks<commit_after>/*
Copyright (c) 2010, Pieter Beyens
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 of conditions 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 materials provided with the distribution.
Neither the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
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 <FL/Fl.H>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Text_Editor.H>
#include <FL/Fl_Text_Buffer.H>
#include <FL/Fl_Button.H>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <list>
#include <signal.h>
#include <argp.h>

#include "flgoban.h"
#include "sgf.h"
#include "goban.h"

using namespace std;

static Fl_Double_Window *win = NULL;
static Fl_Goban *flgoban = NULL;
//static Fl_Text_Buffer *textbuffer = NULL;
//static Fl_Text_Editor *comment = NULL;
static list<int> fds;
static struct goban *g = NULL;
static char broadcast_msg[10000];

struct settings
{
	int width, height, port, nogui, expand;
};
static struct settings setts;

static void handler_sigpipe(int)
{
	return;
}

static void broadcast(const char *cmd)
{
	list<int>::const_iterator cit = fds.begin();
	while(cit!=fds.end()) {
		send(*cit, cmd, strlen(cmd),0);
		++cit;
	}
	printf("%s",cmd);
}

static void read_cb(int fd, void *data)
{
	int n;
	char rd_cmd[10000];
	memset(rd_cmd, '\0', sizeof(rd_cmd));
	memset(broadcast_msg, '\0', sizeof(rd_cmd));
	n = read(fd, rd_cmd, sizeof(rd_cmd));
	if(n <= 0) {
		Fl::remove_fd(fd);
		fds.remove(fd);
		/* if not a gui and not listening then exit */
		if(setts.nogui && !setts.port && !fds.size())
			exit(0);
		return;
	}
	//printf("Received: %s\n",rd_cmd);
	sgf_parse_fast(rd_cmd);
	broadcast(broadcast_msg);
	flgoban->redraw();
}

static void listen_cb(int fd, void *s)
{
	int a = accept(*(int*)s, NULL, 0);
	if(0 > a)
		perror("accept()");
	else {
		Fl::add_fd(a, read_cb, NULL);
		fds.push_back(a);
	}
}

/* GOBAN */
static void goban_ab(struct goban *gob, int x, int y)
{
	char msg[10];
	flgoban->set_stone(x,y,black);
	if(setts.expand) {
		sprintf(msg, "AB[%c%c]", int2sgf(x),int2sgf(y));
		strcat(broadcast_msg, msg);
	}
}

static void goban_aw(struct goban *gob, int x, int y)
{
	char msg[10];
	flgoban->set_stone(x,y,white);
	if(setts.expand) {
		sprintf(msg, "AW[%c%c]", int2sgf(x),int2sgf(y));
		strcat(broadcast_msg, msg);
	}
}

static void goban_ae(struct goban *gob, int x, int y)
{
	char msg[10];
	flgoban->set_stone(x,y,empty);
	if(setts.expand) {
		sprintf(msg, "AE[%c%c]", int2sgf(x),int2sgf(y));
		strcat(broadcast_msg, msg);
	}
}

static const struct goban_cb gcb = { goban_ab, goban_aw, goban_ae };

/* SGF */
static void sgf_node_new(void)
{
	strcat(broadcast_msg, ";");
}

static void sgf_node_end(void)
{
	strcat(broadcast_msg, "\n");
}

static void sgf_sz(int s)
{
	char msg[10];
	goban_free(g);
	g = goban_alloc(s, &gcb);
	flgoban->flresize(s);
	sprintf(msg, "SZ[%d]", s);
	strcat(broadcast_msg, msg);
}

static void sgf_b(char cx, char cy)
{
	char msg[20];
	goban_play(g, sgf2int(cx), sgf2int(cy), black);

	if(!setts.expand) {
		sprintf(msg, "B[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
}

static void sgf_w(char cx, char cy)
{
	char msg[20];

	goban_play(g, sgf2int(cx), sgf2int(cy), white);

	if(!setts.expand) {
		sprintf(msg, "W[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
}

static void sgf_ab(char cx, char cy)
{
	char msg[10];
	goban_set(g, sgf2int(cx), sgf2int(cy), black);
	if(!setts.expand) {
		sprintf(msg, "AB[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
}

static void sgf_aw(char cx, char cy)
{
	char msg[10];
	goban_set(g, sgf2int(cx), sgf2int(cy), white);
	if(!setts.expand) {
		sprintf(msg, "AW[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
}

static void sgf_ae(char cx, char cy)
{
	char msg[10];
	goban_set(g, sgf2int(cx), sgf2int(cy), empty);
	if(!setts.expand) {
		sprintf(msg, "AE[%c%c]", cx,cy);
		strcat(broadcast_msg, msg);
	}
}

static void sgf_pw(const char *prop, int size)
{
	strcat(broadcast_msg, "PW[");
	strncat(broadcast_msg, prop, size);
	strcat(broadcast_msg, "]");
}

static void sgf_pb(const char *prop, int size)
{
	strcat(broadcast_msg, "PB[");
	strncat(broadcast_msg, prop, size);
	strcat(broadcast_msg, "]");
}

static void sgf_cr(char cx, char cy)
{
	char msg[10];
	flgoban->set_mark(sgf2int(cx),sgf2int(cy),circle);
	sprintf(msg, "CR[%c%c]", cx,cy);
	strcat(broadcast_msg, msg);
}

static void sgf_me(char cx, char cy)
{
	char msg[10];
	flgoban->set_mark(sgf2int(cx),sgf2int(cy),empty);
	sprintf(msg, "ME[%c%c]", cx,cy);
	strcat(broadcast_msg, msg);
}

static void sgf_prop_unknown(const char *prop, int size)
{
	strncat(broadcast_msg, prop, size);
}

static const struct sgf_cb scb = { \
	sgf_node_new, sgf_node_end, \
	sgf_sz, \
	sgf_b, sgf_w, sgf_ab, sgf_aw, sgf_ae, \
	sgf_pw, sgf_pb, \
	sgf_cr, sgf_me, \
	sgf_prop_unknown };

/* EVENTS */

static void ev_key(char k)
{
	char e[100];
	sprintf(e, ";KEY[%c]\n", k);
	broadcast(e);
}

static void ev_mou(int x, int y)
{
	char e[100];
	sprintf(e, ";MOU[%c%c]\n", int2sgf(x),int2sgf(y));
	broadcast(e);
}

/* ARGP */
const char *argp_program_version = "flgoban 0.1";
const char *argp_program_bug_address = "<pieter.beyens@gmail.com>";
static char doc[] = "flgoban -- reads, displays and broadcasts sgf";
static char args_doc[] = "";
static struct argp_option options[] = {
	{"width", 'w', "WIDTH", 0, "window width (defaults to 600)" },
	{"height", 'h', "HEIGHT", 0, "window height (defaults to 600)" },
	{"port", 'p', "PORT", 0, "listening port (if set to zero then only read from stdin - defaults to 5000)" },
	{"nogui",'g', 0, 0, "text-only interface (reads and broadcasts sgf)"},
	{"expand",'e', 0, 0, "expand sgf"},
	{ 0 }
};
static error_t parse_opt (int key, char *arg, struct argp_state *state)
{
	switch (key)
	{
		case 'w':
			if(!arg || 1!=sscanf(arg, "%d", &setts.width)) {
				perror("width must be an integer");
				exit(1);
			}
			break;
		case 'h':
			if(!arg || 1!=sscanf(arg, "%d", &setts.height)) {
				perror("height must be an integer");
				exit(1);
			}
			break;
		case 'p':
			if(!arg || 1!=sscanf(arg, "%d", &setts.port)) {
				perror("port must be an integer");
				exit(1);
			}
			break;
		case 'g':
			setts.nogui = 1;
			break;
		case 'e':
			setts.expand = 1;
			break;
		default:
			return ARGP_ERR_UNKNOWN;
	}
	return 0;
}
static struct argp argp = { options, parse_opt, args_doc, doc };

int main(int argc, char **argv) {
	int s;
	struct sockaddr_in addr;

	memset(&setts,'\0', sizeof(setts));
	setts.width = 600;
	setts.height = 600;
	setts.port = 5000;

	argp_parse (&argp, argc, argv, 0, 0, 0);

	if(setts.port) {
		s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
		if(s < 0) {
			perror("socket()");
			return -1;
		}

		bzero(&addr, sizeof(addr));
		addr.sin_family = AF_INET;
		addr.sin_addr.s_addr = htonl(INADDR_ANY);
		addr.sin_port = htons(setts.port);

		int tr=1;
		if (setsockopt(s,SOL_SOCKET,SO_REUSEADDR,&tr,sizeof(int)) == -1) {
			perror("setsockopt");
			exit(1);
		}

		if(0 > bind(s,(struct sockaddr*)&addr,sizeof(addr))) {
			perror("bind()");
			return -1;
		}

		if(0 > listen(s,1)) {
			perror("listen()");
			return -1;
		}
		Fl::add_fd(s, listen_cb, &s);
	}

	Fl::add_fd(STDIN_FILENO, read_cb, NULL);

	win = new Fl_Double_Window(setts.width,setts.height);
	win->begin();
	flgoban = new Fl_Goban(0,0,setts.width,setts.height, ev_key, ev_mou);
	//textbuffer = new Fl_Text_Buffer();
	//comment = new Fl_Text_Editor(10,650,WINDOW_WIDTH-20,90,0);
	//comment->buffer(textbuffer);
	win->end();
	win->resizable(flgoban);
	if(!setts.nogui)
		win->show();

	g = goban_alloc(19, &gcb);
	sgf_init(&scb);

	signal(SIGPIPE,handler_sigpipe);

	if(setts.nogui)
		while(1)
			Fl::check();
	else
		Fl::run();

	if(setts.port)
		close(s);
	goban_free(g);
}
<|endoftext|>


<commit_before>/*
 * scheduler.cpp
 *
 *  Created on: 23 mars 2013
 *      Author: dom
 */

#include <iostream>
#include <stdlib.h>
#include "assert.h"
#include "scheduler.h"
#include "trace.h"

using namespace std;

namespace BaseSimulator {

Scheduler *Scheduler::scheduler=NULL;

Scheduler::Scheduler() {
	OUTPUT << "Scheduler constructor" << endl;

	if (sizeof(uint64_t) != 8) {
		ERRPUT << "\033[1;31m" << "ERROR : Scheduler requires 8bytes integer that are not available on this computer" << "\033[0m" << endl;
		exit(EXIT_FAILURE);
	}

	if (scheduler == NULL) {
		scheduler = this;
	} else {
		ERRPUT << "\033[1;31m" << "Only one Scheduler instance can be created, aborting !" << "\033[0m" << endl;
		exit(EXIT_FAILURE);
	}

	currentDate = 0;
	maximumDate = UINT64_MAX; // no time limitation by default

	eventsMapSize = 0;
	largestEventsMapSize = 0;
}

Scheduler::~Scheduler() {
	OUTPUT << "Scheduler destructor" << endl;
}

bool Scheduler::schedule(Event *ev) {
	assert(ev != NULL);
	stringstream info;

	EventPtr pev(ev);

	info << "Schedule a " << pev->getEventName() << " (" << ev->id << ")";
	//MODIF NICO : cette ligne me spam trop l'affichage^^
	//~ trace(info.str());

	if (pev->date < Scheduler::currentDate) {
		OUTPUT << "ERROR : An event cannot be schedule in the past !\n";
	    OUTPUT << "current time : " << Scheduler::currentDate << endl;
	    OUTPUT << "ev->eventDate : " << pev->date << endl;
	    OUTPUT << "ev->getEventName() : " << pev->getEventName() << endl;
	    return(false);
	}

	if (pev->date > maximumDate) {
		OUTPUT << "WARNING : An event should not be schedule beyond the end of simulation date !\n";
		OUTPUT << "pev->date : " << pev->date << endl;
		OUTPUT << "maximumDate : " << maximumDate << endl;
	    return(false);
	}

	lock();

	eventsMap.insert(pair<uint64_t, EventPtr>(pev->date,pev));

	eventsMapSize++;

	if (largestEventsMapSize < eventsMapSize) largestEventsMapSize = eventsMapSize;

	unlock();

	return(true);
}

void Scheduler::removeEventsToBlock(BuildingBlock *bb) {
	lock();
	multimap<uint64_t,EventPtr>::iterator im = eventsMap.begin();
	BuildingBlock *cb=NULL;
	OUTPUT << bb << endl;
	while (im!=eventsMap.end()) {
		cb=(*im).second->getConcernedBlock();
		OUTPUT << cb << endl;
		if (cb==bb) {
			multimap<uint64_t,EventPtr>::iterator im2 = im;
			if(im != eventsMap.begin()) {
				im--;
				eventsMap.erase(im2);
			} else {
				eventsMap.erase(im2);
				im = eventsMap.begin();
			}
		} else im++;
	}
	unlock();
}

uint64_t Scheduler::now() {
	return(currentDate);
}

bool Scheduler::scheduleLock(Event *ev) {
	return schedule(ev); //lock done in schedule
}

void Scheduler::trace(string message,int id,const Color &color) {
	mutex_trace.lock();
	OUTPUT.precision(6);
	OUTPUT << fixed << (double)(currentDate)/1000000 << " #" << id << ": " << message << endl;
	GlutContext::addTrace(message,id,color);
	mutex_trace.unlock();
}

void Scheduler::lock() {
	mutex_schedule.lock();
}

void Scheduler::unlock() {
	mutex_schedule.unlock();
}

} // BaseSimulator namespace
<commit_msg>scheduler duration limit: UINT_MAX instead of specific UINT64_MAX (compilation errors when using 32-bit virtual machine)<commit_after>/*
 * scheduler.cpp
 *
 *  Created on: 23 mars 2013
 *      Author: dom
 */

#include <iostream>
#include <stdlib.h>
#include "assert.h"
#include "scheduler.h"
#include "trace.h"
#include "stdint.h"

using namespace std;

namespace BaseSimulator {

Scheduler *Scheduler::scheduler=NULL;

Scheduler::Scheduler() {
	OUTPUT << "Scheduler constructor" << endl;

	if (sizeof(uint64_t) != 8) {
		ERRPUT << "\033[1;31m" << "ERROR : Scheduler requires 8bytes integer that are not available on this computer" << "\033[0m" << endl;
		exit(EXIT_FAILURE);
	}

	if (scheduler == NULL) {
		scheduler = this;
	} else {
		ERRPUT << "\033[1;31m" << "Only one Scheduler instance can be created, aborting !" << "\033[0m" << endl;
		exit(EXIT_FAILURE);
	}

	currentDate = 0;
	maximumDate = UINT_MAX; // no time limitation by default

	eventsMapSize = 0;
	largestEventsMapSize = 0;
}

Scheduler::~Scheduler() {
	OUTPUT << "Scheduler destructor" << endl;
}

bool Scheduler::schedule(Event *ev) {
	assert(ev != NULL);
	stringstream info;

	EventPtr pev(ev);

	info << "Schedule a " << pev->getEventName() << " (" << ev->id << ")";
	//MODIF NICO : cette ligne me spam trop l'affichage^^
	//~ trace(info.str());

	if (pev->date < Scheduler::currentDate) {
		OUTPUT << "ERROR : An event cannot be schedule in the past !\n";
	    OUTPUT << "current time : " << Scheduler::currentDate << endl;
	    OUTPUT << "ev->eventDate : " << pev->date << endl;
	    OUTPUT << "ev->getEventName() : " << pev->getEventName() << endl;
	    return(false);
	}

	if (pev->date > maximumDate) {
		OUTPUT << "WARNING : An event should not be schedule beyond the end of simulation date !\n";
		OUTPUT << "pev->date : " << pev->date << endl;
		OUTPUT << "maximumDate : " << maximumDate << endl;
	    return(false);
	}

	lock();

	eventsMap.insert(pair<uint64_t, EventPtr>(pev->date,pev));

	eventsMapSize++;

	if (largestEventsMapSize < eventsMapSize) largestEventsMapSize = eventsMapSize;

	unlock();

	return(true);
}

void Scheduler::removeEventsToBlock(BuildingBlock *bb) {
	lock();
	multimap<uint64_t,EventPtr>::iterator im = eventsMap.begin();
	BuildingBlock *cb=NULL;
	OUTPUT << bb << endl;
	while (im!=eventsMap.end()) {
		cb=(*im).second->getConcernedBlock();
		OUTPUT << cb << endl;
		if (cb==bb) {
			multimap<uint64_t,EventPtr>::iterator im2 = im;
			if(im != eventsMap.begin()) {
				im--;
				eventsMap.erase(im2);
			} else {
				eventsMap.erase(im2);
				im = eventsMap.begin();
			}
		} else im++;
	}
	unlock();
}

uint64_t Scheduler::now() {
	return(currentDate);
}

bool Scheduler::scheduleLock(Event *ev) {
	return schedule(ev); //lock done in schedule
}

void Scheduler::trace(string message,int id,const Color &color) {
	mutex_trace.lock();
	OUTPUT.precision(6);
	OUTPUT << fixed << (double)(currentDate)/1000000 << " #" << id << ": " << message << endl;
	GlutContext::addTrace(message,id,color);
	mutex_trace.unlock();
}

void Scheduler::lock() {
	mutex_schedule.lock();
}

void Scheduler::unlock() {
	mutex_schedule.unlock();
}

} // BaseSimulator namespace
<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	RL78/G13 グループ・シリアル・アレイ・ユニット・レジスター定義 @n
			Copyright 2016 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "common/io_utils.hpp"

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  シリアル・アレイ・ユニット・テンプレート
		@param[in]	UOFS	ユニット・オフセット（0x00、0x40）
		@param[in]	CHOFS	チャネル・オフセット（0x00, 0x02, 0x04, 0x06)
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint32_t UOFS, uint32_t CHOFS>
	struct sau_t {

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・クロック選択レジスタ m（SPS）テンプレート @n
					※ユニット単位
			@param[in]	T	アクセス・クラス
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <class T>
		struct sps_t : public T {
			using T::operator =;
			using T::operator ();
			using T::operator |=;
			using T::operator &=;

			bits_rw_t<T, 0, 4>	PRS0;
			bits_rw_t<T, 4, 4>	PRS1;
		};
		static sps_t< rw8_t<0xF0126 + UOFS> > SPS;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・モード・レジスタ mn（SMR）テンプレート
			@param[in]	T	アクセス・クラス
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <class T>
		struct smr_t : public T {
			using T::operator =;
			using T::operator ();
			using T::operator |=;
			using T::operator &=;

			bit_rw_t<T, 15>		CKS;	///< チャネルnの動作クロック（f MCK ）の選択
			bit_rw_t<T, 14>		CCS;	///< チャネルnの転送クロック（f TCLK ）の選択
			bit_rw_t<T,  8>		STS;	///< スタート・トリガ要因の選択
			bit_rw_t<T,  6>		SIS;	///< UARTモードでのチャネルnの受信データのレベル反転の制御
			bits_rw_t<T,  1, 2>	MD;		///< チャネルnの動作モードの設定
			bit_rw_t<T,  0>		MD0;	///< チャネルnの割り込み要因の選択
		};
		static smr_t< rw16_t<0xF0110 + UOFS + CHOFS> > SMR;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル通信動作設定レジスタ mn（SCR）テンプレート
			@param[in]	T	アクセス・クラス
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <class T>
		struct scr_t : public T {
			using T::operator =;
			using T::operator ();
			using T::operator |=;
			using T::operator &=;

			bit_rw_t<T, 15>		TXE;	///< 送信モードの設定
			bit_rw_t<T, 14>		RXE;	///< 受信モードの設定
			bit_rw_t<T, 13>		DAP;	///< CSIモードでのデータとクロックの位相選択
			bit_rw_t<T, 12>		CKP;	///< CSIモードでのデータとクロックの位相選択

			bit_rw_t<T, 10>		EOC;	///< エラー割り込み信号（INTSREx（x = 0-3））のマスク制御
			bits_rw_t<T,  8, 2>	PTC;	///< UARTモードでのパリティ・ビットの設定
			bit_rw_t<T,  7>		DIR;	///< CSI, UARTモードでのデータ転送順序の選択

			bits_rw_t<T,  4, 2>	SLC;	///< UARTモードでのストップ・ビットの設定

			bits_rw_t<T,  0, 2>	DLS;	///< CSI, UARTモードでのデータ長の設定
		};
		static scr_t< rw16_t<0xF0118 + UOFS + CHOFS> > SCR;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・データ・レジスタ（SDR）@n
					１６ビットアクセス
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static rw16_t<0xFFF10 + UOFS + CHOFS> SDR;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・データ・レジスタ（SDR_L）@n
					下位８ビットアクセス (B0 - B7)
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static  rw8_t<0xFFF10 + UOFS + CHOFS> SDR_L;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・フラグ・クリア・トリガ・レジスタ mn（SIR）テンプレート
			@param[in]	T	アクセス・クラス
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <class T>
		struct sir_t : public T {
			using T::operator =;
			using T::operator ();
			using T::operator |=;
			using T::operator &=;

			bit_rw_t<T, 2>	FEC;	///< チャネルnのフレーミング・エラー・フラグのクリア・トリガ
			bit_rw_t<T, 1>	PEC;	///< チャネルnのパリティ・エラー・フラグのクリア・トリガ
			bit_rw_t<T, 0>	OVC;	///< チャネルnのオーバラン・エラー・フラグのクリア・トリガ
		};
		static sir_t< rw8_t<0xF0108 + UOFS + CHOFS> > SIR;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・ステータス・レジスタmn（SSR）テンプレート
			@param[in]	T	アクセス・クラス
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <class T>
		struct ssr_t : public T {
			using T::operator ();

			bit_ro_t<T, 6>	TSF;	///< チャネルnの通信状態表示フラグ
			bit_ro_t<T, 5>	BFF;	///< チャネルnのバッファ・レジスタ状態表示フラグ

			bit_ro_t<T, 2>	FEF;	///< チャネルnのフレーミング・エラー検出フラグ
			bit_ro_t<T, 1>	PEF;	///< チャネルnのパリティ／ACKエラー検出フラグ
			bit_ro_t<T, 0>	OVF;	///< チャネルnのオーバラン・エラー検出フラグ
		};
		static ssr_t< ro8_t<0xF0100 + UOFS + CHOFS> > SSR;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・チャネル開始レジスタ m（SS）
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw8_t<0xF0122 + UOFS>, CHOFS / 2> SS;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・チャネル停止レジスタ m（ST）
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw8_t<0xF0124 + UOFS>, CHOFS / 2> ST;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・チャネル許可ステータス・レジスタ m（SE）
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_ro_t<ro8_t<0xF0120 + UOFS>, CHOFS / 2> SE;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル出力許可レジスタ m（SOE）
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw8_t<0xF012A + UOFS>, CHOFS / 2> SOE;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル出力レジスタ m（SO）
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw16_t<0xF0128 + UOFS>, CHOFS / 2> SO;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・クロック・レジスタ m（CKO）
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw16_t<0xF0128 + UOFS>, 8 + (CHOFS / 2)> CKO;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル出力レベル・レジスタ m（SOL）
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw8_t<0xF0134 + UOFS>, CHOFS / 2> SOL;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・スタンバイ・コントロール・レジスタ m（SSC）テンプレート @n
					※ユニット単位
			@param[in]	T	アクセス・クラス
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <class T>
		struct ssc_t : public T {
			using T::operator =;
			using T::operator ();
			using T::operator |=;
			using T::operator &=;

			bit_rw_t<T, 1>	SSEC;
			bit_rw_t<T, 0>	SWC;
		};
		static ssc_t<rw8_t<0xF0138 + UOFS> > SSC;

        //-----------------------------------------------------------------//
        /*!
            @brief  ユニット番号を取得
			@return 「０」又は「１」
        */
        //-----------------------------------------------------------------//
		uint8_t get_unit_no() const { return UOFS / 0x40; }

        //-----------------------------------------------------------------//
        /*!
            @brief  チャネル番号を取得
			@return 「０～３」
        */
        //-----------------------------------------------------------------//
		uint8_t get_chanel_no() const { return CHOFS / 0x02; }
	};
	typedef sau_t<0x00, 0x00> SAU00;
	typedef sau_t<0x00, 0x02> SAU01;
	typedef sau_t<0x00, 0x04> SAU02;
	typedef sau_t<0x00, 0x06> SAU03;

	typedef sau_t<0x40, 0x00> SAU10;
	typedef sau_t<0x40, 0x02> SAU11;
	typedef sau_t<0x40, 0x04> SAU12;
	typedef sau_t<0x40, 0x06> SAU13;

	namespace SAU {

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  入力切り替え制御レジスタ（ISC）テンプレート
			@param[in]	T	アクセス・クラス
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <class T>
		struct isc_t : public T {
			using T::operator =;
			using T::operator ();
			using T::operator |=;
			using T::operator &=;

			bit_rw_t<T, 1>	ISC1;	///< タイマ・アレイ・ユニットのチャネル7の入力切り替え
			bit_rw_t<T, 0>	ISC0;	///< 外部割り込み（INTP0）の入力切り替え
		};
		static isc_t<rw8_t<0xF0073> > ISC;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  ノイズ・フィルタ許可レジスタ0（NFEN0）
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static rw8_t<0xF0070> NFEN0;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  ノイズ・フィルタ許可レジスタ0（SNFEN30）
					RxD3端子のノイズ・フィルタ使用可否
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw8_t<0xF0070>, 6> SNFEN30;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  ノイズ・フィルタ許可レジスタ0（SNFEN20）
					RxD2端子のノイズ・フィルタ使用可否
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw8_t<0xF0070>, 4> SNFEN20;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  ノイズ・フィルタ許可レジスタ0（SNFEN10）
					RxD1端子のノイズ・フィルタ使用可否
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw8_t<0xF0070>, 2> SNFEN10;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  ノイズ・フィルタ許可レジスタ0（SNFEN00）
					RxD0端子のノイズ・フィルタ使用可否
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw8_t<0xF0070>, 0> SNFEN00;
	}
}
<commit_msg>update comment<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	RL78/G13 グループ・シリアル・アレイ・ユニット定義 @n
			Copyright 2016 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "common/io_utils.hpp"

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  シリアル・アレイ・ユニット・テンプレート
		@param[in]	UOFS	ユニット・オフセット（0x00、0x40）
		@param[in]	CHOFS	チャネル・オフセット（0x00, 0x02, 0x04, 0x06)
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	template <uint32_t UOFS, uint32_t CHOFS>
	struct sau_t {

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・クロック選択レジスタ m（SPS）テンプレート @n
					※ユニット単位
			@param[in]	T	アクセス・クラス
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <class T>
		struct sps_t : public T {
			using T::operator =;
			using T::operator ();
			using T::operator |=;
			using T::operator &=;

			bits_rw_t<T, 0, 4>	PRS0;
			bits_rw_t<T, 4, 4>	PRS1;
		};
		static sps_t< rw8_t<0xF0126 + UOFS> > SPS;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・モード・レジスタ mn（SMR）テンプレート
			@param[in]	T	アクセス・クラス
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <class T>
		struct smr_t : public T {
			using T::operator =;
			using T::operator ();
			using T::operator |=;
			using T::operator &=;

			bit_rw_t<T, 15>		CKS;	///< チャネルnの動作クロック（f MCK ）の選択
			bit_rw_t<T, 14>		CCS;	///< チャネルnの転送クロック（f TCLK ）の選択
			bit_rw_t<T,  8>		STS;	///< スタート・トリガ要因の選択
			bit_rw_t<T,  6>		SIS;	///< UARTモードでのチャネルnの受信データのレベル反転の制御
			bits_rw_t<T,  1, 2>	MD;		///< チャネルnの動作モードの設定
			bit_rw_t<T,  0>		MD0;	///< チャネルnの割り込み要因の選択
		};
		static smr_t< rw16_t<0xF0110 + UOFS + CHOFS> > SMR;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル通信動作設定レジスタ mn（SCR）テンプレート
			@param[in]	T	アクセス・クラス
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <class T>
		struct scr_t : public T {
			using T::operator =;
			using T::operator ();
			using T::operator |=;
			using T::operator &=;

			bit_rw_t<T, 15>		TXE;	///< 送信モードの設定
			bit_rw_t<T, 14>		RXE;	///< 受信モードの設定
			bit_rw_t<T, 13>		DAP;	///< CSIモードでのデータとクロックの位相選択
			bit_rw_t<T, 12>		CKP;	///< CSIモードでのデータとクロックの位相選択

			bit_rw_t<T, 10>		EOC;	///< エラー割り込み信号（INTSREx（x = 0-3））のマスク制御
			bits_rw_t<T,  8, 2>	PTC;	///< UARTモードでのパリティ・ビットの設定
			bit_rw_t<T,  7>		DIR;	///< CSI, UARTモードでのデータ転送順序の選択

			bits_rw_t<T,  4, 2>	SLC;	///< UARTモードでのストップ・ビットの設定

			bits_rw_t<T,  0, 2>	DLS;	///< CSI, UARTモードでのデータ長の設定
		};
		static scr_t< rw16_t<0xF0118 + UOFS + CHOFS> > SCR;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・データ・レジスタ（SDR）@n
					１６ビットアクセス
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static rw16_t<0xFFF10 + UOFS + CHOFS> SDR;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・データ・レジスタ（SDR_L）@n
					下位８ビットアクセス (B0 - B7)
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static  rw8_t<0xFFF10 + UOFS + CHOFS> SDR_L;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・フラグ・クリア・トリガ・レジスタ mn（SIR）テンプレート
			@param[in]	T	アクセス・クラス
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <class T>
		struct sir_t : public T {
			using T::operator =;
			using T::operator ();
			using T::operator |=;
			using T::operator &=;

			bit_rw_t<T, 2>	FEC;	///< チャネルnのフレーミング・エラー・フラグのクリア・トリガ
			bit_rw_t<T, 1>	PEC;	///< チャネルnのパリティ・エラー・フラグのクリア・トリガ
			bit_rw_t<T, 0>	OVC;	///< チャネルnのオーバラン・エラー・フラグのクリア・トリガ
		};
		static sir_t< rw8_t<0xF0108 + UOFS + CHOFS> > SIR;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・ステータス・レジスタmn（SSR）テンプレート
			@param[in]	T	アクセス・クラス
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <class T>
		struct ssr_t : public T {
			using T::operator ();

			bit_ro_t<T, 6>	TSF;	///< チャネルnの通信状態表示フラグ
			bit_ro_t<T, 5>	BFF;	///< チャネルnのバッファ・レジスタ状態表示フラグ

			bit_ro_t<T, 2>	FEF;	///< チャネルnのフレーミング・エラー検出フラグ
			bit_ro_t<T, 1>	PEF;	///< チャネルnのパリティ／ACKエラー検出フラグ
			bit_ro_t<T, 0>	OVF;	///< チャネルnのオーバラン・エラー検出フラグ
		};
		static ssr_t< ro8_t<0xF0100 + UOFS + CHOFS> > SSR;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・チャネル開始レジスタ m（SS）
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw8_t<0xF0122 + UOFS>, CHOFS / 2> SS;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・チャネル停止レジスタ m（ST）
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw8_t<0xF0124 + UOFS>, CHOFS / 2> ST;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・チャネル許可ステータス・レジスタ m（SE）
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_ro_t<ro8_t<0xF0120 + UOFS>, CHOFS / 2> SE;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル出力許可レジスタ m（SOE）
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw8_t<0xF012A + UOFS>, CHOFS / 2> SOE;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル出力レジスタ m（SO）
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw16_t<0xF0128 + UOFS>, CHOFS / 2> SO;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・クロック・レジスタ m（CKO）
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw16_t<0xF0128 + UOFS>, 8 + (CHOFS / 2)> CKO;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル出力レベル・レジスタ m（SOL）
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw8_t<0xF0134 + UOFS>, CHOFS / 2> SOL;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  シリアル・スタンバイ・コントロール・レジスタ m（SSC）テンプレート @n
					※ユニット単位
			@param[in]	T	アクセス・クラス
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <class T>
		struct ssc_t : public T {
			using T::operator =;
			using T::operator ();
			using T::operator |=;
			using T::operator &=;

			bit_rw_t<T, 1>	SSEC;
			bit_rw_t<T, 0>	SWC;
		};
		static ssc_t<rw8_t<0xF0138 + UOFS> > SSC;

        //-----------------------------------------------------------------//
        /*!
            @brief  ユニット番号を取得
			@return 「０」又は「１」
        */
        //-----------------------------------------------------------------//
		uint8_t get_unit_no() const { return UOFS / 0x40; }

        //-----------------------------------------------------------------//
        /*!
            @brief  チャネル番号を取得
			@return 「０～３」
        */
        //-----------------------------------------------------------------//
		uint8_t get_chanel_no() const { return CHOFS / 0x02; }
	};
	typedef sau_t<0x00, 0x00> SAU00;
	typedef sau_t<0x00, 0x02> SAU01;
	typedef sau_t<0x00, 0x04> SAU02;
	typedef sau_t<0x00, 0x06> SAU03;

	typedef sau_t<0x40, 0x00> SAU10;
	typedef sau_t<0x40, 0x02> SAU11;
	typedef sau_t<0x40, 0x04> SAU12;
	typedef sau_t<0x40, 0x06> SAU13;

	namespace SAU {

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  入力切り替え制御レジスタ（ISC）テンプレート
			@param[in]	T	アクセス・クラス
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <class T>
		struct isc_t : public T {
			using T::operator =;
			using T::operator ();
			using T::operator |=;
			using T::operator &=;

			bit_rw_t<T, 1>	ISC1;	///< タイマ・アレイ・ユニットのチャネル7の入力切り替え
			bit_rw_t<T, 0>	ISC0;	///< 外部割り込み（INTP0）の入力切り替え
		};
		static isc_t<rw8_t<0xF0073> > ISC;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  ノイズ・フィルタ許可レジスタ0（NFEN0）
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static rw8_t<0xF0070> NFEN0;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  ノイズ・フィルタ許可レジスタ0（SNFEN30）
					RxD3端子のノイズ・フィルタ使用可否
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw8_t<0xF0070>, 6> SNFEN30;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  ノイズ・フィルタ許可レジスタ0（SNFEN20）
					RxD2端子のノイズ・フィルタ使用可否
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw8_t<0xF0070>, 4> SNFEN20;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  ノイズ・フィルタ許可レジスタ0（SNFEN10）
					RxD1端子のノイズ・フィルタ使用可否
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw8_t<0xF0070>, 2> SNFEN10;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  ノイズ・フィルタ許可レジスタ0（SNFEN00）
					RxD0端子のノイズ・フィルタ使用可否
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		static bit_rw_t<rw8_t<0xF0070>, 0> SNFEN00;
	}
}
<|endoftext|>


<commit_before><commit_msg>GCD Euclid’s algorithm<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/cros_settings_provider_user.h"

#include "base/string_util.h"
#include "chrome/browser/chromeos/cros_settings_names.h"

namespace chromeos {

UserCrosSettingsProvider::UserCrosSettingsProvider()
    : dict_(new DictionaryValue) {
  Set(kAccountsPrefAllowBWSI, Value::CreateBooleanValue(true));
  Set(kAccountsPrefAllowGuest, Value::CreateBooleanValue(true));

  ListValue* user_list = new ListValue;

  DictionaryValue* mock_user = new DictionaryValue;
  mock_user->SetString(L"email", L"mock_user_1@gmail.com");
  user_list->Append(mock_user);

  mock_user = new DictionaryValue;
  mock_user->SetString(L"email", L"mock_user_2@gmail.com");
  user_list->Append(mock_user);

  Set(kAccountsPrefUsers, user_list);
}

void UserCrosSettingsProvider::Set(const std::wstring& path, Value* in_value) {
  dict_->Set(path, in_value);
}

bool UserCrosSettingsProvider::Get(const std::wstring& path,
                                   Value** out_value) const {
  return dict_->Get(path, out_value);
}

bool UserCrosSettingsProvider::HandlesSetting(const std::wstring& path) {
  return ::StartsWith(path, std::wstring(L"cros.accounts"), true);
}

}  // namespace chromeos
<commit_msg>Add back the lost mock data to get rid of "undefined" in users options page.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/cros_settings_provider_user.h"

#include "base/string_util.h"
#include "chrome/browser/chromeos/cros_settings_names.h"

namespace chromeos {

UserCrosSettingsProvider::UserCrosSettingsProvider()
    : dict_(new DictionaryValue) {
  Set(kAccountsPrefAllowBWSI, Value::CreateBooleanValue(true));
  Set(kAccountsPrefAllowGuest, Value::CreateBooleanValue(true));
  Set(kAccountsPrefShowUserNamesOnSignIn, Value::CreateBooleanValue(true));

  ListValue* user_list = new ListValue;

  DictionaryValue* mock_user = new DictionaryValue;
  mock_user->SetString(L"email", L"mock_user_1@gmail.com");
  mock_user->SetString(L"name", L"Mock User One");
  mock_user->SetBoolean(L"owner", true);
  user_list->Append(mock_user);

  mock_user = new DictionaryValue;
  mock_user->SetString(L"email", L"mock_user_2@gmail.com");
  mock_user->SetString(L"name", L"Mock User Two");
  mock_user->SetBoolean(L"owner", false);
  user_list->Append(mock_user);

  Set(kAccountsPrefUsers, user_list);
}

void UserCrosSettingsProvider::Set(const std::wstring& path, Value* in_value) {
  dict_->Set(path, in_value);
}

bool UserCrosSettingsProvider::Get(const std::wstring& path,
                                   Value** out_value) const {
  return dict_->Get(path, out_value);
}

bool UserCrosSettingsProvider::HandlesSetting(const std::wstring& path) {
  return ::StartsWith(path, std::wstring(L"cros.accounts"), true);
}

}  // namespace chromeos
<|endoftext|>


<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/renderer_host/async_resource_handler.h"

#include "base/logging.h"
#include "base/process.h"
#include "base/shared_memory.h"
#include "chrome/common/render_messages.h"
#include "net/base/io_buffer.h"

// When reading, we don't know if we are going to get EOF (0 bytes read), so
// we typically have a buffer that we allocated but did not use.  We keep
// this buffer around for the next read as a small optimization.
static SharedIOBuffer* g_spare_read_buffer = NULL;

// Our version of IOBuffer that uses shared memory.
class SharedIOBuffer : public net::IOBuffer {
 public:
  SharedIOBuffer(int buffer_size) : net::IOBuffer(), ok_(false) {
    if (shared_memory_.Create(std::wstring(), false, false, buffer_size) &&
        shared_memory_.Map(buffer_size)) {
      ok_ = true;
      data_ = reinterpret_cast<char*>(shared_memory_.memory());
    }
  }
  ~SharedIOBuffer() {
    // TODO(willchan): Remove after debugging bug 16371.
    CHECK(g_spare_read_buffer != this);
    data_ = NULL;
  }

  base::SharedMemory* shared_memory() { return &shared_memory_; }
  bool ok() { return ok_; }

 private:
  base::SharedMemory shared_memory_;
  bool ok_;
};

AsyncResourceHandler::AsyncResourceHandler(
    ResourceDispatcherHost::Receiver* receiver,
    int process_id,
    int routing_id,
    base::ProcessHandle process_handle,
    const GURL& url,
    ResourceDispatcherHost* resource_dispatcher_host)
    : receiver_(receiver),
      process_id_(process_id),
      routing_id_(routing_id),
      process_handle_(process_handle),
      rdh_(resource_dispatcher_host) {
}

bool AsyncResourceHandler::OnUploadProgress(int request_id,
                                            uint64 position,
                                            uint64 size) {
  return receiver_->Send(new ViewMsg_Resource_UploadProgress(routing_id_,
                                                             request_id,
                                                             position, size));
}

bool AsyncResourceHandler::OnRequestRedirected(int request_id,
                                               const GURL& new_url,
                                               ResourceResponse* response,
                                               bool* defer) {
  *defer = true;
  return receiver_->Send(new ViewMsg_Resource_ReceivedRedirect(
      routing_id_, request_id, new_url, response->response_head));
}

bool AsyncResourceHandler::OnResponseStarted(int request_id,
                                             ResourceResponse* response) {
  receiver_->Send(new ViewMsg_Resource_ReceivedResponse(
      routing_id_, request_id, response->response_head));
  return true;
}

bool AsyncResourceHandler::OnWillRead(int request_id, net::IOBuffer** buf,
                                      int* buf_size, int min_size) {
  DCHECK(min_size == -1);
  static const int kReadBufSize = 32768;
  if (g_spare_read_buffer) {
    DCHECK(!read_buffer_);
    read_buffer_.swap(&g_spare_read_buffer);
    // TODO(willchan): Remove after debugging bug 16371.
    CHECK(read_buffer_->data());
  } else {
    read_buffer_ = new SharedIOBuffer(kReadBufSize);
    if (!read_buffer_->ok())
      return false;
    // TODO(willchan): Remove after debugging bug 16371.
    CHECK(read_buffer_->data());
  }
  *buf = read_buffer_.get();
  *buf_size = kReadBufSize;
  return true;
}

bool AsyncResourceHandler::OnReadCompleted(int request_id, int* bytes_read) {
  if (!*bytes_read)
    return true;
  DCHECK(read_buffer_.get());

  if (!rdh_->WillSendData(process_id_, request_id)) {
    // We should not send this data now, we have too many pending requests.
    return true;
  }

  base::SharedMemoryHandle handle;
  if (!read_buffer_->shared_memory()->GiveToProcess(process_handle_, &handle)) {
    // We wrongfully incremented the pending data count. Fake an ACK message
    // to fix this. We can't move this call above the WillSendData because
    // it's killing our read_buffer_, and we don't want that when we pause
    // the request.
    rdh_->DataReceivedACK(process_id_, request_id);
    // We just unmapped the memory.
    read_buffer_ = NULL;
    return false;
  }
  // We just unmapped the memory.
  read_buffer_ = NULL;

  receiver_->Send(new ViewMsg_Resource_DataReceived(
      routing_id_, request_id, handle, *bytes_read));

  return true;
}

bool AsyncResourceHandler::OnResponseCompleted(
    int request_id,
    const URLRequestStatus& status,
    const std::string& security_info) {
  receiver_->Send(new ViewMsg_Resource_RequestComplete(routing_id_,
                                                       request_id,
                                                       status,
                                                       security_info));

  // If we still have a read buffer, then see about caching it for later...
  if (g_spare_read_buffer) {
    read_buffer_ = NULL;
  } else if (read_buffer_.get()) {
    read_buffer_.swap(&g_spare_read_buffer);
  }
  return true;
}

// static
void AsyncResourceHandler::GlobalCleanup() {
  if (g_spare_read_buffer) {
    // Avoid the CHECK in SharedIOBuffer::~SharedIOBuffer().
    SharedIOBuffer* tmp = g_spare_read_buffer;
    g_spare_read_buffer = NULL;
    tmp->Release();
  }
}
<commit_msg>CHECK that IOBuffer::data_ in AsyncResourceHandler is not NULL before caching it. BUG=http://crbug.com/16371<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/renderer_host/async_resource_handler.h"

#include "base/logging.h"
#include "base/process.h"
#include "base/shared_memory.h"
#include "chrome/common/render_messages.h"
#include "net/base/io_buffer.h"

// When reading, we don't know if we are going to get EOF (0 bytes read), so
// we typically have a buffer that we allocated but did not use.  We keep
// this buffer around for the next read as a small optimization.
static SharedIOBuffer* g_spare_read_buffer = NULL;

// Our version of IOBuffer that uses shared memory.
class SharedIOBuffer : public net::IOBuffer {
 public:
  SharedIOBuffer(int buffer_size) : net::IOBuffer(), ok_(false) {
    if (shared_memory_.Create(std::wstring(), false, false, buffer_size) &&
        shared_memory_.Map(buffer_size)) {
      ok_ = true;
      data_ = reinterpret_cast<char*>(shared_memory_.memory());
    }
  }
  ~SharedIOBuffer() {
    // TODO(willchan): Remove after debugging bug 16371.
    CHECK(g_spare_read_buffer != this);
    data_ = NULL;
  }

  base::SharedMemory* shared_memory() { return &shared_memory_; }
  bool ok() { return ok_; }

 private:
  base::SharedMemory shared_memory_;
  bool ok_;
};

AsyncResourceHandler::AsyncResourceHandler(
    ResourceDispatcherHost::Receiver* receiver,
    int process_id,
    int routing_id,
    base::ProcessHandle process_handle,
    const GURL& url,
    ResourceDispatcherHost* resource_dispatcher_host)
    : receiver_(receiver),
      process_id_(process_id),
      routing_id_(routing_id),
      process_handle_(process_handle),
      rdh_(resource_dispatcher_host) {
}

bool AsyncResourceHandler::OnUploadProgress(int request_id,
                                            uint64 position,
                                            uint64 size) {
  return receiver_->Send(new ViewMsg_Resource_UploadProgress(routing_id_,
                                                             request_id,
                                                             position, size));
}

bool AsyncResourceHandler::OnRequestRedirected(int request_id,
                                               const GURL& new_url,
                                               ResourceResponse* response,
                                               bool* defer) {
  *defer = true;
  return receiver_->Send(new ViewMsg_Resource_ReceivedRedirect(
      routing_id_, request_id, new_url, response->response_head));
}

bool AsyncResourceHandler::OnResponseStarted(int request_id,
                                             ResourceResponse* response) {
  receiver_->Send(new ViewMsg_Resource_ReceivedResponse(
      routing_id_, request_id, response->response_head));
  return true;
}

bool AsyncResourceHandler::OnWillRead(int request_id, net::IOBuffer** buf,
                                      int* buf_size, int min_size) {
  DCHECK(min_size == -1);
  static const int kReadBufSize = 32768;
  if (g_spare_read_buffer) {
    DCHECK(!read_buffer_);
    read_buffer_.swap(&g_spare_read_buffer);
    // TODO(willchan): Remove after debugging bug 16371.
    CHECK(read_buffer_->data());
  } else {
    read_buffer_ = new SharedIOBuffer(kReadBufSize);
    if (!read_buffer_->ok())
      return false;
    // TODO(willchan): Remove after debugging bug 16371.
    CHECK(read_buffer_->data());
  }
  *buf = read_buffer_.get();
  *buf_size = kReadBufSize;
  return true;
}

bool AsyncResourceHandler::OnReadCompleted(int request_id, int* bytes_read) {
  if (!*bytes_read)
    return true;
  DCHECK(read_buffer_.get());

  if (!rdh_->WillSendData(process_id_, request_id)) {
    // We should not send this data now, we have too many pending requests.
    return true;
  }

  base::SharedMemoryHandle handle;
  if (!read_buffer_->shared_memory()->GiveToProcess(process_handle_, &handle)) {
    // We wrongfully incremented the pending data count. Fake an ACK message
    // to fix this. We can't move this call above the WillSendData because
    // it's killing our read_buffer_, and we don't want that when we pause
    // the request.
    rdh_->DataReceivedACK(process_id_, request_id);
    // We just unmapped the memory.
    read_buffer_ = NULL;
    return false;
  }
  // We just unmapped the memory.
  read_buffer_ = NULL;

  receiver_->Send(new ViewMsg_Resource_DataReceived(
      routing_id_, request_id, handle, *bytes_read));

  return true;
}

bool AsyncResourceHandler::OnResponseCompleted(
    int request_id,
    const URLRequestStatus& status,
    const std::string& security_info) {
  receiver_->Send(new ViewMsg_Resource_RequestComplete(routing_id_,
                                                       request_id,
                                                       status,
                                                       security_info));

  // If we still have a read buffer, then see about caching it for later...
  if (g_spare_read_buffer) {
    read_buffer_ = NULL;
  } else if (read_buffer_.get()) {
    // TODO(willchan): Remove after debugging bug 16371.
    CHECK(read_buffer_->data());
    read_buffer_.swap(&g_spare_read_buffer);
  }
  return true;
}

// static
void AsyncResourceHandler::GlobalCleanup() {
  if (g_spare_read_buffer) {
    // Avoid the CHECK in SharedIOBuffer::~SharedIOBuffer().
    SharedIOBuffer* tmp = g_spare_read_buffer;
    g_spare_read_buffer = NULL;
    tmp->Release();
  }
}
<|endoftext|>


<commit_before>//
// chat_client.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <cstdlib>
#include <deque>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include "chat_message.hpp"

using boost::asio::ip::tcp;

typedef std::deque<chat_message> chat_message_queue;

/***************************
 * CHAT CLIENT
 ***************************/
class chat_client
{
public:
  chat_client(boost::asio::io_service& io_service,
      tcp::resolver::iterator endpoint_iterator)
    : io_service_(io_service),
      socket_(io_service)
  {
    tcp::endpoint endpoint = *endpoint_iterator;
    socket_.async_connect(endpoint,
        boost::bind(&chat_client::handle_connect, this,
          boost::asio::placeholders::error, ++endpoint_iterator));
  }

  void write(const chat_message& msg)
  {
    io_service_.post(boost::bind(&chat_client::do_write, this, msg));
  }

  void close()
  {
    io_service_.post(boost::bind(&chat_client::do_close, this));
  }

private:

  void handle_connect(const boost::system::error_code& error,
      tcp::resolver::iterator endpoint_iterator)
  {
    if (!error)
    {
      boost::asio::async_read(socket_,
          boost::asio::buffer(read_msg_.data(), chat_message::header_length),
          boost::bind(&chat_client::handle_read_header, this,
            boost::asio::placeholders::error));
    }
    else if (endpoint_iterator != tcp::resolver::iterator())
    {
      socket_.close();
      tcp::endpoint endpoint = *endpoint_iterator;
      socket_.async_connect(endpoint,
          boost::bind(&chat_client::handle_connect, this,
            boost::asio::placeholders::error, ++endpoint_iterator));
    }
  }

  void handle_read_header(const boost::system::error_code& error)
  {
    if (!error && read_msg_.decode_header())
    {
      boost::asio::async_read(socket_,
          boost::asio::buffer(read_msg_.body(), read_msg_.body_length()),
          boost::bind(&chat_client::handle_read_body, this,
            boost::asio::placeholders::error));
    }
    else
    {
      do_close();
    }
  }

  void handle_read_body(const boost::system::error_code& error)
  {
    if (!error)
    {
      std::cout.write(read_msg_.body(), read_msg_.body_length());
      std::cout << "\n";
      boost::asio::async_read(socket_,
          boost::asio::buffer(read_msg_.data(), chat_message::header_length),
          boost::bind(&chat_client::handle_read_header, this,
            boost::asio::placeholders::error));
    }
    else
    {
      do_close();
    }
  }

  void do_write(chat_message msg)
  {
    bool write_in_progress = !write_msgs_.empty();
    write_msgs_.push_back(msg);
    if (!write_in_progress)
    {
      boost::asio::async_write(socket_,
          boost::asio::buffer(write_msgs_.front().data(),
            write_msgs_.front().length()),
          boost::bind(&chat_client::handle_write, this,
            boost::asio::placeholders::error));
    }
  }

  void handle_write(const boost::system::error_code& error)
  {
    if (!error)
    {
      write_msgs_.pop_front();
      if (!write_msgs_.empty())
      {
        boost::asio::async_write(socket_,
            boost::asio::buffer(write_msgs_.front().data(),
              write_msgs_.front().length()),
            boost::bind(&chat_client::handle_write, this,
              boost::asio::placeholders::error));
      }
    }
    else
    {
      do_close();
    }
  }

  void do_close()
  {
    socket_.close();
  }

private:
  boost::asio::io_service& io_service_;
  tcp::socket socket_;
  chat_message read_msg_;
  chat_message_queue write_msgs_;
};

/********************
 * MAIN
 ********************/
int main(int argc, char* argv[])
{
  try
  {
    if (argc != 3)
    {
      std::cerr << "Usage: chat_client <host> <port>\n";
      return 1;
    }

    boost::asio::io_service io_service;

    tcp::resolver resolver(io_service);
    tcp::resolver::query query(argv[1], argv[2]);
    tcp::resolver::iterator iterator = resolver.resolve(query);

    chat_client c(io_service, iterator);

    boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));

    char line[chat_message::max_body_length + 1];
    while (std::cin.getline(line, chat_message::max_body_length + 1))
    {
      using namespace std; // For strlen and memcpy.
      chat_message msg;
      msg.body_length(strlen(line));
      memcpy(msg.body(), line, msg.body_length());
      msg.encode_header();
      c.write(msg);
    }

    c.close();
    t.join();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}

<commit_msg>Example code slightly more readable.<commit_after>//
// chat_client.cpp
// ~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2008 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <cstdlib>
#include <deque>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include "chat_message.hpp"

using boost::asio::ip::tcp;

typedef std::deque<chat_message> chat_message_queue;

/***************************
 * CHAT CLIENT
 ***************************/
class chat_client
{
public:
  chat_client(boost::asio::io_service& io_service,
      tcp::resolver::iterator endpoint_iterator)
    : io_service_(io_service),
      socket(io_service)
  {

		tcp::endpoint endpoint = *endpoint_iterator;

		socket.async_connect(endpoint,
			boost::bind(&chat_client::handle_connect,
				this,
				 boost::asio::placeholders::error,
				++endpoint_iterator)
		);

  }

  void write(const chat_message& msg)
  {
    io_service_.post(boost::bind(&chat_client::do_write, this, msg));
  }

  void close()
  {
    io_service_.post(boost::bind(&chat_client::do_close, this));
  }

private:

  void handle_connect(const boost::system::error_code& error,
      tcp::resolver::iterator endpoint_iterator)
  {

	// If connected with no error:
    if (!error)
    {
			boost::asio::async_read(
				socket,

				boost::asio::buffer(read_msg_.data(),
					chat_message::header_length),

				boost::bind(
					&chat_client::handle_read_header,
					this,
		        	boost::asio::placeholders::error
				)
			);
    }

	// If error, but not at end of resolver:
    else if (endpoint_iterator != tcp::resolver::iterator())
    {
			socket.close();
			tcp::endpoint endpoint = *endpoint_iterator;

			socket.async_connect(
				endpoint,
				boost::bind(&chat_client::handle_connect,
					this,
					boost::asio::placeholders::error,
					++endpoint_iterator
				)
			);
    }

  }

  void handle_read_header(const boost::system::error_code& error)
  {
    if (!error && read_msg_.decode_header())
    {
			boost::asio::async_read(socket,
				boost::asio::buffer(read_msg_.body(),
					read_msg_.body_length()
				),
				boost::bind(&chat_client::handle_read_body,
					this,
					boost::asio::placeholders::error
				)
			);
    }
    else
    {
			do_close();				// WHY CLOSE??
    }
  }

  void handle_read_body(const boost::system::error_code& error)
  {
    if (!error)
    {
			std::cout.write(read_msg_.body(), read_msg_.body_length());
			std::cout << "\n";

			boost::asio::async_read(socket,
				boost::asio::buffer(read_msg_.data(),
					chat_message::header_length),

				boost::bind(&chat_client::handle_read_header,
					this,
					boost::asio::placeholders::error
				)
			);

    }
    else
    {
      do_close();
    }
  }

  void do_write(chat_message msg)
  {

		bool write_in_progress = !write_msgs_.empty();
		write_msgs_.push_back(msg);

		if (!write_in_progress)
		{

				boost::asio::async_write(socket,
					boost::asio::buffer(write_msgs_.front().data(),
						write_msgs_.front().length()
					),
					boost::bind(&chat_client::handle_write,
						this,
						boost::asio::placeholders::error
					)
				);
    }
  }

  void handle_write(const boost::system::error_code& error)
  {
    if (!error)
    {

		write_msgs_.pop_front();

		if (!write_msgs_.empty())
		{
				boost::asio::async_write(socket,
					boost::asio::buffer(write_msgs_.front().data(),
						write_msgs_.front().length()
					),
					boost::bind(&chat_client::handle_write,
						this,
						boost::asio::placeholders::error
					)
				);
      }
    }
    else
    {
      do_close();
    }
  }

  void do_close()
  {
    socket.close();
  }

private:
  boost::asio::io_service& io_service_;
  tcp::socket socket;
  chat_message read_msg_;
  chat_message_queue write_msgs_;
};

/********************
 * MAIN
 ********************/
int main(int argc, char* argv[])
{
  try
  {
    if (argc != 3)
    {
      std::cerr << "Usage: chat_client <host> <port>\n";
      return 1;
    }

    boost::asio::io_service io_service;

    tcp::resolver resolver(io_service);
    tcp::resolver::query query(argv[1], argv[2]);
    tcp::resolver::iterator iterator = resolver.resolve(query);

    chat_client c(io_service, iterator);

    boost::thread t(boost::bind(&boost::asio::io_service::run, &io_service));

    char line[chat_message::max_body_length + 1];
    while (std::cin.getline(line, chat_message::max_body_length + 1))
    {
      using namespace std; // For strlen and memcpy.
      chat_message msg;
      msg.body_length(strlen(line));
      memcpy(msg.body(), line, msg.body_length());
      msg.encode_header();
      c.write(msg);
    }

    c.close();
    t.join();
  }
  catch (std::exception& e)
  {
    std::cerr << "Exception: " << e.what() << "\n";
  }

  return 0;
}

<|endoftext|>