<commit_before>//#include <TCanvas.h>
//#include <TLegend.h>
//#include <TRandom3.h>
//#include "TH1.h"
//#include "TF1.h"
//#include "TMath.h"
#include <string>
#include <cstring>
#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

class hit
{
	double x;
	double y;

	public:

	hit(double _x, double _y): x(_x), y(_y) {}
};

class eeevent
{
	int num1;

	int num_trig;
	int num_acq;

	int secs;
	int nsecs;

	int clk1;
	int clk2;

	vector<hit> event1;
	vector<hit> event2;
	vector<hit> event3;

	double hv1;
	double hv2;
	double hv3;

	public:

	eeevent(int num1, int num_trig, int num_acq, int secs, int nsecs, int clk1, int clk2, double hv1, double hv2, double hv3):
		num1(num1), num_trig(num_trig), num_acq(num_acq), secs(secs), nsecs(nsecs),
		clk1(clk1), clk2(clk2), hv1(hv1), hv2(hv2), hv3(hv3) {}

	void gethit(double x, double y, int z) {
		hit newhit(x, y);
		switch (z) {
			case 149:
				this->event1.push_back(newhit);
				break;
			case 95:
				this->event2.push_back(newhit);
				break;
			case 49:
				this->event3.push_back(newhit);
				break;
			default:
				cout << "Unrecognized chamber" << endl;
		}
	}
};

int parse(string path)
{
	cout << "Path given: " << path << endl;

	ifstream file;
	file.open(path);
	const int linesize=65536;
	char* line = (char*)malloc(linesize*sizeof(char));  // get buffer for every line

	vector<eeevent> evector;               // vector of events
	double hv1, hv2, hv3;                  // variables for high voltage values

	while (!file.eof()) {
		file.getline(line, linesize);       // fill line

		char* piece = strtok (line," \t");  // get initial number
		if (piece==NULL) continue;          // the file is finished at this point, but better run the eof() check
		int num1 = atoi(piece);             // inital number
		if (num1 == 0) continue;            // line needs to start with a number, not characters (like the name line)

		piece = strtok (NULL, " \t");       // get descriptor
		string descriptor = piece;

		if (descriptor=="STATUS") {
			char* next=piece+7;              // hack to get after "STATUS"
			sscanf(next, "HV %lf %*f %lf %*f %lf %*f", &hv1, &hv2, &hv3);
			cout << "hv: " << hv1 << " - " << hv2 << " - " << hv3 << endl;
		}
		else if (descriptor=="EVENT") {

			piece = strtok (NULL, " \t");    // get num_trig
			int num_trig = atoi(piece);

			piece = strtok (NULL, " \t");    // get num_acq
			int num_acq = atoi(piece);

			piece = strtok (NULL, " \t");    // get seconds
			int secs = atoi(piece);

			piece = strtok (NULL, " \t");    // get nseconds
			int nsecs = atoi(piece);

			piece = strtok (NULL, " \t");    // get clk1
			int clk1 = atoi(piece);

			piece = strtok (NULL, " \t");    // get clk2
			int clk2 = atoi(piece);

			eeevent neweeevent(num1, num_trig, num_acq, secs, nsecs, clk1, clk2, hv1, hv2, hv3);

			piece = strtok (NULL, " \t");    // get events
			while (piece != NULL) {
				double x = atof(piece);
				piece = strtok (NULL, " \t");    // get more pieces

				double y = atof(piece);
				piece = strtok (NULL, " \t");    // get more pieces

				int z = atoi(piece);
				piece = strtok (NULL, " \t");    // get more pieces

				neweeevent.gethit(x, y, z);
			}

			evector.push_back(neweeevent);
		}
	}

	return 0;
}

int main(int, char** argv)
{
	parse(argv[1]);
	return 0;
}
<commit_msg>Completed parsing part<commit_after>//#include <TCanvas.h>
//#include <TLegend.h>
//#include <TRandom3.h>
//#include "TH1.h"
//#include "TF1.h"
//#include "TMath.h"
#include <string>
#include <cstring>
#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

class hit
{
	double x;
	double y;

	public:

	hit(double x, double y): x(x), y(y) {}
};

class eeevent
{
	int num1;

	int num_trig;
	int num_acq;

	int secs;
	int nsecs;

	int clk1;
	int clk2;

	vector<hit> events1;
	vector<hit> events2;
	vector<hit> events3;

	double hv1;
	double hv2;
	double hv3;

	public:

	eeevent(int num1, int num_trig, int num_acq, int secs, int nsecs, int clk1, int clk2, double hv1, double hv2, double hv3):
		num1(num1), num_trig(num_trig), num_acq(num_acq), secs(secs), nsecs(nsecs),
		clk1(clk1), clk2(clk2), hv1(hv1), hv2(hv2), hv3(hv3) {}

	void gethit(double x, double y, int z) {
		hit newhit(x, y);
		switch (z) {
			case 149:
				this->events1.push_back(newhit);
				break;
			case 95:
				this->events2.push_back(newhit);
				break;
			case 49:
				this->events3.push_back(newhit);
				break;
			default:
				cout << "Unrecognized chamber" << endl;
		}
	}
};

typedef vector<eeevent> eeevector;
typedef vector<hit> hitvector;

vector<eeevent> parse(string path)
{
	cout << "Path given: " << path << endl;

	ifstream file;
	file.open(path);
	const int linesize=65536;
	char* line = (char*)malloc(linesize*sizeof(char));  // get buffer for every line

	vector<eeevent> evector;               // vector for the events
	double hv1, hv2, hv3;                  // variables for high voltage values

	while (!file.eof()) {
		file.getline(line, linesize);       // fill line

		char* piece = strtok (line," \t");  // get initial number
		if (piece==NULL) continue;          // the file is finished at this point, but better run the eof() check
		int num1 = atoi(piece);             // inital number
		if (num1 == 0) continue;            // line needs to start with a number, not characters (like the name line)

		piece = strtok (NULL, " \t");       // get descriptor
		string descriptor = piece;

		if (descriptor=="STATUS") {
			char* next=piece+7;              // hack to get after "STATUS"
			sscanf(next, "HV %lf %*f %lf %*f %lf %*f", &hv1, &hv2, &hv3);
			//cout << "hv: " << hv1 << " - " << hv2 << " - " << hv3 << endl;
		}
		else if (descriptor=="EVENT") {

			piece = strtok (NULL, " \t");    // get num_trig
			int num_trig = atoi(piece);

			piece = strtok (NULL, " \t");    // get num_acq
			int num_acq = atoi(piece);

			piece = strtok (NULL, " \t");    // get seconds
			int secs = atoi(piece);

			piece = strtok (NULL, " \t");    // get nseconds
			int nsecs = atoi(piece);

			piece = strtok (NULL, " \t");    // get clk1
			int clk1 = atoi(piece);

			piece = strtok (NULL, " \t");    // get clk2
			int clk2 = atoi(piece);

			eeevent neweeevent(num1, num_trig, num_acq, secs, nsecs, clk1, clk2, hv1, hv2, hv3);

			piece = strtok (NULL, " \t");    // get events
			while (piece != NULL) {
				double x = atof(piece);
				piece = strtok (NULL, " \t");    // get more pieces

				if (piece!=NULL) {
					double y = atof(piece);
					piece = strtok (NULL, " \t");    // get more pieces

					int z = atoi(piece);
					piece = strtok (NULL, " \t");    // get more pieces

					neweeevent.gethit(x, y, z);
					//cout << x << " - " << y << " - " << z << endl;
				}
			}

			evector.push_back(neweeevent);
		}
	}
	cout << "Parsing complete: " << evector.size() << " events captured" << endl;

	return evector;
}

void cluster_size_study(eeevector evector)
{

}

int main(int, char** argv)
{
	eeevector evector;
	evector = parse(argv[1]);

	cluster_size_study(evector);

	//compute_eff(1, evector);

	return 0;
}

/* Code graveyard
*
*
*
	hitvector hvector;
	switch (nchamber) {
		case 1: hvector=evector.events1; break;
		case 2: hvector=evector.events2; break;
		case 3: hvector=evector.events3; break;
		default: cout << "Unexpected chamber number" << endl;
	}
*
*
*/
<|endoftext|>


<commit_before>#include "factory.h"
#include <chrono>
#include <thread>

void synopsis()
{
    std::cout << "save_frames"
              << "  [  "
              << std::endl << "                "
              << " help "
              << std::endl << "                "
              << " epiphan   xvid | h265   sdi | dvi "
              << std::endl << "                "
              << " file   </file/path>   xvid | h265 "
              << std::endl << "                "
              << " chess   xvid | h265   <width>   <height> "
              << std::endl << "            "
              << " ]"
              << std::endl;
}

enum TestMode { Epiphan, File, Chessboard };

enum TestMode test_mode = TestMode::Chessboard;
enum gg::Target codec = gg::Target::File_XviD;
std::string codec_string = "xvid", filetype = "avi";
/* following numbers purposefully odd,
 * to test robustness when odd frame
 * width and/or height provided, whereas
 * H265 requires even
 */
int width = 11, height = 7, square_size = 61;
float fps = 20;
int duration = 1; // min
int num_frames = duration * 60 * fps;
int i = 0;
VideoFrame_BGRA frame;
cv::Mat image(height * square_size, width * square_size, CV_8UC4);
cv::VideoCapture cap;
enum gg::Device port = gg::Device::DVI2PCIeDuo_DVI;
std::string port_string = "dvi";
int sleep_duration = 0;
IVideoSource * epiphan = NULL;

