<commit_before>#include <iostream>

using namespace std;
struct Value;

template<typename T>
class Slice {
public:
  Slice(size_t len) : len_(len), cap_(len) {
    ptr_ = new T[cap_];
  }
  template<typename Allocator>
  Slice(size_t len, Allocator allocator) : len_(len), cap_(len) {
    ptr_ = allocator.template alloc<T>(len_);
  }
private:
  T*     ptr_;
  size_t len_;
  size_t cap_;
};

class New {
public:
  template<typename T>
  T* alloc(size_t size) {
    cout << "Allocating " << size << " things!" << endl;
    return new T[size];
  }
};

template<>
int* New::alloc(size_t size) {
  cout << "Allocating " << size << " ints!" << endl;
  return new int[size];
}

typedef Slice<int> int_slice;
typedef Slice<char> char_slice;
typedef Slice<Value> val_slice;

struct Value {
  enum Type {
    NUMBER,
    INT_SLICE,
    STRING,
    SLICE_HEADER
  } type;

  enum Color {
    BLACK,
    GRAY,
    WHITE
  } color;

  union Content {
    double number;
    int_slice ints;
    char_slice chars;
    val_slice vals;
    Content() { }
  } content;
};

int main() {
  cout << "size of Slice: " << sizeof(Slice<Value>) << endl;
  cout << "size of Value: " << sizeof(Value) << endl;
  auto ints = Slice<int>(20, New());
  cout << "size of ints: " << sizeof(ints) << endl;
  auto vals = Slice<Value>(14, New());
  cout << "size of vals: " << sizeof(vals) << endl;
  return 0;
}

<commit_msg>gah, probably need to store a pointer to the beginning of the chunk too<commit_after>#include <iostream>

using namespace std;
struct Value;

template<typename T>
class Slice {
public:
  Slice(size_t len) : len_(len), cap_(len) {
    ptr_ = new T[cap_];
  }
  template<typename Allocator>
  Slice(size_t len, Allocator allocator) : len_(len), cap_(len) {
    ptr_ = allocator.template alloc<T>(len_);
  }
private:
  T*     block_;
  T*     ptr_;
  size_t len_;
  size_t cap_;
};

class New {
public:
  template<typename T>
  T* alloc(size_t size) {
    cout << "Allocating " << size << " things!" << endl;
    return new T[size];
  }
};

template<>
int* New::alloc(size_t size) {
  cout << "Allocating " << size << " ints!" << endl;
  return new int[size];
}

typedef Slice<int> int_slice;
typedef Slice<char> char_slice;
typedef Slice<Value> val_slice;

struct Value {
  enum Type {
    NUMBER,
    INT_SLICE,
    STRING,
    SLICE_HEADER
  } type;

  enum Color {
    BLACK,
    GRAY,
    WHITE
  } color;

  union Content {
    double number;
    int_slice ints;
    char_slice chars;
    val_slice vals;
    Content() { }
  } content;
};

int main() {
  cout << "size of Slice: " << sizeof(Slice<Value>) << endl;
  cout << "size of Value: " << sizeof(Value) << endl;
  auto ints = Slice<int>(20, New());
  cout << "size of ints: " << sizeof(ints) << endl;
  auto vals = Slice<Value>(14, New());
  cout << "size of vals: " << sizeof(vals) << endl;
  return 0;
}

<|endoftext|>


<commit_before>#include "master.hpp"

namespace factor
{

/* Simple wrappers for ANSI C I/O functions, used for bootstrapping.

Note the ugly loop logic in almost every function; we have to handle EINTR
and restart the operation if the system call was interrupted. Naive
applications don't do this, but then they quickly fail if one enables
itimer()s or other signals.

The Factor library provides platform-specific code for Unix and Windows
with many more capabilities so these words are not usually used in
normal operation. */

void factor_vm::init_c_io()
{
	special_objects[OBJ_STDIN] = allot_alien(false_object,(cell)stdin);
	special_objects[OBJ_STDOUT] = allot_alien(false_object,(cell)stdout);
	special_objects[OBJ_STDERR] = allot_alien(false_object,(cell)stderr);
}

void factor_vm::io_error()
{
#ifndef WINCE
	if(errno == EINTR)
		return;
#endif

	general_error(ERROR_IO,tag_fixnum(errno),false_object);
}

FILE *factor_vm::safe_fopen(char *filename, char *mode)
{
	FILE *file;
	for(;;)
	{
		file = fopen(filename,mode);
		if(file == NULL)
			io_error();
		else
			break;
	}
	return file;
}

int factor_vm::safe_fgetc(FILE *stream)
{
	int c;
	for(;;)
	{
		c = fgetc(stream);
		if(c == EOF)
		{
			if(feof(stream))
				return EOF;
			else
				io_error();
		}
		else
			break;
	}
	return c;
}

size_t factor_vm::safe_fread(void *ptr, size_t size, size_t nitems, FILE *stream)
{
	size_t items_read = 0;
	size_t ret = 0;

	do
	{
		ret = fread((void*)((int*)ptr+items_read*size),size,nitems-items_read,stream);
		if(ret == 0)
		{
			if(feof(stream))
				break;
			else
				io_error();
		}
		items_read += ret;
	} while(items_read != nitems);

	return items_read;
}

void factor_vm::safe_fputc(int c, FILE *stream)
{
	for(;;)
	{
		if(fputc(c,stream) == EOF)
			io_error();
		else
			break;
	}
}

size_t factor_vm::safe_fwrite(void *ptr, size_t size, size_t nitems, FILE *stream)
{
	size_t items_written = 0;
	size_t ret = 0;

	do {
		ret = fwrite((void*)((int*)ptr+items_written*size),size,nitems-items_written,stream);
		if(ret == 0)
			io_error();
		items_written += ret;
	} while(items_written != nitems);

	return items_written;
}

int factor_vm::safe_ftell(FILE *stream)
{
	off_t offset;
	for(;;)
	{
		if((offset = FTELL(stream)) == -1)
			io_error();
		else
			break;
	}
	return offset;
}

void factor_vm::safe_fseek(FILE *stream, off_t offset, int whence)
{
	switch(whence)
	{
	case 0: whence = SEEK_SET; break;
	case 1: whence = SEEK_CUR; break;
	case 2: whence = SEEK_END; break;
	default:
		critical_error("Bad value for whence",whence);
	}

	for(;;)
	{
		if(FSEEK(stream,offset,whence) == -1)
			io_error();
		else
			break;
	}
}

void factor_vm::safe_fflush(FILE *stream)
{
	for(;;)
	{
		if(fflush(stream) == EOF)
			io_error();
		else
			break;
	}
}

void factor_vm::safe_fclose(FILE *stream)
{
	for(;;)
	{
		if(fclose(stream) == EOF)
			io_error();
		else
			break;
	}
}

void factor_vm::primitive_fopen()
{
	data_root<byte_array> mode(ctx->pop(),this);
	data_root<byte_array> path(ctx->pop(),this);
	mode.untag_check(this);
	path.untag_check(this);

	FILE *file;
	file = safe_fopen((char *)(path.untagged() + 1),
		(char *)(mode.untagged() + 1));
	ctx->push(allot_alien(file));
}

FILE *factor_vm::pop_file_handle()
{
	return (FILE *)alien_offset(ctx->pop());
}

void factor_vm::primitive_fgetc()
{
	FILE *file = pop_file_handle();

	int c = safe_fgetc(file);
	if(c == EOF && feof(file))
	{
		clearerr(file);
		ctx->push(false_object);
	}
	else
		ctx->push(tag_fixnum(c));
}

void factor_vm::primitive_fread()
{
	FILE *file = pop_file_handle();
	fixnum size = unbox_array_size();

	if(size == 0)
	{
		ctx->push(tag<string>(allot_string(0,0)));
		return;
	}

	data_root<byte_array> buf(allot_uninitialized_array<byte_array>(size),this);

	size_t c = safe_fread(buf.untagged() + 1,1,size,file);
	if(c == 0)
	{
		clearerr(file);
		ctx->push(false_object);
	}
	else
	{
		if(feof(file))
		{
			clearerr(file);
			byte_array *new_buf = allot_byte_array(c);
			memcpy(new_buf->data<char>(), buf->data<char>(),c);
			buf = new_buf;
		}

		ctx->push(buf.value());
	}
}

void factor_vm::primitive_fputc()
{
	FILE *file = pop_file_handle();
	fixnum ch = to_fixnum(ctx->pop());
	safe_fputc((int)ch, file);
}

void factor_vm::primitive_fwrite()
{
	FILE *file = pop_file_handle();
	cell length = to_cell(ctx->pop());
	char *text = alien_offset(ctx->pop());

	if(length == 0)
		return;

	size_t written = safe_fwrite(text,1,length,file);
	if(written != length)
		io_error();
}

void factor_vm::primitive_ftell()
{
	FILE *file = pop_file_handle();
	ctx->push(from_signed_8(safe_ftell(file)));
}

void factor_vm::primitive_fseek()
{
	FILE *file = pop_file_handle();
	int whence = (int)to_fixnum(ctx->pop());
	off_t offset = (off_t)to_signed_8(ctx->pop());
	safe_fseek(file,offset,whence);
}

void factor_vm::primitive_fflush()
{
	FILE *file = pop_file_handle();
	safe_fflush(file);
}

void factor_vm::primitive_fclose()
{
	FILE *file = pop_file_handle();
	safe_fclose(file);
}

/* This function is used by FFI I/O. Accessing the errno global directly is
not portable, since on some libc's errno is not a global but a funky macro that
reads thread-local storage. */
VM_C_API int err_no()
{
	return errno;
}

VM_C_API void set_err_no(int err)
{
	errno = err;
}
}
<commit_msg>vm: non-copying primitive_fread primitive_fread now takes a buffer pointer argument and returns a count of bytes read instead of allocating a byte array.<commit_after>#include "master.hpp"

namespace factor
{

/* Simple wrappers for ANSI C I/O functions, used for bootstrapping.

Note the ugly loop logic in almost every function; we have to handle EINTR
and restart the operation if the system call was interrupted. Naive
applications don't do this, but then they quickly fail if one enables
itimer()s or other signals.

The Factor library provides platform-specific code for Unix and Windows
with many more capabilities so these words are not usually used in
normal operation. */

void factor_vm::init_c_io()
{
	special_objects[OBJ_STDIN] = allot_alien(false_object,(cell)stdin);
	special_objects[OBJ_STDOUT] = allot_alien(false_object,(cell)stdout);
	special_objects[OBJ_STDERR] = allot_alien(false_object,(cell)stderr);
}

void factor_vm::io_error()
{
#ifndef WINCE
	if(errno == EINTR)
		return;
#endif

	general_error(ERROR_IO,tag_fixnum(errno),false_object);
}

FILE *factor_vm::safe_fopen(char *filename, char *mode)
{
	FILE *file;
	for(;;)
	{
		file = fopen(filename,mode);
		if(file == NULL)
			io_error();
		else
			break;
	}
	return file;
}

int factor_vm::safe_fgetc(FILE *stream)
{
	int c;
	for(;;)
	{
		c = fgetc(stream);
		if(c == EOF)
		{
			if(feof(stream))
				return EOF;
			else
				io_error();
		}
		else
			break;
	}
	return c;
}

size_t factor_vm::safe_fread(void *ptr, size_t size, size_t nitems, FILE *stream)
{
	size_t items_read = 0;
	size_t ret = 0;

	do
	{
		ret = fread((void*)((int*)ptr+items_read*size),size,nitems-items_read,stream);
		if(ret == 0)
		{
			if(feof(stream))
				break;
			else
				io_error();
		}
		items_read += ret;
	} while(items_read != nitems);

	return items_read;
}

void factor_vm::safe_fputc(int c, FILE *stream)
{
	for(;;)
	{
		if(fputc(c,stream) == EOF)
			io_error();
		else
			break;
	}
}

size_t factor_vm::safe_fwrite(void *ptr, size_t size, size_t nitems, FILE *stream)
{
	size_t items_written = 0;
	size_t ret = 0;

	do {
		ret = fwrite((void*)((int*)ptr+items_written*size),size,nitems-items_written,stream);
		if(ret == 0)
			io_error();
		items_written += ret;
	} while(items_written != nitems);

	return items_written;
}

int factor_vm::safe_ftell(FILE *stream)
{
	off_t offset;
	for(;;)
	{
		if((offset = FTELL(stream)) == -1)
			io_error();
		else
			break;
	}
	return offset;
}

void factor_vm::safe_fseek(FILE *stream, off_t offset, int whence)
{
	switch(whence)
	{
	case 0: whence = SEEK_SET; break;
	case 1: whence = SEEK_CUR; break;
	case 2: whence = SEEK_END; break;
	default:
		critical_error("Bad value for whence",whence);
	}

	for(;;)
	{
		if(FSEEK(stream,offset,whence) == -1)
			io_error();
		else
			break;
	}
}

void factor_vm::safe_fflush(FILE *stream)
{
	for(;;)
	{
		if(fflush(stream) == EOF)
			io_error();
		else
			break;
	}
}

void factor_vm::safe_fclose(FILE *stream)
{
	for(;;)
	{
		if(fclose(stream) == EOF)
			io_error();
		else
			break;
	}
}

void factor_vm::primitive_fopen()
{
	data_root<byte_array> mode(ctx->pop(),this);
	data_root<byte_array> path(ctx->pop(),this);
	mode.untag_check(this);
	path.untag_check(this);

	FILE *file;
	file = safe_fopen((char *)(path.untagged() + 1),
		(char *)(mode.untagged() + 1));
	ctx->push(allot_alien(file));
}

FILE *factor_vm::pop_file_handle()
{
	return (FILE *)alien_offset(ctx->pop());
}

void factor_vm::primitive_fgetc()
{
	FILE *file = pop_file_handle();

	int c = safe_fgetc(file);
	if(c == EOF && feof(file))
	{
		clearerr(file);
		ctx->push(false_object);
	}
	else
		ctx->push(tag_fixnum(c));
}

void factor_vm::primitive_fread()
{
	FILE *file = pop_file_handle();
	void *buf = (void*)alien_offset(ctx->pop());
	fixnum size = unbox_array_size();

	if(size == 0)
	{
		ctx->push(from_unsigned_cell(0));
		return;
	}

	size_t c = safe_fread(buf,1,size,file);
	if(c == 0 || feof(file))
		clearerr(file);
	ctx->push(from_unsigned_cell(c));
}

void factor_vm::primitive_fputc()
{
	FILE *file = pop_file_handle();
	fixnum ch = to_fixnum(ctx->pop());
	safe_fputc((int)ch, file);
}

void factor_vm::primitive_fwrite()
{
	FILE *file = pop_file_handle();
	cell length = to_cell(ctx->pop());
	char *text = alien_offset(ctx->pop());

	if(length == 0)
		return;

	size_t written = safe_fwrite(text,1,length,file);
	if(written != length)
		io_error();
}

void factor_vm::primitive_ftell()
{
	FILE *file = pop_file_handle();
	ctx->push(from_signed_8(safe_ftell(file)));
}

void factor_vm::primitive_fseek()
{
	FILE *file = pop_file_handle();
	int whence = (int)to_fixnum(ctx->pop());
	off_t offset = (off_t)to_signed_8(ctx->pop());
	safe_fseek(file,offset,whence);
}

void factor_vm::primitive_fflush()
{
	FILE *file = pop_file_handle();
	safe_fflush(file);
}

void factor_vm::primitive_fclose()
{
	FILE *file = pop_file_handle();
	safe_fclose(file);
}

/* This function is used by FFI I/O. Accessing the errno global directly is
not portable, since on some libc's errno is not a global but a funky macro that
reads thread-local storage. */
VM_C_API int err_no()
{
	return errno;
}

VM_C_API void set_err_no(int err)
{
	errno = err;
}
}
<|endoftext|>


