<commit_before>#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <fstream>
#include <stdlib.h>
#include <string.h>
#include <sys/times.h>

using namespace std;

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

	if (argc < 3)
		return 0;

	ifstream test(argv[2]);
	if (test.good())
	{
		test.close();
		cerr << "Output already exists." << endl;
		exit(1);
	}
	if ((argv[3]) && strcmp(argv[3], "-a") == 0)
	{

	// method 1
	struct tms  tmsstart, tmsend;
	clock_t     start, end;
	if ((start = times(&tmsstart)) == -1)    /* starting values */
		cout << "times error" << endl;

	char * input = argv[1];
	char * output = argv[2];
	ifstream infile(input);

	ofstream outfile(output);
	while (infile.good())
	{
		char c;
		infile.get(c);
		if (infile.good())
			outfile.put(c);
	}

	if ((end = times(&tmsend)) == -1)
		cout << "times error" << endl;

	static long clktck = 0;
	if ((clktck = sysconf(_SC_CLK_TCK)) < 0)
		cout << "sysconf error" << endl;

	cout << "Wall time: " << double(end-start)/clktck << endl;
	cout << "User time: " << double(tmsend.tms_utime - tmsstart.tms_utime)
					/clktck << endl;
	cout << "Syst time: " << double(tmsend.tms_stime - tmsstart.tms_stime)
					/clktck << endl;

	// method 2
	if ((start = times(&tmsstart)) == -1)    /* starting values */
		cout << "times error" << endl;

	char c;
	int fd;
	int fd2;
	int status;

	fd = open(argv[1], O_RDONLY);
	if (fd == -1)
		perror("open");

	fd2 = open(argv[2], O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
	if (fd2 == -1)
		perror("open");

	while(read(fd, &c, 1)) {

		status = write(fd2, &c, 1);
		if (status == -1)
			perror("write");

	}
	status = close(fd);
	if (status == -1)
		perror("close");

	status = close(fd2);
	if (status == -1)
		perror("close");

	if ((end = times(&tmsend)) == -1)
		cout << "times error" << endl;

	cout << "Wall time: " << double(end-start)/clktck << endl;
	cout << "User time: " << double(tmsend.tms_utime - tmsstart.tms_utime)
					/clktck << endl;
	cout << "Syst time: " << double(tmsend.tms_stime - tmsstart.tms_stime)
					/clktck << endl;

	}

	// method 3
	struct tms  tmsstart, tmsend;
	clock_t     start, end;
	if ((start = times(&tmsstart)) == -1)    /* starting values */
		cout << "times error" << endl;

	char buf[BUFSIZ];
	int n;
	int status;

	int fd;
	int fd2;

	fd = open(argv[1], O_RDONLY);
	if (fd == -1)
		perror("open");

	fd2 = open(argv[2], O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
	if (fd2 == -1)
		perror("open");

	while ((n = read(fd, buf, BUFSIZ)) >0) {
		status = write(fd2, buf, n);
		if (status == -1)
			perror("write");
	}

	status = close(fd);
	if (status == -1)
		perror("close");

	status = close(fd2);
	if (status == -1)
		perror("close");
		if ((end = times(&tmsend)) == -1)
		cout << "times error" << endl;

	if (argv[3] && strcmp(argv[3], "-a") == 0) {

	static long clktck = 0;
	if ((clktck = sysconf(_SC_CLK_TCK)) < 0)
		cout << "sysconf error" << endl;

	cout << "Wall time: " << (double)(end-start)/clktck << endl;
	cout << "User time: " << double(tmsend.tms_utime - tmsstart.tms_utime)
					/clktck << endl;
	cout << "Syst time: " << double(tmsend.tms_stime - tmsstart.tms_stime)
					/clktck << endl;

	}

}
<commit_msg>Flags now work better in cp<commit_after>#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <time.h>
#include <fstream>
#include <stdlib.h>
#include <string.h>
#include <sys/times.h>

using namespace std;

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

	if (argc < 3)
		return 0;

	ifstream test(argv[2]);
	if (test.good())
	{
		test.close();
		cerr << "Output already exists." << endl;
		exit(1);
	}

	bool flag = false;
	for (int i =1; i<argc; i++)
		if (argv[i][0]=='-')
			for (int j=1; argv[i][j]!=0; j++)
				if (argv[i][j] == 'a')
					flag = true;
	if ((argv[3]) && flag)
	{

	// method 1
	struct tms  tmsstart, tmsend;
	clock_t	 start, end;
	if ((start = times(&tmsstart)) == -1)	/* starting values */
		cout << "times error" << endl;

	char * input = argv[1];
	char * output = argv[2];
	ifstream infile(input);

	ofstream outfile(output);
	while (infile.good())
	{
		char c;
		infile.get(c);
		if (infile.good())
			outfile.put(c);
	}

	if ((end = times(&tmsend)) == -1)
		cout << "times error" << endl;

	static long clktck = 0;
	if ((clktck = sysconf(_SC_CLK_TCK)) < 0)
		cout << "sysconf error" << endl;

	cout << "Wall time: " << double(end-start)/clktck << endl;
	cout << "User time: " << double(tmsend.tms_utime - tmsstart.tms_utime)
					/clktck << endl;
	cout << "Syst time: " << double(tmsend.tms_stime - tmsstart.tms_stime)
					/clktck << endl;

	// method 2
	if ((start = times(&tmsstart)) == -1)	/* starting values */
		cout << "times error" << endl;

	char c;
	int fd;
	int fd2;
	int status;

	fd = open(argv[1], O_RDONLY);
	if (fd == -1)
		perror("open");

	fd2 = open(argv[2], O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
	if (fd2 == -1)
		perror("open");

	while(read(fd, &c, 1)) {

		status = write(fd2, &c, 1);
		if (status == -1)
			perror("write");

	}
	status = close(fd);
	if (status == -1)
		perror("close");

	status = close(fd2);
	if (status == -1)
		perror("close");

	if ((end = times(&tmsend)) == -1)
		cout << "times error" << endl;

	cout << "Wall time: " << double(end-start)/clktck << endl;
	cout << "User time: " << double(tmsend.tms_utime - tmsstart.tms_utime)
					/clktck << endl;
	cout << "Syst time: " << double(tmsend.tms_stime - tmsstart.tms_stime)
					/clktck << endl;

	}

	// method 3
	struct tms  tmsstart, tmsend;
	clock_t	 start, end;
	if ((start = times(&tmsstart)) == -1)	/* starting values */
		cout << "times error" << endl;

	char buf[BUFSIZ];
	int n;
	int status;

	int fd;
	int fd2;

	fd = open(argv[1], O_RDONLY);
	if (fd == -1)
		perror("open");

	fd2 = open(argv[2], O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
	if (fd2 == -1)
		perror("open");

	while ((n = read(fd, buf, BUFSIZ)) >0) {
		status = write(fd2, buf, n);
		if (status == -1)
			perror("write");
	}

	status = close(fd);
	if (status == -1)
		perror("close");

	status = close(fd2);
	if (status == -1)
		perror("close");
		if ((end = times(&tmsend)) == -1)
		cout << "times error" << endl;

	if (argv[3] && flag) {

	static long clktck = 0;
	if ((clktck = sysconf(_SC_CLK_TCK)) < 0)
		cout << "sysconf error" << endl;

	cout << "Wall time: " << (double)(end-start)/clktck << endl;
	cout << "User time: " << double(tmsend.tms_utime - tmsstart.tms_utime)
					/clktck << endl;
	cout << "Syst time: " << double(tmsend.tms_stime - tmsstart.tms_stime)
					/clktck << endl;

	}

}
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>

#include <QFileDialog>
#include <QMessageBox>
#include <QImage>
#include <QPicture>

#include "facerecognizercontainer.h"

MainWindow::MainWindow(QWidget *parent) :
	QMainWindow(parent),
	ui(new Ui::MainWindow)
{
	ui->setupUi(this);

	databaseCreatorWidget.SetDatabase(&database);

	connect(&databaseCreatorWidget, &DatabaseCreator::finished, this, &MainWindow::ContinueCameraProcessing);
	connect(&faceRecognizerSelectorWidget, &FaceRecognizerSelectorWidget::finished, this, &MainWindow::ContinueCameraProcessing);

	connect(&timer, &QTimer::timeout, this, &MainWindow::UpdateCameraImage);
	timer.start(30);

	camera.reset(new cv::VideoCapture(0));
}

MainWindow::~MainWindow()
{
	camera->release();

	delete ui;
}

QImage cvMat2QImage(const cv::Mat &image)
{
	// 8-bits unsigned, NO. OF CHANNELS=1
	if (image.type() == CV_8UC1)
	{
		// Set the color table (used to translate colour indexes to qRgb values)
		QVector<QRgb> colorTable;
		for (int i = 0; i < 256; ++i)
		{
			colorTable.push_back(qRgb(i, i, i));
		}
		// Copy input Mat
		const uchar *qImageBuffer = (const uchar*) image.data;
		// Create QImage with same dimensions as input Mat
		QImage img(qImageBuffer, image.cols, image.rows, image.step, QImage::Format_Indexed8);
		img.setColorTable(colorTable);
		return img;
	}
	// 8-bits unsigned, NO. OF CHANNELS=3
	if (image.type() == CV_8UC3)
	{
		// Copy input Mat
		const uchar *qImageBuffer = (const uchar*) image.data;
		// Create QImage with same dimensions as input Mat
		QImage img(qImageBuffer, image.cols, image.rows, image.step, QImage::Format_RGB888);
		return img.rgbSwapped();
	}
	else
	{
		qDebug() << "ERROR: Mat could not be converted to QImage.";
		return QImage();
	}
}

void MainWindow::UpdateCameraImage()
{
	if (processCamera)
	{
		*camera >> rawCameraImage;

		bool isPreprocessSuccess = false;

		try
		{
			FacePreprocessor facePreprocessor = preprocessorFactory.GetPreprocessor(rawCameraImage, true);
			cv::Mat preprocessedImage = facePreprocessor.Preprocess();

			QImage img = cvMat2QImage(preprocessedImage);
			QPixmap pixmap;
			pixmap.convertFromImage(img);
			ui->label->setPixmap(pixmap);

			isPreprocessSuccess = true;
		}
		catch (std::exception e)
		{
//			qDebug() << e.what();
		}
		catch (NoFaceFoundException)
		{
		}

		if (!isPreprocessSuccess)
		{
			QImage img = cvMat2QImage(rawCameraImage);
			QPixmap pixmap;
			pixmap.convertFromImage(img);
			ui->label->setPixmap(pixmap);
		}
	}
}

void MainWindow::on_actionCreate_database_triggered()
{
	if (FaceRecognizerContainer::Instance()->CurrentFaceRecognizer().obj)
	{
		processCamera = false;
		databaseCreatorWidget.show();
	}
	else
	{
		QMessageBox::critical(this, tr("Face recognizer not selected"), tr("Please select and apply a face recognizer in the \"File/Select face recognizer\" menu!"));
	}
}

void MainWindow::on_actionSelect_face_recognizer_triggered()
{
	processCamera = false;
	faceRecognizerSelectorWidget.show();
}

void MainWindow::ContinueCameraProcessing()
{
	processCamera = true;
}

void MainWindow::on_pushButton_addToDatabasePlan_clicked()
{
	try
	{
		FacePreprocessor facePreprocessor = preprocessorFactory.GetPreprocessor(rawCameraImage, false);
		cv::Mat preprocessedImage = facePreprocessor.Preprocess();

		database.AddImage(ui->lineEdit_label->text(), preprocessedImage);
	}
	catch (std::exception e)
	{
//		qDebug() << e.what();
	}
	catch (NoFaceFoundException)
	{
	}
}

void MainWindow::on_pushButton_createDatabaseFromPlan_clicked()
{
	if (FaceRecognizerContainer::Instance()->CurrentFaceRecognizer().obj)
	{
		QString saveFile = QFileDialog::getSaveFileName(this, tr("Save file"), tr(""), tr("fdb (*.facedb)"));;

		if (!saveFile.isEmpty())
		{
			qDebug() << "Save name labels";
			database.ExportNameLabels(saveFile + ".nlabels");

			qDebug() << "Train face recognizer";
			database.Train();
			qDebug() << "Save face recognizer";
			database.Save(saveFile);
		}
	}
	else
	{
		QMessageBox::critical(this, tr("Face recognizer not selected"), tr("Please select and apply a face recognizer in the \"File/Select face recognizer\" menu!"));
	}
}

void MainWindow::on_pushButton_freezeImage_clicked()
{
	processCamera = !processCamera;
}

void MainWindow::on_actionLoad_database_triggered()
{
	if (FaceRecognizerContainer::Instance()->CurrentFaceRecognizer().obj)
	{
		QString loadFile = QFileDialog::getOpenFileName(this, tr("Save file"), tr(""), tr("fdb (*.facedb)"));;

		if (!loadFile.isEmpty())
		{
			database.ImportNameLabels(loadFile + ".nlabels");
			database.Load(loadFile);
		}
	}
	else
	{
		QMessageBox::critical(this, tr("Face recognizer not selected"), tr("Please select and apply a face recognizer in the \"File/Select face recognizer\" menu!"));
	}
}

void MainWindow::on_pushButton_identifyCamera_clicked()
{
	if (FaceRecognizerContainer::Instance()->CurrentFaceRecognizer().obj == nullptr)
	{
		QMessageBox::critical(this, tr("Face recognizer not selected"), tr("Please select and apply a face recognizer in the \"File/Select face recognizer\" menu!"));
	}
	else if (database.GetNameLabels().empty())
	{
		QMessageBox::critical(this, tr("Face recognizer not selected"), tr("Please select and apply a face recognizer in the \"File/Select face recognizer\" menu!"));
	}
	else
	{
		try
		{
			FacePreprocessor facePreprocessor = preprocessorFactory.GetPreprocessor(rawCameraImage, false);
			cv::Mat preprocessedImage = facePreprocessor.Preprocess();

			int label = -1;
			double confidence = 0.0;
			FaceRecognizerContainer::Instance()->CurrentFaceRecognizer().obj->predict(preprocessedImage, label, confidence);

			qDebug() << label << confidence;
		}
		catch (std::exception e)
		{
//			qDebug() << e.what();
		}
		catch (NoFaceFoundException)
		{
		}
	}
}

void MainWindow::on_pushButton_identifyImage_clicked()
{
	if (FaceRecognizerContainer::Instance()->CurrentFaceRecognizer().obj)
	{
		QString loadFile = QFileDialog::getOpenFileName(this, tr("Save file"), tr(""), tr("Image (*.jpg, *.png, *.jpeg)"));;

		if (!loadFile.isEmpty())
		{
			try
			{
				cv::Mat rawImage = cv::imread(loadFile.toStdString().c_str());

				FacePreprocessor facePreprocessor = preprocessorFactory.GetPreprocessor(rawImage, false);
				cv::Mat preprocessedImage = facePreprocessor.Preprocess();

				int label = -1;
				double confidence = 0.0;
				FaceRecognizerContainer::Instance()->CurrentFaceRecognizer().obj->predict(preprocessedImage, label, confidence);

				qDebug() << label << confidence;
			}
			catch (std::exception e)
			{
	//			qDebug() << e.what();
			}
			catch (NoFaceFoundException)
			{
			}
		}
	}
	else
	{
		QMessageBox::critical(this, tr("Face recognizer not selected"), tr("Please select and apply a face recognizer in the \"File/Select face recognizer\" menu!"));
	}
}
<commit_msg>Bug fix: could not browse image files in case of identifing.<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>

#include <QFileDialog>
#include <QMessageBox>
#include <QImage>
#include <QPicture>

#include "facerecognizercontainer.h"

MainWindow::MainWindow(QWidget *parent) :
	QMainWindow(parent),
	ui(new Ui::MainWindow)
{
	ui->setupUi(this);

	databaseCreatorWidget.SetDatabase(&database);

	connect(&databaseCreatorWidget, &DatabaseCreator::finished, this, &MainWindow::ContinueCameraProcessing);
	connect(&faceRecognizerSelectorWidget, &FaceRecognizerSelectorWidget::finished, this, &MainWindow::ContinueCameraProcessing);

	connect(&timer, &QTimer::timeout, this, &MainWindow::UpdateCameraImage);
	timer.start(30);

	camera.reset(new cv::VideoCapture(0));
}

MainWindow::~MainWindow()
{
	camera->release();

	delete ui;
}

QImage cvMat2QImage(const cv::Mat &image)
{
	// 8-bits unsigned, NO. OF CHANNELS=1
	if (image.type() == CV_8UC1)
	{
		// Set the color table (used to translate colour indexes to qRgb values)
		QVector<QRgb> colorTable;
		for (int i = 0; i < 256; ++i)
		{
			colorTable.push_back(qRgb(i, i, i));
		}
		// Copy input Mat
		const uchar *qImageBuffer = (const uchar*) image.data;
		// Create QImage with same dimensions as input Mat
		QImage img(qImageBuffer, image.cols, image.rows, image.step, QImage::Format_Indexed8);
		img.setColorTable(colorTable);
		return img;
	}
	// 8-bits unsigned, NO. OF CHANNELS=3
	if (image.type() == CV_8UC3)
	{
		// Copy input Mat
		const uchar *qImageBuffer = (const uchar*) image.data;
		// Create QImage with same dimensions as input Mat
		QImage img(qImageBuffer, image.cols, image.rows, image.step, QImage::Format_RGB888);
		return img.rgbSwapped();
	}
	else
	{
		qDebug() << "ERROR: Mat could not be converted to QImage.";
		return QImage();
	}
}

void MainWindow::UpdateCameraImage()
{
	if (processCamera)
	{
		*camera >> rawCameraImage;

		bool isPreprocessSuccess = false;

		try
		{
			FacePreprocessor facePreprocessor = preprocessorFactory.GetPreprocessor(rawCameraImage, true);
			cv::Mat preprocessedImage = facePreprocessor.Preprocess();

			QImage img = cvMat2QImage(preprocessedImage);
			QPixmap pixmap;
			pixmap.convertFromImage(img);
			ui->label->setPixmap(pixmap);

			isPreprocessSuccess = true;
		}
		catch (std::exception e)
		{
//			qDebug() << e.what();
		}
		catch (NoFaceFoundException)
		{
		}

		if (!isPreprocessSuccess)
		{
			QImage img = cvMat2QImage(rawCameraImage);
			QPixmap pixmap;
			pixmap.convertFromImage(img);
			ui->label->setPixmap(pixmap);
		}
	}
}

void MainWindow::on_actionCreate_database_triggered()
{
	if (FaceRecognizerContainer::Instance()->CurrentFaceRecognizer().obj)
	{
		processCamera = false;
		databaseCreatorWidget.show();
	}
	else
	{
		QMessageBox::critical(this, tr("Face recognizer not selected"), tr("Please select and apply a face recognizer in the \"File/Select face recognizer\" menu!"));
	}
}

void MainWindow::on_actionSelect_face_recognizer_triggered()
{
	processCamera = false;
	faceRecognizerSelectorWidget.show();
}

void MainWindow::ContinueCameraProcessing()
{
	processCamera = true;
}

void MainWindow::on_pushButton_addToDatabasePlan_clicked()
{
	try
	{
		FacePreprocessor facePreprocessor = preprocessorFactory.GetPreprocessor(rawCameraImage, false);
		cv::Mat preprocessedImage = facePreprocessor.Preprocess();

		database.AddImage(ui->lineEdit_label->text(), preprocessedImage);
	}
	catch (std::exception e)
	{
//		qDebug() << e.what();
	}
	catch (NoFaceFoundException)
	{
	}
}

void MainWindow::on_pushButton_createDatabaseFromPlan_clicked()
{
	if (FaceRecognizerContainer::Instance()->CurrentFaceRecognizer().obj)
	{
		QString saveFile = QFileDialog::getSaveFileName(this, tr("Save file"), tr(""), tr("fdb (*.facedb)"));;

		if (!saveFile.isEmpty())
		{
			qDebug() << "Save name labels";
			database.ExportNameLabels(saveFile + ".nlabels");

			qDebug() << "Train face recognizer";
			database.Train();
			qDebug() << "Save face recognizer";
			database.Save(saveFile);
		}
	}
	else
	{
		QMessageBox::critical(this, tr("Face recognizer not selected"), tr("Please select and apply a face recognizer in the \"File/Select face recognizer\" menu!"));
	}
}

void MainWindow::on_pushButton_freezeImage_clicked()
{
	processCamera = !processCamera;
}

void MainWindow::on_actionLoad_database_triggered()
{
	if (FaceRecognizerContainer::Instance()->CurrentFaceRecognizer().obj)
	{
		QString loadFile = QFileDialog::getOpenFileName(this, tr("Save file"), tr(""), tr("fdb (*.facedb)"));;

		if (!loadFile.isEmpty())
		{
			database.ImportNameLabels(loadFile + ".nlabels");
			database.Load(loadFile);
		}
	}
	else
	{
		QMessageBox::critical(this, tr("Face recognizer not selected"), tr("Please select and apply a face recognizer in the \"File/Select face recognizer\" menu!"));
	}
}

void MainWindow::on_pushButton_identifyCamera_clicked()
{
	if (FaceRecognizerContainer::Instance()->CurrentFaceRecognizer().obj == nullptr)
	{
		QMessageBox::critical(this, tr("Face recognizer not selected"), tr("Please select and apply a face recognizer in the \"File/Select face recognizer\" menu!"));
	}
	else if (database.GetNameLabels().empty())
	{
		QMessageBox::critical(this, tr("Face recognizer not selected"), tr("Please select and apply a face recognizer in the \"File/Select face recognizer\" menu!"));
	}
	else
	{
		try
		{
			FacePreprocessor facePreprocessor = preprocessorFactory.GetPreprocessor(rawCameraImage, false);
			cv::Mat preprocessedImage = facePreprocessor.Preprocess();

			int label = -1;
			double confidence = 0.0;
			FaceRecognizerContainer::Instance()->CurrentFaceRecognizer().obj->predict(preprocessedImage, label, confidence);

			qDebug() << label << confidence;
		}
		catch (std::exception e)
		{
//			qDebug() << e.what();
		}
		catch (NoFaceFoundException)
		{
		}
	}
}

void MainWindow::on_pushButton_identifyImage_clicked()
{
	if (FaceRecognizerContainer::Instance()->CurrentFaceRecognizer().obj)
	{
		QString loadFile = QFileDialog::getOpenFileName(this, tr("Save file"), tr(""), tr("Image (*.jpg *.png *.jpeg)"));;

		if (!loadFile.isEmpty())
		{
			try
			{
				cv::Mat rawImage = cv::imread(loadFile.toStdString().c_str());

				FacePreprocessor facePreprocessor = preprocessorFactory.GetPreprocessor(rawImage, false);
				cv::Mat preprocessedImage = facePreprocessor.Preprocess();

				int label = -1;
				double confidence = 0.0;
				FaceRecognizerContainer::Instance()->CurrentFaceRecognizer().obj->predict(preprocessedImage, label, confidence);

				qDebug() << label << confidence;
			}
			catch (std::exception e)
			{
	//			qDebug() << e.what();
			}
			catch (NoFaceFoundException)
			{
			}
		}
	}
	else
	{
		QMessageBox::critical(this, tr("Face recognizer not selected"), tr("Please select and apply a face recognizer in the \"File/Select face recognizer\" menu!"));
	}
}
<|endoftext|>


<commit_before>#ifndef GENERICS_H
#define GENERICS_H

#include"objects.hpp"

class Semispace;

/*-----------------------------------------------------------------------------
GenericTraverser
-----------------------------------------------------------------------------*/
/*An abstract base class which provides a
"traverse" method.  This method is invoked
on each reference of an object.
*/
class GenericTraverser {
public:
	virtual void traverse(Object::ref&) =0;
	virtual ~GenericTraverser() {}
};

/*-----------------------------------------------------------------------------
HashingClass
-----------------------------------------------------------------------------*/
/*A class which provides a "enhash" method, which
perturbs its internal state.
*/
class HashingClass {
private:
	uint32_t a, b;
public:
	uint32_t c;
	void enhash(size_t);
	HashingClass(void);
};

/*-----------------------------------------------------------------------------
Generic
-----------------------------------------------------------------------------*/

class Generic {
public:

	virtual void traverse_references(GenericTraverser* gt) {
		/*default to having no references to traverse*/
		/*example for Cons:
		gt->traverse(a);
		gt->traverse(d);
		*/
	}

	/*some objects have extra allocated space at their ends
	(e.g. Closure).
 	This virtual function returns the total size of the class
	plus extra allocated space.
	*/
	virtual size_t real_size(void) const =0;

	/*Copies an object, used for message passing and
	copying garbage collection
	*/
	virtual Generic* clone(Semispace*) const =0;

	/*hash functions for table-ident and table-is*/
	virtual size_t hash_ident(void) const {
		return reinterpret_cast<size_t>(this);
	}
	virtual size_t hash_is(void) const {
		return reinterpret_cast<size_t>(this);
	}

	/*broken hearts for GC*/
	virtual void break_heart(Generic*) =0;

	/*------These two functions must be redefined together------*/
	virtual bool is(Object::ref) {
		/*return true if the given Object::ref is-equal to
		this object, even if they have different addresses
		*/
		return false;
	}
	virtual void enhash(HashingClass* hc) {
		/*Should provide hc with all the values
		it uses to determine equality, as in is()
		above.
		Should *not* provide Generic* pointers,
		because those *will* change in a GC, and
		we want hash tables to work even across
		a GC.
		*/
		return;
	}
	/*------These two functions must be redefined together------*/

	/*dtor*/
	virtual ~Generic() { }
};

/*-----------------------------------------------------------------------------
Broken Heart tags
-----------------------------------------------------------------------------*/

void throw_OverBrokenHeart(Generic*);

class BrokenHeart : public Generic {
private:
	// disallowed
	BrokenHeart();
	BrokenHeart(BrokenHeart const&);
public:
	Generic* to;
	virtual void break_heart(Generic* to) {
		/*already broken - don't break too much!*/
		throw_OverBrokenHeart(to);
	}
	virtual Generic* clone(Semispace*) const {
		/*broken - why are we cloning this?*/
		throw_OverBrokenHeart(to);
	}
	BrokenHeart(Generic* nto) : to(nto) { }
};

class BrokenHeartVariadic : public BrokenHeart {
private:
	// disallowed
	BrokenHeartVariadic();
	BrokenHeartVariadic(BrokenHeart const&);
protected:
	size_t sz;
public:
	BrokenHeartVariadic(Generic* x, size_t nsz)
		: BrokenHeart(x), sz(nsz) { }
};

/*-----------------------------------------------------------------------------
Size computations
-----------------------------------------------------------------------------*/

template<class T>
static inline size_t compute_size(void) {
	size_t sizeofBrokenHeart = Object::round_up_to_alignment(
			sizeof(BrokenHeart)
	);
	size_t sizeofT = Object::round_up_to_alignment(sizeof(T));
	return
	(sizeofT < sizeofBrokenHeart) ?		sizeofBrokenHeart :
	/*otherwise*/				sizeofT ;
}

template<class T>
static inline size_t compute_size_variadic(size_t sz) {
	/*remember that this is variadic*/
	size_t sizeofBrokenHeart = Object::round_up_to_alignment(
			sizeof(BrokenHeartVariadic)
	);
	size_t sizeofT = Object::round_up_to_alignment(sizeof(T))
			 + Object::round_up_to_alignment(
				sz * sizeof(Object::ref)
		);
	return
	(sizeofT < sizeofBrokenHeart) ?		sizeofBrokenHeart :
	/*otherwise*/				sizeofT ;
}

#endif // GENERICS_H

<commit_msg>inc/generics.hpp: Made Generic::is() and Generic::enhash() const functions<commit_after>#ifndef GENERICS_H
#define GENERICS_H

#include"objects.hpp"

class Semispace;

/*-----------------------------------------------------------------------------
GenericTraverser
-----------------------------------------------------------------------------*/
/*An abstract base class which provides a
"traverse" method.  This method is invoked
on each reference of an object.
*/
class GenericTraverser {
public:
	virtual void traverse(Object::ref&) =0;
	virtual ~GenericTraverser() {}
};

/*-----------------------------------------------------------------------------
HashingClass
-----------------------------------------------------------------------------*/
/*A class which provides a "enhash" method, which
perturbs its internal state.
*/
class HashingClass {
private:
	uint32_t a, b;
public:
	uint32_t c;
	void enhash(size_t);
	HashingClass(void);
};

/*-----------------------------------------------------------------------------
Generic
-----------------------------------------------------------------------------*/

class Generic {
public:

	virtual void traverse_references(GenericTraverser* gt) {
		/*default to having no references to traverse*/
		/*example for Cons:
		gt->traverse(a);
		gt->traverse(d);
		*/
	}

	/*some objects have extra allocated space at their ends
	(e.g. Closure).
 	This virtual function returns the total size of the class
	plus extra allocated space.
	*/
	virtual size_t real_size(void) const =0;

	/*Copies an object, used for message passing and
	copying garbage collection
	*/
	virtual Generic* clone(Semispace*) const =0;

	/*hash functions for table-ident and table-is*/
	virtual size_t hash_ident(void) const {
		return reinterpret_cast<size_t>(this);
	}
	virtual size_t hash_is(void) const {
		return reinterpret_cast<size_t>(this);
	}

	/*broken hearts for GC*/
	virtual void break_heart(Generic*) =0;

	/*------These two functions must be redefined together------*/
	virtual bool is(Object::ref) const {
		/*return true if the given Object::ref is-equal to
		this object, even if they have different addresses
		*/
		return false;
	}
	virtual void enhash(HashingClass* hc) const {
		/*Should provide hc with all the values
		it uses to determine equality, as in is()
		above.
		Should *not* provide Generic* pointers,
		because those *will* change in a GC, and
		we want hash tables to work even across
		a GC.
		*/
		return;
	}
	/*------These two functions must be redefined together------*/

	/*dtor*/
	virtual ~Generic() { }
};

/*-----------------------------------------------------------------------------
Broken Heart tags
-----------------------------------------------------------------------------*/

void throw_OverBrokenHeart(Generic*);

class BrokenHeart : public Generic {
private:
	// disallowed
	BrokenHeart();
	BrokenHeart(BrokenHeart const&);
public:
	Generic* to;
	virtual void break_heart(Generic* to) {
		/*already broken - don't break too much!*/
		throw_OverBrokenHeart(to);
	}
	virtual Generic* clone(Semispace*) const {
		/*broken - why are we cloning this?*/
		throw_OverBrokenHeart(to);
	}
	BrokenHeart(Generic* nto) : to(nto) { }
};

class BrokenHeartVariadic : public BrokenHeart {
private:
	// disallowed
	BrokenHeartVariadic();
	BrokenHeartVariadic(BrokenHeart const&);
protected:
	size_t sz;
public:
	BrokenHeartVariadic(Generic* x, size_t nsz)
		: BrokenHeart(x), sz(nsz) { }
};

/*-----------------------------------------------------------------------------
Size computations
-----------------------------------------------------------------------------*/

template<class T>
static inline size_t compute_size(void) {
	size_t sizeofBrokenHeart = Object::round_up_to_alignment(
			sizeof(BrokenHeart)
	);
	size_t sizeofT = Object::round_up_to_alignment(sizeof(T));
	return
	(sizeofT < sizeofBrokenHeart) ?		sizeofBrokenHeart :
	/*otherwise*/				sizeofT ;
}

template<class T>
static inline size_t compute_size_variadic(size_t sz) {
	/*remember that this is variadic*/
	size_t sizeofBrokenHeart = Object::round_up_to_alignment(
			sizeof(BrokenHeartVariadic)
	);
	size_t sizeofT = Object::round_up_to_alignment(sizeof(T))
			 + Object::round_up_to_alignment(
				sz * sizeof(Object::ref)
		);
	return
	(sizeofT < sizeofBrokenHeart) ?		sizeofBrokenHeart :
	/*otherwise*/				sizeofT ;
}

#endif // GENERICS_H

<|endoftext|>


<commit_before>/* This file is part of the KDE libraries
   Copyright (C) 2002 John Firebaugh <jfirebaugh@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

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

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.
*/

 // $Id$

#include "katebookmarks.h"
#include "katebookmarks.moc"

#include <klocale.h>
#include <kaction.h>
#include <kpopupmenu.h>
#include <kstringhandler.h>
#include <kdebug.h>

#include <qregexp.h>
#include <qmemarray.h>

#include "../interfaces/document.h"
#include "../interfaces/view.h"

/**
   Utility: selection sort
   sort a QMemArray<uint> in ascending order.
   max it the largest (zerobased) index to sort.
   To sort the entire array: ssort( *array, array.size() -1 );
   This is only efficient if ran only once.
*/
static void ssort( QMemArray<uint> &a, int max )
{
  uint tmp, j, maxpos;
  for ( uint h = max; h >= 1; h-- )
  {
    maxpos = 0;
    for ( j = 0; j <= h; j++ )
      maxpos = a[j] > a[maxpos] ? j : maxpos;
    tmp = a[maxpos];
    a[maxpos] = a[h];
    a[h] = tmp;
  }
}

// TODO add a insort() or bubble_sort - more efficient for aboutToShow() ?

KateBookmarks::KateBookmarks( Kate::View* view, Sorting sort )
  : QObject( view, "kate bookmarks" )
  , m_view( view )
  , m_sorting( sort )
{
}

KateBookmarks::~KateBookmarks()
{
}

void KateBookmarks::createActions( KActionCollection* ac )
{
  m_bookmarkMenu = new KActionMenu(
    i18n("&Bookmarks"), ac, "bookmarks" );
  m_bookmarkMenu->setWhatsThis(i18n("Bookmark manipulation"));
  QPopupMenu *m = m_bookmarkMenu->popupMenu ();

  // setup bookmark menu
  m_bookmarkToggle = new KAction(
    i18n("Toggle &Bookmark"), CTRL+Key_B,
    this, SLOT(toggleBookmark()),
    ac, "bookmarks_toggle" );
  m_bookmarkToggle->setWhatsThis(i18n("If a line has no bookmark then add one, otherwise remove it."));

  m_bookmarkClear = new KAction(
    i18n("Clear Bookmarks"), 0,
    this, SLOT(clearBookmarks()),
    ac, "bookmarks_clear");
  m_bookmarkClear->setWhatsThis(i18n("Remove all bookmarks of the current document."));

  m_goNext = new KAction(
    "Next Bookmark", ALT + Key_PageDown,
    this, SLOT(goNext()),
    ac, "bookmarks_next");
  m_goNext->setWhatsThis(i18n("Go to the nearest next bookmark."));

  m_goPrevious = new KAction(
    "Previous Bookmark", ALT + Key_PageUp,
    this, SLOT(goPrevious()),
    ac, "bookmarks_previous");
  m_goPrevious->setWhatsThis(i18n("Go to the nearest previous bookmark."));

  // connect bookmarks menu aboutToshow
  connect( m, SIGNAL(aboutToShow()),
           this, SLOT(bookmarkMenuAboutToShow()));

  // anders: I ensure the next/prev actions are available
  // and reset their texts (for edit shortcuts dialog, call me picky!).
  // TODO - come up with a better solution, please anyone?
  connect( m, SIGNAL(aboutToHide()),
           this, SLOT(bookmarkMenuAboutToHide()) );
}

void KateBookmarks::toggleBookmark ()
{
  uint mark = m_view->getDoc()->mark( m_view->cursorLine() );
  if( mark & KTextEditor::MarkInterface::markType01 )
    m_view->getDoc()->removeMark( m_view->cursorLine(),
        KTextEditor::MarkInterface::markType01 );
  else
    m_view->getDoc()->addMark( m_view->cursorLine(),
        KTextEditor::MarkInterface::markType01 );
}

void KateBookmarks::clearBookmarks ()
{
  m_marks = m_view->getDoc()->marks();
  QPtrListIterator<KTextEditor::Mark> it( m_marks );
  for( ; *it; ++it ) {
    m_view->getDoc()->removeMark( (*it)->line, KTextEditor::MarkInterface::markType01 );
  }
}

void KateBookmarks::bookmarkMenuAboutToShow()
{
  m_bookmarkMenu->popupMenu()->clear();
  m_bookmarkToggle->plug( m_bookmarkMenu->popupMenu() );
  m_bookmarkClear->plug( m_bookmarkMenu->popupMenu() );
  m_goNext->plug( m_bookmarkMenu->popupMenu() );
  m_goPrevious->plug( m_bookmarkMenu->popupMenu() );

  KTextEditor::Mark *next = 0;
  KTextEditor::Mark *prev = 0;
  uint line = m_view->cursorLine();

  const QRegExp re("&(?!&)");
  m_marks = m_view->getDoc()->marks();
  int idx( -1 );
  QMemArray<uint> sortArray( m_marks.count() );
  QPtrListIterator<KTextEditor::Mark> it( m_marks );
  if ( it.count() > 0 )
        m_bookmarkMenu->popupMenu()->insertSeparator();
  for( int i = 0; *it; ++it, ++i ) {
    if( (*it)->type & KTextEditor::MarkInterface::markType01 ) {
      QString bText = KStringHandler::rsqueeze( m_view->getDoc()->textLine( (*it)->line ), 32 );
      bText.replace(re, "&&"); // kill undesired accellerators!
      if ( m_sorting == Position )
      {
        sortArray[i] = (*it)->line;
        ssort( sortArray, i );
        idx = sortArray.find( (*it)->line ) + 3;
      }
        m_bookmarkMenu->popupMenu()->insertItem(
        QString("%1 - \"%2\"").arg( (*it)->line+1 ).arg( bText ),
        this, SLOT (gotoBookmark(int)), 0, i, idx );
      if ( (*it)->line < line )
      {
        if ( ! prev || prev->line < (*it)->line )
          prev = (*it);
      }
      else if ( (*it)->line > line )
      {
        if ( ! next || next->line > (*it)->line )
          next = (*it);
      }
    }
  }

  idx = 3;
  if ( next )
  {
    m_goNext->setText( i18n("&Next: %1 - \"%2\"").arg( next->line + 1 )
        .arg( KStringHandler::rsqueeze( m_view->getDoc()->textLine( next->line ), 24 ) ) );
    m_goNext->plug( m_bookmarkMenu->popupMenu(), idx );
    idx++;
  }
  if ( prev )
  {
    m_goPrevious->setText( i18n("&Previous: %1 - \"%2\"").arg(prev->line + 1 )
        .arg( KStringHandler::rsqueeze( m_view->getDoc()->textLine( prev->line ), 24 ) ) );
    m_goPrevious->plug( m_bookmarkMenu->popupMenu(), idx );
    idx++;
  }
  if ( next || prev )
    m_bookmarkMenu->popupMenu()->insertSeparator( idx );
}

/*
   Make sure next/prev actions are plugged, and have a clean text
*/
void KateBookmarks::bookmarkMenuAboutToHide()
{
  m_goNext->setText( i18n("Next Bookmark") );
  m_goNext->plug( m_bookmarkMenu->popupMenu() );
  m_goPrevious->setText( i18n("Previous Bookmark") );
  m_goPrevious->plug( m_bookmarkMenu->popupMenu() );
}

void KateBookmarks::gotoBookmark( int n )
{
  m_view->setCursorPosition( m_marks.at(n)->line, 0 );
}

void KateBookmarks::goNext()
{
  m_marks = m_view->getDoc()->marks();
  if ( ! m_marks.count() )
    return;

  uint line = m_view->cursorLine();
  QMemArray<uint> a( m_marks.count() );
  QPtrListIterator<KTextEditor::Mark> it( m_marks );
  for ( int i=0; *it; ++i, ++it )
    a[i] = (*it)->line;
  ssort( a, m_marks.count()-1 );
  for ( uint j=0; j < m_marks.count() ; j++ )
  {
    if ( a[j] > line )
    {
      m_view->setCursorPosition( a[j], 0 );
      return;
    }
  }
}

void KateBookmarks::goPrevious()
{
  m_marks = m_view->getDoc()->marks();
  if ( ! m_marks.count() )
    return;

  uint line = m_view->cursorLine();
  QMemArray<uint> a( m_marks.count() );
  QPtrListIterator<KTextEditor::Mark> it( m_marks );
  for ( int i=0; *it; ++i, ++it )
    a[i] = (*it)->line;
  ssort( a, m_marks.count()-1 );
  for ( int j = m_marks.count() - 1; j >= 0 ; j-- )
  {
    if ( a[j] < line )
    {
      m_view->setCursorPosition( a[j], 0 );
      return;
    }
  }
}

// vim: noet ts=2
<commit_msg>use an em squeeze to get the bookmark list to line up nicer<commit_after>/* This file is part of the KDE libraries
   Copyright (C) 2002 John Firebaugh <jfirebaugh@kde.org>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public
   License version 2 as published by the Free Software Foundation.

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

   You should have received a copy of the GNU Library General Public License
   along with this library; see the file COPYING.LIB.  If not, write to
   the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.
*/

 // $Id$

#include "katebookmarks.h"
#include "katebookmarks.moc"

#include <klocale.h>
#include <kaction.h>
#include <kpopupmenu.h>
#include <kstringhandler.h>
#include <kdebug.h>

#include <qregexp.h>
#include <qmemarray.h>

#include "../interfaces/document.h"
#include "../interfaces/view.h"

/**
   Utility: selection sort
   sort a QMemArray<uint> in ascending order.
   max it the largest (zerobased) index to sort.
   To sort the entire array: ssort( *array, array.size() -1 );
   This is only efficient if ran only once.
*/
static void ssort( QMemArray<uint> &a, int max )
{
  uint tmp, j, maxpos;
  for ( uint h = max; h >= 1; h-- )
  {
    maxpos = 0;
    for ( j = 0; j <= h; j++ )
      maxpos = a[j] > a[maxpos] ? j : maxpos;
    tmp = a[maxpos];
    a[maxpos] = a[h];
    a[h] = tmp;
  }
}

// TODO add a insort() or bubble_sort - more efficient for aboutToShow() ?

KateBookmarks::KateBookmarks( Kate::View* view, Sorting sort )
  : QObject( view, "kate bookmarks" )
  , m_view( view )
  , m_sorting( sort )
{
}

KateBookmarks::~KateBookmarks()
{
}

void KateBookmarks::createActions( KActionCollection* ac )
{
  m_bookmarkMenu = new KActionMenu(
    i18n("&Bookmarks"), ac, "bookmarks" );
  m_bookmarkMenu->setWhatsThis(i18n("Bookmark manipulation"));
  QPopupMenu *m = m_bookmarkMenu->popupMenu ();

  // setup bookmark menu
  m_bookmarkToggle = new KAction(
    i18n("Toggle &Bookmark"), CTRL+Key_B,
    this, SLOT(toggleBookmark()),
    ac, "bookmarks_toggle" );
  m_bookmarkToggle->setWhatsThis(i18n("If a line has no bookmark then add one, otherwise remove it."));

  m_bookmarkClear = new KAction(
    i18n("Clear Bookmarks"), 0,
    this, SLOT(clearBookmarks()),
    ac, "bookmarks_clear");
  m_bookmarkClear->setWhatsThis(i18n("Remove all bookmarks of the current document."));

  m_goNext = new KAction(
    "Next Bookmark", ALT + Key_PageDown,
    this, SLOT(goNext()),
    ac, "bookmarks_next");
  m_goNext->setWhatsThis(i18n("Go to the nearest next bookmark."));

  m_goPrevious = new KAction(
    "Previous Bookmark", ALT + Key_PageUp,
    this, SLOT(goPrevious()),
    ac, "bookmarks_previous");
  m_goPrevious->setWhatsThis(i18n("Go to the nearest previous bookmark."));

  // connect bookmarks menu aboutToshow
  connect( m, SIGNAL(aboutToShow()),
           this, SLOT(bookmarkMenuAboutToShow()));

  // anders: I ensure the next/prev actions are available
  // and reset their texts (for edit shortcuts dialog, call me picky!).
  // TODO - come up with a better solution, please anyone?
  connect( m, SIGNAL(aboutToHide()),
           this, SLOT(bookmarkMenuAboutToHide()) );
}

void KateBookmarks::toggleBookmark ()
{
  uint mark = m_view->getDoc()->mark( m_view->cursorLine() );
  if( mark & KTextEditor::MarkInterface::markType01 )
    m_view->getDoc()->removeMark( m_view->cursorLine(),
        KTextEditor::MarkInterface::markType01 );
  else
    m_view->getDoc()->addMark( m_view->cursorLine(),
        KTextEditor::MarkInterface::markType01 );
}

void KateBookmarks::clearBookmarks ()
{
  m_marks = m_view->getDoc()->marks();
  QPtrListIterator<KTextEditor::Mark> it( m_marks );
  for( ; *it; ++it ) {
    m_view->getDoc()->removeMark( (*it)->line, KTextEditor::MarkInterface::markType01 );
  }
}

void KateBookmarks::bookmarkMenuAboutToShow()
{
  m_bookmarkMenu->popupMenu()->clear();
  m_bookmarkToggle->plug( m_bookmarkMenu->popupMenu() );
  m_bookmarkClear->plug( m_bookmarkMenu->popupMenu() );
  m_goNext->plug( m_bookmarkMenu->popupMenu() );
  m_goPrevious->plug( m_bookmarkMenu->popupMenu() );

  KTextEditor::Mark *next = 0;
  KTextEditor::Mark *prev = 0;
  uint line = m_view->cursorLine();

  const QRegExp re("&(?!&)");
  m_marks = m_view->getDoc()->marks();
  int idx( -1 );
  QMemArray<uint> sortArray( m_marks.count() );
  QPtrListIterator<KTextEditor::Mark> it( m_marks );
  if ( it.count() > 0 )
        m_bookmarkMenu->popupMenu()->insertSeparator();
  for( int i = 0; *it; ++it, ++i ) {
    if( (*it)->type & KTextEditor::MarkInterface::markType01 ) {
      QString bText = KStringHandler::rEmSqueeze
                      ( m_view->getDoc()->textLine( (*it)->line ),
                        m_bookmarkMenu->popupMenu()->fontMetrics(), 32 );
      bText.replace(re, "&&"); // kill undesired accellerators!
      if ( m_sorting == Position )
      {
        sortArray[i] = (*it)->line;
        ssort( sortArray, i );
        idx = sortArray.find( (*it)->line ) + 3;
      }
        m_bookmarkMenu->popupMenu()->insertItem(
        QString("%1 - \"%2\"").arg( (*it)->line+1 ).arg( bText ),
        this, SLOT (gotoBookmark(int)), 0, i, idx );
      if ( (*it)->line < line )
      {
        if ( ! prev || prev->line < (*it)->line )
          prev = (*it);
      }
      else if ( (*it)->line > line )
      {
        if ( ! next || next->line > (*it)->line )
          next = (*it);
      }
    }
  }

  idx = 3;
  if ( next )
  {
    m_goNext->setText( i18n("&Next: %1 - \"%2\"").arg( next->line + 1 )
        .arg( KStringHandler::rsqueeze( m_view->getDoc()->textLine( next->line ), 24 ) ) );
    m_goNext->plug( m_bookmarkMenu->popupMenu(), idx );
    idx++;
  }
  if ( prev )
  {
    m_goPrevious->setText( i18n("&Previous: %1 - \"%2\"").arg(prev->line + 1 )
        .arg( KStringHandler::rsqueeze( m_view->getDoc()->textLine( prev->line ), 24 ) ) );
    m_goPrevious->plug( m_bookmarkMenu->popupMenu(), idx );
    idx++;
  }
  if ( next || prev )
    m_bookmarkMenu->popupMenu()->insertSeparator( idx );
}

/*
   Make sure next/prev actions are plugged, and have a clean text
*/
void KateBookmarks::bookmarkMenuAboutToHide()
{
  m_goNext->setText( i18n("Next Bookmark") );
  m_goNext->plug( m_bookmarkMenu->popupMenu() );
  m_goPrevious->setText( i18n("Previous Bookmark") );
  m_goPrevious->plug( m_bookmarkMenu->popupMenu() );
}

void KateBookmarks::gotoBookmark( int n )
{
  m_view->setCursorPosition( m_marks.at(n)->line, 0 );
}

void KateBookmarks::goNext()
{
  m_marks = m_view->getDoc()->marks();
  if ( ! m_marks.count() )
    return;

  uint line = m_view->cursorLine();
  QMemArray<uint> a( m_marks.count() );
  QPtrListIterator<KTextEditor::Mark> it( m_marks );
  for ( int i=0; *it; ++i, ++it )
    a[i] = (*it)->line;
  ssort( a, m_marks.count()-1 );
  for ( uint j=0; j < m_marks.count() ; j++ )
  {
    if ( a[j] > line )
    {
      m_view->setCursorPosition( a[j], 0 );
      return;
    }
  }
}

void KateBookmarks::goPrevious()
{
  m_marks = m_view->getDoc()->marks();
  if ( ! m_marks.count() )
    return;

  uint line = m_view->cursorLine();
  QMemArray<uint> a( m_marks.count() );
  QPtrListIterator<KTextEditor::Mark> it( m_marks );
  for ( int i=0; *it; ++i, ++it )
    a[i] = (*it)->line;
  ssort( a, m_marks.count()-1 );
  for ( int j = m_marks.count() - 1; j >= 0 ; j-- )
  {
    if ( a[j] < line )
    {
      m_view->setCursorPosition( a[j], 0 );
      return;
    }
  }
}

// vim: noet ts=2
<|endoftext|>


<commit_before>
#include <iostream>

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#undef WIN32_LEAN_AND_MEAN
#include <ddraw.h>

#include "evas_common.h"
#include "evas_engine.h"

typedef LONG (*fct_DirectDrawCreate)(LPGUID, LPUNKNOWN *, LPUNKNOWN *);

fct_DirectDrawCreate lib_DirectDrawCreate;

typedef struct Evas_Engine_WinCE_DDraw_Priv Evas_Engine_WinCE_DDraw_Priv;

struct Evas_Engine_WinCE_DDraw_Priv
{
   HMODULE             module;
   LPDIRECTDRAW        object;
   LPDIRECTDRAWSURFACE surface;
   int                 width;
   int                 height;
   int                 stride;
};

void *
evas_software_wince_ddraw_init(HWND window,
                               int  width,
                               int  height)
{
   DDSURFACEDESC                 surface_desc;
   Evas_Engine_WinCE_DDraw_Priv *priv;
   HRESULT                       res;

   priv = (Evas_Engine_WinCE_DDraw_Priv *)malloc(sizeof(Evas_Engine_WinCE_DDraw_Priv));
   if (!priv)
     return NULL;

   priv->module = LoadLibrary(L"ddraw.dll");
   if (!priv->module)
     {
        std::cerr << "[Evas] [Engine] [WinCE DDraw] Can not load ddraw.dll" << std::endl;
        goto free_priv;
     }

   lib_DirectDrawCreate = (fct_DirectDrawCreate)GetProcAddress(priv->module, L"DirectDrawCreate");
   if (!lib_DirectDrawCreate)
     {
        std::cerr << "[Evas] [Engine] [WinCE DDraw] Can not initialize DirectDraw" << std::endl;
        goto free_lib;
     }

   res = lib_DirectDrawCreate(NULL, (IUnknown**)&priv->object, NULL);
   if (FAILED(res))
     {
        std::cerr << "[Evas] [Engine] [WinCE DDraw] Can not create DirectDraw object" << std::endl;
        goto free_lib;
     }

   res = priv->object->SetCooperativeLevel(window, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN);
   if (FAILED(res))
     {
        std::cerr<< "[Evas] [Engine] [WinCE DDraw] Can not set window to fullscreen" << std::endl;
        goto release_object;
     }

   memset(&surface_desc, 0, sizeof(surface_desc));
   surface_desc.dwSize = sizeof(surface_desc);
   surface_desc.dwFlags = DDSD_CAPS;
   surface_desc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;

   res = priv->object->CreateSurface(&surface_desc, &priv->surface, NULL);
   if (FAILED(res))
     {
        std::cerr << "[Evas] [Engine] [WinCE DDraw] Can not create surface" << std::endl;
        goto release_object;
     }

   memset(&surface_desc, 0, sizeof(surface_desc));
   surface_desc.dwSize = sizeof(surface_desc);
   res = priv->surface->Lock(NULL, &surface_desc, DDLOCK_READONLY, NULL);
   if (FAILED(res))
     {
        std::cerr << "[Evas] [Engine] [WinCE DDraw] Can not lock surface" << std::endl;
        goto release_surface;
     }

   priv->width = surface_desc.dwWidth;
   priv->height = surface_desc.dwHeight;
   priv->stride = surface_desc.lPitch / 2;

   if ((priv->width != width) ||
       (priv->height != height))
     {
        std::cerr << "[Evas] [Engine] [WinCE DDraw] Size mismatch" << std::endl;
        std::cerr << "[Evas] [Engine] [WinCE DDraw] asked: " << width << "x" << height << std::endl;
        std::cerr << "[Evas] [Engine] [WinCE DDraw] got  : " << priv->width << "x" << priv->height << std::endl;
        goto release_surface;
     }

   res = priv->surface->Unlock(NULL);
   if (FAILED(res))
     {
        std::cerr << "[Evas] [Engine] [WinCE DDraw] Can not unlock surface" << std::endl;
        goto release_surface;
     }

   return priv;

 release_surface:
   priv->surface->Release();
 release_object:
   priv->object->Release();
 free_lib:
   FreeLibrary(priv->module);
 free_priv:
   free(priv);

  return 0;
}

void
evas_software_wince_ddraw_shutdown(void *priv)
{
   ((Evas_Engine_WinCE_DDraw_Priv *)priv)->surface->Release();
   ((Evas_Engine_WinCE_DDraw_Priv *)priv)->object->Release();
   FreeLibrary(((Evas_Engine_WinCE_DDraw_Priv *)priv)->module);
   free(priv);
}

FB_Output_Buffer *
evas_software_wince_ddraw_output_buffer_new(void *priv,
                                            int   width,
                                            int   height)
{
   FB_Output_Buffer *fbob;
   void             *buffer;

   fbob = (FB_Output_Buffer *)calloc(1, sizeof(FB_Output_Buffer));
   if (!fbob) return NULL;

   buffer = malloc (width * height * 2); /* we are sure to have 16bpp */
   if (!buffer)
     {
        free(fbob);
        return NULL;
     }

   fbob->priv = priv;

   fbob->im = (Soft16_Image *) evas_cache_image_data(evas_common_soft16_image_cache_get(), width, height, (DATA32 *)buffer, 0, EVAS_COLORSPACE_RGB565_A5P);
   if (fbob->im)
     fbob->im->stride = ((Evas_Engine_WinCE_DDraw_Priv *)priv)->stride;

   return fbob;
}

void
evas_software_wince_ddraw_output_buffer_free(FB_Output_Buffer *fbob)
{
   free(fbob->im->pixels);
   free(fbob);
}

void
evas_software_wince_ddraw_output_buffer_paste(FB_Output_Buffer *fbob)
{
   DDSURFACEDESC                 surface_desc;
   Evas_Engine_WinCE_DDraw_Priv *priv;
   HRESULT                       res;

   priv = (Evas_Engine_WinCE_DDraw_Priv *)fbob->priv;

   memset(&surface_desc, 0, sizeof(surface_desc));
   surface_desc.dwSize = sizeof(surface_desc);
   res = priv->surface->Lock(NULL, &surface_desc, DDLOCK_WRITEONLY, NULL);
   if (FAILED(res))
     return;

   if ((fbob->im->cache_entry.w == surface_desc.dwWidth) &&
       (fbob->im->cache_entry.h == surface_desc.dwHeight))
     memcpy(surface_desc.lpSurface, fbob->im->pixels,
            surface_desc.dwWidth * surface_desc.dwHeight * 2);

   priv->surface->Unlock(NULL);
}

void
evas_software_wince_ddraw_surface_resize(FB_Output_Buffer *fbob)
{
}
<commit_msg>Use stdio instead of iostream to output error messages<commit_after>
#include <cstdio>

#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#undef WIN32_LEAN_AND_MEAN
#include <ddraw.h>

#include "evas_common.h"
#include "evas_engine.h"

typedef LONG (*fct_DirectDrawCreate)(LPGUID, LPUNKNOWN *, LPUNKNOWN *);

fct_DirectDrawCreate lib_DirectDrawCreate;

typedef struct Evas_Engine_WinCE_DDraw_Priv Evas_Engine_WinCE_DDraw_Priv;

struct Evas_Engine_WinCE_DDraw_Priv
{
   HMODULE             module;
   LPDIRECTDRAW        object;
   LPDIRECTDRAWSURFACE surface;
   int                 width;
   int                 height;
   int                 stride;
};

void *
evas_software_wince_ddraw_init(HWND window,
                               int  width,
                               int  height)
{
   DDSURFACEDESC                 surface_desc;
   Evas_Engine_WinCE_DDraw_Priv *priv;
   HRESULT                       res;

   priv = (Evas_Engine_WinCE_DDraw_Priv *)malloc(sizeof(Evas_Engine_WinCE_DDraw_Priv));
   if (!priv)
     return NULL;

   priv->module = LoadLibrary(L"ddraw.dll");
   if (!priv->module)
     {
        fprintf(stderr, "[Evas] [Engine] [WinCE DDraw] Can not load ddraw.dll\n");
        goto free_priv;
     }

   lib_DirectDrawCreate = (fct_DirectDrawCreate)GetProcAddress(priv->module, L"DirectDrawCreate");
   if (!lib_DirectDrawCreate)
     {
        fprintf(stderr, "[Evas] [Engine] [WinCE DDraw] Can not initialize DirectDraw\n");
        goto free_lib;
     }

   res = lib_DirectDrawCreate(NULL, (IUnknown**)&priv->object, NULL);
   if (FAILED(res))
     {
        fprintf(stderr, "[Evas] [Engine] [WinCE DDraw] Can not create DirectDraw object\n");
        goto free_lib;
     }

   res = priv->object->SetCooperativeLevel(window, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN);
   if (FAILED(res))
     {
        fprintf(stderr, "[Evas] [Engine] [WinCE DDraw] Can not set window to fullscreen\n");
        goto release_object;
     }

   memset(&surface_desc, 0, sizeof(surface_desc));
   surface_desc.dwSize = sizeof(surface_desc);
   surface_desc.dwFlags = DDSD_CAPS;
   surface_desc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;

   res = priv->object->CreateSurface(&surface_desc, &priv->surface, NULL);
   if (FAILED(res))
     {
        fprintf(stderr, "[Evas] [Engine] [WinCE DDraw] Can not create surface\n");
        goto release_object;
     }

   memset(&surface_desc, 0, sizeof(surface_desc));
   surface_desc.dwSize = sizeof(surface_desc);
   res = priv->surface->Lock(NULL, &surface_desc, DDLOCK_READONLY, NULL);
   if (FAILED(res))
     {
        fprintf(stderr, "[Evas] [Engine] [WinCE DDraw] Can not lock surface\n");
        goto release_surface;
     }

   priv->width = surface_desc.dwWidth;
   priv->height = surface_desc.dwHeight;
   priv->stride = surface_desc.lPitch / 2;

   if ((priv->width != width) ||
       (priv->height != height))
     {
        fprintf(stderr, "[Evas] [Engine] [WinCE DDraw] Size mismatch\n");
        fprintf(stderr, "[Evas] [Engine] [WinCE DDraw] asked : %dx%d\n", width, height);
        fprintf(stderr, "[Evas] [Engine] [WinCE DDraw] got   : %dx%d\n", priv->width, priv->height);
        goto release_surface;
     }

   res = priv->surface->Unlock(NULL);
   if (FAILED(res))
     {
        fprintf(stderr, "[Evas] [Engine] [WinCE DDraw] Can not unlock surface\n");
        goto release_surface;
     }

   return priv;

 release_surface:
   priv->surface->Release();
 release_object:
   priv->object->Release();
 free_lib:
   FreeLibrary(priv->module);
 free_priv:
   free(priv);

  return 0;
}

void
evas_software_wince_ddraw_shutdown(void *priv)
{
   ((Evas_Engine_WinCE_DDraw_Priv *)priv)->surface->Release();
   ((Evas_Engine_WinCE_DDraw_Priv *)priv)->object->Release();
   FreeLibrary(((Evas_Engine_WinCE_DDraw_Priv *)priv)->module);
   free(priv);
}

FB_Output_Buffer *
evas_software_wince_ddraw_output_buffer_new(void *priv,
                                            int   width,
                                            int   height)
{
   FB_Output_Buffer *fbob;
   void             *buffer;

   fbob = (FB_Output_Buffer *)calloc(1, sizeof(FB_Output_Buffer));
   if (!fbob) return NULL;

   buffer = malloc (width * height * 2); /* we are sure to have 16bpp */
   if (!buffer)
     {
        free(fbob);
        return NULL;
     }

   fbob->priv = priv;

   fbob->im = (Soft16_Image *) evas_cache_image_data(evas_common_soft16_image_cache_get(), width, height, (DATA32 *)buffer, 0, EVAS_COLORSPACE_RGB565_A5P);
   if (fbob->im)
     fbob->im->stride = ((Evas_Engine_WinCE_DDraw_Priv *)priv)->stride;

   return fbob;
}

void
evas_software_wince_ddraw_output_buffer_free(FB_Output_Buffer *fbob)
{
   free(fbob->im->pixels);
   free(fbob);
}

void
evas_software_wince_ddraw_output_buffer_paste(FB_Output_Buffer *fbob)
{
   DDSURFACEDESC                 surface_desc;
   Evas_Engine_WinCE_DDraw_Priv *priv;
   HRESULT                       res;

   priv = (Evas_Engine_WinCE_DDraw_Priv *)fbob->priv;

   memset(&surface_desc, 0, sizeof(surface_desc));
   surface_desc.dwSize = sizeof(surface_desc);
   res = priv->surface->Lock(NULL, &surface_desc, DDLOCK_WRITEONLY, NULL);
   if (FAILED(res))
     return;

   if ((fbob->im->cache_entry.w == surface_desc.dwWidth) &&
       (fbob->im->cache_entry.h == surface_desc.dwHeight))
     memcpy(surface_desc.lpSurface, fbob->im->pixels,
            surface_desc.dwWidth * surface_desc.dwHeight * 2);

   priv->surface->Unlock(NULL);
}

void
evas_software_wince_ddraw_surface_resize(FB_Output_Buffer *fbob)
{
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include <stdio.h>
#include "db/dbformat.h"
#include "db/version_set.h"
#include "port/port.h"
#include "util/coding.h"

namespace leveldb {

static uint64_t PackSequenceAndType(uint64_t seq, ValueType t) {
  assert(seq <= kMaxSequenceNumber);
  assert(t <= kValueTypeForSeek);
  return (seq << 8) | t;
}

void AppendInternalKey(std::string* result, const ParsedInternalKey& key) {
  result->append(key.user_key.data(), key.user_key.size());
  PutFixed64(result, PackSequenceAndType(key.sequence, key.type));
}

std::string ParsedInternalKey::DebugString() const {
  char buf[50];
  snprintf(buf, sizeof(buf), "' @ %llu : %d",
           (unsigned long long) sequence,
           int(type));
  std::string result = "'";
  result += HexString(user_key.ToString());
  result += buf;
  return result;
}

std::string ParsedInternalKey::DebugStringHex() const {
  char buf[50];
  snprintf(buf, sizeof(buf), "' @ %llu : %d",
           (unsigned long long) sequence,
           int(type));
  std::string result = "'";
  result += HexString(user_key);
  result += buf;
  return result;
}

std::string InternalKey::DebugString() const {
  std::string result;
  ParsedInternalKey parsed;
  if (ParseInternalKey(rep_, &parsed)) {
    result = parsed.DebugString();
  } else {
    result = "(bad)";
    result.append(EscapeString(rep_));
  }
  return result;
}

const char* InternalKeyComparator::Name() const {
  return "leveldb.InternalKeyComparator";
}

int InternalKeyComparator::Compare(const Slice& akey, const Slice& bkey) const {
  // Order by:
  //    increasing user key (according to user-supplied comparator)
  //    decreasing sequence number
  //    decreasing type (though sequence# should be enough to disambiguate)
  int r = user_comparator_->Compare(ExtractUserKey(akey), ExtractUserKey(bkey));
  if (r == 0) {
    const uint64_t anum = DecodeFixed64(akey.data() + akey.size() - 8);
    const uint64_t bnum = DecodeFixed64(bkey.data() + bkey.size() - 8);
    if (anum > bnum) {
      r = -1;
    } else if (anum < bnum) {
      r = +1;
    }
  }
  return r;
}

void InternalKeyComparator::FindShortestSeparator(
      std::string* start,
      const Slice& limit) const {
  // Attempt to shorten the user portion of the key
  Slice user_start = ExtractUserKey(*start);
  Slice user_limit = ExtractUserKey(limit);
  std::string tmp(user_start.data(), user_start.size());
  user_comparator_->FindShortestSeparator(&tmp, user_limit);
  if (tmp.size() < user_start.size() &&
      user_comparator_->Compare(user_start, tmp) < 0) {
    // User key has become shorter physically, but larger logically.
    // Tack on the earliest possible number to the shortened user key.
    PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));
    assert(this->Compare(*start, tmp) < 0);
    assert(this->Compare(tmp, limit) < 0);
    start->swap(tmp);
  }
}

void InternalKeyComparator::FindShortSuccessor(std::string* key) const {
  Slice user_key = ExtractUserKey(*key);
  std::string tmp(user_key.data(), user_key.size());
  user_comparator_->FindShortSuccessor(&tmp);
  if (tmp.size() < user_key.size() &&
      user_comparator_->Compare(user_key, tmp) < 0) {
    // User key has become shorter physically, but larger logically.
    // Tack on the earliest possible number to the shortened user key.
    PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));
    assert(this->Compare(*key, tmp) < 0);
    key->swap(tmp);
  }
}