void init(int argc, char ** argv)
{
    std::vector<std::string> args;
    for (int i = 0; i < argc; i++)
        args.push_back(std::string(argv[i]));

    if (args[1]=="help")
    {
        synopsis(); exit(0);
    }

    if (args[1]=="epiphan")
    {
        test_mode = TestMode::Epiphan;

        if (argc < 4)
        {
            synopsis(); exit(-1);
        }

        codec_string = args[2];
        port_string = args[3];

        if (port_string == "sdi")
            port = gg::Device::DVI2PCIeDuo_SDI;
        else if (port_string == "dvi")
            port = gg::Device::DVI2PCIeDuo_DVI;
        else
        {
            std::cerr << "Port " << port_string << " not recognised" << std::endl;
            synopsis();
            exit(-1);
        }

        epiphan = gg::Factory::connect(port);
        epiphan->set_sub_frame(600, 185, 678, 688); // optimal for Storz 27020 AA straight

        sleep_duration = (int)(1000/fps); // ms
    }

    else if (args[1]=="file")
    {
        test_mode = TestMode::File;

        if (argc < 4)
        {
            synopsis(); exit(-1);
        }

        cap.open(args[2]);
        if (not cap.isOpened())
        {
            std::cerr << "File " << args[2]
                      << " could not be opened"
                      << std::endl;
            exit(-1);
        }

        codec_string = args[3];
        num_frames = cap.get(CV_CAP_PROP_FRAME_COUNT);
        fps = cap.get(CV_CAP_PROP_FPS);
        duration = (num_frames / fps) / 60;
    }

    else if (args[1]=="chess")
    {
        test_mode = TestMode::Chessboard;

        if (argc < 5)
        {
            synopsis(); exit(-1);
        }

        codec_string = args[2];
        width = atoi(argv[3]); height = atoi(argv[4]);
    }

    else
    {
        synopsis(); exit(-1);
    }

    // health checks
    if (codec_string == "xvid")
        codec = gg::Target::File_XviD;
    else if (codec_string == "h265")
    {
        codec = gg::Target::File_H265;
        filetype = "mp4";
    }
    else
    {
        std::cerr << "Codec " << codec_string << " not recognised" << std::endl;
        synopsis();
        exit(-1);
    }
}

std::string which_file()
{
    std::string filename;
    filename.append(std::to_string(duration))
            .append("min_")
            .append(codec_string);
    switch(test_mode)
    {
    case TestMode::Epiphan:
        filename.append("_epiphan."); break;
    case TestMode::File:
        filename.append("_from_file."); break;
    case TestMode::Chessboard:
        filename.append("_colour_chessboard."); break;
    default:
        std::cerr << "Test mode not set" << std::endl;
        exit(-1);
    }
    filename.append(filetype);
    return filename;
}

void get_frame(VideoFrame_BGRA & frame)
{
    // Chessboard params
    float elapsed, remaining;
    int red, green, blue, alpha, min_intensity;
    switch(test_mode)
    {
    case TestMode::Chessboard:
        elapsed = (((float) i) / num_frames);
        remaining = 1 - elapsed;
        red = 0, green = 0, blue = 0, alpha = 0;
        min_intensity = 50; // don't want black
        for (int row = 0; row < height; row++)
        {
            green = min_intensity + elapsed * (((float) row) / height) * (255 - min_intensity);
            for (int col = 0; col < width; col++)
            {
                red = min_intensity + elapsed * (((float) col) / width) * (255 - min_intensity);
                blue = min_intensity +
                       remaining *
                            sqrt( ((float)(row*row + col*col))
                                  /
                                  (height*height+width*width) ) * (255 - min_intensity);
                cv::Mat square(square_size, square_size, CV_8UC4, cv::Scalar(blue, green, red, alpha));
                square.copyTo(image(cv::Rect(col * square_size , row * square_size,
                                             square.cols, square.rows)));
            }
        }
        frame.init_from_opencv_mat(image);
        break;
    case TestMode::Epiphan:
        epiphan->get_frame(frame);
        break;
    case TestMode::File:
        cap >> image;
        cv::cvtColor(image, image, CV_BGR2BGRA);
        frame.init_from_opencv_mat(image);
        break;
    default:
        std::cerr << "Test mode not set" << std::endl;
        exit(-1);
    }
}

auto start = std::chrono::steady_clock::now();
float elapsed;
void time_left()
{
    if (i % 5 == 0)
        std::cout << "Saving frame " << i+1 << " of " << num_frames;

    int left;

    switch(test_mode)
    {
    case TestMode::Chessboard:
        // nop
        break;
    case TestMode::File:
    case TestMode::Epiphan:
        elapsed = std::chrono::duration_cast<std::chrono::seconds>(
                    std::chrono::steady_clock::now() - start).count();
        left = ((float) num_frames - i + 1) * elapsed / (i+1);
        std::cout << " (" << left << " sec. left)";
        break;
    default:
        std::cerr << "Test mode not set" << std::endl;
        exit(-1);
    }

    std::cout << "\r";
}

void wait_for_next()
{
    switch(test_mode)
    {
    case TestMode::File:
    case TestMode::Chessboard:
        // nop
        break;
    case TestMode::Epiphan:
        std::this_thread::sleep_for(std::chrono::milliseconds(sleep_duration));
        break;
    default:
        std::cerr << "Test mode not set" << std::endl;
        exit(-1);
    }
}

void finalise()
{
    switch(test_mode)
    {
    case TestMode::File:
    case TestMode::Chessboard:
        // nop
        break;
    case TestMode::Epiphan:
        gg::Factory::disconnect(port);
        break;
    default:
        std::cerr << "Test mode not set" << std::endl;
        exit(-1);
    }
}

int main(int argc, char ** argv)
{
    try
    {
        init(argc, argv);

        gg::IVideoTarget * file = gg::Factory::create(codec);
        std::string filename = which_file();
        file->init(filename, fps);
        std::cout << "Saving to file " << filename << std::endl;

        start = std::chrono::steady_clock::now();
        for (i = 0; i < num_frames; i++)
        {
            time_left();
            get_frame(frame);
            file->append(frame);
            wait_for_next();
        }

        file->finalise();

        finalise();
    }
    catch (gg::VideoTargetError & e)
    {
        std::cerr << e.what() << std::endl;
        return -1;
    }
    catch (gg::DeviceOffline & e)
    {
        std::cerr << e.what() << std::endl;
        return -1;
    }

    return 0;
}
<commit_msg>Issue #21: 60 fps as default in one-for-all test<commit_after>#include "factory.h"
#include <chrono>
#include <thread>

void synopsis()
{
    std::cout << "save_frames"
              << "  [  "
              << std::endl << "                "
              << " help "
              << std::endl << "                "
              << " epiphan   xvid | h265   sdi | dvi "
              << std::endl << "                "
              << " file   </file/path>   xvid | h265 "
              << std::endl << "                "
              << " chess   xvid | h265   <width>   <height> "
              << std::endl << "            "
              << " ]"
              << std::endl;
}

enum TestMode { Epiphan, File, Chessboard };

enum TestMode test_mode = TestMode::Chessboard;
enum gg::Target codec = gg::Target::File_XviD;
std::string codec_string = "xvid", filetype = "avi";
/* following numbers purposefully odd,
 * to test robustness when odd frame
 * width and/or height provided, whereas
 * H265 requires even
 */
int width = 11, height = 7, square_size = 61;
float fps = 60;
int duration = 1; // min
int num_frames = duration * 60 * fps;
int i = 0;
VideoFrame_BGRA frame;
cv::Mat image(height * square_size, width * square_size, CV_8UC4);
cv::VideoCapture cap;
enum gg::Device port = gg::Device::DVI2PCIeDuo_DVI;
std::string port_string = "dvi";
int sleep_duration = 0;
IVideoSource * epiphan = NULL;

void init(int argc, char ** argv)
{
    std::vector<std::string> args;
    for (int i = 0; i < argc; i++)
        args.push_back(std::string(argv[i]));

    if (args[1]=="help")
    {
        synopsis(); exit(0);
    }

    if (args[1]=="epiphan")
    {
        test_mode = TestMode::Epiphan;

        if (argc < 4)
        {
            synopsis(); exit(-1);
        }

        codec_string = args[2];
        port_string = args[3];

        if (port_string == "sdi")
            port = gg::Device::DVI2PCIeDuo_SDI;
        else if (port_string == "dvi")
            port = gg::Device::DVI2PCIeDuo_DVI;
        else
        {
            std::cerr << "Port " << port_string << " not recognised" << std::endl;
            synopsis();
            exit(-1);
        }

        epiphan = gg::Factory::connect(port);
        epiphan->set_sub_frame(600, 185, 678, 688); // optimal for Storz 27020 AA straight

        sleep_duration = (int)(1000/fps); // ms
    }

    else if (args[1]=="file")
    {
        test_mode = TestMode::File;

        if (argc < 4)
        {
            synopsis(); exit(-1);
        }

        cap.open(args[2]);
        if (not cap.isOpened())
        {
            std::cerr << "File " << args[2]
                      << " could not be opened"
                      << std::endl;
            exit(-1);
        }

        codec_string = args[3];
        num_frames = cap.get(CV_CAP_PROP_FRAME_COUNT);
        fps = cap.get(CV_CAP_PROP_FPS);
        duration = (num_frames / fps) / 60;
    }

    else if (args[1]=="chess")
    {
        test_mode = TestMode::Chessboard;

        if (argc < 5)
        {
            synopsis(); exit(-1);
        }

        codec_string = args[2];
        width = atoi(argv[3]); height = atoi(argv[4]);
    }

    else
    {
        synopsis(); exit(-1);
    }

    // health checks
    if (codec_string == "xvid")
        codec = gg::Target::File_XviD;
    else if (codec_string == "h265")
    {
        codec = gg::Target::File_H265;
        filetype = "mp4";
    }
    else
    {
        std::cerr << "Codec " << codec_string << " not recognised" << std::endl;
        synopsis();
        exit(-1);
    }
}

std::string which_file()
{
    std::string filename;
    filename.append(std::to_string(duration))
            .append("min_")
            .append(codec_string);
    switch(test_mode)
    {
    case TestMode::Epiphan:
        filename.append("_epiphan."); break;
    case TestMode::File:
        filename.append("_from_file."); break;
    case TestMode::Chessboard:
        filename.append("_colour_chessboard."); break;
    default:
        std::cerr << "Test mode not set" << std::endl;
        exit(-1);
    }
    filename.append(filetype);
    return filename;
}

void get_frame(VideoFrame_BGRA & frame)
{
    // Chessboard params
    float elapsed, remaining;
    int red, green, blue, alpha, min_intensity;
    switch(test_mode)
    {
    case TestMode::Chessboard:
        elapsed = (((float) i) / num_frames);
        remaining = 1 - elapsed;
        red = 0, green = 0, blue = 0, alpha = 0;
        min_intensity = 50; // don't want black
        for (int row = 0; row < height; row++)
        {
            green = min_intensity + elapsed * (((float) row) / height) * (255 - min_intensity);
            for (int col = 0; col < width; col++)
            {
                red = min_intensity + elapsed * (((float) col) / width) * (255 - min_intensity);
                blue = min_intensity +
                       remaining *
                            sqrt( ((float)(row*row + col*col))
                                  /
                                  (height*height+width*width) ) * (255 - min_intensity);
                cv::Mat square(square_size, square_size, CV_8UC4, cv::Scalar(blue, green, red, alpha));
                square.copyTo(image(cv::Rect(col * square_size , row * square_size,
                                             square.cols, square.rows)));
            }
        }
        frame.init_from_opencv_mat(image);
        break;
    case TestMode::Epiphan:
        epiphan->get_frame(frame);
        break;
    case TestMode::File:
        cap >> image;
        cv::cvtColor(image, image, CV_BGR2BGRA);
        frame.init_from_opencv_mat(image);
        break;
    default:
        std::cerr << "Test mode not set" << std::endl;
        exit(-1);
    }
}