<commit_before>// PythonStuff.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.

#include "stdafx.h"
#include <wx/file.h>
#include <wx/mimetype.h>
#include <wx/process.h>
#include <wx/stdpaths.h>
#include <wx/filename.h>
#include "PythonStuff.h"
#include "ProgramCanvas.h"
#include "OutputCanvas.h"
#include "Program.h"

class CPyProcess : public wxProcess
{
protected:
	int m_pid;

public:
	CPyProcess(void): wxProcess(heeksCAD->GetMainFrame()), m_pid(0) { }

	void Execute(const wxChar* cmd);
	void Cancel(void);
	void OnTerminate(int pid, int status);

	virtual void ThenDo(void) { }
};

void CPyProcess::Execute(const wxChar* cmd)
{
	m_pid = wxExecute(cmd, wxEXEC_ASYNC, this);
}

void CPyProcess::Cancel(void)
{
	if (m_pid)
	{
		wxProcess::Kill(m_pid);
		m_pid = 0;
	}
}

void CPyProcess::OnTerminate(int pid, int status)
{
	if (pid == m_pid)
	{
		m_pid = 0;
		ThenDo();
	}
}

////////////////////////////////////////////////////////

class CPyBackPlot : public CPyProcess
{
protected:
	const CProgram* m_program;
	HeeksObj* m_into;
	wxString m_filename;
	wxBusyCursor *m_busy_cursor;

	static CPyBackPlot* m_object;

public:
	CPyBackPlot(const CProgram* program, HeeksObj* into, const wxChar* filename): m_program(program), m_into(into),m_filename(filename),m_busy_cursor(NULL) { m_object = this; }
	~CPyBackPlot(void) { m_object = NULL; }

	static void StaticCancel(void) { if (m_object) m_object->Cancel(); }

	void Do(void)
	{
		if(m_busy_cursor == NULL)m_busy_cursor = new wxBusyCursor();

		if (m_program->m_machine.file_name == _T("not found"))
		{
			wxMessageBox(_T("Machine name (defined in Program Properties) not found"));
		} // End if - then
		else
		{
#ifdef WIN32
			Execute(wxString(_T("\"")) + theApp.GetDllFolder() + _T("\\nc_read.bat\" ") + m_program->m_machine.file_name + _T(" \"") + m_filename + _T("\""));
#else
#ifdef RUNINPLACE
            wxString path(_T("/nc/"));
#else
            wxString path(_T("/../heekscnc/nc/"));
#endif

			Execute(wxString(_T("python \"")) + theApp.GetDllFolder() + path + m_program->m_machine.file_name + wxString(_T("_read.py\" \"")) + m_filename + wxString(_T("\"")) );
#endif
		} // End if - else
	}
	void ThenDo(void)
	{
		// there should now be a .nc.xml written
		wxString xml_file_str = m_filename + wxString(_T(".nc.xml"));
		wxFile ofs(xml_file_str.c_str());
		if(!ofs.IsOpened())
		{
			wxMessageBox(wxString(_("Couldn't open file")) + _T(" - ") + xml_file_str);
			return;
		}

		// read the xml file, just like paste, into the program
		heeksCAD->OpenXMLFile(xml_file_str, m_into);
		heeksCAD->Repaint();

		// in Windows, at least, executing the bat file was making HeeksCAD change it's Z order
		heeksCAD->GetMainFrame()->Raise();

		delete m_busy_cursor;
		m_busy_cursor = NULL;
	}
};

CPyBackPlot* CPyBackPlot::m_object = NULL;

class CPyPostProcess : public CPyProcess
{
protected:
	const CProgram* m_program;
	wxString m_filename;
	bool m_include_backplot_processing;

	static CPyPostProcess* m_object;

public:
	CPyPostProcess(const CProgram* program,
			const wxChar* filename,
			const bool include_backplot_processing = true ) :
		m_program(program), m_filename(filename), m_include_backplot_processing(include_backplot_processing)
	{
		m_object = this;
	}

	~CPyPostProcess(void) { m_object = NULL; }

	static void StaticCancel(void) { if (m_object) m_object->Cancel(); }

	void Do(void)
	{
		wxBusyCursor wait; // show an hour glass until the end of this function
		wxStandardPaths standard_paths;
		wxFileName path( standard_paths.GetTempDir().c_str(), _T("post.py"));

#ifdef WIN32
        Execute(wxString(_T("\"")) + theApp.GetDllFolder() + wxString(_T("\\post.bat\" \"")) + path.GetFullPath() + wxString(_T("\"")));
#else

        wxString path = wxString(_T("python ")) + path.GetFullPath();
		Execute(path);
#endif
	}
	void ThenDo(void)
	{
		if (m_include_backplot_processing)
		{
			(new CPyBackPlot(m_program, (HeeksObj*)m_program, m_filename))->Do();
		}
	}
};

CPyPostProcess* CPyPostProcess::m_object = NULL;

////////////////////////////////////////////////////////

static bool write_python_file(const wxString& python_file_path)
{
	wxFile ofs(python_file_path.c_str(), wxFile::write);
	if(!ofs.IsOpened())return false;

	ofs.Write(theApp.m_program->m_python_program.c_str());

	return true;
}

bool HeeksPyPostProcess(const CProgram* program, const wxString &filepath, const bool include_backplot_processing)
{
	try{
		theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window

		// write the python file
		wxStandardPaths standard_paths;
		wxFileName file_str( standard_paths.GetTempDir().c_str(), _T("post.py"));

		if(!write_python_file(file_str.GetFullPath()))
		{
		    wxString error;
		    error << _T("couldn't write ") << file_str.GetFullPath();
		    wxMessageBox(error.c_str());
		}
		else
		{
#ifdef WIN32
			// Set the working directory to the area that contains the DLL so that
			// the system can find the post.bat file correctly.
			::wxSetWorkingDirectory(theApp.GetDllFolder());
#else
			::wxSetWorkingDirectory(standard_paths.GetTempDir());
#endif

			// call the python file
			(new CPyPostProcess(program, filepath, include_backplot_processing))->Do();

			return true;
		}
	}
	catch(...)
	{
		wxMessageBox(_T("Error while post-processing the program!"));
	}
	return false;
}

bool HeeksPyBackplot(const CProgram* program, HeeksObj* into, const wxString &filepath)
{
	try{
		theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window

		::wxSetWorkingDirectory(theApp.GetDllFolder());

		// call the python file
		(new CPyBackPlot(program, into, filepath))->Do();

		// in Windows, at least, executing the bat file was making HeeksCAD change it's Z order
		heeksCAD->GetMainFrame()->Raise();

		return true;
	}
	catch(...)
	{
		wxMessageBox(_T("Error while backplotting the program!"));
	}
	return false;
}

void HeeksPyCancel(void)
{
	CPyBackPlot::StaticCancel();
	CPyPostProcess::StaticCancel();
}

<commit_msg>last change still didn't compile.<commit_after>// PythonStuff.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.

#include "stdafx.h"
#include <wx/file.h>
#include <wx/mimetype.h>
#include <wx/process.h>
#include <wx/stdpaths.h>
#include <wx/filename.h>
#include "PythonStuff.h"
#include "ProgramCanvas.h"
#include "OutputCanvas.h"
#include "Program.h"

class CPyProcess : public wxProcess
{
protected:
	int m_pid;

public:
	CPyProcess(void): wxProcess(heeksCAD->GetMainFrame()), m_pid(0) { }

	void Execute(const wxChar* cmd);
	void Cancel(void);
	void OnTerminate(int pid, int status);

	virtual void ThenDo(void) { }
};

void CPyProcess::Execute(const wxChar* cmd)
{
	m_pid = wxExecute(cmd, wxEXEC_ASYNC, this);
}

void CPyProcess::Cancel(void)
{
	if (m_pid)
	{
		wxProcess::Kill(m_pid);
		m_pid = 0;
	}
}

void CPyProcess::OnTerminate(int pid, int status)
{
	if (pid == m_pid)
	{
		m_pid = 0;
		ThenDo();
	}
}

////////////////////////////////////////////////////////

class CPyBackPlot : public CPyProcess
{
protected:
	const CProgram* m_program;
	HeeksObj* m_into;
	wxString m_filename;
	wxBusyCursor *m_busy_cursor;

	static CPyBackPlot* m_object;

public:
	CPyBackPlot(const CProgram* program, HeeksObj* into, const wxChar* filename): m_program(program), m_into(into),m_filename(filename),m_busy_cursor(NULL) { m_object = this; }
	~CPyBackPlot(void) { m_object = NULL; }

	static void StaticCancel(void) { if (m_object) m_object->Cancel(); }

	void Do(void)
	{
		if(m_busy_cursor == NULL)m_busy_cursor = new wxBusyCursor();

		if (m_program->m_machine.file_name == _T("not found"))
		{
			wxMessageBox(_T("Machine name (defined in Program Properties) not found"));
		} // End if - then
		else
		{
#ifdef WIN32
			Execute(wxString(_T("\"")) + theApp.GetDllFolder() + _T("\\nc_read.bat\" ") + m_program->m_machine.file_name + _T(" \"") + m_filename + _T("\""));
#else
#ifdef RUNINPLACE
            wxString path(_T("/nc/"));
#else
            wxString path(_T("/../heekscnc/nc/"));
#endif

			Execute(wxString(_T("python \"")) + theApp.GetDllFolder() + path + m_program->m_machine.file_name + wxString(_T("_read.py\" \"")) + m_filename + wxString(_T("\"")) );
#endif
		} // End if - else
	}
	void ThenDo(void)
	{
		// there should now be a .nc.xml written
		wxString xml_file_str = m_filename + wxString(_T(".nc.xml"));
		wxFile ofs(xml_file_str.c_str());
		if(!ofs.IsOpened())
		{
			wxMessageBox(wxString(_("Couldn't open file")) + _T(" - ") + xml_file_str);
			return;
		}

		// read the xml file, just like paste, into the program
		heeksCAD->OpenXMLFile(xml_file_str, m_into);
		heeksCAD->Repaint();

		// in Windows, at least, executing the bat file was making HeeksCAD change it's Z order
		heeksCAD->GetMainFrame()->Raise();

		delete m_busy_cursor;
		m_busy_cursor = NULL;
	}
};

CPyBackPlot* CPyBackPlot::m_object = NULL;

class CPyPostProcess : public CPyProcess
{
protected:
	const CProgram* m_program;
	wxString m_filename;
	bool m_include_backplot_processing;

	static CPyPostProcess* m_object;

public:
	CPyPostProcess(const CProgram* program,
			const wxChar* filename,
			const bool include_backplot_processing = true ) :
		m_program(program), m_filename(filename), m_include_backplot_processing(include_backplot_processing)
	{
		m_object = this;
	}

	~CPyPostProcess(void) { m_object = NULL; }