const char* InternalFilterPolicy::Name() const {
  return user_policy_->Name();
}

void InternalFilterPolicy::CreateFilter(const Slice* keys, int n,
                                        std::string* dst) const {
  // We rely on the fact that the code in table.cc does not mind us
  // adjusting keys[].
  Slice* mkey = const_cast<Slice*>(keys);
  for (int i = 0; i < n; i++) {
    mkey[i] = ExtractUserKey(keys[i]);
    // TODO(sanjay): Suppress dups?
  }
  user_policy_->CreateFilter(keys, n, dst);
}

bool InternalFilterPolicy::KeyMayMatch(const Slice& key, const Slice& f) const {
  return user_policy_->KeyMayMatch(ExtractUserKey(key), f);
}

LookupKey::LookupKey(const Slice& user_key, SequenceNumber s) {
  size_t usize = user_key.size();
  size_t needed = usize + 13;  // A conservative estimate
  char* dst;
  if (needed <= sizeof(space_)) {
    dst = space_;
  } else {
    dst = new char[needed];
  }
  start_ = dst;
  dst = EncodeVarint32(dst, usize + 8);
  kstart_ = dst;
  memcpy(dst, user_key.data(), usize);
  dst += usize;
  EncodeFixed64(dst, PackSequenceAndType(s, kValueTypeForSeek));
  dst += 8;
  end_ = dst;
}