auto start = std::chrono::steady_clock::now();
float elapsed;
void time_left()
{
    if (i % 5 == 0)
        std::cout << "Saving frame " << i+1 << " of " << num_frames;

    int left;

    switch(test_mode)
    {
    case TestMode::Chessboard:
        // nop
        break;
    case TestMode::File:
    case TestMode::Epiphan:
        elapsed = std::chrono::duration_cast<std::chrono::seconds>(
                    std::chrono::steady_clock::now() - start).count();
        left = ((float) num_frames - i + 1) * elapsed / (i+1);
        std::cout << " (" << left << " sec. left)";
        break;
    default:
        std::cerr << "Test mode not set" << std::endl;
        exit(-1);
    }

    std::cout << "\r";
}

void wait_for_next()
{
    switch(test_mode)
    {
    case TestMode::File:
    case TestMode::Chessboard:
        // nop
        break;
    case TestMode::Epiphan:
        std::this_thread::sleep_for(std::chrono::milliseconds(sleep_duration));
        break;
    default:
        std::cerr << "Test mode not set" << std::endl;
        exit(-1);
    }
}

void finalise()
{
    switch(test_mode)
    {
    case TestMode::File:
    case TestMode::Chessboard:
        // nop
        break;
    case TestMode::Epiphan:
        gg::Factory::disconnect(port);
        break;
    default:
        std::cerr << "Test mode not set" << std::endl;
        exit(-1);
    }
}

int main(int argc, char ** argv)
{
    try
    {
        init(argc, argv);

        gg::IVideoTarget * file = gg::Factory::create(codec);
        std::string filename = which_file();
        file->init(filename, fps);
        std::cout << "Saving to file " << filename << std::endl;

        start = std::chrono::steady_clock::now();
        for (i = 0; i < num_frames; i++)
        {
            time_left();
            get_frame(frame);
            file->append(frame);
            wait_for_next();
        }

        file->finalise();

        finalise();
    }
    catch (gg::VideoTargetError & e)
    {
        std::cerr << e.what() << std::endl;
        return -1;
    }
    catch (gg::DeviceOffline & e)
    {
        std::cerr << e.what() << std::endl;
        return -1;
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>

#include <zxtk/modules/memory.cpp>

#include <iostream>

using namespace std;

struct Memory : ::testing::Test
{
    zxtk::memory::Memory m;
}

TEST(Memory, DefaultConstructor)
{
    cout << "Created memory";
}
<commit_msg>Fixed tiepo<commit_after>#include <gtest/gtest.h>

#include <zxtk/modules/memory.hpp>

#include <iostream>

using namespace std;

struct Memory : ::testing::Test
{
    zxtk::memory::Memory m;
}

TEST(Memory, DefaultConstructor)
{
    cout << "Created memory";
}
<|endoftext|>


<commit_before>/*
   +----------------------------------------------------------------------+
   | HipHop for PHP                                                       |
   +----------------------------------------------------------------------+
   | Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com)     |
   +----------------------------------------------------------------------+
   | This source file is subject to version 3.01 of the PHP license,      |
   | that is bundled with this package in the file LICENSE, and is        |
   | available through the world-wide-web at the following url:           |
   | http://www.php.net/license/3_01.txt                                  |
   | If you did not receive a copy of the PHP license and are unable to   |
   | obtain it through the world-wide-web, please send a note to          |
   | license@php.net so we can mail you a copy immediately.               |
   +----------------------------------------------------------------------+
*/

#include "hphp/runtime/base/base-includes.h"
#include "msgpack-variant.h"

#define MSGPACK_HHVM_VERSION "0.0.1"

namespace HPHP {

static String HHVM_FUNCTION(msgpack_pack, const Variant &var) {
  msgpack::sbuffer sbuf;
  msgpack::pack(sbuf, var);

  return String(sbuf.data(), sbuf.size(), CopyString);
}

static Variant HHVM_FUNCTION(msgpack_unpack, const String &pack) {
  msgpack::zone zone;
  msgpack::object obj;

  try {
    msgpack::unpack(pack.c_str(), pack.size(), NULL, &zone, &obj);
  } catch (msgpack::type_error&) {
    raise_warning("unpack error");
    return false;
  }

  Variant v;
  obj.convert(&v);

  return v;
}

static class MsgpackExtension : public Extension {
 public:
  MsgpackExtension() : Extension("msgpack", MSGPACK_HHVM_VERSION) {}
  virtual void moduleInit() {
    HHVM_FE(msgpack_pack);
    HHVM_FE(msgpack_unpack);

    HHVM_FALIAS(msgpack_serialize, msgpack_pack);
    HHVM_FALIAS(msgpack_unserialize, msgpack_unpack);

    loadSystemlib();
  }
} s_msgpack_extension;

HHVM_GET_MODULE(msgpack);

} // namespace HPHP
<commit_msg>Fixed compability for HHVM 2.*<commit_after>/*
   +----------------------------------------------------------------------+
   | HipHop for PHP                                                       |
   +----------------------------------------------------------------------+
   | Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com)     |
   +----------------------------------------------------------------------+
   | This source file is subject to version 3.01 of the PHP license,      |
   | that is bundled with this package in the file LICENSE, and is        |
   | available through the world-wide-web at the following url:           |
   | http://www.php.net/license/3_01.txt                                  |
   | If you did not receive a copy of the PHP license and are unable to   |
   | obtain it through the world-wide-web, please send a note to          |
   | license@php.net so we can mail you a copy immediately.               |
   +----------------------------------------------------------------------+
*/

#include "hphp/runtime/base/base-includes.h"
#include "msgpack-variant.h"

#define MSGPACK_HHVM_VERSION "0.0.1"

namespace HPHP {

static String HHVM_FUNCTION(msgpack_pack, const Variant &var) {
  msgpack::sbuffer sbuf;
  msgpack::pack(sbuf, var);

  return String(sbuf.data(), sbuf.size(), CopyString);
}

static Variant HHVM_FUNCTION(msgpack_unpack, const String &pack) {
  msgpack::zone zone;
  msgpack::object obj;

  try {
    msgpack::unpack(pack.c_str(), pack.size(), NULL, &zone, &obj);
  } catch (msgpack::type_error&) {
    raise_warning("unpack error");
    return false;
  }

  Variant v;
  obj.convert(&v);

  return v;
}

#ifndef HHVM_FALIAS
#define HHVM_FALIAS(fn, falias) HHVM_NAMED_FE(fn, HHVM_FN(falias))
#endif

static class MsgpackExtension : public Extension {
 public:
  MsgpackExtension() : Extension("msgpack", MSGPACK_HHVM_VERSION) {}
  virtual void moduleInit() {
    HHVM_FE(msgpack_pack);
    HHVM_FE(msgpack_unpack);

    HHVM_FALIAS(msgpack_serialize, msgpack_pack);
    HHVM_FALIAS(msgpack_unserialize, msgpack_unpack);

    loadSystemlib();
  }
} s_msgpack_extension;

HHVM_GET_MODULE(msgpack);

} // namespace HPHP
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------
/// \file   enum.hpp
/// \author Serge Aleynikov
//----------------------------------------------------------------------------
/// \brief This file defines enum stringification declaration macro.
//----------------------------------------------------------------------------
// Copyright (c) 2015 Serge Aleynikov <saleyn@gmail.com>
// Created: 2015-04-11
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****

This file is part of the utxx open-source project.

Copyright (c) 2015 Serge Aleynikov <saleyn@gmail.com>

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

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

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

***** END LICENSE BLOCK *****
*/
#pragma once

#include <boost/preprocessor/variadic/to_seq.hpp>
#include <boost/preprocessor/variadic/size.hpp>
#include <boost/preprocessor/seq/enum.hpp>
#include <boost/preprocessor/seq/size.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/seq/transform.hpp>
#include <boost/preprocessor/seq/variadic_seq_to_seq.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/preprocessor/facilities/empty.hpp>
#include <boost/preprocessor/comparison/greater.hpp>
#include <boost/preprocessor/control/if.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/preprocessor/tuple/size.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <utxx/string.hpp>
#include <cassert>
#include <map>

#ifdef UTXX_ENUM_SUPPORT_SERIALIZATION
#include <boost/serialization/access.hpp>
#define UTXX__ENUM_FRIEND_SERIALIZATION__ \
    friend class boost::serialization::access
#endif

// The difference between enum.hpp and enumx.hpp is that UTXX_ENUMX
// allows to assign specific values to the enumerated constants.
//
// Note: Make sure that UndefValue is distinct from other values in this enum!
//
// Enum declaration:
//  #include <utxx/enumx.hpp>
//
//  UTXX_ENUMX(MyEnumT,
//               char,          // This is enum storage type
//               ' '            // This is an "UNDEFINED" value
//               (Apple, 'x')
//               (Pear,  'y')
//               (Grape)        // Grape will be equal to 'y'+1
//            );
//
// Sample usage:
//  MyEnumT val = MyEnumT::from_string("Pear");
//  std::cout << "Value: " << to_string(val) << std::endl;
//  std::cout << "Value: " << val            << std::endl;
//
#define UTXX_ENUMX(ENUM, TYPE, UndefValue, ...)                              \
    struct ENUM {                                                            \
        enum type : TYPE {                                                   \
            UNDEFINED = (UndefValue),                                        \
            BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(                        \
                UTXX_INTERNAL_ENUM_VAL, _,                                   \
                BOOST_PP_VARIADIC_SEQ_TO_SEQ(__VA_ARGS__)))                  \
        };                                                                   \
                                                                             \
        explicit  ENUM(long v) : m_val(type(v))   {}                         \
        constexpr ENUM()       : m_val(UNDEFINED) {}                         \
        constexpr ENUM(type v) : m_val(v) {}                                 \
                                                                             \
        ENUM(ENUM&&)                 = default;                              \
        ENUM(ENUM const&)            = default;                              \
                                                                             \
        ENUM& operator=(ENUM const&) = default;                              \
        ENUM& operator=(ENUM&&)      = default;                              \
                                                                             \
        constexpr operator type()      const { return m_val; }               \
        constexpr bool     empty()     const { return m_val == UNDEFINED; }  \
        const std::string& to_string() const {                               \
            auto it = names().find(m_val);                                   \
            return (it == names().end() ? null_pair() : *it).second;         \
        }                                                                    \
                                                                             \
        static const std::string&                                            \
                           to_string(type a){ return ENUM(a).to_string();  } \
        const char*        c_str()     const { return to_string().c_str(); } \
        static const char* c_str(type a)    { return to_string(a).c_str(); } \
                                                                             \
        static ENUM from_string(const char* a, bool a_nocase=false){         \
            auto f = a_nocase ? &strcasecmp : &strcmp;                       \
            for (auto& t : names())                                          \
                if (f(t.second.c_str(), a) == 0)                             \
                    return t.first;                                          \
            return UNDEFINED;                                                \
        }                                                                    \
                                                                             \
        static ENUM from_string(const std::string& a, bool a_nocase=false) { \
            return from_string(a.c_str(), a_nocase);                         \
        }                                                                    \
                                                                             \
        inline friend std::ostream& operator<< (std::ostream& out, ENUM a) { \
            return out << ENUM::to_string(a);                                \
        }                                                                    \
                                                                             \
        static constexpr size_t size()  { return s_size-1; }                 \
                                                                             \
        template <typename Visitor>                                          \
        static void for_each(const Visitor& a_fun) {                         \
            for (auto it = ++names().begin(), e = names().end(); it!=e; ++it)\
                if (!a_fun(it->first, it->second))                           \
                    break;                                                   \
        }                                                                    \
                                                                             \
    private:                                                                 \
        static const std::pair<const type, std::string>& null_pair() {       \
            static const std::pair<const type, std::string> s_val =          \
                std::make_pair(UNDEFINED, "UNDEFINED");                      \
            return s_val;                                                    \
        }                                                                    \
        static const size_t s_size =                                         \
            1+BOOST_PP_SEQ_SIZE(BOOST_PP_VARIADIC_SEQ_TO_SEQ(__VA_ARGS__));  \
        static const std::map<type, std::string>& names() {                  \
            static const std::map<type, std::string> s_names{                \
                null_pair(),                                                 \
                BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(                    \
                    UTXX_INTERNAL_ENUM_PAIR, _,                              \
                    BOOST_PP_VARIADIC_SEQ_TO_SEQ(__VA_ARGS__)                \
                ))                                                           \
            };                                                               \
            return s_names;                                                  \
        }                                                                    \
                                                                             \
        UTXX__ENUM_FRIEND_SERIALIZATION__;                                   \
                                                                             \
        type m_val;                                                          \
    }