	static void StaticCancel(void) { if (m_object) m_object->Cancel(); }

	void Do(void)
	{
		wxBusyCursor wait; // show an hour glass until the end of this function
		wxStandardPaths standard_paths;
		wxFileName path( standard_paths.GetTempDir().c_str(), _T("post.py"));

#ifdef WIN32
        Execute(wxString(_T("\"")) + theApp.GetDllFolder() + wxString(_T("\\post.bat\" \"")) + path.GetFullPath() + wxString(_T("\"")));
#else

        wxString post_path = wxString(_T("python ")) + path.GetFullPath();
		Execute(post_path);
#endif
	}
	void ThenDo(void)
	{
		if (m_include_backplot_processing)
		{
			(new CPyBackPlot(m_program, (HeeksObj*)m_program, m_filename))->Do();
		}
	}
};

CPyPostProcess* CPyPostProcess::m_object = NULL;

////////////////////////////////////////////////////////

static bool write_python_file(const wxString& python_file_path)
{
	wxFile ofs(python_file_path.c_str(), wxFile::write);
	if(!ofs.IsOpened())return false;

	ofs.Write(theApp.m_program->m_python_program.c_str());

	return true;
}

bool HeeksPyPostProcess(const CProgram* program, const wxString &filepath, const bool include_backplot_processing)
{
	try{
		theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window

		// write the python file
		wxStandardPaths standard_paths;
		wxFileName file_str( standard_paths.GetTempDir().c_str(), _T("post.py"));

		if(!write_python_file(file_str.GetFullPath()))
		{
		    wxString error;
		    error << _T("couldn't write ") << file_str.GetFullPath();
		    wxMessageBox(error.c_str());
		}
		else
		{
#ifdef WIN32
			// Set the working directory to the area that contains the DLL so that
			// the system can find the post.bat file correctly.
			::wxSetWorkingDirectory(theApp.GetDllFolder());
#else
			::wxSetWorkingDirectory(standard_paths.GetTempDir());
#endif

			// call the python file
			(new CPyPostProcess(program, filepath, include_backplot_processing))->Do();

			return true;
		}
	}
	catch(...)
	{
		wxMessageBox(_T("Error while post-processing the program!"));
	}
	return false;
}

bool HeeksPyBackplot(const CProgram* program, HeeksObj* into, const wxString &filepath)
{
	try{
		theApp.m_output_canvas->m_textCtrl->Clear(); // clear the output window

		::wxSetWorkingDirectory(theApp.GetDllFolder());

		// call the python file
		(new CPyBackPlot(program, into, filepath))->Do();

		// in Windows, at least, executing the bat file was making HeeksCAD change it's Z order
		heeksCAD->GetMainFrame()->Raise();

		return true;
	}
	catch(...)
	{
		wxMessageBox(_T("Error while backplotting the program!"));
	}
	return false;
}