KeyRetirement::KeyRetirement(
    const Comparator * Comparator,
    SequenceNumber SmallestSnapshot,
    Compaction * const Compaction)
    : has_current_user_key(false), last_sequence_for_key(kMaxSequenceNumber),
      user_comparator(Comparator), smallest_snapshot(SmallestSnapshot),
      compaction(Compaction),
      valid(false)
{
    // NULL is ok for compaction
    valid=(NULL!=user_comparator);

    return;
}   // KeyRetirement::KeyRetirement

bool
KeyRetirement::operator()(
    Slice & key)
{
    ParsedInternalKey ikey;
    bool drop = false;

    if (valid)
    {
        if (!ParseInternalKey(key, &ikey))
        {
            // Do not hide error keys
            current_user_key.clear();
            has_current_user_key = false;
            last_sequence_for_key = kMaxSequenceNumber;
        }   // else
        else
        {
            if (!has_current_user_key ||
                user_comparator->Compare(ikey.user_key,
                                         Slice(current_user_key)) != 0)
            {
                // First occurrence of this user key
                current_user_key.assign(ikey.user_key.data(), ikey.user_key.size());
                has_current_user_key = true;
                last_sequence_for_key = kMaxSequenceNumber;
            }   // if

            if (last_sequence_for_key <= smallest_snapshot)
            {
                // Hidden by an newer entry for same user key
                drop = true;    // (A)
            }   // if

            else if (ikey.type == kTypeDeletion
                     && ikey.sequence <= smallest_snapshot
                     && NULL!=compaction  // mem to level0 ignores this test
                     && compaction->IsBaseLevelForKey(ikey.user_key))
            {
                // For this user key:
                // (1) there is no data in higher levels
                // (2) data in lower levels will have larger sequence numbers
                // (3) data in layers that are being compacted here and have
                //     smaller sequence numbers will be dropped in the next
                //     few iterations of this loop (by rule (A) above).
                // Therefore this deletion marker is obsolete and can be dropped.
                drop = true;
            }   // else if

            last_sequence_for_key = ikey.sequence;
        }   // else
    }   // if

#if 0
    // needs clean up to be used again
    Log(options_.info_log,
        "  Compact: %s, seq %d, type: %d %d, drop: %d, is_base: %d, "
        "%d smallest_snapshot: %d",
        ikey.user_key.ToString().c_str(),
        (int)ikey.sequence, ikey.type, kTypeValue, drop,
        compact->compaction->IsBaseLevelForKey(ikey.user_key),
        (int)last_sequence_for_key, (int)compact->smallest_snapshot);
#endif
    return(drop);

}   // KeyRetirement::operator(Slice & )

}  // namespace leveldb
<commit_msg>Update ParsedInternalKey routines to be expiry aware.  Update Compare() function to handle Expire type as if plain Value type<commit_after>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include <stdio.h>
#include "db/dbformat.h"
#include "db/version_set.h"
#include "port/port.h"
#include "util/coding.h"