// DEPRECATED!!! Use UTXX_ENUMX!
//
// Same as UTXX_ENUMX except that the enum is untyped.
//
// The difference between enum.hpp and enumx.hpp is that UTXX_DEFINE_ENUMX
// allows to assign specific values to the enumerated constants.
//
// Enum declaration:
//  #include <utxx/enumx.hpp>
//
//  UTXX_DEFINE_ENUMX(MyEnumT,  ' '  /* This is an "UNDEFINED" value */,
//                      (Apple, 'x')
//                      (Pear,  'y')
//                      (Grape)      /* Grape will be equal to 'y'+1 */
//                   );
//
// Sample usage:
//  MyEnumT val = MyEnumT::from_string("Pear");
//  std::cout << "Value: " << to_string(val) << std::endl;
//  std::cout << "Value: " << val            << std::endl;
//
#define UTXX_DEFINE_ENUMX(ENUM, UndefValue, ...)                             \
    struct [[deprecated]] ENUM {                                             \
        enum etype {                                                         \
            UNDEFINED = (UndefValue),                                        \
            BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(                        \
                UTXX_INTERNAL_ENUM_VAL, _,                                   \
                BOOST_PP_VARIADIC_SEQ_TO_SEQ(__VA_ARGS__)))                  \
        };                                                                   \
                                                                             \
    private:                                                                 \
        static const std::pair<const etype, std::string>& null_pair() {      \
            static const std::pair<const etype, std::string> s_val =         \
                std::make_pair(UNDEFINED, "UNDEFINED");                      \
            return s_val;                                                    \
        }                                                                    \
        static const size_t s_size =                                         \
            1+BOOST_PP_SEQ_SIZE(BOOST_PP_VARIADIC_SEQ_TO_SEQ(__VA_ARGS__));  \
        static const std::map<etype, std::string>& names() {                 \
            static const std::map<etype, std::string> s_names{               \
                null_pair(),                                                 \
                BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(                    \
                    UTXX_INTERNAL_ENUM_PAIR, _,                              \
                    BOOST_PP_VARIADIC_SEQ_TO_SEQ(__VA_ARGS__)                \
                ))                                                           \
            };                                                               \
            return s_names;                                                  \
        }                                                                    \
                                                                             \
        UTXX__ENUM_FRIEND_SERIALIZATION__;                                   \
                                                                             \
        etype m_val;                                                         \
                                                                             \
    public:                                                                  \
        explicit  ENUM(long v)  : m_val(etype(v))  {}                        \
        constexpr ENUM()        : m_val(UNDEFINED) {}                        \
        constexpr ENUM(etype v) : m_val(v) {}                                \
                                                                             \
        ENUM(ENUM&&)                 = default;                              \
        ENUM(ENUM const&)            = default;                              \
                                                                             \
        ENUM& operator=(ENUM const&) = default;                              \
        ENUM& operator=(ENUM&&)      = default;                              \
                                                                             \
        constexpr operator etype()     const { return m_val; }               \
        constexpr bool     empty()     const { return m_val == UNDEFINED; }  \
        const std::string& to_string() const {                               \
            auto it = names().find(m_val);                                   \
            return (it == names().end() ? null_pair() : *it).second;         \
        }                                                                    \
                                                                             \
        static const std::string&                                            \
                           to_string(etype a){ return ENUM(a).to_string();  }\
        const char*        c_str()     const { return to_string().c_str();  }\
        static const char* c_str(etype a)    { return to_string(a).c_str(); }\
                                                                             \
        static ENUM from_string(const char* a, bool a_nocase=false){         \
            auto f = a_nocase ? &strcasecmp : &strcmp;                       \
            for (auto& t : names())                                          \
                if (f(t.second.c_str(), a) == 0)                             \
                    return t.first;                                          \
            return UNDEFINED;                                                \
        }                                                                    \
                                                                             \
        static ENUM from_string(const std::string& a, bool a_nocase=false) { \
            return from_string(a.c_str(), a_nocase);                         \
        }                                                                    \
                                                                             \
        inline friend std::ostream& operator<< (std::ostream& out, ENUM a) { \
            return out << ENUM::to_string(a);                                \
        }                                                                    \
                                                                             \
        static constexpr size_t size()  { return s_size-1; }                 \
                                                                             \
        template <typename Visitor>                                          \
        static void for_each(const Visitor& a_fun) {                         \
            for (auto it = ++names().begin(), e = names().end(); it!=e; ++it)\
                if (!a_fun(it->first))                                       \
                    break;                                                   \
        }                                                                    \
    }

// Internal macro for supporting BOOST_PP_SEQ_TRANSFORM
#define UTXX_INTERNAL_ENUM_VAL(x, _, val)                                    \
    BOOST_PP_TUPLE_ELEM(0, val)                                              \
    BOOST_PP_IF(                                                             \
        BOOST_PP_GREATER(BOOST_PP_TUPLE_SIZE(val), 1),                       \
        = BOOST_PP_TUPLE_ELEM(1, val),                                       \
        BOOST_PP_EMPTY())
#define UTXX_INTERNAL_ENUM_PAIR(x, _, val)                                   \
    {std::make_pair(BOOST_PP_TUPLE_ELEM(0, val),                             \
                    BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(0, val)))}
<commit_msg>Formatting change<commit_after>//----------------------------------------------------------------------------
/// \file   enum.hpp
/// \author Serge Aleynikov
//----------------------------------------------------------------------------
/// \brief This file defines enum stringification declaration macro.
//----------------------------------------------------------------------------
// Copyright (c) 2015 Serge Aleynikov <saleyn@gmail.com>
// Created: 2015-04-11
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****

This file is part of the utxx open-source project.

Copyright (c) 2015 Serge Aleynikov <saleyn@gmail.com>

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

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

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

***** END LICENSE BLOCK *****
*/
#pragma once

#include <boost/preprocessor/variadic/to_seq.hpp>
#include <boost/preprocessor/variadic/size.hpp>
#include <boost/preprocessor/seq/enum.hpp>
#include <boost/preprocessor/seq/size.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/seq/transform.hpp>
#include <boost/preprocessor/seq/variadic_seq_to_seq.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/preprocessor/facilities/empty.hpp>
#include <boost/preprocessor/comparison/greater.hpp>
#include <boost/preprocessor/control/if.hpp>
#include <boost/preprocessor/tuple/elem.hpp>
#include <boost/preprocessor/tuple/size.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <utxx/string.hpp>
#include <cassert>
#include <map>

#ifdef UTXX_ENUM_SUPPORT_SERIALIZATION
#include <boost/serialization/access.hpp>
#define UTXX__ENUM_FRIEND_SERIALIZATION__ \
    friend class boost::serialization::access
#endif