void HeeksPyCancel(void)
{
	CPyBackPlot::StaticCancel();
	CPyPostProcess::StaticCancel();
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008-2010 The QXmpp developers
 *
 * Authors:
 *  Manjeet Dahiya
 *  Jeremy Lainé
 *
 * Source:
 *  http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * 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.
 *
 */

#include "QXmppConstants.h"
#include "QXmppLogger.h"
#include "QXmppPacket.h"
#include "QXmppStream.h"
#include "QXmppUtils.h"

#include <QBuffer>
#include <QDomDocument>
#include <QHostAddress>
#include <QRegExp>
#include <QSslSocket>
#include <QStringList>
#include <QTime>
#include <QXmlStreamWriter>

static bool randomSeeded = false;
static const QString capabilitiesNode = "http://code.google.com/p/qxmpp";
static const QByteArray streamRootElementEnd = "</stream:stream>";

class QXmppStreamPrivate
{
public:
    QXmppStreamPrivate();

    QByteArray dataBuffer;
    QXmppLogger* logger;
    QSslSocket* socket;

    // stream state
    QByteArray streamStart;
};

QXmppStreamPrivate::QXmppStreamPrivate()
    : logger(0),
    socket(0)
{
}

/// Constructs a base XMPP stream.
///
/// \param parent

QXmppStream::QXmppStream(QObject *parent)
    : QObject(parent),
    d(new QXmppStreamPrivate)
{
    // Make sure the random number generator is seeded
    if (!randomSeeded)
    {
        qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
        randomSeeded = true;
    }
}

/// Destroys a base XMPP stream.

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

/// Disconnects from the remote host.
///

void QXmppStream::disconnectFromHost()
{
    sendData(streamRootElementEnd);
    if (d->socket)
    {
        d->socket->flush();
        d->socket->disconnectFromHost();
    }
}

void QXmppStream::handleStart()
{
}

/// Returns the QXmppLogger associated with the current stream.

QXmppLogger *QXmppStream::logger()
{
    return d->logger;
}

/// Sets the QXmppLogger associated with the current stream.

void QXmppStream::setLogger(QXmppLogger *logger)
{
    if (d->logger)
        disconnect(this, SIGNAL(logMessage(QXmppLogger::MessageType, QString)),
                   d->logger, SLOT(log(QXmppLogger::MessageType, QString)));
    d->logger = logger;
    if (d->logger)
        connect(this, SIGNAL(logMessage(QXmppLogger::MessageType, QString)),
                d->logger, SLOT(log(QXmppLogger::MessageType, QString)));
}

void QXmppStream::debug(const QString &data)
{
    emit logMessage(QXmppLogger::DebugMessage, data);
}

void QXmppStream::info(const QString &data)
{
    emit logMessage(QXmppLogger::InformationMessage, data);
}

void QXmppStream::warning(const QString &data)
{
    emit logMessage(QXmppLogger::WarningMessage, data);
}

/// Returns true if the stream is connected.
///

bool QXmppStream::isConnected() const
{
    return d->socket &&
           d->socket->state() == QAbstractSocket::ConnectedState;
}

/// Sends raw data to the peer.
///
/// \param data

bool QXmppStream::sendData(const QByteArray &data)
{
    emit logMessage(QXmppLogger::SentMessage, QString::fromUtf8(data));
    if (!d->socket || d->socket->state() != QAbstractSocket::ConnectedState)
        return false;
    return d->socket->write(data) == data.size();
}

/// Sends an XML element to the peer.
///
/// \param element

bool QXmppStream::sendElement(const QDomElement &element)
{
    // prepare packet
    QBuffer buffer;
    buffer.open(QIODevice::ReadWrite);
    QXmlStreamWriter writer(&buffer);
    const QStringList omitNamespaces = QStringList() << ns_client << ns_server;
    helperToXmlAddDomElement(&writer, element, omitNamespaces);

    // send packet
    return sendData(buffer.data());
}

/// Sends an XMPP packet to the peer.
///
/// \param packet

bool QXmppStream::sendPacket(const QXmppPacket &packet)
{
    // prepare packet
    QByteArray data;
    QXmlStreamWriter xmlStream(&data);
    packet.toXml(&xmlStream);

    // send packet
    return sendData(data);
}

/// Returns the QSslSocket used for this stream.
///

QSslSocket *QXmppStream::socket()
{
    return d->socket;
}

/// Sets the QSslSocket used for this stream.
///

void QXmppStream::setSocket(QSslSocket *socket)
{
    d->socket = socket;

    // socket events
    bool check = connect(socket, SIGNAL(connected()),
                    this, SLOT(socketConnected()));
    Q_ASSERT(check);

    check = connect(socket, SIGNAL(disconnected()),
                    this, SLOT(socketDisconnected()));
    Q_ASSERT(check);

    check = connect(socket, SIGNAL(encrypted()),
                    this, SLOT(socketEncrypted()));
    Q_ASSERT(check);

    check = connect(socket, SIGNAL(readyRead()),
                    this, SLOT(socketReadyRead()));
    Q_ASSERT(check);

    // relay signals
    check = connect(socket, SIGNAL(disconnected()),
                    this, SIGNAL(disconnected()));
    Q_ASSERT(check);
}

void QXmppStream::socketConnected()
{
    info(QString("Socket connected to %1 %2").arg(
        socket()->peerAddress().toString(),
        QString::number(socket()->peerPort())));
    d->dataBuffer.clear();
    handleStart();
}

void QXmppStream::socketDisconnected()
{
    info("Socket disconnected");
    d->dataBuffer.clear();
}

void QXmppStream::socketEncrypted()
{
    debug("Socket encrypted");
    d->dataBuffer.clear();
    handleStart();
}

void QXmppStream::socketReadyRead()
{
    const QByteArray data = socket()->readAll();
    //debug("SERVER [COULD BE PARTIAL DATA]:" + data.left(20));

    d->dataBuffer.append(data);

    // FIXME : maybe these QRegExps could be static?
    QRegExp startStreamRegex("^(<\\?xml.*\\?>)?\\s*<stream:stream.*>");
    startStreamRegex.setMinimal(true);
    QRegExp endStreamRegex("</stream:stream>$");
    endStreamRegex.setMinimal(true);

    // check whether we need to add stream start / end elements
    QByteArray completeXml;
    const QString strData = QString::fromUtf8(d->dataBuffer);
    bool streamStart = false;
    if(strData.contains(startStreamRegex))
    {
        completeXml = d->dataBuffer + streamRootElementEnd;
        streamStart = true;
        d->streamStart = startStreamRegex.cap(0).toUtf8();
    }
    else if(strData.contains(endStreamRegex))
        completeXml = d->streamStart + d->dataBuffer;
    else
        completeXml = d->streamStart + d->dataBuffer + streamRootElementEnd;

    // check whether we have a valid XML document
    QDomDocument doc;
    if(!doc.setContent(completeXml, true))
        return;

    // remove data from buffer
    emit logMessage(QXmppLogger::ReceivedMessage, strData);
    d->dataBuffer.clear();

    // process stream start
    QDomElement nodeRecv = doc.documentElement().firstChildElement();
    if (streamStart)
    {
        QDomElement streamElement = doc.documentElement();
        handleStream(streamElement);
    }

    // process stanzas
    while(!nodeRecv.isNull())
    {
        handleStanza(nodeRecv);
        nodeRecv = nodeRecv.nextSiblingElement();
    }
}

<commit_msg>we can receive both a stream start and stream end at once<commit_after>/*
 * Copyright (C) 2008-2010 The QXmpp developers
 *
 * Authors:
 *  Manjeet Dahiya
 *  Jeremy Lainé
 *
 * Source:
 *  http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * 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.
 *
 */

#include "QXmppConstants.h"
#include "QXmppLogger.h"
#include "QXmppPacket.h"
#include "QXmppStream.h"
#include "QXmppUtils.h"

#include <QBuffer>
#include <QDomDocument>
#include <QHostAddress>
#include <QRegExp>
#include <QSslSocket>
#include <QStringList>
#include <QTime>
#include <QXmlStreamWriter>

static bool randomSeeded = false;
static const QString capabilitiesNode = "http://code.google.com/p/qxmpp";
static const QByteArray streamRootElementEnd = "</stream:stream>";

class QXmppStreamPrivate
{
public:
    QXmppStreamPrivate();

    QByteArray dataBuffer;
    QXmppLogger* logger;
    QSslSocket* socket;

    // stream state
    QByteArray streamStart;
};

QXmppStreamPrivate::QXmppStreamPrivate()
    : logger(0),
    socket(0)
{
}

/// Constructs a base XMPP stream.
///
/// \param parent

QXmppStream::QXmppStream(QObject *parent)
    : QObject(parent),
    d(new QXmppStreamPrivate)
{
    // Make sure the random number generator is seeded
    if (!randomSeeded)
    {
        qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
        randomSeeded = true;
    }
}

/// Destroys a base XMPP stream.

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

/// Disconnects from the remote host.
///

void QXmppStream::disconnectFromHost()
{
    sendData(streamRootElementEnd);
    if (d->socket)
    {
        d->socket->flush();
        d->socket->disconnectFromHost();
    }
}

void QXmppStream::handleStart()
{
}

/// Returns the QXmppLogger associated with the current stream.

QXmppLogger *QXmppStream::logger()
{
    return d->logger;
}

/// Sets the QXmppLogger associated with the current stream.

void QXmppStream::setLogger(QXmppLogger *logger)
{
    if (d->logger)
        disconnect(this, SIGNAL(logMessage(QXmppLogger::MessageType, QString)),
                   d->logger, SLOT(log(QXmppLogger::MessageType, QString)));
    d->logger = logger;
    if (d->logger)
        connect(this, SIGNAL(logMessage(QXmppLogger::MessageType, QString)),
                d->logger, SLOT(log(QXmppLogger::MessageType, QString)));
}

void QXmppStream::debug(const QString &data)
{
    emit logMessage(QXmppLogger::DebugMessage, data);
}

void QXmppStream::info(const QString &data)
{
    emit logMessage(QXmppLogger::InformationMessage, data);
}

void QXmppStream::warning(const QString &data)
{
    emit logMessage(QXmppLogger::WarningMessage, data);
}

/// Returns true if the stream is connected.
///

bool QXmppStream::isConnected() const
{
    return d->socket &&
           d->socket->state() == QAbstractSocket::ConnectedState;
}

/// Sends raw data to the peer.
///
/// \param data

bool QXmppStream::sendData(const QByteArray &data)
{
    emit logMessage(QXmppLogger::SentMessage, QString::fromUtf8(data));
    if (!d->socket || d->socket->state() != QAbstractSocket::ConnectedState)
        return false;
    return d->socket->write(data) == data.size();
}

/// Sends an XML element to the peer.
///
/// \param element

bool QXmppStream::sendElement(const QDomElement &element)
{
    // prepare packet
    QByteArray data;
    QXmlStreamWriter xmlStream(&data);
    const QStringList omitNamespaces = QStringList() << ns_client << ns_server;
    helperToXmlAddDomElement(&xmlStream, element, omitNamespaces);

    // send packet
    return sendData(data);
}

/// Sends an XMPP packet to the peer.
///
/// \param packet

bool QXmppStream::sendPacket(const QXmppPacket &packet)
{
    // prepare packet
    QByteArray data;
    QXmlStreamWriter xmlStream(&data);
    packet.toXml(&xmlStream);

    // send packet
    return sendData(data);
}

/// Returns the QSslSocket used for this stream.
///

QSslSocket *QXmppStream::socket()
{
    return d->socket;
}

/// Sets the QSslSocket used for this stream.
///

void QXmppStream::setSocket(QSslSocket *socket)
{
    d->socket = socket;

    // socket events
    bool check = connect(socket, SIGNAL(connected()),
                    this, SLOT(socketConnected()));
    Q_ASSERT(check);

    check = connect(socket, SIGNAL(disconnected()),
                    this, SLOT(socketDisconnected()));
    Q_ASSERT(check);

    check = connect(socket, SIGNAL(encrypted()),
                    this, SLOT(socketEncrypted()));
    Q_ASSERT(check);

    check = connect(socket, SIGNAL(readyRead()),
                    this, SLOT(socketReadyRead()));
    Q_ASSERT(check);

    // relay signals
    check = connect(socket, SIGNAL(disconnected()),
                    this, SIGNAL(disconnected()));
    Q_ASSERT(check);
}

void QXmppStream::socketConnected()
{
    info(QString("Socket connected to %1 %2").arg(
        socket()->peerAddress().toString(),
        QString::number(socket()->peerPort())));
    d->dataBuffer.clear();
    handleStart();
}

void QXmppStream::socketDisconnected()
{
    info("Socket disconnected");
    d->dataBuffer.clear();
}

void QXmppStream::socketEncrypted()
{
    debug("Socket encrypted");
    d->dataBuffer.clear();
    handleStart();
}

void QXmppStream::socketReadyRead()
{
    const QByteArray data = socket()->readAll();
    //debug("SERVER [COULD BE PARTIAL DATA]:" + data.left(20));

    d->dataBuffer.append(data);

    // FIXME : maybe these QRegExps could be static?
    QRegExp startStreamRegex("^(<\\?xml.*\\?>)?\\s*<stream:stream.*>");
    startStreamRegex.setMinimal(true);
    QRegExp endStreamRegex("</stream:stream>$");
    endStreamRegex.setMinimal(true);

    // check whether we need to add stream start / end elements
    QByteArray completeXml = d->dataBuffer;
    const QString strData = QString::fromUtf8(d->dataBuffer);
    bool streamStart = false;
    if(strData.contains(startStreamRegex))
    {
        streamStart = true;
        d->streamStart = startStreamRegex.cap(0).toUtf8();
    }
    else
        completeXml.prepend(d->streamStart);
    if(!strData.contains(endStreamRegex))
        completeXml.append(streamRootElementEnd);

    // check whether we have a valid XML document
    QDomDocument doc;
    if(!doc.setContent(completeXml, true))
        return;

    // remove data from buffer
    emit logMessage(QXmppLogger::ReceivedMessage, strData);
    d->dataBuffer.clear();

    // process stream start
    QDomElement nodeRecv = doc.documentElement().firstChildElement();
    if (streamStart)
    {
        QDomElement streamElement = doc.documentElement();
        handleStream(streamElement);
    }

    // process stanzas
    while(!nodeRecv.isNull())
    {
        handleStanza(nodeRecv);
        nodeRecv = nodeRecv.nextSiblingElement();
    }
}

<|endoftext|>


<commit_before>#include "ScoreWindow.h"
#include <Button.h>

#include "EscapeCancelFilter.h"
#include "Globals.h"

#define M_RESET_SCORES 'rssc'

ScoreWindow::ScoreWindow(void)
	:	DWindow(BRect(100,500,100,400),"Best Times",B_TITLED_WINDOW,
				B_NOT_RESIZABLE | B_NOT_ZOOMABLE)
{
	AddCommonFilter(new EscapeCancelFilter());

	BView *top = GetBackgroundView();

	BStringView *begLabel = new BStringView(BRect(10,10,11,11),"beglabel",
											"Beginner:");
	begLabel->SetFont(be_bold_font);
	begLabel->ResizeToPreferred();
	top->AddChild(begLabel);

	BStringView *intLabel = new BStringView(BRect(10,10,11,11),"intlabel",
											"Intermediate:");
	intLabel->SetFont(be_bold_font);
	intLabel->ResizeToPreferred();
	intLabel->MoveBy(0,intLabel->Bounds().Height() + 10);
	top->AddChild(intLabel);

	BStringView *expLabel = new BStringView(BRect(10,10,11,11),"explabel",
											"Expert:");
	expLabel->SetFont(be_bold_font);
	expLabel->ResizeToPreferred();
	expLabel->MoveBy(0,(expLabel->Bounds().Height() + 10) * 2);
	top->AddChild(expLabel);

	fBegScore = new BStringView(BRect(10,10,11,11),"begscore",
								"Anonymous, 999 seconds");
	fBegScore->MoveTo(intLabel->Frame().right + 50,begLabel->Frame().top);
	fBegScore->ResizeToPreferred();
	top->AddChild(fBegScore);

	fIntScore = new BStringView(BRect(10,10,11,11),"intscore",
								"Anonymous, 999 seconds");
	fIntScore->MoveTo(intLabel->Frame().right + 50,intLabel->Frame().top);
	fIntScore->ResizeToPreferred();
	top->AddChild(fIntScore);

	fExpScore = new BStringView(BRect(10,10,11,11),"expscore",
								"Anonymous, 999 seconds");
	fExpScore->MoveTo(intLabel->Frame().right + 50,expLabel->Frame().top);
	fExpScore->ResizeToPreferred();
	top->AddChild(fExpScore);

	UpdateLabels();

	BButton *reset = new BButton(BRect(0,0,1,1),"reset","Reset Times",
								new BMessage(M_RESET_SCORES),
								B_FOLLOW_RIGHT | B_FOLLOW_BOTTOM);
	reset->ResizeToPreferred();
	top->AddChild(reset);

	BButton *close = new BButton(reset->Frame(),"close","Close",
								new BMessage(B_QUIT_REQUESTED),
								B_FOLLOW_RIGHT | B_FOLLOW_BOTTOM);
	close->MoveTo(Bounds().right - close->Bounds().Width() - 10.0,
					Bounds().bottom - close->Bounds().Height() - 10.0);
	top->AddChild(close);

	reset->MoveTo(close->Frame().left - 10.0 - reset->Frame().Width(),
					close->Frame().top);

	ResizeTo(fBegScore->Frame().right + 10.0,
			fExpScore->Frame().bottom + 20.0 + close->Bounds().Height());

	MakeCenteredOnShow(true);

	close->MakeDefault(true);
}

void
ScoreWindow::MessageReceived(BMessage *msg)
{
	if (msg->what == M_RESET_SCORES)
	{
		gBestTimes[DIFFICULTY_BEGINNER].Reset();
		gBestTimes[DIFFICULTY_INTERMEDIATE].Reset();
		gBestTimes[DIFFICULTY_EXPERT].Reset();
		UpdateLabels();
	}
	else
		BWindow::MessageReceived(msg);
}

void
ScoreWindow::UpdateLabels(void)
{
	BString scoreLabel;
	scoreLabel << gBestTimes[DIFFICULTY_BEGINNER].name
				<< ", " << (int)gBestTimes[DIFFICULTY_BEGINNER].time << " seconds";
	fBegScore->SetText(scoreLabel.String());
	fBegScore->ResizeToPreferred();

	scoreLabel = "";
	scoreLabel << gBestTimes[DIFFICULTY_INTERMEDIATE].name
				<< ", " << (int)gBestTimes[DIFFICULTY_INTERMEDIATE].time << " seconds";
	fIntScore->SetText(scoreLabel.String());
	fIntScore->ResizeToPreferred();

	scoreLabel = "";
	scoreLabel << gBestTimes[DIFFICULTY_EXPERT].name
				<< ", " << (int)gBestTimes[DIFFICULTY_EXPERT].time << " seconds";
	fExpScore->SetText(scoreLabel.String());
	fExpScore->ResizeToPreferred();

	BView *close = FindView("close");

	float right = MAX(fBegScore->Frame().right, fIntScore->Frame().right);
	right = MAX(right, fExpScore->Frame().right);
	right += 20;

	float bottom = fExpScore->Frame().bottom + 20.0;
	bottom += (close) ? close->Bounds().Height() : 0;
	ResizeTo(right, bottom);
}
<commit_msg>Fixes Issue #9. The current resize logic in this method did not look at the widths of all three names. The resize logic in UpdateLabels() does this correctly.<commit_after>#include "ScoreWindow.h"
#include <Button.h>

#include "EscapeCancelFilter.h"
#include "Globals.h"

#define M_RESET_SCORES 'rssc'

ScoreWindow::ScoreWindow(void)
	:	DWindow(BRect(100,500,100,400),"Best Times",B_TITLED_WINDOW,
				B_NOT_RESIZABLE | B_NOT_ZOOMABLE)
{
	AddCommonFilter(new EscapeCancelFilter());

	BView *top = GetBackgroundView();

	BStringView *begLabel = new BStringView(BRect(10,10,11,11),"beglabel",
											"Beginner:");
	begLabel->SetFont(be_bold_font);
	begLabel->ResizeToPreferred();
	top->AddChild(begLabel);

	BStringView *intLabel = new BStringView(BRect(10,10,11,11),"intlabel",
											"Intermediate:");
	intLabel->SetFont(be_bold_font);
	intLabel->ResizeToPreferred();
	intLabel->MoveBy(0,intLabel->Bounds().Height() + 10);
	top->AddChild(intLabel);

	BStringView *expLabel = new BStringView(BRect(10,10,11,11),"explabel",
											"Expert:");
	expLabel->SetFont(be_bold_font);
	expLabel->ResizeToPreferred();
	expLabel->MoveBy(0,(expLabel->Bounds().Height() + 10) * 2);
	top->AddChild(expLabel);

	fBegScore = new BStringView(BRect(10,10,11,11),"begscore",
								"Anonymous, 999 seconds");
	fBegScore->MoveTo(intLabel->Frame().right + 50,begLabel->Frame().top);
	fBegScore->ResizeToPreferred();
	top->AddChild(fBegScore);

	fIntScore = new BStringView(BRect(10,10,11,11),"intscore",
								"Anonymous, 999 seconds");
	fIntScore->MoveTo(intLabel->Frame().right + 50,intLabel->Frame().top);
	fIntScore->ResizeToPreferred();
	top->AddChild(fIntScore);

	fExpScore = new BStringView(BRect(10,10,11,11),"expscore",
								"Anonymous, 999 seconds");
	fExpScore->MoveTo(intLabel->Frame().right + 50,expLabel->Frame().top);
	fExpScore->ResizeToPreferred();
	top->AddChild(fExpScore);

	BButton *reset = new BButton(BRect(0,0,1,1),"reset","Reset Times",
								new BMessage(M_RESET_SCORES),
								B_FOLLOW_RIGHT | B_FOLLOW_BOTTOM);
	reset->ResizeToPreferred();
	top->AddChild(reset);

	BButton *close = new BButton(reset->Frame(),"close","Close",
								new BMessage(B_QUIT_REQUESTED),
								B_FOLLOW_RIGHT | B_FOLLOW_BOTTOM);
	close->MoveTo(Bounds().right - close->Bounds().Width() - 10.0,
					Bounds().bottom - close->Bounds().Height() - 10.0);
	top->AddChild(close);

	reset->MoveTo(close->Frame().left - 10.0 - reset->Frame().Width(),
					close->Frame().top);

	UpdateLabels();

	MakeCenteredOnShow(true);

	close->MakeDefault(true);
}

void
ScoreWindow::MessageReceived(BMessage *msg)
{
	if (msg->what == M_RESET_SCORES)
	{
		gBestTimes[DIFFICULTY_BEGINNER].Reset();
		gBestTimes[DIFFICULTY_INTERMEDIATE].Reset();
		gBestTimes[DIFFICULTY_EXPERT].Reset();
		UpdateLabels();
	}
	else
		BWindow::MessageReceived(msg);
}

void
ScoreWindow::UpdateLabels(void)
{
	BString scoreLabel;
	scoreLabel << gBestTimes[DIFFICULTY_BEGINNER].name
				<< ", " << (int)gBestTimes[DIFFICULTY_BEGINNER].time << " seconds";
	fBegScore->SetText(scoreLabel.String());
	fBegScore->ResizeToPreferred();

	scoreLabel = "";
	scoreLabel << gBestTimes[DIFFICULTY_INTERMEDIATE].name
				<< ", " << (int)gBestTimes[DIFFICULTY_INTERMEDIATE].time << " seconds";
	fIntScore->SetText(scoreLabel.String());
	fIntScore->ResizeToPreferred();

	scoreLabel = "";
	scoreLabel << gBestTimes[DIFFICULTY_EXPERT].name
				<< ", " << (int)gBestTimes[DIFFICULTY_EXPERT].time << " seconds";
	fExpScore->SetText(scoreLabel.String());
	fExpScore->ResizeToPreferred();

	BView *close = FindView("close");

	float right = MAX(fBegScore->Frame().right, fIntScore->Frame().right);
	right = MAX(right, fExpScore->Frame().right);
	right += 20;

	float bottom = fExpScore->Frame().bottom + 20.0;
	bottom += (close) ? close->Bounds().Height() : 0;
	ResizeTo(right, bottom);
}
<|endoftext|>


<commit_before>#include <cstdlib>
#include <sstream>
#include <osg/io_utils>
#include <osg/ArgumentParser>
#include <osg/Geode>
#include <osg/MatrixTransform>
#include <osgDB/WriteFile>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/StateSetManipulator>

void textInfo(osgText::Text* text)
{
    const osgText::Text::TextureGlyphQuadMap& tgqm = text->getTextureGlyphQuadMap();

    const osgText::Text::TextureGlyphQuadMap::const_iterator tgqmi = tgqm.begin();

    osgText::String& s = text->getText();

    for(unsigned int i = 0; i < s.size(); i++)
    {
        osg::Vec2 ul; text->getCoord(0 + (i * 4), ul); // upperLeft
        osg::Vec2 ll; text->getCoord(1 + (i * 4), ll); // lowerLeft
        osg::Vec2 lr; text->getCoord(2 + (i * 4), lr); // lowerRight
        osg::Vec2 ur; text->getCoord(3 + (i * 4), ur); // upperRight

        osg::notify(osg::NOTICE)
            << "'" << static_cast<char>(s[i]) << "':"
            << " width(" << lr.x() - ll.x() << ")"
            << " height(" << ul.y() - ll.y() << ")" << std::endl << "\t"
            << "ul(" << ul << "), "
            << "ll(" << ll << "), "
            << "lr(" << lr << "), "
            << "ur(" << ur << ")"
            << std::endl
        ;
    }
}

osg::Camera* createOrthoCamera(double width, double height)
{
    osg::Camera* camera = new osg::Camera();

    camera->getOrCreateStateSet()->setMode(
        GL_LIGHTING,
        osg::StateAttribute::PROTECTED | osg::StateAttribute::OFF
    );

    osg::Matrix m = osg::Matrix::ortho2D(0.0f, width, 0.0f, height);

    camera->setProjectionMatrix(m);
    camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
    camera->setViewMatrix(osg::Matrix::identity());
    camera->setClearMask(GL_DEPTH_BUFFER_BIT);
    camera->setRenderOrder(osg::Camera::POST_RENDER);

    return camera;
}

struct TextSettings
{
    TextSettings():
        fontFilename("fonts/arial.ttf"),
        textColor(1.0f, 1.0f, 1.0f, 1.0f),
        backdropType(osgText::Text::NONE),
        backdropOffset(0.04f, 0.04f),
        backdropColor(0.0f, 0.0f, 0.0f, 1.0f)
    {
    }

    void read(osg::ArgumentParser& arguments)
    {
        if (arguments.read("--outline")) backdropType = osgText::Text::OUTLINE;
        if (arguments.read("--shadow")) backdropType = osgText::Text::DROP_SHADOW_BOTTOM_RIGHT;

        float offset;
        if (arguments.read("--offset", offset)) backdropOffset.set(offset, offset);

        if (arguments.read("--text-color", textColor.r(), textColor.g(), textColor.b(), textColor.a())) {}
        if (arguments.read("--bd-color", backdropColor.r(), backdropColor.g(), backdropColor.b(), backdropColor.a())) {}
    }

    void setText(osgText::Text& text)
    {
        OSG_NOTICE<<"Settings::setText()"<<std::endl;
        text.setFont(fontFilename);
        text.setColor(textColor);
        text.setBackdropType(backdropType);
        text.setBackdropOffset(backdropOffset.x(), backdropOffset.y());
        text.setBackdropColor(backdropColor);
    }

    std::string                 fontFilename;
    osg::Vec4                   textColor;
    osgText::Text::BackdropType backdropType;
    osg::Vec2                   backdropOffset;
    osg::Vec4                   backdropColor;
};

osgText::Text* createLabel(const std::string& l, TextSettings& settings, unsigned int size)
{
    static osg::Vec3 pos(10.0f, 10.0f, 0.0f);

    osgText::Text* label = new osgText::Text();
    osg::ref_ptr<osgText::Font> font  = osgText::readRefFontFile(settings.fontFilename);

    settings.setText(*label);

    label->setCharacterSize(size);
    label->setFontResolution(size, size);
    label->setPosition(pos);
    label->setAlignment(osgText::Text::LEFT_BOTTOM);

    // It seems to be important we do this last to get best results?
    label->setText(l);

    // textInfo(label);

    pos.y() += size + 10.0f;

    return label;
}

typedef std::list<unsigned int> Sizes;

int main(int argc, char** argv)
{
    osg::ArgumentParser args(&argc, argv);
    osgViewer::Viewer viewer(args);

    // Make sure we have the minimum args...
    if(argc <= 2)
    {
        osg::notify(osg::FATAL) << "usage: " << args[0] << " fontfile size1 [size2 ...]" << std::endl;

        return 1;
    }

    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );
    viewer.addEventHandler(new osgViewer::StatsHandler());
    viewer.addEventHandler(new osgViewer::WindowSizeHandler());

    osg::Vec4d backgroudColor = viewer.getCamera()->getClearColor();
    if (args.read("--bg-color", backgroudColor.r(), backgroudColor.g(), backgroudColor.b(), backgroudColor.a()))
    {
        viewer.getCamera()->setClearColor(backgroudColor);
    }

    osg::ref_ptr<osg::Group> root = new osg::Group;

    bool ortho = args.read("--ortho");
    if (ortho)
    {
        osg::ref_ptr<osg::Camera> camera = createOrthoCamera(1280.0f, 1024.0f);
        root->addChild(camera.get());
        root = camera;
    }
    else
    {
        osg::ref_ptr<osg::MatrixTransform> transform = new osg::MatrixTransform;
        transform->setMatrix(osg::Matrixd::rotate(osg::DegreesToRadians(90.0), 1.0, 0.0, 0.0));
        root->addChild(transform.get());
        root = transform;
    }

    TextSettings settings;
    settings.fontFilename = argv[1];
    settings.read(args);

    // Create the list of desired sizes.
    Sizes sizes;

    for(int i = 2; i < argc; i++)
    {
        if(!args.isNumber(i)) continue;

        sizes.push_back(std::atoi(args[i]));
    }

    osg::Geode* geode = new osg::Geode();

    // Add all of our osgText drawables.
    for(Sizes::const_iterator i = sizes.begin(); i != sizes.end(); i++)
    {
        std::stringstream ss;

        ss << *i << " 1234567890 abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        geode->addDrawable(createLabel(ss.str(), settings, *i));
    }

    root->addChild(geode);

    std::string filename;
    if (args.read("-o", filename))
    {
        osgDB::writeNodeFile(*root, filename);
        return 0;
    }

    viewer.setSceneData(root.get());

    return viewer.run();
}