namespace leveldb {

static uint64_t PackSequenceAndType(uint64_t seq, ValueType t) {
  assert(seq <= kMaxSequenceNumber);
  assert(t <= kValueTypeForSeek);
  return (seq << 8) | t;
}

void AppendInternalKey(std::string* result, const ParsedInternalKey& key) {
  result->append(key.user_key.data(), key.user_key.size());
  if (IsExpiryKey(key.type))
    PutFixed64(result, key.expiry);
  PutFixed64(result, PackSequenceAndType(key.sequence, key.type));
}

std::string ParsedInternalKey::DebugString() const {
  char buf[50];
  if (IsExpiryKey(type))
    snprintf(buf, sizeof(buf), "' @ %llu %llu : %d",
             (unsigned long long) expiry,
             (unsigned long long) sequence,
             int(type));
  else
    snprintf(buf, sizeof(buf), "' @ %llu : %d",
             (unsigned long long) sequence,
             int(type));
  std::string result = "'";
  result += HexString(user_key.ToString());
  result += buf;
  return result;
}

std::string ParsedInternalKey::DebugStringHex() const {
  char buf[50];
  if (IsExpiryKey(type))
    snprintf(buf, sizeof(buf), "' @ %llu %llu : %d",
             (unsigned long long) expiry,
             (unsigned long long) sequence,
             int(type));
  else
    snprintf(buf, sizeof(buf), "' @ %llu : %d",
             (unsigned long long) sequence,
             int(type));
  std::string result = "'";
  result += HexString(user_key);
  result += buf;
  return result;
}

std::string InternalKey::DebugString() const {
  std::string result;
  ParsedInternalKey parsed;
  if (ParseInternalKey(rep_, &parsed)) {
    result = parsed.DebugString();
  } else {
    result = "(bad)";
    result.append(EscapeString(rep_));
  }
  return result;
}

const char* InternalKeyComparator::Name() const {
  return "leveldb.InternalKeyComparator";
}

int InternalKeyComparator::Compare(const Slice& akey, const Slice& bkey) const {
  // Order by:
  //    increasing user key (according to user-supplied comparator)
  //    decreasing sequence number
  //    decreasing type (though sequence# should be enough to disambiguate)
  int r = user_comparator_->Compare(ExtractUserKey(akey), ExtractUserKey(bkey));
  if (r == 0) {
    uint64_t anum = DecodeFixed64(akey.data() + akey.size() - 8);
    uint64_t bnum = DecodeFixed64(bkey.data() + bkey.size() - 8);
    if (IsExpiryKey((ValueType)*(unsigned char *)&anum)) *(unsigned char*)&anum=(unsigned char)kTypeValue;
    if (IsExpiryKey((ValueType)*(unsigned char *)&bnum)) *(unsigned char*)&bnum=(unsigned char)kTypeValue;
    if (anum > bnum) {
      r = -1;
    } else if (anum < bnum) {
      r = +1;
    }
  }
  return r;
}

void InternalKeyComparator::FindShortestSeparator(
      std::string* start,
      const Slice& limit) const {
  // Attempt to shorten the user portion of the key
  Slice user_start = ExtractUserKey(*start);
  Slice user_limit = ExtractUserKey(limit);
  std::string tmp(user_start.data(), user_start.size());
  user_comparator_->FindShortestSeparator(&tmp, user_limit);
  if (tmp.size() < user_start.size() &&
      user_comparator_->Compare(user_start, tmp) < 0) {
    // User key has become shorter physically, but larger logically.
    // Tack on the earliest possible number to the shortened user key.
    PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));
    assert(this->Compare(*start, tmp) < 0);
    assert(this->Compare(tmp, limit) < 0);
    start->swap(tmp);
  }
}