// The difference between enum.hpp and enumx.hpp is that UTXX_ENUMX
// allows to assign specific values to the enumerated constants.
//
// Note: Make sure that UndefValue is distinct from other values in this enum!
//
// Enum declaration:
//  #include <utxx/enumx.hpp>
//
//  UTXX_ENUMX(MyEnumT,
//               char,          // This is enum storage type
//               ' '            // This is an "UNDEFINED" value
//               (Apple, 'x')
//               (Pear,  'y')
//               (Grape)        // Grape will be equal to 'y'+1
//            );
//
// Sample usage:
//  MyEnumT val = MyEnumT::from_string("Pear");
//  std::cout << "Value: " << to_string(val) << std::endl;
//  std::cout << "Value: " << val            << std::endl;
//
#define UTXX_ENUMX(ENUM, TYPE, UndefValue, ...)                              \
    struct ENUM {                                                            \
        enum type : TYPE {                                                   \
            UNDEFINED = (UndefValue),                                        \
            BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(                        \
                UTXX_INTERNAL_ENUM_VAL, _,                                   \
                BOOST_PP_VARIADIC_SEQ_TO_SEQ(__VA_ARGS__)))                  \
        };                                                                   \
                                                                             \
        explicit  ENUM(long v) : m_val(type(v))   {}                         \
        constexpr ENUM()       : m_val(UNDEFINED) {}                         \
        constexpr ENUM(type v) : m_val(v) {}                                 \
                                                                             \
        ENUM(ENUM&&)                 = default;                              \
        ENUM(ENUM const&)            = default;                              \
                                                                             \
        ENUM& operator=(ENUM const&) = default;                              \
        ENUM& operator=(ENUM&&)      = default;                              \
                                                                             \
        constexpr operator type()      const { return m_val; }               \
        constexpr bool     empty()     const { return m_val == UNDEFINED; }  \
        const std::string& to_string() const {                               \
            auto it = names().find(m_val);                                   \
            return (it == names().end() ? null_pair() : *it).second;         \
        }                                                                    \
                                                                             \
        static const std::string&                                            \
                           to_string(type a){ return ENUM(a).to_string();  } \
        const char*        c_str()    const { return to_string().c_str();  } \
        static const char* c_str(type a)    { return to_string(a).c_str(); } \
                                                                             \
        static ENUM from_string(const char* a, bool a_nocase=false){         \
            auto f = a_nocase ? &strcasecmp : &strcmp;                       \
            for (auto& t : names())                                          \
                if (f(t.second.c_str(), a) == 0)                             \
                    return t.first;                                          \
            return UNDEFINED;                                                \
        }                                                                    \
                                                                             \
        static ENUM from_string(const std::string& a, bool a_nocase=false) { \
            return from_string(a.c_str(), a_nocase);                         \
        }                                                                    \
                                                                             \
        inline friend std::ostream& operator<< (std::ostream& out, ENUM a) { \
            return out << ENUM::to_string(a);                                \
        }                                                                    \
                                                                             \
        static constexpr size_t size()  { return s_size-1; }                 \
                                                                             \
        template <typename Visitor>                                          \
        static void for_each(const Visitor& a_fun) {                         \
            for (auto it = ++names().begin(), e = names().end(); it!=e; ++it)\
                if (!a_fun(it->first, it->second))                           \
                    break;                                                   \
        }                                                                    \
                                                                             \
    private:                                                                 \
        static const std::pair<const type, std::string>& null_pair() {       \
            static const std::pair<const type, std::string> s_val =          \
                std::make_pair(UNDEFINED, "UNDEFINED");                      \
            return s_val;                                                    \
        }                                                                    \
        static const size_t s_size =                                         \
            1+BOOST_PP_SEQ_SIZE(BOOST_PP_VARIADIC_SEQ_TO_SEQ(__VA_ARGS__));  \
        static const std::map<type, std::string>& names() {                  \
            static const std::map<type, std::string> s_names{                \
                null_pair(),                                                 \
                BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(                    \
                    UTXX_INTERNAL_ENUM_PAIR, _,                              \
                    BOOST_PP_VARIADIC_SEQ_TO_SEQ(__VA_ARGS__)                \
                ))                                                           \
            };                                                               \
            return s_names;                                                  \
        }                                                                    \
                                                                             \
        UTXX__ENUM_FRIEND_SERIALIZATION__;                                   \
                                                                             \
        type m_val;                                                          \
    }

// DEPRECATED!!! Use UTXX_ENUMX!
//
// Same as UTXX_ENUMX except that the enum is untyped.
//
// The difference between enum.hpp and enumx.hpp is that UTXX_DEFINE_ENUMX
// allows to assign specific values to the enumerated constants.
//
// Enum declaration:
//  #include <utxx/enumx.hpp>
//
//  UTXX_DEFINE_ENUMX(MyEnumT,  ' '  /* This is an "UNDEFINED" value */,
//                      (Apple, 'x')
//                      (Pear,  'y')
//                      (Grape)      /* Grape will be equal to 'y'+1 */
//                   );
//
// Sample usage:
//  MyEnumT val = MyEnumT::from_string("Pear");
//  std::cout << "Value: " << to_string(val) << std::endl;
//  std::cout << "Value: " << val            << std::endl;
//
#define UTXX_DEFINE_ENUMX(ENUM, UndefValue, ...)                             \
    struct [[deprecated]] ENUM {                                             \
        enum etype {                                                         \
            UNDEFINED = (UndefValue),                                        \
            BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(                        \
                UTXX_INTERNAL_ENUM_VAL, _,                                   \
                BOOST_PP_VARIADIC_SEQ_TO_SEQ(__VA_ARGS__)))                  \
        };                                                                   \
                                                                             \
    private:                                                                 \
        static const std::pair<const etype, std::string>& null_pair() {      \
            static const std::pair<const etype, std::string> s_val =         \
                std::make_pair(UNDEFINED, "UNDEFINED");                      \
            return s_val;                                                    \
        }                                                                    \
        static const size_t s_size =                                         \
            1+BOOST_PP_SEQ_SIZE(BOOST_PP_VARIADIC_SEQ_TO_SEQ(__VA_ARGS__));  \
        static const std::map<etype, std::string>& names() {                 \
            static const std::map<etype, std::string> s_names{               \
                null_pair(),                                                 \
                BOOST_PP_SEQ_ENUM(BOOST_PP_SEQ_TRANSFORM(                    \
                    UTXX_INTERNAL_ENUM_PAIR, _,                              \
                    BOOST_PP_VARIADIC_SEQ_TO_SEQ(__VA_ARGS__)                \
                ))                                                           \
            };                                                               \
            return s_names;                                                  \
        }                                                                    \
                                                                             \
        UTXX__ENUM_FRIEND_SERIALIZATION__;                                   \
                                                                             \
        etype m_val;                                                         \
                                                                             \
    public:                                                                  \
        explicit  ENUM(long v)  : m_val(etype(v))  {}                        \
        constexpr ENUM()        : m_val(UNDEFINED) {}                        \
        constexpr ENUM(etype v) : m_val(v) {}                                \
                                                                             \
        ENUM(ENUM&&)                 = default;                              \
        ENUM(ENUM const&)            = default;                              \
                                                                             \
        ENUM& operator=(ENUM const&) = default;                              \
        ENUM& operator=(ENUM&&)      = default;                              \
                                                                             \
        constexpr operator etype()     const { return m_val; }               \
        constexpr bool     empty()     const { return m_val == UNDEFINED; }  \
        const std::string& to_string() const {                               \
            auto it = names().find(m_val);                                   \
            return (it == names().end() ? null_pair() : *it).second;         \
        }                                                                    \
                                                                             \
        static const std::string&                                            \
                           to_string(etype a){ return ENUM(a).to_string();  }\
        const char*        c_str()     const { return to_string().c_str();  }\
        static const char* c_str(etype a)    { return to_string(a).c_str(); }\
                                                                             \
        static ENUM from_string(const char* a, bool a_nocase=false){         \
            auto f = a_nocase ? &strcasecmp : &strcmp;                       \
            for (auto& t : names())                                          \
                if (f(t.second.c_str(), a) == 0)                             \
                    return t.first;                                          \
            return UNDEFINED;                                                \
        }                                                                    \
                                                                             \
        static ENUM from_string(const std::string& a, bool a_nocase=false) { \
            return from_string(a.c_str(), a_nocase);                         \
        }                                                                    \
                                                                             \
        inline friend std::ostream& operator<< (std::ostream& out, ENUM a) { \
            return out << ENUM::to_string(a);                                \
        }                                                                    \
                                                                             \
        static constexpr size_t size()  { return s_size-1; }                 \
                                                                             \
        template <typename Visitor>                                          \
        static void for_each(const Visitor& a_fun) {                         \
            for (auto it = ++names().begin(), e = names().end(); it!=e; ++it)\
                if (!a_fun(it->first))                                       \
                    break;                                                   \
        }                                                                    \
    }

// Internal macro for supporting BOOST_PP_SEQ_TRANSFORM
#define UTXX_INTERNAL_ENUM_VAL(x, _, val)                                    \
    BOOST_PP_TUPLE_ELEM(0, val)                                              \
    BOOST_PP_IF(                                                             \
        BOOST_PP_GREATER(BOOST_PP_TUPLE_SIZE(val), 1),                       \
        = BOOST_PP_TUPLE_ELEM(1, val),                                       \
        BOOST_PP_EMPTY())
#define UTXX_INTERNAL_ENUM_PAIR(x, _, val)                                   \
    {std::make_pair(BOOST_PP_TUPLE_ELEM(0, val),                             \
                    BOOST_PP_STRINGIZE(BOOST_PP_TUPLE_ELEM(0, val)))}
<|endoftext|>


<commit_before>/**
 * \file FFTCheckerFilter.cpp
 */

#include "FFTCheckerFilter.h"

#include <cmath>

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>

namespace ATK
{
  template<class DataType_>
  FFTCheckerFilter<DataType_>::FFTCheckerFilter()
  :TypedBaseFilter<DataType_>(1, 0)
  {
    FFTimpl.reset(new FFT<DataType_>);
  }

  template<class DataType_>
  FFTCheckerFilter<DataType_>::~FFTCheckerFilter()
  {
  }

  template<class DataType_>
  void FFTCheckerFilter<DataType_>::set_checks(const std::vector<std::pair<int, DataType> >& frequency_checks)
  {
    this->frequency_checks = frequency_checks;
  }

  template<class DataType_>
  void FFTCheckerFilter<DataType_>::setup()
  {
    FFTimpl->set_size(input_sampling_rate);
  }

  template<class DataType_>
  void FFTCheckerFilter<DataType_>::process_impl(int64_t size) const
  {
    for(int64_t i = 0; i < size/input_sampling_rate; ++i)
    {
      FFTimpl->process(converted_inputs[0] + i * input_sampling_rate, input_sampling_rate);
      std::vector<DataType_> output_freqs;
      FFTimpl->get_amp(output_freqs);

      for(int j = 0; j < frequency_checks.size(); ++j)
      {
        DataType amp = output_freqs[frequency_checks[j].first];
        DataType amp_check = frequency_checks[j].second * frequency_checks[j].second;
        if(amp_check == 0)
        {
          BOOST_REQUIRE_SMALL(amp, 0.1);
        }
        else
        {
          BOOST_REQUIRE_CLOSE(amp, amp_check, 0.1);
        }
      }
    }
  }

  template class FFTCheckerFilter<double>;
}
<commit_msg>Seems that changing the FFT computation factor messed up the default values, so let's fix that in the checker instead...<commit_after>/**
 * \file FFTCheckerFilter.cpp
 */

#include "FFTCheckerFilter.h"