<commit_msg>Added --test command line option that sets up all the sizes and font settings required for a useufl unit test.<commit_after>#include <cstdlib>
#include <sstream>
#include <osg/io_utils>
#include <osg/ArgumentParser>
#include <osg/Geode>
#include <osg/MatrixTransform>
#include <osgDB/WriteFile>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
#include <osgGA/StateSetManipulator>

void textInfo(osgText::Text* text)
{
    const osgText::Text::TextureGlyphQuadMap& tgqm = text->getTextureGlyphQuadMap();

    const osgText::Text::TextureGlyphQuadMap::const_iterator tgqmi = tgqm.begin();

    osgText::String& s = text->getText();

    for(unsigned int i = 0; i < s.size(); i++)
    {
        osg::Vec2 ul; text->getCoord(0 + (i * 4), ul); // upperLeft
        osg::Vec2 ll; text->getCoord(1 + (i * 4), ll); // lowerLeft
        osg::Vec2 lr; text->getCoord(2 + (i * 4), lr); // lowerRight
        osg::Vec2 ur; text->getCoord(3 + (i * 4), ur); // upperRight

        osg::notify(osg::NOTICE)
            << "'" << static_cast<char>(s[i]) << "':"
            << " width(" << lr.x() - ll.x() << ")"
            << " height(" << ul.y() - ll.y() << ")" << std::endl << "\t"
            << "ul(" << ul << "), "
            << "ll(" << ll << "), "
            << "lr(" << lr << "), "
            << "ur(" << ur << ")"
            << std::endl
        ;
    }
}

osg::Camera* createOrthoCamera(double width, double height)
{
    osg::Camera* camera = new osg::Camera();

    camera->getOrCreateStateSet()->setMode(
        GL_LIGHTING,
        osg::StateAttribute::PROTECTED | osg::StateAttribute::OFF
    );

    osg::Matrix m = osg::Matrix::ortho2D(0.0f, width, 0.0f, height);

    camera->setProjectionMatrix(m);
    camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
    camera->setViewMatrix(osg::Matrix::identity());
    camera->setClearMask(GL_DEPTH_BUFFER_BIT);
    camera->setRenderOrder(osg::Camera::POST_RENDER);

    return camera;
}

typedef std::list<unsigned int> Sizes;

struct TextSettings
{
    TextSettings():
        fontFilename("fonts/arial.ttf"),
        textColor(1.0f, 1.0f, 1.0f, 1.0f),
        backdropType(osgText::Text::NONE),
        backdropOffset(0.04f, 0.04f),
        backdropColor(0.0f, 0.0f, 0.0f, 1.0f)
    {
    }

    void read(osg::ArgumentParser& arguments)
    {
        if (arguments.read("--test"))
        {
            backgroundColor = osg::Vec4(1.0, 1.0, 1.0, 1.0);

            fontFilename = "fonts/arialbd.ttf";
            backdropType = osgText::Text::OUTLINE;

            sizes.clear();
            sizes.push_back(8);
            sizes.push_back(16);
            sizes.push_back(32);
            sizes.push_back(64);
            sizes.push_back(128);
        }

        if (arguments.read("--font",fontFilename)) {}

        if (arguments.read("--outline")) backdropType = osgText::Text::OUTLINE;
        if (arguments.read("--shadow")) backdropType = osgText::Text::DROP_SHADOW_BOTTOM_RIGHT;

        float offset;
        if (arguments.read("--offset", offset)) backdropOffset.set(offset, offset);

        if (arguments.read("--text-color", textColor.r(), textColor.g(), textColor.b(), textColor.a())) {}
        if (arguments.read("--bd-color", backdropColor.r(), backdropColor.g(), backdropColor.b(), backdropColor.a())) {}
        if (arguments.read("--bg-color", backgroundColor.r(), backgroundColor.g(), backgroundColor.b(), backgroundColor.a())) {}

    }

    void setText(osgText::Text& text)
    {
        OSG_NOTICE<<"Settings::setText()"<<std::endl;
        text.setFont(fontFilename);
        text.setColor(textColor);
        text.setBackdropType(backdropType);
        text.setBackdropOffset(backdropOffset.x(), backdropOffset.y());
        text.setBackdropColor(backdropColor);
    }

    std::string                 fontFilename;
    osg::Vec4                   textColor;
    osgText::Text::BackdropType backdropType;
    osg::Vec2                   backdropOffset;
    osg::Vec4                   backdropColor;
    osg::Vec4                   backgroundColor;
    Sizes                       sizes;
};

osgText::Text* createLabel(const std::string& l, TextSettings& settings, unsigned int size)
{
    static osg::Vec3 pos(10.0f, 10.0f, 0.0f);

    osgText::Text* label = new osgText::Text();
    osg::ref_ptr<osgText::Font> font  = osgText::readRefFontFile(settings.fontFilename);

    settings.setText(*label);

    label->setCharacterSize(size);
    label->setFontResolution(size, size);
    label->setPosition(pos);
    label->setAlignment(osgText::Text::LEFT_BOTTOM);

    // It seems to be important we do this last to get best results?
    label->setText(l);

    // textInfo(label);

    pos.y() += size + 10.0f;

    return label;
}