void InternalKeyComparator::FindShortSuccessor(std::string* key) const {
  Slice user_key = ExtractUserKey(*key);
  std::string tmp(user_key.data(), user_key.size());
  user_comparator_->FindShortSuccessor(&tmp);
  if (tmp.size() < user_key.size() &&
      user_comparator_->Compare(user_key, tmp) < 0) {
    // User key has become shorter physically, but larger logically.
    // Tack on the earliest possible number to the shortened user key.
    PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));
    assert(this->Compare(*key, tmp) < 0);
    key->swap(tmp);
  }
}

const char* InternalFilterPolicy::Name() const {
  return user_policy_->Name();
}

void InternalFilterPolicy::CreateFilter(const Slice* keys, int n,
                                        std::string* dst) const {
  // We rely on the fact that the code in table.cc does not mind us
  // adjusting keys[].
  Slice* mkey = const_cast<Slice*>(keys);
  for (int i = 0; i < n; i++) {
    mkey[i] = ExtractUserKey(keys[i]);
    // TODO(sanjay): Suppress dups?
  }
  user_policy_->CreateFilter(keys, n, dst);
}

bool InternalFilterPolicy::KeyMayMatch(const Slice& key, const Slice& f) const {
  return user_policy_->KeyMayMatch(ExtractUserKey(key), f);
}