#include <cmath>

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_NO_MAIN
#include <boost/test/unit_test.hpp>

namespace ATK
{
  template<class DataType_>
  FFTCheckerFilter<DataType_>::FFTCheckerFilter()
  :TypedBaseFilter<DataType_>(1, 0)
  {
    FFTimpl.reset(new FFT<DataType_>);
  }

  template<class DataType_>
  FFTCheckerFilter<DataType_>::~FFTCheckerFilter()
  {
  }

  template<class DataType_>
  void FFTCheckerFilter<DataType_>::set_checks(const std::vector<std::pair<int, DataType> >& frequency_checks)
  {
    this->frequency_checks = frequency_checks;
  }

  template<class DataType_>
  void FFTCheckerFilter<DataType_>::setup()
  {
    FFTimpl->set_size(input_sampling_rate);
  }

  template<class DataType_>
  void FFTCheckerFilter<DataType_>::process_impl(int64_t size) const
  {
    for(int64_t i = 0; i < size/input_sampling_rate; ++i)
    {
      FFTimpl->process(converted_inputs[0] + i * input_sampling_rate, input_sampling_rate);
      std::vector<DataType_> output_freqs;
      FFTimpl->get_amp(output_freqs);

      for(int j = 0; j < frequency_checks.size(); ++j)
      {
        DataType amp = output_freqs[frequency_checks[j].first];
        DataType amp_check = frequency_checks[j].second * frequency_checks[j].second;
        if(amp_check == 0)
        {
          BOOST_REQUIRE_SMALL(amp, 0.1);
        }
        else
        {
          BOOST_REQUIRE_CLOSE(2*amp, amp_check, 0.1);
        }
      }
    }
  }

  template class FFTCheckerFilter<double>;
}
<|endoftext|>


<commit_before>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
* Copyright (c) 2010 Ruslan Kabatsayev <b7.10110111@gmail.com>
*
* based on the Null Theme Engine for Gtk+.
* Copyright (c) 2008 Robert Staudinger <robert.staudinger@gmail.com>
*
* This  library is free  software; you can  redistribute it and/or
* modify it  under  the terms  of the  GNU Lesser  General  Public
* License  as published  by the Free  Software  Foundation; either
* version 2 of the License, or( at your option ) any later version.
*
* This library is distributed  in the hope that it will be useful,
* but  WITHOUT ANY WARRANTY; without even  the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License  along  with  this library;  if not,  write to  the Free
* Software Foundation, Inc., 51  Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

#include <gtk/gtk.h>
#include <dlfcn.h>
#include <string>

enum WinDecoOptions
{
    WinIsMaximized=1<<0,
    WinIsShaded=1<<2,
    WinIsResizable=1<<3,
    WinIsActive=1<<4,
    WinHasAlpha=1<<5,
};

//! button status
enum ButtonStatus
{
    Normal,
    Disabled, // this shouldn't be specified by WMs unless button is really insensitive
    Hovered,
    Pressed,
    ButtonStatusCount
};

//! buttons
enum ButtonType
{
    ButtonHelp=0,
    ButtonMax,
    ButtonMin,
    ButtonClose,
    ButtonMenu,
    ButtonSticky,
    ButtonAbove,
    ButtonBelow,
    ButtonShade,
    ButtonUnmax,
    ButtonUnstick,
    ButtonUnshade,
    ButtonUndoAbove,
    ButtonUndoBelow,
    ButtonTypeCount
};

enum Metric
{
    BorderLeft=0,
    BorderRight,
    BorderBottom,
    // BorderTop includes title and resize handle heights
    BorderTop,
    ButtonSpacing,
    ButtonMarginTop,
    ButtonMarginBottom,
    ShadowLeft,
    ShadowTop,
    ShadowRight,
    ShadowBottom,
    MetricsCount
};

//___________________________________________________________________
// external pointers to functions
void (*drawWindowDecoration)(cairo_t*, unsigned long, gint, gint, gint, gint, const gchar**, gint, gint) = 0L;
void (*drawWindecoButton)(cairo_t*, unsigned long, unsigned long, unsigned long, gint, gint, gint, gint) = 0L;
void (*drawWindecoShapeMask)(cairo_t*, unsigned long, gint, gint, gint, gint) = 0L;
void (*drawWindowShadow)(cairo_t*, unsigned long, gint, gint, gint, gint) = 0L;
gint (*getWindecoABIVersion)(void) = 0L;
gint (*getWindecoMetric)(unsigned long) = 0L;
gint (*getWindecoButtonSize)(unsigned long) = 0L;

// window dimensions
int ww( 700 );
int wh( 200 );

// widgets
GtkWidget *mw0( 0L );
GtkWidget *mw1( 0L );

const gboolean useAlpha( TRUE );

// windeco metrics
int shadowLeft=0;
int shadowRight=0;
int shadowTop=0;
int shadowBottom=0;
int borderLeft=0;
int borderRight=0;
int borderTop=0;
int borderBottom=0;
int dw=0;
int dh=0;

//___________________________________________________________________
gboolean initLib()
{
    void* library;
    char* error=0;
    char* moduleDir=gtk_rc_get_module_dir();
    if(moduleDir)
    {
        std::string libpath(moduleDir+std::string("/liboxygen-gtk.so"));
        g_free(moduleDir);
        library=dlopen(libpath.c_str(),RTLD_LAZY);
        bool success=false;
        do{
            if(!library)
            {
                break;
            } else {

                getWindecoABIVersion=(gint(*)(void))dlsym(library, "getWindecoABIVersion");
                if((error=dlerror())!=0L)
                {
                    break;
                } else {

                    #define EXPECTED_ABI_VERSION 3
                    gint version=getWindecoABIVersion();
                    if(version != EXPECTED_ABI_VERSION)
                    {
                        fprintf(stderr, "ABI version %d is not equal to expected version %d\n", version, EXPECTED_ABI_VERSION);
                        return FALSE;
                    }

                }

                // store drawWindowDecoration symbol
                drawWindowDecoration = (void(*)(cairo_t*, unsigned long, gint, gint, gint, gint, const gchar**, gint, gint))dlsym(library, "drawWindowDecoration");
                if((error=dlerror())!=0L)
                    break;

                // store drawWindecoButton symbol
                drawWindecoButton = (void (*)(cairo_t*, unsigned long, unsigned long, unsigned long, gint, gint, gint, gint))dlsym(library, "drawWindecoButton");
                if((error=dlerror())!=0L)
                    break;

                // store drawWindecoShapeMask symbol
                drawWindecoShapeMask=(void (*)(cairo_t*, unsigned long, gint, gint, gint, gint))dlsym(library, "drawWindecoShapeMask");
                if((error=dlerror())!=0L)
                    break;

                // store drawWindowShadow symbol
                drawWindowShadow=(void (*)(cairo_t*, unsigned long, gint, gint, gint, gint))dlsym(library, "drawWindowShadow");
                if((error=dlerror())!=0L)
                    break;

                // store drawWindecoMetric symbol
                getWindecoMetric=(gint (*)(unsigned long))dlsym(library, "getWindecoMetric");
                if((error=dlerror())!=0L)
                    break;

                // store drawWindecoButtonSize symbol
                getWindecoButtonSize=(gint (*)(unsigned long))dlsym(library, "getWindecoButtonSize");
                if((error=dlerror())!=0L)
                    break;
              }
        }
        while(0);
        if(error)
        {
            fprintf(stderr, "%s\n", error);
            return FALSE;
        }
    }
    return TRUE;
}

void getMetrics()
{
    shadowLeft=getWindecoMetric(ShadowLeft);
    shadowRight=getWindecoMetric(ShadowRight);
    shadowTop=getWindecoMetric(ShadowTop);
    shadowBottom=getWindecoMetric(ShadowBottom);

    borderLeft=getWindecoMetric(BorderLeft);
    borderRight=getWindecoMetric(BorderRight);
    borderTop=getWindecoMetric(BorderTop);
    borderBottom=getWindecoMetric(BorderBottom);

    dw = borderLeft + borderRight + shadowLeft + shadowRight;
    dh = borderTop + borderBottom + shadowTop + shadowBottom;
}

//___________________________________________________________________
gboolean on_expose(GtkWidget* mw0, GdkEventExpose* event, gpointer user_data)
{
    cairo_t* cr=gdk_cairo_create( gtk_widget_get_window( mw0 ) );

    // define options
    int opt( WinIsResizable );
    if( useAlpha ) opt |= WinHasAlpha;
    if( !gtk_window_is_active( GTK_WINDOW(mw1) ) ) opt|= WinIsActive;

    drawWindowShadow(cr, (WinDecoOptions) opt, 0, 0, mw0->allocation.width, mw0->allocation.height);

    const gchar* windowStrings[] = {
        "This is a caption",
        "WindowClass10110111",
        0 };

    drawWindowDecoration(cr, (WinDecoOptions) opt, 0+shadowLeft, 0+shadowTop, mw0->allocation.width-shadowLeft-shadowRight, mw0->allocation.height-shadowTop-shadowBottom, windowStrings, 0, 20*ButtonTypeCount);

    for( int status=0; status<ButtonStatusCount; status++)
    {
        for( int type=0; type<ButtonTypeCount; type++)
        {
            int buttonSize=getWindecoButtonSize(type);
            int buttonSpacing=getWindecoMetric(ButtonSpacing);
            int dbut=buttonSize+buttonSpacing;
            drawWindecoButton(cr, type, status, opt,
                    mw0->allocation.width-shadowRight-borderRight-buttonSize-buttonSize*type,
                    status*dbut+shadowTop+(borderTop-buttonSize)/2,
                    buttonSize, buttonSize);
        }
    }

    cairo_destroy(cr);
    return TRUE;
}

//___________________________________________________________________
gboolean on_configure1(GtkWidget* mw1, GdkEventConfigure* event, gpointer user_data)
{
    static int w=0, h=0;
    gboolean redraw( event->width != w || event->height != h );
    if( redraw  )
    {
        w=event->width;
        h=event->height;

        int opt( WinIsActive|WinIsResizable );
        if( useAlpha ) opt|= WinHasAlpha;

        gtk_window_resize(GTK_WINDOW(mw0), event->width+dw, event->height+dh);

        if(!useAlpha)
        {
            GdkBitmap* mask=gdk_pixmap_new(0L, event->width+dw, event->height+dh, 1);
            cairo_t* cr=gdk_cairo_create(mask);
            drawWindecoShapeMask(cr, (WinDecoOptions) opt, 0+shadowLeft, 0+shadowRight, event->width+dw-shadowLeft-shadowRight, event->height+dh-shadowTop-shadowBottom);
            gdk_window_shape_combine_mask( gtk_widget_get_window( mw0 ), 0L, 0, 0 ); // remove old mask
            gdk_window_shape_combine_mask( gtk_widget_get_window( mw0 ), mask, 0, 0 ); // apply new mask
            gdk_pixmap_unref(mask);
        }
    }

    return FALSE;

}