int main(int argc, char** argv)
{
    osg::ArgumentParser args(&argc, argv);
    osgViewer::Viewer viewer(args);

    viewer.addEventHandler( new osgGA::StateSetManipulator(viewer.getCamera()->getOrCreateStateSet()) );
    viewer.addEventHandler(new osgViewer::StatsHandler());
    viewer.addEventHandler(new osgViewer::WindowSizeHandler());

    TextSettings settings;
    settings.backgroundColor = viewer.getCamera()->getClearColor();

    settings.read(args);

    viewer.getCamera()->setClearColor(settings.backgroundColor);

    osg::ref_ptr<osg::Group> root = new osg::Group;

    bool ortho = args.read("--ortho");
    if (ortho)
    {
        osg::ref_ptr<osg::Camera> camera = createOrthoCamera(1280.0f, 1024.0f);
        root->addChild(camera.get());
        root = camera;
    }
    else
    {
        osg::ref_ptr<osg::MatrixTransform> transform = new osg::MatrixTransform;
        transform->setMatrix(osg::Matrixd::rotate(osg::DegreesToRadians(90.0), 1.0, 0.0, 0.0));
        root->addChild(transform.get());
        root = transform;
    }

    if (args.argc() > 1)
    {
        settings.fontFilename = argv[1];

        // Create the list of desired sizes.
        for(int i = 2; i < args.argc(); i++)
        {
            if(!args.isNumber(i)) continue;

            settings.sizes.push_back(std::atoi(args[i]));
        }
    }

    if (settings.sizes.empty())
    {
        settings.sizes.push_back(8);
        settings.sizes.push_back(16);
        settings.sizes.push_back(32);
        settings.sizes.push_back(64);
    }

    osg::Geode* geode = new osg::Geode();

    // Add all of our osgText drawables.
    for(Sizes::const_iterator i = settings.sizes.begin(); i != settings.sizes.end(); i++)
    {
        std::stringstream ss;

        ss << *i << " 1234567890 abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ";

        geode->addDrawable(createLabel(ss.str(), settings, *i));
    }

    root->addChild(geode);

    std::string filename;
    if (args.read("-o", filename))
    {
        osgDB::writeNodeFile(*root, filename);
        return 0;
    }

    viewer.setSceneData(root.get());

    return viewer.run();
}

<|endoftext|>