LookupKey::LookupKey(const Slice& user_key, SequenceNumber s) {
  size_t usize = user_key.size();
  size_t needed = usize + 13;  // A conservative estimate
  char* dst;
  if (needed <= sizeof(space_)) {
    dst = space_;
  } else {
    dst = new char[needed];
  }
  start_ = dst;
  dst = EncodeVarint32(dst, usize + 8);
  kstart_ = dst;
  memcpy(dst, user_key.data(), usize);
  dst += usize;
  EncodeFixed64(dst, PackSequenceAndType(s, kValueTypeForSeek));
  dst += 8;
  end_ = dst;
}

KeyRetirement::KeyRetirement(
    const Comparator * Comparator,
    SequenceNumber SmallestSnapshot,
    Compaction * const Compaction)
    : has_current_user_key(false), last_sequence_for_key(kMaxSequenceNumber),
      user_comparator(Comparator), smallest_snapshot(SmallestSnapshot),
      compaction(Compaction),
      valid(false)
{
    // NULL is ok for compaction
    valid=(NULL!=user_comparator);

    return;
}   // KeyRetirement::KeyRetirement

bool
KeyRetirement::operator()(
    Slice & key)
{
    ParsedInternalKey ikey;
    bool drop = false;

    if (valid)
    {
        if (!ParseInternalKey(key, &ikey))
        {
            // Do not hide error keys
            current_user_key.clear();
            has_current_user_key = false;
            last_sequence_for_key = kMaxSequenceNumber;
        }   // else
        else
        {
            if (!has_current_user_key ||
                user_comparator->Compare(ikey.user_key,
                                         Slice(current_user_key)) != 0)
            {
                // First occurrence of this user key
                current_user_key.assign(ikey.user_key.data(), ikey.user_key.size());
                has_current_user_key = true;
                last_sequence_for_key = kMaxSequenceNumber;
            }   // if

            if (last_sequence_for_key <= smallest_snapshot)
            {
                // Hidden by an newer entry for same user key
                drop = true;    // (A)
            }   // if

            else if (ikey.type == kTypeDeletion
                     && ikey.sequence <= smallest_snapshot
                     && NULL!=compaction  // mem to level0 ignores this test
                     && compaction->IsBaseLevelForKey(ikey.user_key))
            {
                // For this user key:
                // (1) there is no data in higher levels
                // (2) data in lower levels will have larger sequence numbers
                // (3) data in layers that are being compacted here and have
                //     smaller sequence numbers will be dropped in the next
                //     few iterations of this loop (by rule (A) above).
                // Therefore this deletion marker is obsolete and can be dropped.
                drop = true;
            }   // else if

            last_sequence_for_key = ikey.sequence;
        }   // else
    }   // if

#if 0
    // needs clean up to be used again
    Log(options_.info_log,
        "  Compact: %s, seq %d, type: %d %d, drop: %d, is_base: %d, "
        "%d smallest_snapshot: %d",
        ikey.user_key.ToString().c_str(),
        (int)ikey.sequence, ikey.type, kTypeValue, drop,
        compact->compaction->IsBaseLevelForKey(ikey.user_key),
        (int)last_sequence_for_key, (int)compact->smallest_snapshot);
#endif
    return(drop);

}   // KeyRetirement::operator(Slice & )

}  // namespace leveldb
<|endoftext|>