//___________________________________________________________________
gboolean on_configure0(GtkWidget* mw0, GdkEventConfigure* event, gpointer user_data)
{
    static int w=0, h=0;
    static gboolean active=FALSE;

    gboolean redraw( event->width != w || event->height != h );
    if(!(gtk_window_is_active(GTK_WINDOW(mw1))!=active))
    {
        active ^= TRUE;
        redraw = TRUE;
    }

    if( redraw )
    {
        w=event->width;
        h=event->height;

        gdk_window_begin_paint_rect( gtk_widget_get_window( mw0 ), (GdkRectangle*)&mw0->allocation);
        on_expose(mw0, 0L, 0L );
        gdk_window_end_paint( gtk_widget_get_window( mw0 ) );
    }

    return FALSE;

}

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

    // load methods from style library
    if(!initLib()) return 1;

    // initialize gtk
    gtk_init(&argc, &argv);

    // draw
    mw0=gtk_window_new(GTK_WINDOW_TOPLEVEL);
    mw1=gtk_window_new(GTK_WINDOW_TOPLEVEL);

    GdkColormap* cmap=gdk_screen_get_rgba_colormap(gdk_screen_get_default());
    gtk_widget_set_colormap(mw0, cmap);

    g_signal_connect(G_OBJECT(mw0), "destroy", G_CALLBACK(gtk_main_quit), 0L);
    g_signal_connect(G_OBJECT(mw1), "destroy", G_CALLBACK(gtk_main_quit), 0L);

    gtk_window_set_default_size( GTK_WINDOW(mw1), ww, wh );
    gtk_window_set_default_size( GTK_WINDOW(mw0), ww+dw, wh+dh );
    gtk_window_set_decorated(GTK_WINDOW(mw0), FALSE);

    gtk_window_set_title( GTK_WINDOW(mw1), "This is a caption");

    g_signal_connect( G_OBJECT(mw0), "expose-event", G_CALLBACK(on_expose), 0L);
    g_signal_connect( G_OBJECT(mw1), "configure-event", G_CALLBACK(on_configure1), 0L);
    g_signal_connect( G_OBJECT(mw0), "configure-event", G_CALLBACK(on_configure0), 0L);

    gtk_widget_show( mw1 );
    gtk_widget_show( mw0 );

    gtk_window_move( GTK_WINDOW(mw0), 300, 320);
    gtk_window_move( GTK_WINDOW(mw1), 300, 320);

    // FIXME: this call crashes in Oxygen::StyleHelper::initializeRefSurface()
    // if done right after gtk_init() call, i.e. until any widget is created
    getMetrics();

    gtk_main();
    return 0;
}
<commit_msg>Remove no longer needed casts from oxygen-gtk-deco<commit_after>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
* Copyright (c) 2010 Ruslan Kabatsayev <b7.10110111@gmail.com>
*
* based on the Null Theme Engine for Gtk+.
* Copyright (c) 2008 Robert Staudinger <robert.staudinger@gmail.com>
*
* This  library is free  software; you can  redistribute it and/or
* modify it  under  the terms  of the  GNU Lesser  General  Public
* License  as published  by the Free  Software  Foundation; either
* version 2 of the License, or( at your option ) any later version.
*
* This library is distributed  in the hope that it will be useful,
* but  WITHOUT ANY WARRANTY; without even  the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License  along  with  this library;  if not,  write to  the Free
* Software Foundation, Inc., 51  Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

#include <gtk/gtk.h>
#include <dlfcn.h>
#include <string>

enum WinDecoOptions
{
    WinIsMaximized=1<<0,
    WinIsShaded=1<<2,
    WinIsResizable=1<<3,
    WinIsActive=1<<4,
    WinHasAlpha=1<<5,
};

//! button status
enum ButtonStatus
{
    Normal,
    Disabled, // this shouldn't be specified by WMs unless button is really insensitive
    Hovered,
    Pressed,
    ButtonStatusCount
};

//! buttons
enum ButtonType
{
    ButtonHelp=0,
    ButtonMax,
    ButtonMin,
    ButtonClose,
    ButtonMenu,
    ButtonSticky,
    ButtonAbove,
    ButtonBelow,
    ButtonShade,
    ButtonUnmax,
    ButtonUnstick,
    ButtonUnshade,
    ButtonUndoAbove,
    ButtonUndoBelow,
    ButtonTypeCount
};

enum Metric
{
    BorderLeft=0,
    BorderRight,
    BorderBottom,
    // BorderTop includes title and resize handle heights
    BorderTop,
    ButtonSpacing,
    ButtonMarginTop,
    ButtonMarginBottom,
    ShadowLeft,
    ShadowTop,
    ShadowRight,
    ShadowBottom,
    MetricsCount
};

//___________________________________________________________________
// external pointers to functions
void (*drawWindowDecoration)(cairo_t*, unsigned long, gint, gint, gint, gint, const gchar**, gint, gint) = 0L;
void (*drawWindecoButton)(cairo_t*, unsigned long, unsigned long, unsigned long, gint, gint, gint, gint) = 0L;
void (*drawWindecoShapeMask)(cairo_t*, unsigned long, gint, gint, gint, gint) = 0L;
void (*drawWindowShadow)(cairo_t*, unsigned long, gint, gint, gint, gint) = 0L;
gint (*getWindecoABIVersion)(void) = 0L;
gint (*getWindecoMetric)(unsigned long) = 0L;
gint (*getWindecoButtonSize)(unsigned long) = 0L;

// window dimensions
int ww( 700 );
int wh( 200 );

// widgets
GtkWidget *mw0( 0L );
GtkWidget *mw1( 0L );

const gboolean useAlpha( TRUE );

// windeco metrics
int shadowLeft=0;
int shadowRight=0;
int shadowTop=0;
int shadowBottom=0;
int borderLeft=0;
int borderRight=0;
int borderTop=0;
int borderBottom=0;
int dw=0;
int dh=0;

//___________________________________________________________________
gboolean initLib()
{
    void* library;
    char* error=0;
    char* moduleDir=gtk_rc_get_module_dir();
    if(moduleDir)
    {
        std::string libpath(moduleDir+std::string("/liboxygen-gtk.so"));
        g_free(moduleDir);
        library=dlopen(libpath.c_str(),RTLD_LAZY);
        bool success=false;
        do{
            if(!library)
            {
                break;
            } else {

                getWindecoABIVersion=(gint(*)(void))dlsym(library, "getWindecoABIVersion");
                if((error=dlerror())!=0L)
                {
                    break;
                } else {

                    #define EXPECTED_ABI_VERSION 3
                    gint version=getWindecoABIVersion();
                    if(version != EXPECTED_ABI_VERSION)
                    {
                        fprintf(stderr, "ABI version %d is not equal to expected version %d\n", version, EXPECTED_ABI_VERSION);
                        return FALSE;
                    }

                }

                // store drawWindowDecoration symbol
                drawWindowDecoration = (void(*)(cairo_t*, unsigned long, gint, gint, gint, gint, const gchar**, gint, gint))dlsym(library, "drawWindowDecoration");
                if((error=dlerror())!=0L)
                    break;

                // store drawWindecoButton symbol
                drawWindecoButton = (void (*)(cairo_t*, unsigned long, unsigned long, unsigned long, gint, gint, gint, gint))dlsym(library, "drawWindecoButton");
                if((error=dlerror())!=0L)
                    break;

                // store drawWindecoShapeMask symbol
                drawWindecoShapeMask=(void (*)(cairo_t*, unsigned long, gint, gint, gint, gint))dlsym(library, "drawWindecoShapeMask");
                if((error=dlerror())!=0L)
                    break;

                // store drawWindowShadow symbol
                drawWindowShadow=(void (*)(cairo_t*, unsigned long, gint, gint, gint, gint))dlsym(library, "drawWindowShadow");
                if((error=dlerror())!=0L)
                    break;

                // store drawWindecoMetric symbol
                getWindecoMetric=(gint (*)(unsigned long))dlsym(library, "getWindecoMetric");
                if((error=dlerror())!=0L)
                    break;

                // store drawWindecoButtonSize symbol
                getWindecoButtonSize=(gint (*)(unsigned long))dlsym(library, "getWindecoButtonSize");
                if((error=dlerror())!=0L)
                    break;
              }
        }
        while(0);
        if(error)
        {
            fprintf(stderr, "%s\n", error);
            return FALSE;
        }
    }
    return TRUE;
}

void getMetrics()
{
    shadowLeft=getWindecoMetric(ShadowLeft);
    shadowRight=getWindecoMetric(ShadowRight);
    shadowTop=getWindecoMetric(ShadowTop);
    shadowBottom=getWindecoMetric(ShadowBottom);

    borderLeft=getWindecoMetric(BorderLeft);
    borderRight=getWindecoMetric(BorderRight);
    borderTop=getWindecoMetric(BorderTop);
    borderBottom=getWindecoMetric(BorderBottom);

    dw = borderLeft + borderRight + shadowLeft + shadowRight;
    dh = borderTop + borderBottom + shadowTop + shadowBottom;
}

//___________________________________________________________________
gboolean on_expose(GtkWidget* mw0, GdkEventExpose* event, gpointer user_data)
{
    cairo_t* cr=gdk_cairo_create( gtk_widget_get_window( mw0 ) );

    // define options
    int opt( WinIsResizable );
    if( useAlpha ) opt |= WinHasAlpha;
    if( !gtk_window_is_active( GTK_WINDOW(mw1) ) ) opt|= WinIsActive;

    drawWindowShadow(cr, opt, 0, 0, mw0->allocation.width, mw0->allocation.height);

    const gchar* windowStrings[] = {
        "This is a caption",
        "WindowClass10110111",
        0 };

    drawWindowDecoration(cr, opt, 0+shadowLeft, 0+shadowTop, mw0->allocation.width-shadowLeft-shadowRight, mw0->allocation.height-shadowTop-shadowBottom, windowStrings, 0, 20*ButtonTypeCount);

    for( int status=0; status<ButtonStatusCount; status++)
    {
        for( int type=0; type<ButtonTypeCount; type++)
        {
            int buttonSize=getWindecoButtonSize(type);
            int buttonSpacing=getWindecoMetric(ButtonSpacing);
            int dbut=buttonSize+buttonSpacing;
            drawWindecoButton(cr, type, status, opt,
                    mw0->allocation.width-shadowRight-borderRight-buttonSize-buttonSize*type,
                    status*dbut+shadowTop+(borderTop-buttonSize)/2,
                    buttonSize, buttonSize);
        }
    }

    cairo_destroy(cr);
    return TRUE;
}