<commit_before>/*
 Copyright (C) 2003-2005 Justin Karneges

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <QtCore>
#include <QtNetwork>
#include <QtCrypto>

void showCertInfo(const QCA::Certificate &cert)
{
	printf("-- Cert --\n");
	printf(" CN: %s\n", qPrintable(cert.commonName()));
	printf(" Valid from: %s, until %s\n",
		qPrintable(cert.notValidBefore().toString()),
		qPrintable(cert.notValidAfter().toString()));
	printf(" PEM:\n%s\n", qPrintable(cert.toPEM()));
}

static QString validityToString(QCA::Validity v)
{
	QString s;
	switch(v)
	{
		case QCA::ValidityGood:
			s = "Validated";
			break;
		case QCA::ErrorRejected:
			s = "Root CA is marked to reject the specified purpose";
			break;
		case QCA::ErrorUntrusted:
			s = "Certificate not trusted for the required purpose";
			break;
		case QCA::ErrorSignatureFailed:
			s = "Invalid signature";
			break;
		case QCA::ErrorInvalidCA:
			s = "Invalid CA certificate";
			break;
		case QCA::ErrorInvalidPurpose:
			s = "Invalid certificate purpose";
			break;
		case QCA::ErrorSelfSigned:
			s = "Certificate is self-signed";
			break;
		case QCA::ErrorRevoked:
			s = "Certificate has been revoked";
			break;
		case QCA::ErrorPathLengthExceeded:
			s = "Maximum certificate chain length exceeded";
			break;
		case QCA::ErrorExpired:
			s = "Certificate has expired";
			break;
		case QCA::ErrorExpiredCA:
			s = "CA has expired";
			break;
		case QCA::ErrorValidityUnknown:
		default:
			s = "General certificate validation error";
			break;
	}
	return s;
}

class SecureTest : public QObject
{
	Q_OBJECT
public:
	SecureTest()
	{
		sock = new QTcpSocket;
		connect(sock, SIGNAL(connected()), SLOT(sock_connected()));
		connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead()));
		connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(sock_error(QAbstractSocket::SocketError)));

		ssl = new QCA::TLS;
		connect(ssl, SIGNAL(handshaken()), SLOT(ssl_handshaken()));
		connect(ssl, SIGNAL(readyRead()), SLOT(ssl_readyRead()));
		connect(ssl, SIGNAL(readyReadOutgoing()), SLOT(ssl_readyReadOutgoing()));
		connect(ssl, SIGNAL(closed()), SLOT(ssl_closed()));
		connect(ssl, SIGNAL(error()), SLOT(ssl_error()));

		if(!QCA::haveSystemStore())
			printf("Warning: no root certs\n");

		rootCerts = QCA::systemStore();
	}

	~SecureTest()
	{
		delete ssl;
		delete sock;
	}

	void start(const QString &_host)
	{
		int n = _host.indexOf(':');
		int port;
		if(n != -1)
		{
			host = _host.mid(0, n);
			port = _host.mid(n+1).toInt();
		}
		else
		{
			host = _host;
			port = 443;
		}

		printf("Trying %s:%d...\n", qPrintable(host), port);
		sock->connectToHost(host, port);
	}

signals:
	void quit();

private slots:
	void sock_connected()
	{
		printf("Connected, starting TLS handshake...\n");
		ssl->setTrustedCertificates(rootCerts);
		ssl->startClient(host);
	}

	void sock_readyRead()
	{
		ssl->writeIncoming(sock->readAll());
	}

	void sock_connectionClosed()
	{
		printf("\nConnection closed.\n");
		quit();
	}

	void sock_error(QAbstractSocket::SocketError x)
	{
		if(x == QAbstractSocket::RemoteHostClosedError)
		{
			sock_connectionClosed();
			return;
		}

		printf("\nSocket error.\n");
		quit();
	}

	void ssl_handshaken()
	{
		QCA::TLS::IdentityResult r = ssl->peerIdentityResult();

		printf("Successful SSL handshake.\n");
		if(r != QCA::TLS::NoCertificate)
		{
			cert = ssl->peerCertificateChain().primary();
			if(!cert.isNull())
				showCertInfo(cert);
		}

		QString str = "Peer Identity: ";
		if(r == QCA::TLS::Valid)
			str += "Valid";
		else if(r == QCA::TLS::HostMismatch)
			str += "Error: Wrong certificate";
		else if(r == QCA::TLS::InvalidCertificate)
			str += "Error: Invalid certificate.\n -> Reason: " + validityToString(ssl->peerCertificateValidity());
		else
			str += "Error: No certificate";
		printf("%s\n", qPrintable(str));

		printf("Let's try a GET request now.\n");
		QString req = "GET / HTTP/1.0\nHost: " + host + "\n\n";
		ssl->write(req.toLatin1());
	}

	void ssl_readyRead()
	{
		QByteArray a = ssl->read();
		printf("%s", a.data());
	}

	void ssl_readyReadOutgoing()
	{
		sock->write(ssl->readOutgoing());
	}

	void ssl_closed()
	{
		printf("SSL session closed.\n");
	}

	void ssl_error()
	{
		int x = ssl->errorCode();
		if(x == QCA::TLS::ErrorHandshake)
		{
			printf("SSL Handshake Error!\n");
			quit();
		}
		else
		{
			printf("SSL Error!\n");
			quit();
		}
	}

private:
	QString host;
	QTcpSocket *sock;
	QCA::TLS *ssl;
	QCA::Certificate cert;
	QCA::CertificateCollection rootCerts;
};

#include "ssltest.moc"

int main(int argc, char **argv)
{
	QCA::Initializer init;

	QCoreApplication app(argc, argv);
	QString host = argc > 1 ? argv[1] : "andbit.net";

	if(!QCA::isSupported("tls"))
	{
		printf("TLS not supported!\n");
		return 1;
	}

	SecureTest *s = new SecureTest;
	QObject::connect(s, SIGNAL(quit()), &app, SLOT(quit()));
	s->start(host);
	app.exec();
	delete s;

	return 0;
}
<commit_msg>Minor tweaks to make it work better in the API documentation.<commit_after>/*
 Copyright (C) 2003-2005 Justin Karneges

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <QtCore>
#include <QtNetwork>
#include <QtCrypto>

void showCertInfo(const QCA::Certificate &cert)
{
	printf("-- Cert --\n");
	printf(" CN: %s\n", qPrintable(cert.commonName()));
	printf(" Valid from: %s, until %s\n",
		qPrintable(cert.notValidBefore().toString()),
		qPrintable(cert.notValidAfter().toString()));
	printf(" PEM:\n%s\n", qPrintable(cert.toPEM()));
}

static QString validityToString(QCA::Validity v)
{
	QString s;
	switch(v)
	{
		case QCA::ValidityGood:
			s = "Validated";
			break;
		case QCA::ErrorRejected:
			s = "Root CA is marked to reject the specified purpose";
			break;
		case QCA::ErrorUntrusted:
			s = "Certificate not trusted for the required purpose";
			break;
		case QCA::ErrorSignatureFailed:
			s = "Invalid signature";
			break;
		case QCA::ErrorInvalidCA:
			s = "Invalid CA certificate";
			break;
		case QCA::ErrorInvalidPurpose:
			s = "Invalid certificate purpose";
			break;
		case QCA::ErrorSelfSigned:
			s = "Certificate is self-signed";
			break;
		case QCA::ErrorRevoked:
			s = "Certificate has been revoked";
			break;
		case QCA::ErrorPathLengthExceeded:
			s = "Maximum certificate chain length exceeded";
			break;
		case QCA::ErrorExpired:
			s = "Certificate has expired";
			break;
		case QCA::ErrorExpiredCA:
			s = "CA has expired";
			break;
		case QCA::ErrorValidityUnknown:
		default:
			s = "General certificate validation error";
			break;
	}
	return s;
}

class SecureTest : public QObject
{
	Q_OBJECT
public:
	SecureTest()
	{
		sock = new QTcpSocket;
		connect(sock, SIGNAL(connected()), SLOT(sock_connected()));
		connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead()));
		connect(sock, SIGNAL(error(QAbstractSocket::SocketError)),
			SLOT(sock_error(QAbstractSocket::SocketError)));

		ssl = new QCA::TLS;
		connect(ssl, SIGNAL(handshaken()), SLOT(ssl_handshaken()));
		connect(ssl, SIGNAL(readyRead()), SLOT(ssl_readyRead()));
		connect(ssl, SIGNAL(readyReadOutgoing()),
			SLOT(ssl_readyReadOutgoing()));
		connect(ssl, SIGNAL(closed()), SLOT(ssl_closed()));
		connect(ssl, SIGNAL(error()), SLOT(ssl_error()));
	}

	~SecureTest()
	{
		delete ssl;
		delete sock;
	}

	void start(const QString &_host)
	{
		int n = _host.indexOf(':');
		int port;
		if(n != -1)
		{
			host = _host.mid(0, n);
			port = _host.mid(n+1).toInt();
		}
		else
		{
			host = _host;
			port = 443;
		}

		printf("Trying %s:%d...\n", qPrintable(host), port);
		sock->connectToHost(host, port);
	}

signals:
	void quit();

private slots:
	void sock_connected()
	{
		// We just do this to help doxygen...
		QCA::TLS *ssl = SecureTest::ssl;

		printf("Connected, starting TLS handshake...\n");

		if(!QCA::haveSystemStore())
			printf("Warning: no root certs\n");
		else
			ssl->setTrustedCertificates(QCA::systemStore());

		ssl->startClient(host);
	}

	void sock_readyRead()
	{
		// We just do this to help doxygen...
		QCA::TLS *ssl = SecureTest::ssl;

		ssl->writeIncoming(sock->readAll());
	}

	void sock_connectionClosed()
	{
		printf("\nConnection closed.\n");
		quit();
	}

	void sock_error(QAbstractSocket::SocketError x)
	{
		if(x == QAbstractSocket::RemoteHostClosedError)
		{
			sock_connectionClosed();
			return;
		}

		printf("\nSocket error.\n");
		quit();
	}

	void ssl_handshaken()
	{
		// We just do this to help doxygen...
		QCA::TLS *ssl = SecureTest::ssl;

		QCA::TLS::IdentityResult r = ssl->peerIdentityResult();

		printf("Successful SSL handshake using %s (%i of %i bits)\n",
		       qPrintable(ssl->cipherSuite()),
		       ssl->cipherBits(),
		       ssl->cipherMaxBits() );
		if(r != QCA::TLS::NoCertificate)
		{
			cert = ssl->peerCertificateChain().primary();
			if(!cert.isNull())
				showCertInfo(cert);
		}

		QString str = "Peer Identity: ";
		if(r == QCA::TLS::Valid)
			str += "Valid";
		else if(r == QCA::TLS::HostMismatch)
			str += "Error: Wrong certificate";
		else if(r == QCA::TLS::InvalidCertificate)
			str += "Error: Invalid certificate.\n -> Reason: " +
				validityToString(ssl->peerCertificateValidity());
		else
			str += "Error: No certificate";
		printf("%s\n", qPrintable(str));

		printf("Let's try a GET request now.\n");
		QString req = "GET / HTTP/1.0\nHost: " + host + "\n\n";
		ssl->write(req.toLatin1());
	}

	void ssl_readyRead()
	{
		// We just do this to help doxygen...
		QCA::TLS *ssl = SecureTest::ssl;

		QByteArray a = ssl->read();
		printf("%s", a.data());
	}

	void ssl_readyReadOutgoing()
	{
		// We just do this to help doxygen...
		QCA::TLS *ssl = SecureTest::ssl;

		sock->write(ssl->readOutgoing());
	}

	void ssl_closed()
	{
		printf("SSL session closed.\n");
	}

	void ssl_error()
	{
		// We just do this to help doxygen...
		QCA::TLS *ssl = SecureTest::ssl;

		int x = ssl->errorCode();
		if(x == QCA::TLS::ErrorHandshake)
		{
			printf("SSL Handshake Error!\n");
			quit();
		}
		else
		{
			printf("SSL Error!\n");
			quit();
		}
	}

private:
	QString host;
	QTcpSocket *sock;
	QCA::TLS *ssl;
	QCA::Certificate cert;
};

#include "ssltest.moc"

int main(int argc, char **argv)
{
	QCA::Initializer init;

	QCoreApplication app(argc, argv);
	QString host = argc > 1 ? argv[1] : "andbit.net";

	if(!QCA::isSupported("tls"))
	{
		printf("TLS not supported!\n");
		return 1;
	}

	SecureTest *s = new SecureTest;
	QObject::connect(s, SIGNAL(quit()), &app, SLOT(quit()));
	s->start(host);
	app.exec();
	delete s;

	return 0;
}
<|endoftext|>


<commit_before>#include "HalideRuntime.h"

// Grab the internal device_interface functions
#define WEAK
#include "device_interface.h"

#include <stdio.h>
#include <stdlib.h>

#include "cleanup_on_error.h"
#include "static_image.h"

const int size = 64;

int successful_mallocs = 0, failed_mallocs = 0, frees = 0, errors = 0, device_mallocs = 0, device_frees = 0;

extern "C" void *halide_malloc(void *user_context, size_t x) {
    // Only the first malloc succeeds
    if (successful_mallocs) {
        failed_mallocs++;
        return NULL;
    }
    successful_mallocs++;

    void *orig = malloc(x+40);
    // Round up to next multiple of 32. Should add at least 8 bytes so we can fit the original pointer.
    void *ptr = (void *)((((size_t)orig + 32) >> 5) << 5);
    ((void **)ptr)[-1] = orig;
    return ptr;
}

extern "C" void halide_free(void *user_context, void *ptr) {
    frees++;
    free(((void**)ptr)[-1]);
}

extern "C" void halide_error(void *user_context, const char *msg) {
    errors++;
}

extern "C" int halide_device_free(void *user_context, struct buffer_t *buf) {
    device_frees++;
    const halide_device_interface *interface = halide_get_device_interface(buf->dev);
    return interface->device_free(user_context, buf);
}

extern "C" int halide_device_malloc(void *user_context, struct buffer_t *buf, const halide_device_interface *interface) {
    device_mallocs++;
    return interface->device_malloc(user_context, buf);
}

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

    Image<int32_t> output(size);
    int result = cleanup_on_error(output);

    if (result != halide_error_code_out_of_memory) {
        printf("The exit status was %d instead of -10\n", result);
        return -1;
    }

    if (failed_mallocs != 1) {
        printf("One of the mallocs was supposed to fail\n");
        return -1;
    }

    if (successful_mallocs != 1) {
        printf("One of the mallocs was supposed to succeed\n");
        return -1;
    }

    if (frees != 1) {
        printf("The successful malloc should have been freed\n");
        return -1;
    }

    if (errors != 1) {
        // There's one error from the malloc failing
        printf("There was supposed to be one error\n");
        return -1;
    }

    if (device_mallocs != device_frees) {
        printf("There were a different number of device mallocs (%d) and frees (%d)\n", device_mallocs, device_frees);
        return -1;
    }

    printf("Success!\n");
    return 0;
}
<commit_msg>Missed a case where I was using a number instead of an error code<commit_after>#include "HalideRuntime.h"

// Grab the internal device_interface functions
#define WEAK
#include "device_interface.h"

#include <stdio.h>
#include <stdlib.h>

#include "cleanup_on_error.h"
#include "static_image.h"

const int size = 64;

int successful_mallocs = 0, failed_mallocs = 0, frees = 0, errors = 0, device_mallocs = 0, device_frees = 0;

extern "C" void *halide_malloc(void *user_context, size_t x) {
    // Only the first malloc succeeds
    if (successful_mallocs) {
        failed_mallocs++;
        return NULL;
    }
    successful_mallocs++;

    void *orig = malloc(x+40);
    // Round up to next multiple of 32. Should add at least 8 bytes so we can fit the original pointer.
    void *ptr = (void *)((((size_t)orig + 32) >> 5) << 5);
    ((void **)ptr)[-1] = orig;
    return ptr;
}

extern "C" void halide_free(void *user_context, void *ptr) {
    frees++;
    free(((void**)ptr)[-1]);
}

extern "C" void halide_error(void *user_context, const char *msg) {
    errors++;
}

extern "C" int halide_device_free(void *user_context, struct buffer_t *buf) {
    device_frees++;
    const halide_device_interface *interface = halide_get_device_interface(buf->dev);
    return interface->device_free(user_context, buf);
}

extern "C" int halide_device_malloc(void *user_context, struct buffer_t *buf, const halide_device_interface *interface) {
    device_mallocs++;
    return interface->device_malloc(user_context, buf);
}

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

    Image<int32_t> output(size);
    int result = cleanup_on_error(output);

    if (result != halide_error_code_out_of_memory) {
        printf("The exit status was %d instead of %d\n", result, halide_error_code_out_of_memory);
        return -1;
    }

    if (failed_mallocs != 1) {
        printf("One of the mallocs was supposed to fail\n");
        return -1;
    }

    if (successful_mallocs != 1) {
        printf("One of the mallocs was supposed to succeed\n");
        return -1;
    }

    if (frees != 1) {
        printf("The successful malloc should have been freed\n");
        return -1;
    }

    if (errors != 1) {
        // There's one error from the malloc failing
        printf("There was supposed to be one error\n");
        return -1;
    }

    if (device_mallocs != device_frees) {
        printf("There were a different number of device mallocs (%d) and frees (%d)\n", device_mallocs, device_frees);
        return -1;
    }

    printf("Success!\n");
    return 0;
}
<|endoftext|>


<commit_before>// Copyright 2015 by Martin Moene
//
// gsl-lite is based on GSL: Guideline Support Library,
// https://github.com/microsoft/gsl
//
// This code is licensed under the MIT License (MIT).
//

#include "gsl-lite.t.h"

#define gsl_PRESENT( x ) \
    std::cout << #x << ": " << x << "\n"

#define gsl_ABSENT( x ) \
    std::cout << #x << ": (undefined)\n"

lest::tests & specification()
{
    static lest::tests tests;
    return tests;
}

CASE( "__cplusplus" "[.stdc++]" )
{
    gsl_PRESENT( __cplusplus );
}

CASE( "Presence of C++ language features" "[.stdlanguage]" )
{
#if gsl_HAVE_AUTO
    gsl_PRESENT( gsl_HAVE_AUTO );
#else
    gsl_ABSENT(  gsl_HAVE_AUTO );
#endif

#if gsl_HAVE_NULLPTR
    gsl_PRESENT( gsl_HAVE_NULLPTR );
#else
    gsl_ABSENT(  gsl_HAVE_NULLPTR );
#endif

#if gsl_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG
    gsl_PRESENT( gsl_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG );
#else
    gsl_ABSENT(  gsl_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG );
#endif

#if gsl_HAVE_ALIAS_TEMPLATE
    gsl_PRESENT( gsl_HAVE_ALIAS_TEMPLATE );
#else
    gsl_ABSENT(  gsl_HAVE_ALIAS_TEMPLATE );
#endif

#if gsl_HAVE_CONSTEXPR_11
    gsl_PRESENT( gsl_HAVE_CONSTEXPR_11 );
#else
    gsl_ABSENT(  gsl_HAVE_CONSTEXPR_11 );
#endif

#if gsl_HAVE_CONSTEXPR_14
    gsl_PRESENT( gsl_HAVE_CONSTEXPR_14 );
#else
    gsl_ABSENT(  gsl_HAVE_CONSTEXPR_14 );
#endif

#if gsl_HAVE_ENUM_CLASS
    gsl_PRESENT( gsl_HAVE_ENUM_CLASS );
#else
    gsl_ABSENT(  gsl_HAVE_ENUM_CLASS );
#endif

#if gsl_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE
    gsl_PRESENT( gsl_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE );
#else
    gsl_ABSENT(  gsl_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE );
#endif

#if gsl_HAVE_EXPLICIT_CONVERSION
    gsl_PRESENT( gsl_HAVE_EXPLICIT_CONVERSION );
#else
    gsl_ABSENT(  gsl_HAVE_EXPLICIT_CONVERSION );
#endif

#if gsl_HAVE_INITIALIZER_LIST
    gsl_PRESENT( gsl_HAVE_INITIALIZER_LIST );
#else
    gsl_ABSENT(  gsl_HAVE_INITIALIZER_LIST );
#endif

#if gsl_HAVE_IS_DEFAULT
    gsl_PRESENT( gsl_HAVE_IS_DEFAULT );
#else
    gsl_ABSENT(  gsl_HAVE_IS_DEFAULT );
#endif

#if gsl_HAVE_IS_DELETE
    gsl_PRESENT( gsl_HAVE_IS_DELETE );
#else
    gsl_ABSENT(  gsl_HAVE_IS_DELETE );
#endif

#if gsl_HAVE_NOEXCEPT
    gsl_PRESENT( gsl_HAVE_NOEXCEPT );
#else
    gsl_ABSENT(  gsl_HAVE_NOEXCEPT );
#endif
}

CASE( "Presence of C++ library features" "[.stdlibrary]" )
{
#if gsl_HAVE_ARRAY
    gsl_PRESENT( gsl_HAVE_ARRAY );
#else
    gsl_ABSENT(  gsl_HAVE_ARRAY );
#endif

#if gsl_HAVE_CONTAINER_DATA_METHOD
    gsl_PRESENT( gsl_HAVE_CONTAINER_DATA_METHOD );
#else
    gsl_ABSENT(  gsl_HAVE_CONTAINER_DATA_METHOD );
#endif

#if gsl_HAVE_SIZED_TYPES
    gsl_PRESENT( gsl_HAVE_SIZED_TYPES );
#else
    gsl_ABSENT(  gsl_HAVE_SIZED_TYPES );
#endif

#if gsl_HAVE_SHARED_PTR
    gsl_PRESENT( gsl_HAVE_SHARED_PTR );
#else
    gsl_ABSENT(  gsl_HAVE_SHARED_PTR );
#endif

#if gsl_HAVE_UNIQUE_PTR
    gsl_PRESENT( gsl_HAVE_UNIQUE_PTR );
#else
    gsl_ABSENT(  gsl_HAVE_UNIQUE_PTR );
#endif

#if gsl_HAVE_TYPE_TRAITS
    gsl_PRESENT( gsl_HAVE_TYPE_TRAITS );
#else
    gsl_ABSENT(  gsl_HAVE_TYPE_TRAITS );
#endif

#if _HAS_CPP0X
    gsl_PRESENT( _HAS_CPP0X );
#else
    gsl_ABSENT(  _HAS_CPP0X );
#endif
}

int main( int argc, char * argv[] )
{
    return lest::run( specification(), argc, argv );
}

#if 0
g++            -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp byte.t.cpp issue.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass
g++ -std=c++98 -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp byte.t.cpp issue.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass
g++ -std=c++03 -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp byte.t.cpp issue.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass
g++ -std=c++0x -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp byte.t.cpp issue.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass
g++ -std=c++11 -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp byte.t.cpp issue.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass
g++ -std=c++14 -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp byte.t.cpp issue.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass

cl -EHsc -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS gsl-lite.t.cpp assert.t.cpp at.t.cpp byte.t.cpp issue.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass

cl -EHsc -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -Dgsl_CONFIG_CONFIRMS_COMPILATION_ERRORS gsl-lite.t.cpp assert.t.cpp at.t.cpp byte.t.cpp issue.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass
#endif

// end of file
<commit_msg>Add gsl lite version to output<commit_after>// Copyright 2015 by Martin Moene
//
// gsl-lite is based on GSL: Guideline Support Library,
// https://github.com/microsoft/gsl
//
// This code is licensed under the MIT License (MIT).
//

#include "gsl-lite.t.h"

#define gsl_PRESENT( x ) \
    std::cout << #x << ": " << x << "\n"

#define gsl_ABSENT( x ) \
    std::cout << #x << ": (undefined)\n"

lest::tests & specification()
{
    static lest::tests tests;
    return tests;
}

CASE( "gsl-lite version" "[.version]" )
{
    gsl_PRESENT( gsl_lite_VERSION );
}

CASE( "__cplusplus" "[.stdc++]" )
{
    gsl_PRESENT( __cplusplus );
}

CASE( "Presence of C++ language features" "[.stdlanguage]" )
{
#if gsl_HAVE_AUTO
    gsl_PRESENT( gsl_HAVE_AUTO );
#else
    gsl_ABSENT(  gsl_HAVE_AUTO );
#endif

#if gsl_HAVE_NULLPTR
    gsl_PRESENT( gsl_HAVE_NULLPTR );
#else
    gsl_ABSENT(  gsl_HAVE_NULLPTR );
#endif

#if gsl_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG
    gsl_PRESENT( gsl_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG );
#else
    gsl_ABSENT(  gsl_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG );
#endif

#if gsl_HAVE_ALIAS_TEMPLATE
    gsl_PRESENT( gsl_HAVE_ALIAS_TEMPLATE );
#else
    gsl_ABSENT(  gsl_HAVE_ALIAS_TEMPLATE );
#endif

#if gsl_HAVE_CONSTEXPR_11
    gsl_PRESENT( gsl_HAVE_CONSTEXPR_11 );
#else
    gsl_ABSENT(  gsl_HAVE_CONSTEXPR_11 );
#endif

#if gsl_HAVE_CONSTEXPR_14
    gsl_PRESENT( gsl_HAVE_CONSTEXPR_14 );
#else
    gsl_ABSENT(  gsl_HAVE_CONSTEXPR_14 );
#endif

#if gsl_HAVE_ENUM_CLASS
    gsl_PRESENT( gsl_HAVE_ENUM_CLASS );
#else
    gsl_ABSENT(  gsl_HAVE_ENUM_CLASS );
#endif

#if gsl_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE
    gsl_PRESENT( gsl_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE );
#else
    gsl_ABSENT(  gsl_HAVE_ENUM_CLASS_CONSTRUCTION_FROM_UNDERLYING_TYPE );
#endif

#if gsl_HAVE_EXPLICIT_CONVERSION
    gsl_PRESENT( gsl_HAVE_EXPLICIT_CONVERSION );
#else
    gsl_ABSENT(  gsl_HAVE_EXPLICIT_CONVERSION );
#endif

#if gsl_HAVE_INITIALIZER_LIST
    gsl_PRESENT( gsl_HAVE_INITIALIZER_LIST );
#else
    gsl_ABSENT(  gsl_HAVE_INITIALIZER_LIST );
#endif

#if gsl_HAVE_IS_DEFAULT
    gsl_PRESENT( gsl_HAVE_IS_DEFAULT );
#else
    gsl_ABSENT(  gsl_HAVE_IS_DEFAULT );
#endif

#if gsl_HAVE_IS_DELETE
    gsl_PRESENT( gsl_HAVE_IS_DELETE );
#else
    gsl_ABSENT(  gsl_HAVE_IS_DELETE );
#endif

#if gsl_HAVE_NOEXCEPT
    gsl_PRESENT( gsl_HAVE_NOEXCEPT );
#else
    gsl_ABSENT(  gsl_HAVE_NOEXCEPT );
#endif
}

CASE( "Presence of C++ library features" "[.stdlibrary]" )
{
#if gsl_HAVE_ARRAY
    gsl_PRESENT( gsl_HAVE_ARRAY );
#else
    gsl_ABSENT(  gsl_HAVE_ARRAY );
#endif

#if gsl_HAVE_CONTAINER_DATA_METHOD
    gsl_PRESENT( gsl_HAVE_CONTAINER_DATA_METHOD );
#else
    gsl_ABSENT(  gsl_HAVE_CONTAINER_DATA_METHOD );
#endif

#if gsl_HAVE_SIZED_TYPES
    gsl_PRESENT( gsl_HAVE_SIZED_TYPES );
#else
    gsl_ABSENT(  gsl_HAVE_SIZED_TYPES );
#endif

#if gsl_HAVE_SHARED_PTR
    gsl_PRESENT( gsl_HAVE_SHARED_PTR );
#else
    gsl_ABSENT(  gsl_HAVE_SHARED_PTR );
#endif

#if gsl_HAVE_UNIQUE_PTR
    gsl_PRESENT( gsl_HAVE_UNIQUE_PTR );
#else
    gsl_ABSENT(  gsl_HAVE_UNIQUE_PTR );
#endif

#if gsl_HAVE_TYPE_TRAITS
    gsl_PRESENT( gsl_HAVE_TYPE_TRAITS );
#else
    gsl_ABSENT(  gsl_HAVE_TYPE_TRAITS );
#endif

#if _HAS_CPP0X
    gsl_PRESENT( _HAS_CPP0X );
#else
    gsl_ABSENT(  _HAS_CPP0X );
#endif
}

int main( int argc, char * argv[] )
{
    return lest::run( specification(), argc, argv );
}

#if 0
g++            -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp byte.t.cpp issue.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass
g++ -std=c++98 -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp byte.t.cpp issue.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass
g++ -std=c++03 -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp byte.t.cpp issue.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass
g++ -std=c++0x -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp byte.t.cpp issue.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass
g++ -std=c++11 -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp byte.t.cpp issue.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass
g++ -std=c++14 -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -o gsl-lite.t.exe gsl-lite.t.cpp assert.t.cpp at.t.cpp byte.t.cpp issue.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass

cl -EHsc -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS gsl-lite.t.cpp assert.t.cpp at.t.cpp byte.t.cpp issue.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass

cl -EHsc -I../include/gsl -Dgsl_CONFIG_CONTRACT_VIOLATION_THROWS -Dgsl_CONFIG_CONFIRMS_COMPILATION_ERRORS gsl-lite.t.cpp assert.t.cpp at.t.cpp byte.t.cpp issue.t.cpp not_null.t.cpp owner.t.cpp span.t.cpp string_span.t.cpp util.t.cpp && gsl-lite.t.exe --pass
#endif

// end of file
<|endoftext|>


<commit_before>#include <silicium/make_array.hpp>
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE(make_array_inferred_type)
{
	{
		std::array<int, 1> a = Si::make_array(1);
		BOOST_CHECK_EQUAL(1, a[0]);
	}
	{
		std::array<int, 2> b = Si::make_array(1, 2);
		BOOST_CHECK_EQUAL(1, b[0]);
		BOOST_CHECK_EQUAL(2, b[1]);
	}
	{
		std::array<long, 2> c = Si::make_array(1, 2L);
		BOOST_CHECK_EQUAL(1, c[0]);
		BOOST_CHECK_EQUAL(2, c[1]);
	}
	{
		std::array<long long, 3> d = Si::make_array(1, 2L, 3LL);
		BOOST_CHECK_EQUAL(1, d[0]);
		BOOST_CHECK_EQUAL(2, d[1]);
		BOOST_CHECK_EQUAL(3, d[2]);
	}
}

BOOST_AUTO_TEST_CASE(make_array_explicit_type)
{
	{
		std::array<int, 1> a = Si::make_array<int>(1);
		BOOST_CHECK_EQUAL(1, a[0]);
	}
	{
		std::array<int, 2> b = Si::make_array<int>(1, 2);
		BOOST_CHECK_EQUAL(1, b[0]);
		BOOST_CHECK_EQUAL(2, b[1]);
	}
	{
		std::array<long, 2> c = Si::make_array<long>(1, 2L);
		BOOST_CHECK_EQUAL(1, c[0]);
		BOOST_CHECK_EQUAL(2, c[1]);
	}
	{
		std::array<long long, 3> d = Si::make_array<long long>(1, 2L, 3LL);
		BOOST_CHECK_EQUAL(1, d[0]);
		BOOST_CHECK_EQUAL(2, d[1]);
		BOOST_CHECK_EQUAL(3, d[2]);
	}
	{
		std::array<long long, 1> a = Si::make_array<long long>(1);
		BOOST_CHECK_EQUAL(1, a[0]);
	}
}
<commit_msg>test make_array with zero elements<commit_after>#include <silicium/make_array.hpp>
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE(make_array_inferred_type)
{
	{
		std::array<int, 1> a = Si::make_array(1);
		BOOST_CHECK_EQUAL(1, a[0]);
	}
	{
		std::array<int, 2> b = Si::make_array(1, 2);
		BOOST_CHECK_EQUAL(1, b[0]);
		BOOST_CHECK_EQUAL(2, b[1]);
	}
	{
		std::array<long, 2> c = Si::make_array(1, 2L);
		BOOST_CHECK_EQUAL(1, c[0]);
		BOOST_CHECK_EQUAL(2, c[1]);
	}
	{
		std::array<long long, 3> d = Si::make_array(1, 2L, 3LL);
		BOOST_CHECK_EQUAL(1, d[0]);
		BOOST_CHECK_EQUAL(2, d[1]);
		BOOST_CHECK_EQUAL(3, d[2]);
	}
}

BOOST_AUTO_TEST_CASE(make_array_explicit_type)
{
	{
		std::array<int, 1> a = Si::make_array<int>(1);
		BOOST_CHECK_EQUAL(1, a[0]);
	}
	{
		std::array<int, 2> b = Si::make_array<int>(1, 2);
		BOOST_CHECK_EQUAL(1, b[0]);
		BOOST_CHECK_EQUAL(2, b[1]);
	}
	{
		std::array<long, 2> c = Si::make_array<long>(1, 2L);
		BOOST_CHECK_EQUAL(1, c[0]);
		BOOST_CHECK_EQUAL(2, c[1]);
	}
	{
		std::array<long long, 3> d = Si::make_array<long long>(1, 2L, 3LL);
		BOOST_CHECK_EQUAL(1, d[0]);
		BOOST_CHECK_EQUAL(2, d[1]);
		BOOST_CHECK_EQUAL(3, d[2]);
	}
	{
		std::array<long long, 1> e = Si::make_array<long long>(1);
		BOOST_CHECK_EQUAL(1, e[0]);
	}
	{
		std::array<int, 0> f = Si::make_array<int>();
		BOOST_CHECK_EQUAL(0, f.size());
	}
}
<|endoftext|>


<commit_before>///
/// @file   pod_vector.cpp
/// @brief  Plain old data vector, like std::vector but does not
///         default initialize memory.
///
/// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <pod_vector.hpp>
#include <macros.hpp>

#include <cstdlib>
#include <iostream>
#include <random>
#include <numeric>

using std::size_t;
using primecount::pod_vector;

void check(bool OK)
{
  std::cout << "   " << (OK ? "OK" : "ERROR") << "\n";
  if (!OK)
    std::exit(1);
}

NOINLINE void resize(pod_vector<char>& vect, size_t size)
{
  vect.resize(0);
  vect.resize(size);
}

int main()
{
  // The pod_vector class uses std::vector internally. For
  // performance reasons we want vector::resize() not to
  // free memory when resizing to a smaller size. The C++
  // standard seems to indirectly guarantee this behavior,
  // but it is not 100% clear. So this tests verifies this
  // behavior.

  // Allocate from 1 KiB to 128 MiB
  for (size_t i = 10; i <= 27; i++)
  {
    pod_vector<char> vect;
    vect.resize(size_t(1) << i);
    auto capacity1 = vect.capacity();
    vect.resize(100);
    auto capacity2 = vect.capacity();

    std::cout << "vect.resize(100).capacity = " << capacity1;
    check(capacity1 == capacity2);
  }

  {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<int> dist(10000, 20000);

    int size = dist(gen);
    pod_vector<int> vect(size);
    std::fill_n(&vect[0], size, 123);

    // Test if resize does not default initilize
    vect.resize(0);
    vect.resize(size);
    int sum = std::accumulate(&vect[0], &vect[0] + size, 0);
    std::cout << "Vect sum after resize: " << sum;
    check(sum == 123 * size);
  }

  // This test would take forever (3000 secs on i5-12600K
  // CPU from 2022) using std::vector because
  // std::vector.resize() default initializes memory
  // (to 0) on each resize whereas pod_vector does not.
  pod_vector<char> vect;
  for (int i = 0; i < 1000000; i++)
    resize(vect, /* size = 64MiB */ 64 << 20);

  std::cout << std::endl;
  std::cout << "All tests passed successfully!" << std::endl;

  return 0;
}
<commit_msg>Speed up test<commit_after>///
/// @file   pod_vector.cpp
/// @brief  Plain old data vector, like std::vector but does not
///         default initialize memory.
///
/// Copyright (C) 2022 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <pod_vector.hpp>
#include <macros.hpp>