<commit_before>#include <Arduino.h>
#include <SoftwareSerial.h>
#include "PacketSerial.h"
#include "Adafruit_BNO055.h"
#include "Adafruit_DRV2605.h"

extern "C" {
	//#include "pfleury/uart.h"
};

FUSES =
{
	.low = 0xFF,	//0xFF
	.high = FUSE_SPIEN & FUSE_BOOTSZ0 & FUSE_BOOTRST,	//0xDC
	.extended = FUSE_BODLEVEL1	//0xFD
};
LOCKBITS = LB_MODE_3;	//0xFC

#define UART_BAUD_RATE	115200

Adafruit_BNO055 bno = Adafruit_BNO055(55);
Adafruit_DRV2605 drv = Adafruit_DRV2605();

PacketSerial PSerial;
SoftwareSerial RFID_1(2, 3);
SoftwareSerial RFID_2(4, 5);
uint8_t switchcnt;
#define ID_LENGTH 12
uint8_t listcnt = 0;
uint8_t ledcnt = 0;
#define VIB_CNT 15
#define VIB_BIB 1
#define VIB_NR 14
uint8_t vibcnt = 0;
uint8_t vibr[] = {14, 15, 16, 47, 48, 54, 64, 70, 73, 74};
#define KEY	6
#define SWITCH	7
#define CAPSENS	8
#define MYOSENS A6

typedef struct {
	uint8_t rfid[ID_LENGTH];
	float ex, ey, ez;
	float ax, ay, az;
	uint16_t myo;
	uint8_t key : 1;
	uint8_t sw : 1;
	uint8_t capsens : 1;
	uint8_t lastnr : 1;
} packet;
packet pkg;

void process_rfid(uint8_t c)
{
	static uint8_t buffer[64];
	static int count = 0;
	if (c == 0x02)
	{
		count = 0;
	}
	else if (c == 0x03)
	{
		ledcnt = 0;
		if (memcmp(buffer, pkg.rfid, sizeof(pkg.rfid)) != 0)
		{
			memcpy(pkg.rfid, buffer, sizeof(pkg.rfid));
			drv.setWaveform(VIB_BIB, VIB_NR);
			drv.go();
			vibcnt = VIB_CNT;
		}
	}
	else if(count < 64)
	{
		buffer[count++] = c;
	}
}

inline void set_led(void)
{
	if (ledcnt < 10)
	{
		if (ledcnt == 0)
		{
			digitalWrite(LED_BUILTIN, HIGH);
		}
		ledcnt++;
	}
	else
	{
		digitalWrite(LED_BUILTIN, LOW);
	}
}

inline void process_cmd(uint8_t cmd)
{
	if (cmd >= '0' && cmd <= '9' && cmd - '0' < (uint8_t) sizeof(vibr))
	{
		drv.setWaveform(VIB_BIB, vibr[cmd - '0']);
		drv.go();
	}
}