//___________________________________________________________________
gboolean on_configure1(GtkWidget* mw1, GdkEventConfigure* event, gpointer user_data)
{
    static int w=0, h=0;
    gboolean redraw( event->width != w || event->height != h );
    if( redraw  )
    {
        w=event->width;
        h=event->height;

        int opt( WinIsActive|WinIsResizable );
        if( useAlpha ) opt|= WinHasAlpha;

        gtk_window_resize(GTK_WINDOW(mw0), event->width+dw, event->height+dh);

        if(!useAlpha)
        {
            GdkBitmap* mask=gdk_pixmap_new(0L, event->width+dw, event->height+dh, 1);
            cairo_t* cr=gdk_cairo_create(mask);
            drawWindecoShapeMask(cr, opt, 0+shadowLeft, 0+shadowRight, event->width+dw-shadowLeft-shadowRight, event->height+dh-shadowTop-shadowBottom);
            gdk_window_shape_combine_mask( gtk_widget_get_window( mw0 ), 0L, 0, 0 ); // remove old mask
            gdk_window_shape_combine_mask( gtk_widget_get_window( mw0 ), mask, 0, 0 ); // apply new mask
            gdk_pixmap_unref(mask);
        }
    }

    return FALSE;

}

//___________________________________________________________________
gboolean on_configure0(GtkWidget* mw0, GdkEventConfigure* event, gpointer user_data)
{
    static int w=0, h=0;
    static gboolean active=FALSE;

    gboolean redraw( event->width != w || event->height != h );
    if(!(gtk_window_is_active(GTK_WINDOW(mw1))!=active))
    {
        active ^= TRUE;
        redraw = TRUE;
    }

    if( redraw )
    {
        w=event->width;
        h=event->height;

        gdk_window_begin_paint_rect( gtk_widget_get_window( mw0 ), (GdkRectangle*)&mw0->allocation);
        on_expose(mw0, 0L, 0L );
        gdk_window_end_paint( gtk_widget_get_window( mw0 ) );
    }

    return FALSE;

}

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

    // load methods from style library
    if(!initLib()) return 1;

    // initialize gtk
    gtk_init(&argc, &argv);

    // draw
    mw0=gtk_window_new(GTK_WINDOW_TOPLEVEL);
    mw1=gtk_window_new(GTK_WINDOW_TOPLEVEL);

    GdkColormap* cmap=gdk_screen_get_rgba_colormap(gdk_screen_get_default());
    gtk_widget_set_colormap(mw0, cmap);

    g_signal_connect(G_OBJECT(mw0), "destroy", G_CALLBACK(gtk_main_quit), 0L);
    g_signal_connect(G_OBJECT(mw1), "destroy", G_CALLBACK(gtk_main_quit), 0L);

    gtk_window_set_default_size( GTK_WINDOW(mw1), ww, wh );
    gtk_window_set_default_size( GTK_WINDOW(mw0), ww+dw, wh+dh );
    gtk_window_set_decorated(GTK_WINDOW(mw0), FALSE);

    gtk_window_set_title( GTK_WINDOW(mw1), "This is a caption");

    g_signal_connect( G_OBJECT(mw0), "expose-event", G_CALLBACK(on_expose), 0L);
    g_signal_connect( G_OBJECT(mw1), "configure-event", G_CALLBACK(on_configure1), 0L);
    g_signal_connect( G_OBJECT(mw0), "configure-event", G_CALLBACK(on_configure0), 0L);

    gtk_widget_show( mw1 );
    gtk_widget_show( mw0 );

    gtk_window_move( GTK_WINDOW(mw0), 300, 320);
    gtk_window_move( GTK_WINDOW(mw1), 300, 320);

    // FIXME: this call crashes in Oxygen::StyleHelper::initializeRefSurface()
    // if done right after gtk_init() call, i.e. until any widget is created
    getMetrics();

    gtk_main();
    return 0;
}
<|endoftext|>


<commit_before>// Disable some warnings which are caused with CUDA headers
#pragma warning(disable: 4201 4408 4100)

#include <iostream>
#include <cvconfig.h>
#include "opencv2/core/core.hpp"
#include <opencv2/gpu/gpu.hpp>

#if !defined(HAVE_CUDA) || !defined(HAVE_TBB)

int main()
{
#if !defined(HAVE_CUDA)
    cout << "CUDA support is required (CMake key 'WITH_CUDA' must be true).\n";
#endif

#if !defined(HAVE_TBB)
    cout << "TBB support is required (CMake key 'WITH_TBB' must be true).\n";
#endif

    return 0;
}

#else

#include <cuda.h>
#include <cuda_runtime.h>
#include "opencv2/core/internal.hpp" // For TBB wrappers

using namespace std;
using namespace cv;
using namespace cv::gpu;

struct Worker { void operator()(int device_id) const; };
void destroyContexts();

#define cuSafeCall(code) if (code != CUDA_SUCCESS) { \
    cout << "CUDA driver API error: code " << code \
        << ", file " << __FILE__ << ", line " << __LINE__ << endl; \
    destroyContexts(); \
    exit(-1); \
}

// Each GPU is associated with its own context
CUcontext contexts[2];

int main()
{
    if (getCudaEnabledDeviceCount() < 2)
    {
        cout << "Two or more GPUs are required\n";
        return -1;
    }

    cuSafeCall(cuInit(0));

    // Create context for the first GPU
    CUdevice device;
    cuSafeCall(cuDeviceGet(&device, 0));
    cuSafeCall(cuCtxCreate(&contexts[0], 0, device));

    CUcontext prev_context;
    cuCtxPopCurrent(&prev_context);

    // Create context for the second GPU
    cuSafeCall(cuDeviceGet(&device, 1));
    cuSafeCall(cuCtxCreate(&contexts[1], 1, device));

    cuCtxPopCurrent(&prev_context);

    // Execute calculation in two threads using two GPUs
    int devices[] = {0, 1};
    parallel_do(devices, devices + 2, Worker());

    destroyContexts();
    return 0;
}

void Worker::operator()(int device_id) const
{
    cuCtxPushCurrent(contexts[device_id]);

    // Generate random matrix
    Mat src(1000, 1000, CV_32F);
    RNG rng(0);
    rng.fill(src, RNG::UNIFORM, 0, 1);

    // Upload data on GPU
    GpuMat d_src(src);
    GpuMat d_dst;

    transpose(d_src, d_dst);

    // Deallocate here, otherwise deallocation will be performed
    // after context is extracted from the stack
    d_src.release();
    d_dst.release();

    CUcontext prev_context;
    cuCtxPopCurrent(&prev_context);

    cout << "Device " << device_id << " finished\n";
}

void destroyContexts()
{
    cuCtxDestroy(contexts[0]);
    cuCtxDestroy(contexts[1]);
}

#endif<commit_msg>added results check into multi_gpu sample<commit_after>// Disable some warnings which are caused with CUDA headers
#pragma warning(disable: 4201 4408 4100)

#include <iostream>
#include <cvconfig.h>
#include "opencv2/core/core.hpp"
#include <opencv2/gpu/gpu.hpp>

#if !defined(HAVE_CUDA) || !defined(HAVE_TBB)

int main()
{
#if !defined(HAVE_CUDA)
    cout << "CUDA support is required (CMake key 'WITH_CUDA' must be true).\n";
#endif

#if !defined(HAVE_TBB)
    cout << "TBB support is required (CMake key 'WITH_TBB' must be true).\n";
#endif

    return 0;
}

#else

#include <cuda.h>
#include <cuda_runtime.h>
#include "opencv2/core/internal.hpp" // For TBB wrappers

using namespace std;
using namespace cv;
using namespace cv::gpu;

struct Worker { void operator()(int device_id) const; };
void destroyContexts();

#define cuSafeCall(code) if (code != CUDA_SUCCESS) { \
    cout << "CUDA driver API error: code " << code \
        << ", file " << __FILE__ << ", line " << __LINE__ << endl; \
    destroyContexts(); \
    exit(-1); \
}

// Each GPU is associated with its own context
CUcontext contexts[2];

int main()
{
    if (getCudaEnabledDeviceCount() < 2)
    {
        cout << "Two or more GPUs are required\n";
        return -1;
    }

    cuSafeCall(cuInit(0));

    // Create context for the first GPU
    CUdevice device;
    cuSafeCall(cuDeviceGet(&device, 0));
    cuSafeCall(cuCtxCreate(&contexts[0], 0, device));

    CUcontext prev_context;
    cuSafeCall(cuCtxPopCurrent(&prev_context));

    // Create context for the second GPU
    cuSafeCall(cuDeviceGet(&device, 1));
    cuSafeCall(cuCtxCreate(&contexts[1], 1, device));

    cuSafeCall(cuCtxPopCurrent(&prev_context));

    // Execute calculation in two threads using two GPUs
    int devices[] = {0, 1};
    parallel_do(devices, devices + 2, Worker());

    destroyContexts();
    return 0;
}

void Worker::operator()(int device_id) const
{
    // Set proper context
    cuSafeCall(cuCtxPushCurrent(contexts[device_id]));

    Mat src(1000, 1000, CV_32F);
    Mat dst;

    RNG rng(0);
    rng.fill(src, RNG::UNIFORM, 0, 1);

    // CPU works
    transpose(src, dst);

    GpuMat d_src(src);
    GpuMat d_dst;

    // GPU works
    transpose(d_src, d_dst);

    // Check results
    bool passed = norm(dst - Mat(d_dst), NORM_INF) < 1e-3;
    cout << "GPU #" << device_id << ": "<< (passed ? "passed" : "FAILED") << endl;

    // Deallocate data here, otherwise deallocation will be performed
    // after context is extracted from the stack
    d_src.release();
    d_dst.release();

    CUcontext prev_context;
    cuSafeCall(cuCtxPopCurrent(&prev_context));
}

void destroyContexts()
{
    cuSafeCall(cuCtxDestroy(contexts[0]));
    cuSafeCall(cuCtxDestroy(contexts[1]));
}

#endif<|endoftext|>