#include <cstdlib>
#include <iostream>
#include <random>
#include <numeric>

using std::size_t;
using primecount::pod_vector;

void check(bool OK)
{
  std::cout << "   " << (OK ? "OK" : "ERROR") << "\n";
  if (!OK)
    std::exit(1);
}

NOINLINE void resize(pod_vector<char>& vect, size_t size)
{
  vect.resize(0);
  vect.resize(size);
}

int main()
{
  // The pod_vector class uses std::vector internally. For
  // performance reasons we want vector::resize() not to
  // free memory when resizing to a smaller size. The C++
  // standard seems to indirectly guarantee this behavior,
  // but it is not 100% clear. So this tests verifies this
  // behavior.

  // Allocate from 1 KiB to 128 MiB
  for (size_t i = 10; i <= 27; i++)
  {
    pod_vector<char> vect;
    vect.resize(size_t(1) << i);
    auto capacity1 = vect.capacity();
    vect.resize(100);
    auto capacity2 = vect.capacity();

    std::cout << "vect.resize(100).capacity = " << capacity1;
    check(capacity1 == capacity2);
  }

  {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<int> dist(10000, 20000);

    int size = dist(gen);
    pod_vector<int> vect(size);
    std::fill_n(&vect[0], size, 123);

    // Test if resize does not default initilize
    vect.resize(0);
    vect.resize(size);
    int sum = std::accumulate(&vect[0], &vect[0] + size, 0);
    std::cout << "Vect sum after resize: " << sum;
    check(sum == 123 * size);
  }

  // This test runs too slow without
  // compiler optimization flags.
#if defined(__OPTIMIZE__)
  // This test would take forever (3000 secs on i5-12600K
  // CPU from 2022) using std::vector because
  // std::vector.resize() default initializes memory
  // (to 0) on each resize whereas pod_vector does not.
  pod_vector<char> vect;
  for (int i = 0; i < 1000000; i++)
    resize(vect, /* size = 64MiB */ 64 << 20);
#endif

  std::cout << std::endl;
  std::cout << "All tests passed successfully!" << std::endl;

  return 0;
}
<|endoftext|>