inline void set_vib_2nd(void)
{
	if (vibcnt != 0)
	{
		vibcnt--;
		if (vibcnt == 0)
		{
			drv.setWaveform(VIB_BIB, VIB_NR);
			drv.go();
		}
	}
}

inline void read_bno(void)
{
	sensors_event_t event;
	bno.getEvent(&event);
	pkg.ex = event.orientation.x;
	pkg.ey = event.orientation.y;
	pkg.ez = event.orientation.z;

	imu::Vector<3> vec = bno.getVector(Adafruit_BNO055::VECTOR_LINEARACCEL);
	pkg.ax = vec.x();
	pkg.ay = vec.y();
	pkg.az = vec.z();
}

inline void read_inputs(void)
{
	pkg.key = digitalRead(KEY);
	pkg.sw = digitalRead(SWITCH);
	pkg.capsens = digitalRead(CAPSENS);

	pkg.myo = analogRead(MYOSENS);
}

void setup()
{
	pinMode(LED_BUILTIN, OUTPUT);
	pinMode(KEY, INPUT_PULLUP);
	pinMode(SWITCH, INPUT_PULLUP);
	pinMode(CAPSENS, INPUT_PULLUP);
	PSerial.begin(115200);
	RFID_1.begin(9600);
	RFID_2.begin(9600);
	bno.begin();
	delay(1000);
	bno.setExtCrystalUse(true);

	drv.begin();
	drv.useERM();
	drv.selectLibrary(2);
	drv.setWaveform(VIB_BIB, VIB_NR);

	sei();
}

void loop()
{
	read_bno();
	read_inputs();
	PSerial.send((uint8_t*) &pkg, sizeof(pkg));
	set_led();

	delay(20);

	if (switchcnt++ % 10 < 5)
	{
		RFID_1.listen();
		while(RFID_1.available() > 0)
		{
			pkg.lastnr = 0;
			process_rfid(RFID_1.read());
		}
	} else {
		RFID_2.listen();
		while(RFID_2.available() > 0)
		{
			pkg.lastnr = 1;
			process_rfid(RFID_2.read());
		}
	}
	if (Serial.available())
	{
		process_cmd(Serial.read());
	}
	set_vib_2nd();
}
<commit_msg>Remove vibrate at RFID, Change RFID packet behaviour<commit_after>#include <Arduino.h>
#include <SoftwareSerial.h>
#include "PacketSerial.h"
#include "Adafruit_BNO055.h"
#include "Adafruit_DRV2605.h"

extern "C" {
	//#include "pfleury/uart.h"
};

FUSES =
{
	.low = 0xFF,	//0xFF
	.high = FUSE_SPIEN & FUSE_BOOTSZ0 & FUSE_BOOTRST,	//0xDC
	.extended = FUSE_BODLEVEL1	//0xFD
};
LOCKBITS = LB_MODE_3;	//0xFC

#define UART_BAUD_RATE	115200

Adafruit_BNO055 bno = Adafruit_BNO055(55);
Adafruit_DRV2605 drv = Adafruit_DRV2605();

PacketSerial PSerial;
SoftwareSerial RFID_1(2, 3);
SoftwareSerial RFID_2(4, 5);
uint8_t switchcnt;
#define ID_LENGTH 12
uint8_t rfidcnt = 0;
#define RFID_CNT 4;
uint8_t ledcnt = 0;
#define VIB_BIB 1
#define VIB_NR 14
uint8_t vibr[] = {14, 15, 16, 47, 48, 54, 64, 70, 73, 74};
#define KEY	6
#define SWITCH	7
#define CAPSENS	8
#define MYOSENS A6

typedef struct {
	uint8_t rfid[ID_LENGTH];
	float ex, ey, ez;
	float ax, ay, az;
	uint16_t myo;
	uint8_t key : 1;
	uint8_t sw : 1;
	uint8_t capsens : 1;
	uint8_t lastnr : 1;
} packet;
packet pkg;

void process_rfid(uint8_t c)
{
	static uint8_t buffer[64];
	static int count = 0;
	if (c == 0x02)
	{
		count = 0;
	}
	else if (c == 0x03)
	{
		ledcnt = 0;
		memcpy(pkg.rfid, buffer, sizeof(pkg.rfid));
		rfidcnt = RFID_CNT;
	}
	else if(count < 64)
	{
		buffer[count++] = c;
	}
}

inline void set_led(void)
{
	if (ledcnt < 10)
	{
		if (ledcnt == 0)
		{
			digitalWrite(LED_BUILTIN, HIGH);
		}
		ledcnt++;
	}
	else
	{
		digitalWrite(LED_BUILTIN, LOW);
	}
}

inline void process_cmd(uint8_t cmd)
{
	if (cmd >= '0' && cmd <= '9' && cmd - '0' < (uint8_t) sizeof(vibr))
	{
		drv.setWaveform(VIB_BIB, vibr[cmd - '0']);
		drv.go();
	}
}

inline void read_bno(void)
{
	sensors_event_t event;
	bno.getEvent(&event);
	pkg.ex = event.orientation.x;
	pkg.ey = event.orientation.y;
	pkg.ez = event.orientation.z;

	imu::Vector<3> vec = bno.getVector(Adafruit_BNO055::VECTOR_LINEARACCEL);
	pkg.ax = vec.x();
	pkg.ay = vec.y();
	pkg.az = vec.z();
}

inline void read_inputs(void)
{
	pkg.key = digitalRead(KEY);
	pkg.sw = digitalRead(SWITCH);
	pkg.capsens = digitalRead(CAPSENS);

	pkg.myo = analogRead(MYOSENS);
}

void setup()
{
	pinMode(LED_BUILTIN, OUTPUT);
	pinMode(KEY, INPUT_PULLUP);
	pinMode(SWITCH, INPUT_PULLUP);
	pinMode(CAPSENS, INPUT_PULLUP);
	PSerial.begin(115200);
	RFID_1.begin(9600);
	RFID_2.begin(9600);
	bno.begin();
	delay(1000);
	bno.setExtCrystalUse(true);

	drv.begin();
	drv.useERM();
	drv.selectLibrary(2);
	drv.setWaveform(VIB_BIB, VIB_NR);

	sei();
}

void loop()
{
	read_bno();
	read_inputs();
	PSerial.send((uint8_t*) &pkg, sizeof(pkg));
	if (rfidcnt)
	{
		rfidcnt--;
	}
	else
	{
		memset(pkg.rfid, 0, sizeof(pkg.rfid));
	}
	set_led();

	delay(20);

	if (switchcnt++ % 10 < 5)
	{
		RFID_1.listen();
		while(RFID_1.available() > 0)
		{
			pkg.lastnr = 0;
			process_rfid(RFID_1.read());
		}
	} else {
		RFID_2.listen();
		while(RFID_2.available() > 0)
		{
			pkg.lastnr = 1;
			process_rfid(RFID_2.read());
		}
	}
	if (Serial.available())
	{
		process_cmd(Serial.read());
	}
}
<|endoftext|>


<commit_before>#ifndef ___INANITY_META_IMPL_HPP___
#define ___INANITY_META_IMPL_HPP___

#include "ClassBase.ipp"

// Before inclusion of this header, do the following:
// * include header of needed meta provider class
// * define a macro META_PROVIDER to a full name of the meta provider class
// After inclusion you likely want to undef META_PROVIDER.

#ifndef META_PROVIDER
#error "META_PROVIDER isn't defined"
#endif

#define META_CLASS(className, fullClassName) \
	BEGIN_INANITY_META \
	template <> \
	class Class<META_PROVIDER, className> : public META_PROVIDER::Class<className> \
	{ \
	private: \
		typedef META_PROVIDER Provider; \
		typedef className ClassType; \
	public: \
		Class(); \
	}; \
	template <> \
	META_PROVIDER::ClassBase* MetaOf<META_PROVIDER, className>() \
	{ \
		static Class<META_PROVIDER, className> instance; \
		return &instance; \
	} \
	Class<META_PROVIDER, className>::Class() \
		: META_PROVIDER::Class<className>(#className, #fullClassName) \
	{
#define META_CLASS_END() } END_INANITY_META

#define META_CLASS_PARENT(parentClassName) \
	SetParent(MetaOf<Provider, parentClassName>())

#define META_CONSTRUCTOR(...) \
	{ \
		static Provider::Constructor<void (ClassType::*)(__VA_ARGS__)> c; \
		SetConstructor(&c); \
	}

#define META_METHOD(methodName) \
	{ \
		static Provider::Method<decltype(&ClassType::methodName), &ClassType::methodName> m(#methodName); \
		AddMethod(&m); \
	}

#define META_METHOD_FULL(methodName, methodType, methodScriptAlias) \
	{ \
		static Provider::Method<methodType, &ClassType::methodName> m(#methodScriptAlias); \
		AddMethod(&m); \
	}

#define META_STATIC_METHOD(methodName) \
	{ \
		static Provider::Function<decltype(&ClassType::methodName), &ClassType::methodName> f(#methodName); \
		AddStaticMethod(&f); \
	}

#define META_STATIC_METHOD_FULL(methodName, methodType, methodScriptAlias) \
	{ \
		static Provider::Function<methodScriptAlias, &ClassType::methodName> f(#methodScriptAlias); \
		AddStaticMethod(&f); \
	}

#endif
<commit_msg>fix full static method metaimpl<commit_after>#ifndef ___INANITY_META_IMPL_HPP___
#define ___INANITY_META_IMPL_HPP___

#include "ClassBase.ipp"

// Before inclusion of this header, do the following:
// * include header of needed meta provider class
// * define a macro META_PROVIDER to a full name of the meta provider class
// After inclusion you likely want to undef META_PROVIDER.

#ifndef META_PROVIDER
#error "META_PROVIDER isn't defined"
#endif

#define META_CLASS(className, fullClassName) \
	BEGIN_INANITY_META \
	template <> \
	class Class<META_PROVIDER, className> : public META_PROVIDER::Class<className> \
	{ \
	private: \
		typedef META_PROVIDER Provider; \
		typedef className ClassType; \
	public: \
		Class(); \
	}; \
	template <> \
	META_PROVIDER::ClassBase* MetaOf<META_PROVIDER, className>() \
	{ \
		static Class<META_PROVIDER, className> instance; \
		return &instance; \
	} \
	Class<META_PROVIDER, className>::Class() \
		: META_PROVIDER::Class<className>(#className, #fullClassName) \
	{
#define META_CLASS_END() } END_INANITY_META

#define META_CLASS_PARENT(parentClassName) \
	SetParent(MetaOf<Provider, parentClassName>())

#define META_CONSTRUCTOR(...) \
	{ \
		static Provider::Constructor<void (ClassType::*)(__VA_ARGS__)> c; \
		SetConstructor(&c); \
	}

#define META_METHOD(methodName) \
	{ \
		static Provider::Method<decltype(&ClassType::methodName), &ClassType::methodName> m(#methodName); \
		AddMethod(&m); \
	}

#define META_METHOD_FULL(methodName, methodType, methodScriptAlias) \
	{ \
		static Provider::Method<methodType, &ClassType::methodName> m(#methodScriptAlias); \
		AddMethod(&m); \
	}

#define META_STATIC_METHOD(methodName) \
	{ \
		static Provider::Function<decltype(&ClassType::methodName), &ClassType::methodName> f(#methodName); \
		AddStaticMethod(&f); \
	}

#define META_STATIC_METHOD_FULL(methodName, methodType, methodScriptAlias) \
	{ \
		static Provider::Function<methodType, &ClassType::methodName> f(#methodScriptAlias); \
		AddStaticMethod(&f); \
	}

#endif
<|endoftext|>