<commit_before>#include "Core/Time.h"
#include "Containers/String.h"

#include <time.h>
#include <cstdio>

namespace Intra {

DateTime DateTime::Now()
{
	const time_t t = time(0);
	tm* now = localtime(&t);
	return {ushort(now->tm_year+1900), byte(now->tm_mon+1), (byte)now->tm_mday,
		(byte)now->tm_hour, (byte)now->tm_min, (byte)now->tm_sec};
}

String ToString(const DateTime& datetime)
{
	return String::Format()
		(datetime.Day, 2, '0')(".")(datetime.Month, 2, '0')(".")(datetime.Year)(" ")
		(datetime.Hour, 2, '0')(":")(datetime.Minute, 2, '0')(":")(datetime.Second, 2, '0');
}

}

#if(INTRA_LIBRARY_TIMER==INTRA_LIBRARY_TIMER_Dummy)

namespace Intra {

Timer::Timer() = default;
Timer::~Timer() = default;
void Timer::Reset() {}
double Timer::GetTime() {return 0;}
double Timer::GetTimeAndReset() {return 0;}
void Timer::Wait(uint msec) {}

}

#elif(INTRA_LIBRARY_TIMER==INTRA_LIBRARY_TIMER_QPC)

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>

namespace Intra {

static ulong64 g_timer_frequency;

Timer::Timer()
{
	QueryPerformanceFrequency((LARGE_INTEGER*)&g_timer_frequency);
	Reset();
}

Timer::~Timer() = default;

void Timer::Reset() {GetTimeAndReset();}

double Timer::GetTime()
{
	const ulong64 oldHndl = hndl;
	const double result = GetTimeAndReset();
	hndl = oldHndl;
	return result;
}

double Timer::GetTimeAndReset()
{
	ulong64 current;
	QueryPerformanceCounter((LARGE_INTEGER*)&current);
	double result = double(current-hndl)/g_timer_frequency;
	hndl = current;
	return result;
}

}

#elif(INTRA_LIBRARY_TIMER==INTRA_LIBRARY_TIMER_CPPLIB)

#include <chrono>
#include <thread>

namespace Intra {

Timer::Timer()
{
	hndl = (ulong64)new std::chrono::high_resolution_clock::time_point(std::chrono::high_resolution_clock::now());
}

Timer::~Timer()
{
	delete (std::chrono::high_resolution_clock::time_point*)hndl;
}

//Получить время таймера и сбросить его
double Timer::GetTimeAndReset()
{
	auto current = std::chrono::high_resolution_clock::now();
	auto& prev = *(std::chrono::high_resolution_clock::time_point*)hndl;
	auto result = std::chrono::duration<double, std::ratio<1,1>>(current-prev).count();
	*(std::chrono::high_resolution_clock::time_point*)hndl = current;
	return result;
}

double Timer::GetTime()
{
	auto current = std::chrono::high_resolution_clock::now();
	auto& prev = *(std::chrono::high_resolution_clock::time_point*)hndl;
	auto result = std::chrono::duration<double, std::ratio<1, 1>>(current-prev).count();
	return result;
}

void Timer::Reset()
{
	auto current = std::chrono::high_resolution_clock::now();
	*(std::chrono::high_resolution_clock::time_point*)hndl = current;
}

//void Timer::Wait(uint msec) {std::this_thread::sleep_for(std::chrono::milliseconds(msec));}

}

#elif INTRA_LIBRARY_TIMER==INTRA_LIBRARY_TIMER_Qt
#include <QtCore/QElapsedTimer>
#include <QtCore/QThread>

namespace Intra {

Timer::Timer()
{
	hndl = (ulong64)new QElapsedTimer;
	Reset();
}

Timer::~Timer() {delete (QElapsedTimer*)hndl;}

void Timer::Reset() {((QElapsedTimer*)hndl)->start();}

double Timer::GetTime()
{
	const double result = (double)((QElapsedTimer*)hndl)->nsecsElapsed()/1000000000;
	return result;
}

double Timer::GetTimeAndReset()
{
	const double result = GetTime();
	Reset();
	return result;
}

/*void Timer::Wait(uint msec)
{
	struct SleepThread: public QThread {using QThread::msleep;};
	SleepThread::msleep(msec);
}*/

}

#elif INTRA_LIBRARY_TIMER==INTRA_LIBRARY_TIMER_CLIB

namespace Intra {

Timer::Timer() {hndl = clock();}
Timer::~Timer() = default;
void Timer::Reset() {hndl = clock();}
double Timer::GetTime() {return double(clock()-hndl)/CLOCKS_PER_SEC;}

double Timer::GetTimeAndReset()
{
	auto newHndl = clock();
	const double result = double(newHndl-hndl)/CLOCKS_PER_SEC;
	hndl = newHndl;
	return result;
}

}

#else
#error "INTRA_LIBRARY_TIMER define is invalid!"
#endif

#if INTRA_PLATFORM_OS==INTRA_PLATFORM_OS_Windows

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>

namespace Intra {

void Timer::Wait(uint msec) {Sleep(msec);}

}

#elif defined(INTRA_PLATFORM_IS_POSIX)

#include <unistd.h>

namespace Intra {

void Timer::Wait(uint msec)
{
	if(msec < (1 << 29)/125 ) usleep(msec*1000);
	else sleep((msec+999)/1000);
}

}

#endif

<commit_msg>Clang fix<commit_after>#include "Core/Time.h"
#include "Containers/String.h"

#include <time.h>

namespace Intra {

DateTime DateTime::Now()
{
	const time_t t = time(0);
	tm* now = localtime(&t);
	return {ushort(now->tm_year+1900), byte(now->tm_mon+1), (byte)now->tm_mday,
		(byte)now->tm_hour, (byte)now->tm_min, (byte)now->tm_sec};
}

String ToString(const DateTime& datetime)
{
	return String::Format()
		(datetime.Day, 2, '0')(".")(datetime.Month, 2, '0')(".")(datetime.Year)(" ")
		(datetime.Hour, 2, '0')(":")(datetime.Minute, 2, '0')(":")(datetime.Second, 2, '0');
}

}

#if(INTRA_LIBRARY_TIMER==INTRA_LIBRARY_TIMER_Dummy)

namespace Intra {

Timer::Timer() = default;
Timer::~Timer() = default;
void Timer::Reset() {}
double Timer::GetTime() {return 0;}
double Timer::GetTimeAndReset() {return 0;}
void Timer::Wait(uint msec) {}

}

#elif(INTRA_LIBRARY_TIMER==INTRA_LIBRARY_TIMER_QPC)

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>

namespace Intra {

static ulong64 g_timer_frequency;

Timer::Timer()
{
	QueryPerformanceFrequency((LARGE_INTEGER*)&g_timer_frequency);
	Reset();
}

Timer::~Timer() = default;

void Timer::Reset() {GetTimeAndReset();}

double Timer::GetTime()
{
	const ulong64 oldHndl = hndl;
	const double result = GetTimeAndReset();
	hndl = oldHndl;
	return result;
}

double Timer::GetTimeAndReset()
{
	ulong64 current;
	QueryPerformanceCounter((LARGE_INTEGER*)&current);
	double result = double(current-hndl)/g_timer_frequency;
	hndl = current;
	return result;
}

}

#elif(INTRA_LIBRARY_TIMER==INTRA_LIBRARY_TIMER_CPPLIB)

char* gets(char* str);

#include <chrono>
#include <thread>

namespace Intra {

Timer::Timer()
{
	hndl = (ulong64)new std::chrono::high_resolution_clock::time_point(std::chrono::high_resolution_clock::now());
}

Timer::~Timer()
{
	delete (std::chrono::high_resolution_clock::time_point*)hndl;
}

//Получить время таймера и сбросить его
double Timer::GetTimeAndReset()
{
	auto current = std::chrono::high_resolution_clock::now();
	auto& prev = *(std::chrono::high_resolution_clock::time_point*)hndl;
	auto result = std::chrono::duration<double, std::ratio<1,1>>(current-prev).count();
	*(std::chrono::high_resolution_clock::time_point*)hndl = current;
	return result;
}

double Timer::GetTime()
{
	auto current = std::chrono::high_resolution_clock::now();
	auto& prev = *(std::chrono::high_resolution_clock::time_point*)hndl;
	auto result = std::chrono::duration<double, std::ratio<1, 1>>(current-prev).count();
	return result;
}

void Timer::Reset()
{
	auto current = std::chrono::high_resolution_clock::now();
	*(std::chrono::high_resolution_clock::time_point*)hndl = current;
}

//void Timer::Wait(uint msec) {std::this_thread::sleep_for(std::chrono::milliseconds(msec));}

}

#elif INTRA_LIBRARY_TIMER==INTRA_LIBRARY_TIMER_Qt
#include <QtCore/QElapsedTimer>
#include <QtCore/QThread>

namespace Intra {

Timer::Timer()
{
	hndl = (ulong64)new QElapsedTimer;
	Reset();
}

Timer::~Timer() {delete (QElapsedTimer*)hndl;}

void Timer::Reset() {((QElapsedTimer*)hndl)->start();}

double Timer::GetTime()
{
	const double result = (double)((QElapsedTimer*)hndl)->nsecsElapsed()/1000000000;
	return result;
}

double Timer::GetTimeAndReset()
{
	const double result = GetTime();
	Reset();
	return result;
}

/*void Timer::Wait(uint msec)
{
	struct SleepThread: public QThread {using QThread::msleep;};
	SleepThread::msleep(msec);
}*/

}

#elif INTRA_LIBRARY_TIMER==INTRA_LIBRARY_TIMER_CLIB

namespace Intra {

Timer::Timer() {hndl = clock();}
Timer::~Timer() = default;
void Timer::Reset() {hndl = clock();}
double Timer::GetTime() {return double(clock()-hndl)/CLOCKS_PER_SEC;}

double Timer::GetTimeAndReset()
{
	auto newHndl = clock();
	const double result = double(newHndl-hndl)/CLOCKS_PER_SEC;
	hndl = newHndl;
	return result;
}

}

#else
#error "INTRA_LIBRARY_TIMER define is invalid!"
#endif

#if INTRA_PLATFORM_OS==INTRA_PLATFORM_OS_Windows

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>

namespace Intra {

void Timer::Wait(uint msec) {Sleep(msec);}

}

#elif defined(INTRA_PLATFORM_IS_POSIX)

#include <unistd.h>

namespace Intra {

void Timer::Wait(uint msec)
{
	if(msec < (1 << 29)/125 ) usleep(msec*1000);
	else sleep((msec+999)/1000);
}

}

#endif

<|endoftext|>


<commit_before>/*
 * tools_p.cpp
 *
 * Copyright (c) 2001, 2002, 2003 Frerich Raabe <raabe@kde.org>
 *
 * This program 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. For licensing and distribution details, check the
 * accompanying file 'COPYING'.
 */
#include "tools_p.h"

#include <krfcdate.h>
#include <qdom.h>

time_t RSS::parseISO8601Date(const QString &s)
{
	if (s.find('T') != -1)
		return KRFCDate::parseDateISO8601(s);
	QString time=s;
	time += "T12:00:00";
	return KRFCDate::parseDateISO8601(time);
}

QString RSS::extractNode(const QDomNode &parent, const QString &elemName, bool simplifyWhiteSpace)
{
	QDomNode node = parent.namedItem(elemName);
	if (node.isNull())
		return QString::null;

	QString result = node.toElement().text();
	if (simplifyWhiteSpace) {
		result=result.simplifyWhiteSpace();
	}
	if (result.isEmpty())
		return QString::null;

	return result;
}

// vim:noet:ts=4
<commit_msg>here, we assume that an article containing no < is empty from any html tags, and has to be plain text. so we exapnd linebreaks before the spaces simplifications.<commit_after>/*
 * tools_p.cpp
 *
 * Copyright (c) 2001, 2002, 2003 Frerich Raabe <raabe@kde.org>
 *
 * This program 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. For licensing and distribution details, check the
 * accompanying file 'COPYING'.
 */
#include "tools_p.h"

#include <krfcdate.h>
#include <qdom.h>

time_t RSS::parseISO8601Date(const QString &s)
{
	if (s.find('T') != -1)
		return KRFCDate::parseDateISO8601(s);
	QString time=s;
	time += "T12:00:00";
	return KRFCDate::parseDateISO8601(time);
}

QString RSS::extractNode(const QDomNode &parent, const QString &elemName, bool simplifyWhiteSpace)
{
	QDomNode node = parent.namedItem(elemName);
	if (node.isNull())
		return QString::null;

	QString result = node.toElement().text();
	if (simplifyWhiteSpace) {
		// MC : this line assumes that a feed containing no < has no html tags
		// and then have no formattig, so we should convert \n into
 to make it readable
		// Mon, 23 Aug 2004 15:22:06 +0200
		if(!result.contains("<")) result=result.replace(QChar('\n'),"
");

		result=result.simplifyWhiteSpace();
	}
	if (result.isEmpty())
		return QString::null;

	return result;
}

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


<commit_before>/**
 *  @file cursor.cpp
 *  @date 12.12.2014
 *  @author mkoenig
 *  @brief
 *
 *  $LastChangedDate$
 *  $LastChangedBy$
 *  $LastChangedRevision$
 *
 */

#include <pydbc/cursor.h>
#include <pydbc/column_types.h>
#include <sqlext.h>
#include <stdexcept>

namespace pydbc {

namespace {

	bool is_string_type(long type)
	{
		switch (type) {
			case SQL_VARCHAR:
			case SQL_LONGVARCHAR:
			case SQL_WVARCHAR:
			case SQL_CHAR:
			case SQL_WLONGVARCHAR:
			case SQL_WCHAR:
				return true;
			default:
				return false;
		}

	}

}

result_set::result_set(std::shared_ptr<cpp_odbc::statement const> statement) :
	statement_(statement)
{
	std::size_t const n_columns = statement_->number_of_columns();

	for (std::size_t one_based_index = 1; one_based_index <= n_columns; ++one_based_index) {
		auto const type = statement_->get_integer_column_attribute(one_based_index, SQL_DESC_TYPE);

		if (is_string_type(type)) {
			columns_.emplace_back(new string_column(*statement_, one_based_index));
		} else {
			columns_.emplace_back(new long_column(*statement_, one_based_index));
		}
	}
}

std::vector<field> result_set::fetch_one()
{
	auto const has_results = statement_->fetch_next();
	if (has_results) {
		std::vector<field> row;
		for (auto const & column : columns_) {
			row.push_back(column->get_field());
		}
		return row;
	} else {
		return {};
	}
}

}
<commit_msg>Extracted column factory. Added exception for unsupported type identifiers<commit_after>/**
 *  @file cursor.cpp
 *  @date 12.12.2014
 *  @author mkoenig
 *  @brief
 *
 *  $LastChangedDate$
 *  $LastChangedBy$
 *  $LastChangedRevision$
 *
 */

#include <pydbc/cursor.h>
#include <pydbc/column_types.h>
#include <sqlext.h>
#include <stdexcept>
#include <sstream>

namespace pydbc {

namespace {

	std::unique_ptr<column> make_column(cpp_odbc::statement const & statement, std::size_t one_based_index)
	{
		auto const type = statement.get_integer_column_attribute(one_based_index, SQL_DESC_TYPE);

		switch (type) {
			case SQL_VARCHAR:
			case SQL_LONGVARCHAR:
			case SQL_WVARCHAR:
			case SQL_CHAR:
			case SQL_WLONGVARCHAR:
			case SQL_WCHAR:
				return std::unique_ptr<column>(new string_column(statement, one_based_index));
			case SQL_INTEGER:
			case SQL_SMALLINT:
			case SQL_BIGINT:
			case SQL_BIT:
				return std::unique_ptr<column>(new long_column(statement, one_based_index));
			default:
				std::ostringstream message;
				message << "Error! Unsupported type identifier '" << type << "'";
				throw std::runtime_error(message.str());
		}
	}

}

result_set::result_set(std::shared_ptr<cpp_odbc::statement const> statement) :
	statement_(statement)
{
	std::size_t const n_columns = statement_->number_of_columns();

	for (std::size_t one_based_index = 1; one_based_index <= n_columns; ++one_based_index) {
		columns_.push_back(make_column(*statement, one_based_index));
	}
}

std::vector<field> result_set::fetch_one()
{
	auto const has_results = statement_->fetch_next();
	if (has_results) {
		std::vector<field> row;
		for (auto const & column : columns_) {
			row.push_back(column->get_field());
		}
		return row;
	} else {
		return {};
	}
}

}
<|endoftext|>


<commit_before>//
//  ZX8081.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 04/06/2017.
//  Copyright © 2017 Thomas Harte. All rights reserved.
//

#include "ZX8081.hpp"

#include "../MemoryFuzzer.hpp"

using namespace ZX8081;

namespace {
	// The clock rate is 3.25Mhz.
	const unsigned int ZX8081ClockRate = 3250000;
}

Machine::Machine() :
	vsync_(false),
	hsync_(false),
	tape_player_(ZX8081ClockRate) {
	set_clock_rate(ZX8081ClockRate);
	tape_player_.set_motor_control(true);
	clear_all_keys();
}

int Machine::perform_machine_cycle(const CPU::Z80::MachineCycle &cycle) {
	int previous_counter = horizontal_counter_;
	horizontal_counter_ += cycle.length;
	if(previous_counter < 16 && horizontal_counter_ >= 16) {
		video_->run_for_cycles(16 - previous_counter);
		set_hsync(true);
		video_->run_for_cycles(horizontal_counter_ - 16);
	} else if(previous_counter < 32 && horizontal_counter_ >= 32) {
		video_->run_for_cycles(32 - previous_counter);
		set_hsync(false);
		video_->run_for_cycles(horizontal_counter_ - 32);
	} else {
		video_->run_for_cycles(cycle.length);
	}

//	tape_player_.run_for_cycles(cycle.length);

	uint16_t refresh = 0;
	uint16_t address = cycle.address ? *cycle.address : 0;
	switch(cycle.operation) {
		case CPU::Z80::BusOperation::Output:
			set_vsync(false);
			line_counter_ = 0;
		break;

		case CPU::Z80::BusOperation::Input: {
			uint8_t value = 0xff;
			if(!(address&1)) {
				set_vsync(true);

				uint16_t mask = 0x100;
				for(int c = 0; c < 8; c++) {
					if(!(address & mask)) value &= key_states_[c];
					mask <<= 1;
				}

				value &= ~(tape_player_.get_input() ? 0x00 : 0x80);
			}
			*cycle.value = value;
		} break;

		case CPU::Z80::BusOperation::Interrupt:
//			set_hsync(true);
			line_counter_ = (line_counter_ + 1) & 7;
			*cycle.value = 0xff;
			horizontal_counter_ = 0;	// TODO: more than this?
		break;

		case CPU::Z80::BusOperation::ReadOpcode:
//			set_hsync(false);

			// The ZX80 and 81 signal an interrupt while refresh is active and bit 6 of the refresh
			// address is low. The Z80 signals a refresh, providing the refresh address during the
			// final two cycles of an opcode fetch. Therefore communicate a transient signalling
			// of the IRQ line if necessary.
			refresh = get_value_of_register(CPU::Z80::Register::Refresh);
			set_interrupt_line(!(refresh & 0x40), -2);
			set_interrupt_line(false);

			// Check for use of the fast tape hack.
			if(address == tape_trap_address_) { // TODO: && fast_tape_hack_enabled_
				int next_byte = parser_.get_next_byte(tape_player_.get_tape());
				if(next_byte != -1) {
					uint16_t hl = get_value_of_register(CPU::Z80::Register::HL);
					ram_[hl & ram_mask_] = (uint8_t)next_byte;
					*cycle.value = 0x00;
					set_value_of_register(CPU::Z80::Register::ProgramCounter, tape_return_address_ - 1);
					return 0;
				}
			}

		case CPU::Z80::BusOperation::Read:
			if(address < ram_base_) {
				*cycle.value = rom_[address & rom_mask_];
			} else {
				uint8_t value = ram_[address & ram_mask_];

				// If this is an M1 cycle reading from above the 32kb mark and HALT is not
				// currently active, perform a video output and return a NOP. Otherwise,
				// just return the value as read.
				if(cycle.operation == CPU::Z80::BusOperation::ReadOpcode && address&0x8000 && !(value & 0x40) && !get_halt_line()) {
					size_t char_address = (size_t)((refresh & 0xff00) | ((value & 0x3f) << 3) | line_counter_);
					if(char_address < ram_base_) {
						uint8_t mask = (value & 0x80) ? 0x00 : 0xff;
						value = rom_[char_address & rom_mask_] ^ mask;
					}

					video_->output_byte(value);
					*cycle.value = 0;
				} else *cycle.value = value;
			}
		break;

		case CPU::Z80::BusOperation::Write:
			if(address >= ram_base_) {
				ram_[address & ram_mask_] = *cycle.value;
			}
		break;

		default: break;
	}

	return 0;
}

void Machine::flush() {
	video_->flush();
}

void Machine::setup_output(float aspect_ratio) {
	video_.reset(new Video);
}

void Machine::close_output() {
	video_.reset();
}

std::shared_ptr<Outputs::CRT::CRT> Machine::get_crt() {
	return video_->get_crt();
}

std::shared_ptr<Outputs::Speaker> Machine::get_speaker() {
	return nullptr;
}

void Machine::run_for_cycles(int number_of_cycles) {
	CPU::Z80::Processor<Machine>::run_for_cycles(number_of_cycles);
}

void Machine::configure_as_target(const StaticAnalyser::Target &target) {
	is_zx81_ = target.zx8081.isZX81;
	if(is_zx81_) {
		rom_ = zx81_rom_;
		tape_trap_address_ = 0x37c;
		tape_return_address_ = 0x380;
	} else {
		rom_ = zx80_rom_;
		tape_trap_address_ = 0x220;
		tape_return_address_ = 0x248;
	}
	rom_mask_ = (uint16_t)(rom_.size() - 1);

	switch(target.zx8081.memory_model) {
		case StaticAnalyser::ZX8081MemoryModel::Unexpanded:
			ram_.resize(1024);
			ram_base_ = 16384;
			ram_mask_ = 1023;
		break;
		case StaticAnalyser::ZX8081MemoryModel::SixteenKB:
			ram_.resize(16384);
			ram_base_ = 16384;
			ram_mask_ = 16383;
		break;
		case StaticAnalyser::ZX8081MemoryModel::SixtyFourKB:
			ram_.resize(65536);
			ram_base_ = 8192;
			ram_mask_ = 65535;
		break;
	}
	Memory::Fuzz(ram_);

	if(target.tapes.size()) {
		tape_player_.set_tape(target.tapes.front());
	}
}

void Machine::set_rom(ROMType type, std::vector<uint8_t> data) {
	switch(type) {
		case ZX80: zx80_rom_ = data; break;
		case ZX81: zx81_rom_ = data; break;
	}
}

#pragma mark - Video

void Machine::set_vsync(bool sync) {
	vsync_ = sync;
	update_sync();
}

void Machine::set_hsync(bool sync) {
	hsync_ = sync;
	update_sync();
}

void Machine::update_sync() {
	video_->set_sync(vsync_ || hsync_);
}

#pragma mark - Keyboard

void Machine::set_key_state(uint16_t key, bool isPressed) {
	if(isPressed)
		key_states_[key >> 8] &= (uint8_t)(~key);
	else
		key_states_[key >> 8] |= (uint8_t)key;
}

void Machine::clear_all_keys() {
	memset(key_states_, 0xff, 8);
}
<commit_msg>Started splitting ZX80 and ZX81 paths. Also the '80 fires its horizontal sync a little earlier than the '81, so pulled that back a little.<commit_after>//
//  ZX8081.cpp
//  Clock Signal
//
//  Created by Thomas Harte on 04/06/2017.
//  Copyright © 2017 Thomas Harte. All rights reserved.
//

#include "ZX8081.hpp"

#include "../MemoryFuzzer.hpp"

using namespace ZX8081;

namespace {
	// The clock rate is 3.25Mhz.
	const unsigned int ZX8081ClockRate = 3250000;
}

Machine::Machine() :
	vsync_(false),
	hsync_(false),
	tape_player_(ZX8081ClockRate) {
	set_clock_rate(ZX8081ClockRate);
	tape_player_.set_motor_control(true);
	clear_all_keys();
}

int Machine::perform_machine_cycle(const CPU::Z80::MachineCycle &cycle) {
	const int vsync_length = 16;

	int previous_counter = horizontal_counter_;
	horizontal_counter_ += cycle.length;

	if(is_zx81_) {
	} else {
		const int vsync_start_cycle = 13;
		const int vsync_end_cycle = vsync_start_cycle + vsync_length;

		if(previous_counter < vsync_start_cycle && horizontal_counter_ >= vsync_start_cycle) {
			video_->run_for_cycles(vsync_start_cycle - previous_counter);
			set_hsync(true);
			video_->run_for_cycles(horizontal_counter_ - vsync_start_cycle);
		} else if(previous_counter < vsync_end_cycle  && horizontal_counter_ >= vsync_end_cycle) {
			video_->run_for_cycles(vsync_end_cycle - previous_counter);
			set_hsync(false);
			video_->run_for_cycles(horizontal_counter_ - vsync_end_cycle);
		} else {
			video_->run_for_cycles(cycle.length);
		}
	}

//	tape_player_.run_for_cycles(cycle.length);

	uint16_t refresh = 0;
	uint16_t address = cycle.address ? *cycle.address : 0;
	switch(cycle.operation) {
		case CPU::Z80::BusOperation::Output:
			set_vsync(false);
			line_counter_ = 0;
		break;

		case CPU::Z80::BusOperation::Input: {
			uint8_t value = 0xff;
			if(!(address&1)) {
				set_vsync(true);

				uint16_t mask = 0x100;
				for(int c = 0; c < 8; c++) {
					if(!(address & mask)) value &= key_states_[c];
					mask <<= 1;
				}

				value &= ~(tape_player_.get_input() ? 0x00 : 0x80);
			}
			*cycle.value = value;
		} break;

		case CPU::Z80::BusOperation::Interrupt:
//			set_hsync(true);
			line_counter_ = (line_counter_ + 1) & 7;
			*cycle.value = 0xff;
			horizontal_counter_ = 0;	// TODO: more than this?
		break;

		case CPU::Z80::BusOperation::ReadOpcode:
//			set_hsync(false);

			// The ZX80 and 81 signal an interrupt while refresh is active and bit 6 of the refresh
			// address is low. The Z80 signals a refresh, providing the refresh address during the
			// final two cycles of an opcode fetch. Therefore communicate a transient signalling
			// of the IRQ line if necessary.
			refresh = get_value_of_register(CPU::Z80::Register::Refresh);
			set_interrupt_line(!(refresh & 0x40), -2);
			set_interrupt_line(false);

			// Check for use of the fast tape hack.
			if(address == tape_trap_address_) { // TODO: && fast_tape_hack_enabled_
				int next_byte = parser_.get_next_byte(tape_player_.get_tape());
				if(next_byte != -1) {
					uint16_t hl = get_value_of_register(CPU::Z80::Register::HL);
					ram_[hl & ram_mask_] = (uint8_t)next_byte;
					*cycle.value = 0x00;
					set_value_of_register(CPU::Z80::Register::ProgramCounter, tape_return_address_ - 1);
					return 0;
				}
			}

		case CPU::Z80::BusOperation::Read:
			if(address < ram_base_) {
				*cycle.value = rom_[address & rom_mask_];
			} else {
				uint8_t value = ram_[address & ram_mask_];

				// If this is an M1 cycle reading from above the 32kb mark and HALT is not
				// currently active, perform a video output and return a NOP. Otherwise,
				// just return the value as read.
				if(cycle.operation == CPU::Z80::BusOperation::ReadOpcode && address&0x8000 && !(value & 0x40) && !get_halt_line()) {
					size_t char_address = (size_t)((refresh & 0xff00) | ((value & 0x3f) << 3) | line_counter_);
					if(char_address < ram_base_) {
						uint8_t mask = (value & 0x80) ? 0x00 : 0xff;
						value = rom_[char_address & rom_mask_] ^ mask;
					}

					video_->output_byte(value);
					*cycle.value = 0;
				} else *cycle.value = value;
			}
		break;

		case CPU::Z80::BusOperation::Write:
			if(address >= ram_base_) {
				ram_[address & ram_mask_] = *cycle.value;
			}
		break;

		default: break;
	}

	return 0;
}

void Machine::flush() {
	video_->flush();
}

void Machine::setup_output(float aspect_ratio) {
	video_.reset(new Video);
}

void Machine::close_output() {
	video_.reset();
}

std::shared_ptr<Outputs::CRT::CRT> Machine::get_crt() {
	return video_->get_crt();
}

std::shared_ptr<Outputs::Speaker> Machine::get_speaker() {
	return nullptr;
}

void Machine::run_for_cycles(int number_of_cycles) {
	CPU::Z80::Processor<Machine>::run_for_cycles(number_of_cycles);
}

void Machine::configure_as_target(const StaticAnalyser::Target &target) {
	is_zx81_ = target.zx8081.isZX81;
	if(is_zx81_) {
		rom_ = zx81_rom_;
		tape_trap_address_ = 0x37c;
		tape_return_address_ = 0x380;
	} else {
		rom_ = zx80_rom_;
		tape_trap_address_ = 0x220;
		tape_return_address_ = 0x248;
	}
	rom_mask_ = (uint16_t)(rom_.size() - 1);

	switch(target.zx8081.memory_model) {
		case StaticAnalyser::ZX8081MemoryModel::Unexpanded:
			ram_.resize(1024);
			ram_base_ = 16384;
			ram_mask_ = 1023;
		break;
		case StaticAnalyser::ZX8081MemoryModel::SixteenKB:
			ram_.resize(16384);
			ram_base_ = 16384;
			ram_mask_ = 16383;
		break;
		case StaticAnalyser::ZX8081MemoryModel::SixtyFourKB:
			ram_.resize(65536);
			ram_base_ = 8192;
			ram_mask_ = 65535;
		break;
	}
	Memory::Fuzz(ram_);

	if(target.tapes.size()) {
		tape_player_.set_tape(target.tapes.front());
	}
}

void Machine::set_rom(ROMType type, std::vector<uint8_t> data) {
	switch(type) {
		case ZX80: zx80_rom_ = data; break;
		case ZX81: zx81_rom_ = data; break;
	}
}

#pragma mark - Video

void Machine::set_vsync(bool sync) {
	vsync_ = sync;
	update_sync();
}

void Machine::set_hsync(bool sync) {
	hsync_ = sync;
	update_sync();
}

void Machine::update_sync() {
	video_->set_sync(vsync_ || hsync_);
}

#pragma mark - Keyboard

void Machine::set_key_state(uint16_t key, bool isPressed) {
	if(isPressed)
		key_states_[key >> 8] &= (uint8_t)(~key);
	else
		key_states_[key >> 8] |= (uint8_t)key;
}

void Machine::clear_all_keys() {
	memset(key_states_, 0xff, 8);
}
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// *       Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// *       Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// *       Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////

#include <testRoots.h>
#include <testFun.h>
#include <testInvert.h>
#include <testFrustum.h>
#include <testRandom.h>
#include <testColor.h>
#include <testShear.h>
#include <testMatrix.h>
#include <testExtractEuler.h>
#include <testExtractSHRT.h>

#include <string.h>

#define TEST(x) if (argc < 2 || !strcmp (argv[1], #x)) x();

int
main (int argc, char *argv[])
{
    TEST (testColor);
    TEST (testShear);
    TEST (testMatrix);
    TEST (testRoots);
    TEST (testFun);
    TEST (testInvert);
    TEST (testFrustum);
    TEST (testRandom);
    TEST (testExtractEuler);
    TEST (testExtractSHRT);
    return 0;
}
<commit_msg><commit_after>///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// *       Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// *       Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// *       Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////

#include <testRoots.h>
#include <testFun.h>
#include <testInvert.h>
#include <testFrustum.h>
#include <testRandom.h>
#include <testColor.h>
#include <testShear.h>
#include <testMatrix.h>
#include <testExtractEuler.h>
#include <testExtractSHRT.h>
#include <testTMatrix.h>
#include <testTMatrixData.h>

#include <string.h>

#define TEST(x) if (argc < 2 || !strcmp (argv[1], #x)) x();

int
main (int argc, char *argv[])
{
    TEST (testColor);
    TEST (testShear);
    TEST (testMatrix);
    TEST (testRoots);
    TEST (testFun);
    TEST (testInvert);
    TEST (testFrustum);
    TEST (testRandom);
    TEST (testExtractEuler);
    TEST (testExtractSHRT);
    TEST (testTMatrix);
    TEST (testTMatrixData);
    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: tabsthdl.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: mib $ $Date: 2001-07-02 09:50:34 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _XMLOFF_PROPERTYHANDLER_TABSTOPTYPES_HXX
#include <tabsthdl.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

#ifndef _COM_SUN_STAR_STYLE_TABSTOP_HPP_
#include <com/sun/star/style/TabStop.hpp>
#endif

using namespace ::com::sun::star;

///////////////////////////////////////////////////////////////////////////////
//
// class XMLFontFamilyNamePropHdl
//

XMLTabStopPropHdl::~XMLTabStopPropHdl()
{
    // Nothing to do
}

sal_Bool XMLTabStopPropHdl::equals( const uno::Any& r1, const uno::Any& r2 ) const
{
    sal_Bool bEqual = sal_False;

    uno::Sequence< style::TabStop> aSeq1;
    if( r1 >>= aSeq1 )
    {
        uno::Sequence< style::TabStop> aSeq2;
        if( r2 >>= aSeq2 )
        {
            if( aSeq1.getLength() == aSeq2.getLength() )
            {
                bEqual = sal_True;
                if( aSeq1.getLength() > 0 )
                {
                    const style::TabStop* pTabs1 = aSeq1.getConstArray();
                    const style::TabStop* pTabs2 = aSeq2.getConstArray();

                    int i=0;

                    do
                    {
                        bEqual = ( pTabs1[i].Position == pTabs2[i].Position       &&
                                   pTabs1[i].Alignment == pTabs2[i].Alignment     &&
                                   pTabs1[i].DecimalChar == pTabs2[i].DecimalChar &&
                                   pTabs1[i].FillChar == pTabs2[i].FillChar );
                        i++;

                    } while( bEqual && i < aSeq1.getLength() );
                }
            }
        }
    }

    return bEqual;
}

sal_Bool XMLTabStopPropHdl::importXML( const ::rtl::OUString& rStrImpValue, ::com::sun::star::uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    return sal_False;
}

sal_Bool XMLTabStopPropHdl::exportXML( ::rtl::OUString& rStrExpValue, const ::com::sun::star::uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    return sal_False;
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.636); FILE MERGED 2005/09/05 14:39:31 rt 1.2.636.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tabsthdl.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 14:49:13 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _XMLOFF_PROPERTYHANDLER_TABSTOPTYPES_HXX
#include <tabsthdl.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

#ifndef _COM_SUN_STAR_STYLE_TABSTOP_HPP_
#include <com/sun/star/style/TabStop.hpp>
#endif

using namespace ::com::sun::star;

///////////////////////////////////////////////////////////////////////////////
//
// class XMLFontFamilyNamePropHdl
//

XMLTabStopPropHdl::~XMLTabStopPropHdl()
{
    // Nothing to do
}

sal_Bool XMLTabStopPropHdl::equals( const uno::Any& r1, const uno::Any& r2 ) const
{
    sal_Bool bEqual = sal_False;

    uno::Sequence< style::TabStop> aSeq1;
    if( r1 >>= aSeq1 )
    {
        uno::Sequence< style::TabStop> aSeq2;
        if( r2 >>= aSeq2 )
        {
            if( aSeq1.getLength() == aSeq2.getLength() )
            {
                bEqual = sal_True;
                if( aSeq1.getLength() > 0 )
                {
                    const style::TabStop* pTabs1 = aSeq1.getConstArray();
                    const style::TabStop* pTabs2 = aSeq2.getConstArray();

                    int i=0;

                    do
                    {
                        bEqual = ( pTabs1[i].Position == pTabs2[i].Position       &&
                                   pTabs1[i].Alignment == pTabs2[i].Alignment     &&
                                   pTabs1[i].DecimalChar == pTabs2[i].DecimalChar &&
                                   pTabs1[i].FillChar == pTabs2[i].FillChar );
                        i++;

                    } while( bEqual && i < aSeq1.getLength() );
                }
            }
        }
    }

    return bEqual;
}

sal_Bool XMLTabStopPropHdl::importXML( const ::rtl::OUString& rStrImpValue, ::com::sun::star::uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    return sal_False;
}

sal_Bool XMLTabStopPropHdl::exportXML( ::rtl::OUString& rStrExpValue, const ::com::sun::star::uno::Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const
{
    return sal_False;
}

<|endoftext|>


<commit_before>#include <nan.h>
#include <string.h>
#ifdef WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif // win32

extern "C" {
  #include <git2.h>
  {% each cDependencies as dependency %}
    #include <{{ dependency }}>
  {% endeach %}
}

#include <iostream>
#include "../include/nodegit.h"
#include "../include/lock_master.h"
#include "../include/functions/copy.h"
#include "../include/{{ filename }}.h"
#include "nodegit_wrapper.cc"

{% each dependencies as dependency %}
  #include "{{ dependency }}"
{% endeach %}

using namespace v8;
using namespace node;
using namespace std;

// generated from struct_content.cc
{{ cppClassName }}::{{ cppClassName }}() : NodeGitWrapper<{{ cppClassName }}Traits>(NULL, true, v8::Local<v8::Object>())
{
  {% if ignoreInit == true %}
  this->raw = new {{ cType }};
  {% else %}
    {% if isExtendedStruct %}
      {{ cType }}_extended wrappedValue = {{ cType|upper }}_INIT;
      this->raw = ({{ cType }}*) malloc(sizeof({{ cType }}_extended));
      memcpy(this->raw, &wrappedValue, sizeof({{ cType }}_extended));
    {% else %}
      {{ cType }} wrappedValue = {{ cType|upper }}_INIT;
      this->raw = ({{ cType }}*) malloc(sizeof({{ cType }}));
      memcpy(this->raw, &wrappedValue, sizeof({{ cType }}));
    {% endif %}
  {% endif %}

  this->ConstructFields();
}

{{ cppClassName }}::{{ cppClassName }}({{ cType }}* raw, bool selfFreeing, v8::Local<v8::Object> owner)
 : NodeGitWrapper<{{ cppClassName }}Traits>(raw, selfFreeing, owner)
{
  this->ConstructFields();
}

{{ cppClassName }}::~{{ cppClassName }}() {
  {% each fields|fieldsInfo as field %}
    {% if not field.ignore %}
      {% if not field.isEnum %}
        {% if field.isCallbackFunction %}
          if (this->{{ field.name }}.HasCallback()) {
            {% if isExtendedStruct %}
              (({{ cType }}_extended *)this->raw)->payload = NULL;
            {% else %}
              this->raw->{{ fields|payloadFor field.name }} = NULL;
            {% endif %}
          }
        {% endif %}
      {% endif %}
    {% endif %}
  {% endeach %}
}

void {{ cppClassName }}::ConstructFields() {
  {% each fields|fieldsInfo as field %}
    {% if not field.ignore %}
      {% if not field.isEnum %}
        {% if field.hasConstructor |or field.isLibgitType %}
          v8::Local<Object> {{ field.name }}Temp = {{ field.cppClassName }}::New(
            {%if not field.cType|isPointer %}&{%endif%}this->raw->{{ field.name }},
            false
          )->ToObject();
          this->{{ field.name }}.Reset({{ field.name }}Temp);

        {% elsif field.isCallbackFunction %}

          // Set the static method call and set the payload for this function to be
          // the current instance
          this->raw->{{ field.name }} = NULL;
          {% if isExtendedStruct  %}
            (({{ cType }}_extended *)this->raw)->payload = (void *)this;
          {% else %}
            this->raw->{{ fields|payloadFor field.name }} = (void *)this;
          {% endif %}
        {% elsif field.payloadFor %}

          v8::Local<Value> {{ field.name }} = Nan::Undefined();
          this->{{ field.name }}.Reset({{ field.name }});
        {% endif %}
      {% endif %}
    {% endif %}
  {% endeach %}
}

void {{ cppClassName }}::InitializeComponent(v8::Local<v8::Object> target) {
  Nan::HandleScope scope;

  v8::Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(JSNewFunction);

  tpl->InstanceTemplate()->SetInternalFieldCount(1);
  tpl->SetClassName(Nan::New("{{ jsClassName }}").ToLocalChecked());

  {% each fields as field %}
    {% if not field.ignore %}
    {% if not field | isPayload %}
      Nan::SetAccessor(tpl->InstanceTemplate(), Nan::New("{{ field.jsFunctionName }}").ToLocalChecked(), Get{{ field.cppFunctionName}}, Set{{ field.cppFunctionName}});
    {% endif %}
    {% endif %}
  {% endeach %}

  InitializeTemplate(tpl);

  v8::Local<Function> _constructor_template = Nan::GetFunction(tpl).ToLocalChecked();
  constructor_template.Reset(_constructor_template);
  Nan::Set(target, Nan::New("{{ jsClassName }}").ToLocalChecked(), _constructor_template);
}

{% partial fieldAccessors . %}

// force base class template instantiation, to make sure we get all the
// methods, statics, etc.
template class NodeGitWrapper<{{ cppClassName }}Traits>;
<commit_msg>We should clear the persistent cell in structs when they are destroyed<commit_after>#include <nan.h>
#include <string.h>
#ifdef WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif // win32

extern "C" {
  #include <git2.h>
  {% each cDependencies as dependency %}
    #include <{{ dependency }}>
  {% endeach %}
}

#include <iostream>
#include "../include/nodegit.h"
#include "../include/lock_master.h"
#include "../include/functions/copy.h"
#include "../include/{{ filename }}.h"
#include "nodegit_wrapper.cc"

{% each dependencies as dependency %}
  #include "{{ dependency }}"
{% endeach %}

using namespace v8;
using namespace node;
using namespace std;

// generated from struct_content.cc
{{ cppClassName }}::{{ cppClassName }}() : NodeGitWrapper<{{ cppClassName }}Traits>(NULL, true, v8::Local<v8::Object>())
{
  {% if ignoreInit == true %}
  this->raw = new {{ cType }};
  {% else %}
    {% if isExtendedStruct %}
      {{ cType }}_extended wrappedValue = {{ cType|upper }}_INIT;
      this->raw = ({{ cType }}*) malloc(sizeof({{ cType }}_extended));
      memcpy(this->raw, &wrappedValue, sizeof({{ cType }}_extended));
    {% else %}
      {{ cType }} wrappedValue = {{ cType|upper }}_INIT;
      this->raw = ({{ cType }}*) malloc(sizeof({{ cType }}));
      memcpy(this->raw, &wrappedValue, sizeof({{ cType }}));
    {% endif %}
  {% endif %}

  this->ConstructFields();
}

{{ cppClassName }}::{{ cppClassName }}({{ cType }}* raw, bool selfFreeing, v8::Local<v8::Object> owner)
 : NodeGitWrapper<{{ cppClassName }}Traits>(raw, selfFreeing, owner)
{
  this->ConstructFields();
}

{{ cppClassName }}::~{{ cppClassName }}() {
  {% each fields|fieldsInfo as field %}
    {% if not field.ignore %}
      {% if not field.isEnum %}
        {% if field.isCallbackFunction %}
          if (this->{{ field.name }}.HasCallback()) {
            {% if isExtendedStruct %}
              (({{ cType }}_extended *)this->raw)->payload = NULL;
            {% else %}
              this->raw->{{ fields|payloadFor field.name }} = NULL;
            {% endif %}
          }
        {% elsif field.hasConstructor |or field.isLibgitType %}
          this->{{ field.name }}.Reset();
        {% endif %}
      {% endif %}
    {% endif %}
  {% endeach %}
}

void {{ cppClassName }}::ConstructFields() {
  {% each fields|fieldsInfo as field %}
    {% if not field.ignore %}
      {% if not field.isEnum %}
        {% if field.hasConstructor |or field.isLibgitType %}
          v8::Local<Object> {{ field.name }}Temp = {{ field.cppClassName }}::New(
            {%if not field.cType|isPointer %}&{%endif%}this->raw->{{ field.name }},
            false
          )->ToObject();
          this->{{ field.name }}.Reset({{ field.name }}Temp);

        {% elsif field.isCallbackFunction %}

          // Set the static method call and set the payload for this function to be
          // the current instance
          this->raw->{{ field.name }} = NULL;
          {% if isExtendedStruct  %}
            (({{ cType }}_extended *)this->raw)->payload = (void *)this;
          {% else %}
            this->raw->{{ fields|payloadFor field.name }} = (void *)this;
          {% endif %}
        {% elsif field.payloadFor %}

          v8::Local<Value> {{ field.name }} = Nan::Undefined();
          this->{{ field.name }}.Reset({{ field.name }});
        {% endif %}
      {% endif %}
    {% endif %}
  {% endeach %}
}

void {{ cppClassName }}::InitializeComponent(v8::Local<v8::Object> target) {
  Nan::HandleScope scope;

  v8::Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(JSNewFunction);

  tpl->InstanceTemplate()->SetInternalFieldCount(1);
  tpl->SetClassName(Nan::New("{{ jsClassName }}").ToLocalChecked());

  {% each fields as field %}
    {% if not field.ignore %}
    {% if not field | isPayload %}
      Nan::SetAccessor(tpl->InstanceTemplate(), Nan::New("{{ field.jsFunctionName }}").ToLocalChecked(), Get{{ field.cppFunctionName}}, Set{{ field.cppFunctionName}});
    {% endif %}
    {% endif %}
  {% endeach %}

  InitializeTemplate(tpl);

  v8::Local<Function> _constructor_template = Nan::GetFunction(tpl).ToLocalChecked();
  constructor_template.Reset(_constructor_template);
  Nan::Set(target, Nan::New("{{ jsClassName }}").ToLocalChecked(), _constructor_template);
}

{% partial fieldAccessors . %}

// force base class template instantiation, to make sure we get all the
// methods, statics, etc.
template class NodeGitWrapper<{{ cppClassName }}Traits>;
<|endoftext|>


<commit_before>// Draws 2D star
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <cmath>
#include "common.hpp"

#define PI 3.14159265359

void display();
void display2();
void init();
void par(GLfloat hx, GLfloat hy, GLfloat lx, GLfloat ly, int colornum);
void write(GLubyte text[]);
void star();
void star2();
void myMouseFunc( int button, int state, int x, int y );
void keyboard(unsigned char key, int a, int b);
void updateWindows();
void addPar(int);

int c1 = 3, c2 = 2;
int win1, win2;

double IncFactor = PI;
int clicks = 1;

void addPar(int no = 1)
{
  clicks += no;
  IncFactor = PI/(clicks/2.0);
  updateWindows();
}

void updateWindows()
{
  glutSetWindow(win1);
  glutPostRedisplay();
  glutSetWindow(win2);
  glutPostRedisplay();
}

void keyboard(unsigned char key, int a, int b)
{
  switch (key)
  {
    case('a'):
    case('A'):
      c1 = (c1 < 8)? c1 + 1 : c1;
    break;

    case('q'):
    case('Q'):
      c1 = (c1 > 0)? c1 - 1 : c1;
    break;

    case('w'):
    case('W'):
      c2 = (c2 < 8)? c2 + 1 : c2;
    break;

    case('s'):
    case('S'):
      c2 = (c2 > 0)? c2 - 1 : c2;
    break;

    case(' '):
    case('.'):
    case('>'):
      addPar();
    break;

    case(','):
    case('<'):
      addPar(-1);
    break;

    case 27:			// Escape key
      exit(0);
    break;
  }

  updateWindows();
}

void myMouseFunc( int button, int state, int x, int y ) {
	if ( button==GLUT_LEFT_BUTTON && state==GLUT_DOWN ) {
    addPar();
	}
}

void display()
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glLoadIdentity();
  star();
  glutSwapBuffers();
}

void display2()
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glLoadIdentity();
  star2();
  glutSwapBuffers();
}

void par(double hx, double hy, double lx, double ly, int colornum)
{
  glBegin(GL_TRIANGLE_FAN);
    glColor3fv(color[colornum]);
    glVertex2d(0.0,0.0);
    glVertex2d(hx,hy);
    glVertex2d(lx,ly);
  glEnd();
  glLoadIdentity();
}

void star2()
{
  for (double deg = 0.0; deg < 2*PI; deg += IncFactor)
    {
      par(cos(deg), sin(deg), 0.2 * cos(deg + IncFactor/2.0), 0.2 * sin(deg + IncFactor/2.0), c1);
      par(0.2 * sin(deg + IncFactor/2.0), 0.2 * cos(deg + IncFactor/2.0), sin(deg), cos(deg), c2);
    }
}

void star()
{
  glBegin(GL_TRIANGLE_FAN);
    glColor3fv(color[c1]);
    glVertex2f(0.0, 0.0);
    glColor3fv(color[c2]);
    for (double deg = 0.0; deg < 2*PI; deg += IncFactor)
    {
      glVertex2f(cos(deg), sin(deg));
      glVertex2f(0.2 * cos(deg + IncFactor/2.0), 0.2 * sin(deg + IncFactor/2.0));
    }
    glVertex2f(1.0, 0.0);
  glEnd();
  glLoadIdentity();
}

void init()
{
  glClearColor(0.0 ,0.0 ,0.0 ,0.0);
	glLoadIdentity();
}

int main(int argc, char **argv)
{
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);

  // window one
  glutInitWindowSize(500, 500);
  glutInitWindowPosition(0,0);
  win1 = glutCreateWindow("Star fade color");
  glutDisplayFunc(display);

  glutMouseFunc(myMouseFunc);
  glutKeyboardFunc(keyboard);

  // window two
  glutInitWindowSize(500, 500);
  glutInitWindowPosition(600, 0);
  win2 = glutCreateWindow("Star solid color");
  glutDisplayFunc(display2);

  glutMouseFunc(myMouseFunc);
  glutKeyboardFunc(keyboard);

  init();
  glutMainLoop();
}
<commit_msg>rearranged functions<commit_after>// Draws 2D star
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <cmath>
#include "common.hpp"

#define PI 3.14159265359

void par(double hx, double hy, double lx, double ly, int colornum);
void addPar(int);
void star();
void star2();
void updateWindows();
void Mouse( int button, int state, int x, int y );
void keyboard(unsigned char key, int a, int b);
void display();
void display2();
void init();

int color1 = 3, color2 = 2;
int clicks = 1;
int win1, win2;
double IncFactor = PI;

void star()
{
  glBegin(GL_TRIANGLE_FAN);
    glColor3fv(color[color1]);
    glVertex2f(0.0, 0.0);
    glColor3fv(color[color2]);
    for (double deg = 0.0; deg < 2*PI; deg += IncFactor)
    {
      glVertex2f(cos(deg), sin(deg));
      glVertex2f(0.2 * cos(deg + IncFactor/2.0), 0.2 * sin(deg + IncFactor/2.0));
    }
    glVertex2f(1.0, 0.0);
  glEnd();
  glLoadIdentity();
}

void par(double hx, double hy, double lx, double ly, int colornum)
{
  glBegin(GL_TRIANGLE_FAN);
    glColor3fv(color[colornum]);
    glVertex2d(0.0,0.0);
    glVertex2d(hx,hy);
    glVertex2d(lx,ly);
  glEnd();
  glLoadIdentity();
}

void star2()
{
  for (double deg = 0.0; deg < 2*PI; deg += IncFactor)
    {
      par(cos(deg), sin(deg), 0.2 * cos(deg + IncFactor/2.0), 0.2 * sin(deg + IncFactor/2.0), color1);
      par(0.2 * sin(deg + IncFactor/2.0), 0.2 * cos(deg + IncFactor/2.0), sin(deg), cos(deg), color2);
    }
}

void addPar(int no = 1)
{
  clicks += no;
  IncFactor = PI/(clicks/2.0);
  updateWindows();
}

void init()
{
  glClearColor(0.0 ,0.0 ,0.0 ,0.0);
	glLoadIdentity();
}

int main(int argc, char **argv)
{
  glutInit(&argc, argv);
  glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);

  // window one
  glutInitWindowSize(500, 500);
  glutInitWindowPosition(0,0);
  win1 = glutCreateWindow("Star fade color");
  glutDisplayFunc(display);

  glutMouseFunc(Mouse);
  glutKeyboardFunc(keyboard);

  // window two
  glutInitWindowSize(500, 500);
  glutInitWindowPosition(600, 0);
  win2 = glutCreateWindow("Star solid color");
  glutDisplayFunc(display2);

  glutMouseFunc(Mouse);
  glutKeyboardFunc(keyboard);

  init();
  glutMainLoop();
}

void updateWindows()
{
  glutSetWindow(win1);
  glutPostRedisplay();
  glutSetWindow(win2);
  glutPostRedisplay();
}

void keyboard(unsigned char key, int a, int b)
{
  switch (key)
  {
    case('a'):
    case('A'):
      color1 = (color1 < 8)? color1 + 1 : color1;
    break;

    case('q'):
    case('Q'):
      color1 = (color1 > 0)? color1 - 1 : color1;
    break;

    case('w'):
    case('W'):
      color2 = (color2 < 8)? color2 + 1 : color2;
    break;

    case('s'):
    case('S'):
      color2 = (color2 > 0)? color2 - 1 : color2;
    break;

    case(' '):
    case('.'):
    case('>'):
      addPar();
    break;

    case(','):
    case('<'):
      addPar(-1);
    break;

    case 27:			// Escape key
      exit(0);
    break;
  }

  updateWindows();
}

void Mouse( int button, int state, int x, int y ) {
	if ( button==GLUT_LEFT_BUTTON && state==GLUT_DOWN ) {
    addPar();
	}
}

void display()
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glLoadIdentity();
  star();
  glutSwapBuffers();
}

void display2()
{
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glLoadIdentity();
  star2();
  glutSwapBuffers();
}
<|endoftext|>


<commit_before>#ifndef __PLUGINSETTINGS_HPP__
#define __PLUGINSETTINGS_HPP__

#include "plugin.hpp"

class PluginSettings
{
	HANDLE handle;
	FARAPISETTINGSCONTROL SettingsControl;

public:

	PluginSettings(const GUID &guid, FARAPISETTINGSCONTROL SettingsControl)
	{
		this->SettingsControl = SettingsControl;
		handle = INVALID_HANDLE_VALUE;

		FarSettingsCreate settings={sizeof(FarSettingsCreate),guid,handle};
		if (SettingsControl(INVALID_HANDLE_VALUE,SCTL_CREATE,0,&settings))
			handle = settings.Handle;
	}

	~PluginSettings()
	{
	    SettingsControl(handle,SCTL_FREE,0,0);
	}

	int CreateSubKey(int Root, const wchar_t *Name)
	{
		FarSettingsValue value={Root,Name};
		return (int)SettingsControl(handle,SCTL_SUBKEY,0,&value);
	}

	const wchar_t *Get(int Root, const wchar_t *Name, const wchar_t *Default)
	{
		FarSettingsItem item={Root,Name,FST_STRING};
		if (SettingsControl(handle,SCTL_GET,0,&item))
		{
			return item.String;
		}
		return Default;
	}

	void Get(int Root, const wchar_t *Name, wchar_t *Value, size_t Size, const wchar_t *Default)
	{
		lstrcpyn(Value, Get(Root,Name,Default), (int)Size);
	}

	unsigned __int64 Get(int Root, const wchar_t *Name, unsigned __int64 Default)
	{
		FarSettingsItem item={Root,Name,FST_QWORD};
		if (SettingsControl(handle,SCTL_GET,0,&item))
		{
			return item.Number;
		}
		return Default;
	}

	__int64      Get(int Root, const wchar_t *Name, __int64 Default) { return (__int64)Get(Root,Name,(unsigned __int64)Default); }
	int          Get(int Root, const wchar_t *Name, int Default)  { return (int)Get(Root,Name,(unsigned __int64)Default); }
	unsigned int Get(int Root, const wchar_t *Name, unsigned int Default) { return (unsigned int)Get(Root,Name,(unsigned __int64)Default); }
	DWORD        Get(int Root, const wchar_t *Name, DWORD Default) { return (DWORD)Get(Root,Name,(unsigned __int64)Default); }
	bool         Get(int Root, const wchar_t *Name, bool Default) { return Get(Root,Name,Default?1ull:0ull)?true:false; }

	bool Set(int Root, const wchar_t *Name, const wchar_t *Value)
	{
		FarSettingsItem item={Root,Name,FST_STRING};
		item.String=Value;
		return SettingsControl(handle,SCTL_SET,0,&item)!=FALSE;
	}

	bool Set(int Root, const wchar_t *Name, unsigned __int64 Value)
	{
		FarSettingsItem item={Root,Name,FST_QWORD};
		item.Number=Value;
		return SettingsControl(handle,SCTL_SET,0,&item)!=FALSE;
	}

	bool Set(int Root, const wchar_t *Name, __int64 Value) { return Set(Root,Name,(unsigned __int64)Value); }
	bool Set(int Root, const wchar_t *Name, int Value) { return Set(Root,Name,(unsigned __int64)Value); }
	bool Set(int Root, const wchar_t *Name, unsigned int Value) { return Set(Root,Name,(unsigned __int64)Value); }
	bool Set(int Root, const wchar_t *Name, DWORD Value) { return Set(Root,Name,(unsigned __int64)Value); }
	bool Set(int Root, const wchar_t *Name, bool Value) { return Set(Root,Name,Value?1ull:0ull); }
};

#endif
<commit_msg>add delete<commit_after>#ifndef __PLUGINSETTINGS_HPP__
#define __PLUGINSETTINGS_HPP__

#include "plugin.hpp"

class PluginSettings
{
	HANDLE handle;
	FARAPISETTINGSCONTROL SettingsControl;

public:

	PluginSettings(const GUID &guid, FARAPISETTINGSCONTROL SettingsControl)
	{
		this->SettingsControl = SettingsControl;
		handle = INVALID_HANDLE_VALUE;

		FarSettingsCreate settings={sizeof(FarSettingsCreate),guid,handle};
		if (SettingsControl(INVALID_HANDLE_VALUE,SCTL_CREATE,0,&settings))
			handle = settings.Handle;
	}

	~PluginSettings()
	{
	    SettingsControl(handle,SCTL_FREE,0,0);
	}

	int CreateSubKey(int Root, const wchar_t *Name)
	{
		FarSettingsValue value={Root,Name};
		return (int)SettingsControl(handle,SCTL_SUBKEY,0,&value);
	}

	bool DeleteSubKey(int Root)
	{
		FarSettingsValue value={Root,nullptr};
		return (int)SettingsControl(handle,SCTL_DELETE,0,&value) ? true : false;
	}

	bool DeleteValue(int Root, const wchar_t *Name)
	{
		FarSettingsValue value={Root,Name};
		return (int)SettingsControl(handle,SCTL_DELETE,0,&value) ? true : false;
	}

	const wchar_t *Get(int Root, const wchar_t *Name, const wchar_t *Default)
	{
		FarSettingsItem item={Root,Name,FST_STRING};
		if (SettingsControl(handle,SCTL_GET,0,&item))
		{
			return item.String;
		}
		return Default;
	}

	void Get(int Root, const wchar_t *Name, wchar_t *Value, size_t Size, const wchar_t *Default)
	{
		lstrcpyn(Value, Get(Root,Name,Default), (int)Size);
	}

	unsigned __int64 Get(int Root, const wchar_t *Name, unsigned __int64 Default)
	{
		FarSettingsItem item={Root,Name,FST_QWORD};
		if (SettingsControl(handle,SCTL_GET,0,&item))
		{
			return item.Number;
		}
		return Default;
	}

	__int64      Get(int Root, const wchar_t *Name, __int64 Default) { return (__int64)Get(Root,Name,(unsigned __int64)Default); }
	int          Get(int Root, const wchar_t *Name, int Default)  { return (int)Get(Root,Name,(unsigned __int64)Default); }
	unsigned int Get(int Root, const wchar_t *Name, unsigned int Default) { return (unsigned int)Get(Root,Name,(unsigned __int64)Default); }
	DWORD        Get(int Root, const wchar_t *Name, DWORD Default) { return (DWORD)Get(Root,Name,(unsigned __int64)Default); }
	bool         Get(int Root, const wchar_t *Name, bool Default) { return Get(Root,Name,Default?1ull:0ull)?true:false; }

	bool Set(int Root, const wchar_t *Name, const wchar_t *Value)
	{
		FarSettingsItem item={Root,Name,FST_STRING};
		item.String=Value;
		return SettingsControl(handle,SCTL_SET,0,&item)!=FALSE;
	}

	bool Set(int Root, const wchar_t *Name, unsigned __int64 Value)
	{
		FarSettingsItem item={Root,Name,FST_QWORD};
		item.Number=Value;
		return SettingsControl(handle,SCTL_SET,0,&item)!=FALSE;
	}

	bool Set(int Root, const wchar_t *Name, __int64 Value) { return Set(Root,Name,(unsigned __int64)Value); }
	bool Set(int Root, const wchar_t *Name, int Value) { return Set(Root,Name,(unsigned __int64)Value); }
	bool Set(int Root, const wchar_t *Name, unsigned int Value) { return Set(Root,Name,(unsigned __int64)Value); }
	bool Set(int Root, const wchar_t *Name, DWORD Value) { return Set(Root,Name,(unsigned __int64)Value); }
	bool Set(int Root, const wchar_t *Name, bool Value) { return Set(Root,Name,Value?1ull:0ull); }
};

#endif
<|endoftext|>


<commit_before>/**
 * @file
 *
 * @brief Source for cpptemplate plugin
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 *
 */

#include "cpptemplate.hpp"
#include "cpptemplate_delegate.hpp"

#include <kdbhelper.h>

using elektra::CppTemplateDelegate;

extern "C" {

typedef Delegator<CppTemplateDelegate> delegator;

/** @see elektraDocOpen */
int elektraCppTemplateOpen (Plugin * handle, Key * key)
{
	// After the call to `delegator::open` you can retrieve a pointer to the delegate via `coderDelegator::get (handle)`
	return delegator::open (handle, key);
}

/** @see elektraDocClose */
int elektraCppTemplateClose (Plugin * handle, Key * key)
{
	return delegator::close (handle, key);
}

/** @see elektraDocGet */
int elektraCppTemplateGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey)
{
	if (!elektraStrCmp (keyName (parentKey), "system/elektra/modules/cpptemplate"))
	{
		KeySet * contract = ksNew (
			30, keyNew ("system/elektra/modules/cpptemplate", KEY_VALUE, "cpptemplate plugin waits for your orders", KEY_END),
			keyNew ("system/elektra/modules/cpptemplate/exports", KEY_END),
			keyNew ("system/elektra/modules/cpptemplate/exports/open", KEY_FUNC, elektraCppTemplateOpen, KEY_END),
			keyNew ("system/elektra/modules/cpptemplate/exports/close", KEY_FUNC, elektraCppTemplateClose, KEY_END),
			keyNew ("system/elektra/modules/cpptemplate/exports/get", KEY_FUNC, elektraCppTemplateGet, KEY_END),
			keyNew ("system/elektra/modules/cpptemplate/exports/set", KEY_FUNC, elektraCppTemplateSet, KEY_END),
			keyNew ("system/elektra/modules/cpptemplate/exports/error", KEY_FUNC, elektraCppTemplateError, KEY_END),
			keyNew ("system/elektra/modules/cpptemplate/exports/checkconf", KEY_FUNC, elektraCppTemplateCheckConfig, KEY_END),
#include ELEKTRA_README (cpptemplate)
			keyNew ("system/elektra/modules/cpptemplate/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
		ksAppend (returned, contract);
		ksDel (contract);

		return ELEKTRA_PLUGIN_STATUS_SUCCESS;
	}

	return ELEKTRA_PLUGIN_STATUS_NO_UPDATE;
}

/** @see elektraDocSet */
int elektraCppTemplateSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
	return ELEKTRA_PLUGIN_STATUS_NO_UPDATE;
}

/** @see elektraDocError */
int elektraCppTemplateError (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
	return ELEKTRA_PLUGIN_STATUS_SUCCESS;
}

/** @see elektraDocCheckConf */
int elektraCppTemplateCheckConfig (Key * errorKey ELEKTRA_UNUSED, KeySet * conf ELEKTRA_UNUSED)
{
	return ELEKTRA_PLUGIN_STATUS_NO_UPDATE;
}

Plugin * ELEKTRA_PLUGIN_EXPORT (cpptemplate)
{
	// clang-format off
	return elektraPluginExport ("cpptemplate",
		ELEKTRA_PLUGIN_OPEN,	&elektraCppTemplateOpen,
		ELEKTRA_PLUGIN_CLOSE,	&elektraCppTemplateClose,
		ELEKTRA_PLUGIN_GET,	&elektraCppTemplateGet,
		ELEKTRA_PLUGIN_SET,	&elektraCppTemplateSet,
		ELEKTRA_PLUGIN_ERROR,	&elektraCppTemplateError,
		ELEKTRA_PLUGIN_END);
}

} // end extern "C"
<commit_msg>CPP Template: Add function for plugin contract<commit_after>/**
 * @file
 *
 * @brief Source for cpptemplate plugin
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 *
 */

#include "cpptemplate.hpp"
#include "cpptemplate_delegate.hpp"

#include <kdbhelper.h>

using elektra::CppTemplateDelegate;

using CppKey = kdb::Key;
using CppKeySet = kdb::KeySet;

namespace
{

/**
 * @brief This function returns a key set containing the plugin contract.
 *
 * @return A key set specifying the capabilities of the plugin
 */
CppKeySet getContract ()
{
	return CppKeySet{ 30,
			  keyNew ("system/elektra/modules/cpptemplate", KEY_VALUE, "cpptemplate plugin waits for your orders", KEY_END),
			  keyNew ("system/elektra/modules/cpptemplate/exports", KEY_END),
			  keyNew ("system/elektra/modules/cpptemplate/exports/open", KEY_FUNC, elektraCppTemplateOpen, KEY_END),
			  keyNew ("system/elektra/modules/cpptemplate/exports/close", KEY_FUNC, elektraCppTemplateClose, KEY_END),
			  keyNew ("system/elektra/modules/cpptemplate/exports/get", KEY_FUNC, elektraCppTemplateGet, KEY_END),
			  keyNew ("system/elektra/modules/cpptemplate/exports/set", KEY_FUNC, elektraCppTemplateSet, KEY_END),
			  keyNew ("system/elektra/modules/cpptemplate/exports/error", KEY_FUNC, elektraCppTemplateError, KEY_END),
			  keyNew ("system/elektra/modules/cpptemplate/exports/checkconf", KEY_FUNC, elektraCppTemplateCheckConfig, KEY_END),
#include ELEKTRA_README (cpptemplate)
			  keyNew ("system/elektra/modules/cpptemplate/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END),
			  KS_END };
}

} // end namespace

extern "C" {

typedef Delegator<CppTemplateDelegate> delegator;

/** @see elektraDocOpen */
int elektraCppTemplateOpen (Plugin * handle, Key * key)
{
	// After the call to `delegator::open` you can retrieve a pointer to the delegate via `coderDelegator::get (handle)`
	return delegator::open (handle, key);
}

/** @see elektraDocClose */
int elektraCppTemplateClose (Plugin * handle, Key * key)
{
	return delegator::close (handle, key);
}

/** @see elektraDocGet */
int elektraCppTemplateGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey)
{
	CppKeySet keys{ returned };
	CppKey parent{ parentKey };
	bool updated = false;

	if (parent.getName () == "system/elektra/modules/cpptemplate")
	{
		keys.append (getContract ());
		updated = true;
	}

	parent.release ();
	keys.release ();
	return updated ? ELEKTRA_PLUGIN_STATUS_SUCCESS : ELEKTRA_PLUGIN_STATUS_NO_UPDATE;
}

/** @see elektraDocSet */
int elektraCppTemplateSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
	return ELEKTRA_PLUGIN_STATUS_NO_UPDATE;
}

/** @see elektraDocError */
int elektraCppTemplateError (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
	return ELEKTRA_PLUGIN_STATUS_SUCCESS;
}

/** @see elektraDocCheckConf */
int elektraCppTemplateCheckConfig (Key * errorKey ELEKTRA_UNUSED, KeySet * conf ELEKTRA_UNUSED)
{
	return ELEKTRA_PLUGIN_STATUS_NO_UPDATE;
}

Plugin * ELEKTRA_PLUGIN_EXPORT (cpptemplate)
{
	// clang-format off
	return elektraPluginExport ("cpptemplate",
		ELEKTRA_PLUGIN_OPEN,	&elektraCppTemplateOpen,
		ELEKTRA_PLUGIN_CLOSE,	&elektraCppTemplateClose,
		ELEKTRA_PLUGIN_GET,	&elektraCppTemplateGet,
		ELEKTRA_PLUGIN_SET,	&elektraCppTemplateSet,
		ELEKTRA_PLUGIN_ERROR,	&elektraCppTemplateError,
		ELEKTRA_PLUGIN_END);
}

} // end extern "C"
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "registerwindow.h"

#include "debuggeractions.h"
#include "debuggerconstants.h"

#include <utils/qtcassert.h>
#include <utils/savedaction.h>

#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QFileInfoList>

#include <QtGui/QAction>
#include <QtGui/QHeaderView>
#include <QtGui/QItemDelegate>
#include <QtGui/QLineEdit>
#include <QtGui/QMenu>
#include <QtGui/QPainter>
#include <QtGui/QResizeEvent>
#include <QtGui/QToolButton>

namespace Debugger {
namespace Internal {

///////////////////////////////////////////////////////////////////////
//
// RegisterDelegate
//
///////////////////////////////////////////////////////////////////////

class RegisterDelegate : public QItemDelegate
{
public:
    RegisterDelegate(RegisterWindow *owner, QObject *parent)
        : QItemDelegate(parent), m_owner(owner)
    {}

    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &,
        const QModelIndex &) const
    {
        QLineEdit *lineEdit = new QLineEdit(parent);
        lineEdit->setAlignment(Qt::AlignRight);
        return lineEdit;
    }

    void setEditorData(QWidget *editor, const QModelIndex &index) const
    {
        QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
        QTC_ASSERT(lineEdit, return);
        lineEdit->setText(index.data(Qt::DisplayRole).toString());
    }

    void setModelData(QWidget *editor, QAbstractItemModel *model,
        const QModelIndex &index) const
    {
        Q_UNUSED(model);
        //qDebug() << "SET MODEL DATA";
        QLineEdit *lineEdit = qobject_cast<QLineEdit*>(editor);
        QTC_ASSERT(lineEdit, return);
        QString value = lineEdit->text();
        //model->setData(index, value, Qt::EditRole);
        if (index.column() == 1)
            m_owner->model()->setData(index, value, RequestSetRegisterRole);
    }

    void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
        const QModelIndex &) const
    {
        editor->setGeometry(option.rect);
    }

    void paint(QPainter *painter, const QStyleOptionViewItem &option,
        const QModelIndex &index) const
    {
        if (index.column() == 1) {
            bool paintRed = index.data(RegisterChangedRole).toBool();
            QPen oldPen = painter->pen();
            if (paintRed)
                painter->setPen(QColor(200, 0, 0));
            // FIXME: performance? this changes only on real font changes.
            QFontMetrics fm(option.font);
            int charWidth = fm.width(QLatin1Char('x'));
            for (int i = '1'; i <= '9'; ++i)
                charWidth = qMax(charWidth, fm.width(QLatin1Char(i)));
            for (int i = 'a'; i <= 'f'; ++i)
                charWidth = qMax(charWidth, fm.width(QLatin1Char(i)));
            QString str = index.data(Qt::DisplayRole).toString();
            int x = option.rect.x();
            for (int i = 0; i < str.size(); ++i) {
                QRect r = option.rect;
                r.setX(x);
                r.setWidth(charWidth);
                x += charWidth;
                painter->drawText(r, Qt::AlignHCenter, QString(str.at(i)));
            }
            if (paintRed)
                painter->setPen(oldPen);
        } else {
            QItemDelegate::paint(painter, option, index);
        }
    }

private:
    RegisterWindow *m_owner;
};

///////////////////////////////////////////////////////////////////////
//
// RegisterWindow
//
///////////////////////////////////////////////////////////////////////

RegisterWindow::RegisterWindow(QWidget *parent)
  : QTreeView(parent), m_alwaysResizeColumnsToContents(true)
{
    QAction *act = theDebuggerAction(UseAlternatingRowColors);
    setWindowTitle(tr("Registers"));
    setAttribute(Qt::WA_MacShowFocusRect, false);
    setAlternatingRowColors(act->isChecked());
    setRootIsDecorated(false);
    setItemDelegate(new RegisterDelegate(this, this));

    connect(act, SIGNAL(toggled(bool)),
        this, SLOT(setAlternatingRowColorsHelper(bool)));
}

void RegisterWindow::resizeEvent(QResizeEvent *ev)
{
    QTreeView::resizeEvent(ev);
}

void RegisterWindow::contextMenuEvent(QContextMenuEvent *ev)
{
    QMenu menu;

    const unsigned engineCapabilities = modelData(EngineCapabilitiesRole).toUInt();
    const bool actionsEnabled = modelData(EngineActionsEnabledRole).toInt();
    const int state = modelData(EngineStateRole).toInt();

    QAction *actReload = menu.addAction(tr("Reload Register Listing"));
    actReload->setEnabled((engineCapabilities & RegisterCapability)
        && (state == InferiorStopOk || state == InferiorUnrunnable));

    menu.addSeparator();

    QModelIndex idx = indexAt(ev->pos());
    QString address = modelData(RegisterAddressRole, idx).toString();
    QAction *actShowMemory = menu.addAction(QString());
    if (address.isEmpty()) {
        actShowMemory->setText(tr("Open Memory Editor"));
        actShowMemory->setEnabled(false);
    } else {
        actShowMemory->setText(tr("Open Memory Editor at %1").arg(address));
        actShowMemory->setEnabled(actionsEnabled
            && (engineCapabilities & ShowMemoryCapability));
    }
    menu.addSeparator();

    int base = modelData(RegisterNumberBaseRole).toInt();
    QAction *act16 = menu.addAction(tr("Hexadecimal"));
    act16->setCheckable(true);
    act16->setChecked(base == 16);
    QAction *act10 = menu.addAction(tr("Decimal"));
    act10->setCheckable(true);
    act10->setChecked(base == 10);
    QAction *act8 = menu.addAction(tr("Octal"));
    act8->setCheckable(true);
    act8->setChecked(base == 8);
    QAction *act2 = menu.addAction(tr("Binary"));
    act2->setCheckable(true);
    act2->setChecked(base == 2);
    menu.addSeparator();

    QAction *actAdjust = menu.addAction(tr("Adjust Column Widths to Contents"));
    QAction *actAlwaysAdjust =
        menu.addAction(tr("Always Adjust Column Widths to Contents"));
    actAlwaysAdjust->setCheckable(true);
    actAlwaysAdjust->setChecked(m_alwaysResizeColumnsToContents);
    menu.addSeparator();

    menu.addAction(theDebuggerAction(SettingsDialog));

    QAction *act = menu.exec(ev->globalPos());

    if (act == actAdjust)
        resizeColumnsToContents();
    else if (act == actAlwaysAdjust)
        setAlwaysResizeColumnsToContents(!m_alwaysResizeColumnsToContents);
    else if (act == actReload)
        setModelData(RequestReloadRegistersRole);
    else if (act == actShowMemory)
        setModelData(RequestShowMemoryRole, address);
    else if (act) {
        base = (act == act10 ? 10 : act == act8 ? 8 : act == act2 ? 2 : 16);
        QMetaObject::invokeMethod(model(), "setNumberBase", Q_ARG(int, base));
    }
}

void RegisterWindow::resizeColumnsToContents()
{
    resizeColumnToContents(0);
    resizeColumnToContents(1);
}

void RegisterWindow::setAlwaysResizeColumnsToContents(bool on)
{
    m_alwaysResizeColumnsToContents = on;
    QHeaderView::ResizeMode mode = on
        ? QHeaderView::ResizeToContents : QHeaderView::Interactive;
    header()->setResizeMode(0, mode);
    header()->setResizeMode(1, mode);
}

void RegisterWindow::setModel(QAbstractItemModel *model)
{
    QTreeView::setModel(model);
    setAlwaysResizeColumnsToContents(true);
}

void RegisterWindow::reloadRegisters()
{
    // FIXME: Only trigger when becoming visible?
    setModelData(RequestReloadRegistersRole);
}

void RegisterWindow::setModelData
    (int role, const QVariant &value, const QModelIndex &index)
{
    QTC_ASSERT(model(), return);
    model()->setData(index, value, role);
}

QVariant RegisterWindow::modelData(int role, const QModelIndex &index)
{
    QTC_ASSERT(model(), return QVariant());
    return model()->data(index, role);
}

} // namespace Internal
} // namespace Debugger
<commit_msg>debugger: the register view should have no extra frame.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/

#include "registerwindow.h"

#include "debuggeractions.h"
#include "debuggerconstants.h"

#include <utils/qtcassert.h>
#include <utils/savedaction.h>

#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QFileInfoList>

#include <QtGui/QAction>
#include <QtGui/QHeaderView>
#include <QtGui/QItemDelegate>
#include <QtGui/QLineEdit>
#include <QtGui/QMenu>
#include <QtGui/QPainter>
#include <QtGui/QResizeEvent>
#include <QtGui/QToolButton>

namespace Debugger {
namespace Internal {

///////////////////////////////////////////////////////////////////////
//
// RegisterDelegate
//
///////////////////////////////////////////////////////////////////////

class RegisterDelegate : public QItemDelegate
{
public:
    RegisterDelegate(RegisterWindow *owner, QObject *parent)
        : QItemDelegate(parent), m_owner(owner)
    {}

    QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &,
        const QModelIndex &) const
    {
        QLineEdit *lineEdit = new QLineEdit(parent);
        lineEdit->setAlignment(Qt::AlignRight);
        return lineEdit;
    }

    void setEditorData(QWidget *editor, const QModelIndex &index) const
    {
        QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
        QTC_ASSERT(lineEdit, return);
        lineEdit->setText(index.data(Qt::DisplayRole).toString());
    }

    void setModelData(QWidget *editor, QAbstractItemModel *model,
        const QModelIndex &index) const
    {
        Q_UNUSED(model);
        //qDebug() << "SET MODEL DATA";
        QLineEdit *lineEdit = qobject_cast<QLineEdit*>(editor);
        QTC_ASSERT(lineEdit, return);
        QString value = lineEdit->text();
        //model->setData(index, value, Qt::EditRole);
        if (index.column() == 1)
            m_owner->model()->setData(index, value, RequestSetRegisterRole);
    }

    void updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
        const QModelIndex &) const
    {
        editor->setGeometry(option.rect);
    }

    void paint(QPainter *painter, const QStyleOptionViewItem &option,
        const QModelIndex &index) const
    {
        if (index.column() == 1) {
            bool paintRed = index.data(RegisterChangedRole).toBool();
            QPen oldPen = painter->pen();
            if (paintRed)
                painter->setPen(QColor(200, 0, 0));
            // FIXME: performance? this changes only on real font changes.
            QFontMetrics fm(option.font);
            int charWidth = fm.width(QLatin1Char('x'));
            for (int i = '1'; i <= '9'; ++i)
                charWidth = qMax(charWidth, fm.width(QLatin1Char(i)));
            for (int i = 'a'; i <= 'f'; ++i)
                charWidth = qMax(charWidth, fm.width(QLatin1Char(i)));
            QString str = index.data(Qt::DisplayRole).toString();
            int x = option.rect.x();
            for (int i = 0; i < str.size(); ++i) {
                QRect r = option.rect;
                r.setX(x);
                r.setWidth(charWidth);
                x += charWidth;
                painter->drawText(r, Qt::AlignHCenter, QString(str.at(i)));
            }
            if (paintRed)
                painter->setPen(oldPen);
        } else {
            QItemDelegate::paint(painter, option, index);
        }
    }

private:
    RegisterWindow *m_owner;
};

///////////////////////////////////////////////////////////////////////
//
// RegisterWindow
//
///////////////////////////////////////////////////////////////////////

RegisterWindow::RegisterWindow(QWidget *parent)
  : QTreeView(parent), m_alwaysResizeColumnsToContents(true)
{
    QAction *act = theDebuggerAction(UseAlternatingRowColors);
    setFrameStyle(QFrame::NoFrame);
    setWindowTitle(tr("Registers"));
    setAttribute(Qt::WA_MacShowFocusRect, false);
    setAlternatingRowColors(act->isChecked());
    setRootIsDecorated(false);
    setItemDelegate(new RegisterDelegate(this, this));

    connect(act, SIGNAL(toggled(bool)),
        this, SLOT(setAlternatingRowColorsHelper(bool)));
}

void RegisterWindow::resizeEvent(QResizeEvent *ev)
{
    QTreeView::resizeEvent(ev);
}

void RegisterWindow::contextMenuEvent(QContextMenuEvent *ev)
{
    QMenu menu;

    const unsigned engineCapabilities = modelData(EngineCapabilitiesRole).toUInt();
    const bool actionsEnabled = modelData(EngineActionsEnabledRole).toInt();
    const int state = modelData(EngineStateRole).toInt();

    QAction *actReload = menu.addAction(tr("Reload Register Listing"));
    actReload->setEnabled((engineCapabilities & RegisterCapability)
        && (state == InferiorStopOk || state == InferiorUnrunnable));

    menu.addSeparator();

    QModelIndex idx = indexAt(ev->pos());
    QString address = modelData(RegisterAddressRole, idx).toString();
    QAction *actShowMemory = menu.addAction(QString());
    if (address.isEmpty()) {
        actShowMemory->setText(tr("Open Memory Editor"));
        actShowMemory->setEnabled(false);
    } else {
        actShowMemory->setText(tr("Open Memory Editor at %1").arg(address));
        actShowMemory->setEnabled(actionsEnabled
            && (engineCapabilities & ShowMemoryCapability));
    }
    menu.addSeparator();

    int base = modelData(RegisterNumberBaseRole).toInt();
    QAction *act16 = menu.addAction(tr("Hexadecimal"));
    act16->setCheckable(true);
    act16->setChecked(base == 16);
    QAction *act10 = menu.addAction(tr("Decimal"));
    act10->setCheckable(true);
    act10->setChecked(base == 10);
    QAction *act8 = menu.addAction(tr("Octal"));
    act8->setCheckable(true);
    act8->setChecked(base == 8);
    QAction *act2 = menu.addAction(tr("Binary"));
    act2->setCheckable(true);
    act2->setChecked(base == 2);
    menu.addSeparator();

    QAction *actAdjust = menu.addAction(tr("Adjust Column Widths to Contents"));
    QAction *actAlwaysAdjust =
        menu.addAction(tr("Always Adjust Column Widths to Contents"));
    actAlwaysAdjust->setCheckable(true);
    actAlwaysAdjust->setChecked(m_alwaysResizeColumnsToContents);
    menu.addSeparator();

    menu.addAction(theDebuggerAction(SettingsDialog));

    QAction *act = menu.exec(ev->globalPos());

    if (act == actAdjust)
        resizeColumnsToContents();
    else if (act == actAlwaysAdjust)
        setAlwaysResizeColumnsToContents(!m_alwaysResizeColumnsToContents);
    else if (act == actReload)
        setModelData(RequestReloadRegistersRole);
    else if (act == actShowMemory)
        setModelData(RequestShowMemoryRole, address);
    else if (act) {
        base = (act == act10 ? 10 : act == act8 ? 8 : act == act2 ? 2 : 16);
        QMetaObject::invokeMethod(model(), "setNumberBase", Q_ARG(int, base));
    }
}

void RegisterWindow::resizeColumnsToContents()
{
    resizeColumnToContents(0);
    resizeColumnToContents(1);
}

void RegisterWindow::setAlwaysResizeColumnsToContents(bool on)
{
    m_alwaysResizeColumnsToContents = on;
    QHeaderView::ResizeMode mode = on
        ? QHeaderView::ResizeToContents : QHeaderView::Interactive;
    header()->setResizeMode(0, mode);
    header()->setResizeMode(1, mode);
}

void RegisterWindow::setModel(QAbstractItemModel *model)
{
    QTreeView::setModel(model);
    setAlwaysResizeColumnsToContents(true);
}

void RegisterWindow::reloadRegisters()
{
    // FIXME: Only trigger when becoming visible?
    setModelData(RequestReloadRegistersRole);
}

void RegisterWindow::setModelData
    (int role, const QVariant &value, const QModelIndex &index)
{
    QTC_ASSERT(model(), return);
    model()->setData(index, value, role);
}

QVariant RegisterWindow::modelData(int role, const QModelIndex &index)
{
    QTC_ASSERT(model(), return QVariant());
    return model()->data(index, role);
}

} // namespace Internal
} // namespace Debugger
<|endoftext|>


<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

// Implements C wrappers around the CUDA library for easy linking in ORC jit.
// Also adds some debugging helpers that are helpful when writing MLIR code to
// run on GPUs.

#include <cassert>
#include <numeric>

#include "absl/container/flat_hash_map.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"

#if GOOGLE_CUDA
#include "third_party/gpus/cuda/include/cuda.h"

#define CUDA_REPORT_IF_ERROR(expr)                                      \
  [](CUresult result) {                                                 \
    if (!result) return;                                                \
    const char *name = nullptr;                                         \
    cuGetErrorName(result, &name);                                      \
    if (!name) name = "<unknown>";                                      \
    LOG(WARNING) << "'" << #expr << "' failed with '" << name << "'\n"; \
  }(expr)

namespace {
// Implements a cache for loading modules and creating streams. The assumption
// is that we never unload modules or delete streams again during the lifetime
// of a tensorflow runtime process.
struct CudaRuntimeCache {
 public:
  CUmodule loadModule(void *data) {
    tensorflow::mutex_lock lock(module_handle_mutex);
    auto it = module_handles.find(data);
    if (it != module_handles.end()) {
      return it->second;
    }
    CUmodule module = nullptr;
    CUDA_REPORT_IF_ERROR(cuModuleLoadData(&module, data));
    module_handles.insert({data, module});
    return module;
  }

  CUstream createStream() {
    tensorflow::mutex_lock lock(stream_handle_mutex);
    CUstream stream = nullptr;
    if (stream_handles.empty()) {
      CUDA_REPORT_IF_ERROR(cuStreamCreate(&stream, CU_STREAM_NON_BLOCKING));
    } else {
      stream = stream_handles.back();
      stream_handles.pop_back();
    }
    return stream;
  }

  void releaseStream(CUstream stream) {
    tensorflow::mutex_lock lock(stream_handle_mutex);
    stream_handles.push_back(stream);
  }

  static CudaRuntimeCache *get() {
    static auto *instance = new CudaRuntimeCache();
    return instance;
  }

 private:
  CudaRuntimeCache() = default;

  tensorflow::mutex stream_handle_mutex;
  std::vector<CUstream> stream_handles TF_GUARDED_BY(stream_handle_mutex);
  tensorflow::mutex module_handle_mutex;
  absl::flat_hash_map<void *, CUmodule> module_handles
      TF_GUARDED_BY(module_handle_mutex);
};
}  // namespace

extern "C" CUmodule mgpuModuleLoad(void *data) {
  return CudaRuntimeCache::get()->loadModule(data);
}

extern "C" void mgpuModuleUnload(CUmodule module) {
  // We never unload modules.
}

extern "C" CUfunction mgpuModuleGetFunction(CUmodule module, const char *name) {
  CUfunction function = nullptr;
  CUDA_REPORT_IF_ERROR(cuModuleGetFunction(&function, module, name));
  return function;
}

// The wrapper uses intptr_t instead of CUDA's unsigned int to match
// the type of MLIR's index type. This avoids the need for casts in the
// generated MLIR code.
extern "C" void mgpuLaunchKernel(CUfunction function, intptr_t gridX,
                                 intptr_t gridY, intptr_t gridZ,
                                 intptr_t blockX, intptr_t blockY,
                                 intptr_t blockZ, int32_t smem, CUstream stream,
                                 void **params, void **extra) {
  CUDA_REPORT_IF_ERROR(cuLaunchKernel(function, gridX, gridY, gridZ, blockX,
                                      blockY, blockZ, smem, stream, params,
                                      extra));
}

extern "C" CUstream mgpuStreamCreate() {
  return CudaRuntimeCache::get()->createStream();
}

extern "C" void mgpuStreamDestroy(CUstream stream) {
  return CudaRuntimeCache::get()->releaseStream(stream);
}

extern "C" void mgpuStreamSynchronize(CUstream stream) {
  CUDA_REPORT_IF_ERROR(cuStreamSynchronize(stream));
}

extern "C" void mgpuStreamWaitEvent(CUstream stream, CUevent event) {
  CUDA_REPORT_IF_ERROR(cuStreamWaitEvent(stream, event, /*flags=*/0));
}

extern "C" CUevent mgpuEventCreate() {
  CUevent event = nullptr;
  CUDA_REPORT_IF_ERROR(cuEventCreate(&event, CU_EVENT_DISABLE_TIMING));
  return event;
}

extern "C" void mgpuEventDestroy(CUevent event) {
  CUDA_REPORT_IF_ERROR(cuEventDestroy(event));
}

extern "C" void mgpuEventSynchronize(CUevent event) {
  CUDA_REPORT_IF_ERROR(cuEventSynchronize(event));
}

extern "C" void mgpuEventRecord(CUevent event, CUstream stream) {
  CUDA_REPORT_IF_ERROR(cuEventRecord(event, stream));
}

#endif
<commit_msg>Make the runtime cache in the tf cuda runtime wrappers context specific.<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

// Implements C wrappers around the CUDA library for easy linking in ORC jit.
// Also adds some debugging helpers that are helpful when writing MLIR code to
// run on GPUs.

#include <cassert>
#include <numeric>

#include "absl/container/flat_hash_map.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"

#if GOOGLE_CUDA
#include "third_party/gpus/cuda/include/cuda.h"

#define CUDA_REPORT_IF_ERROR(expr)                                      \
  [](CUresult result) {                                                 \
    if (!result) return;                                                \
    const char *name = nullptr;                                         \
    cuGetErrorName(result, &name);                                      \
    if (!name) name = "<unknown>";                                      \
    LOG(WARNING) << "'" << #expr << "' failed with '" << name << "'\n"; \
  }(expr)

namespace {
// Implements a cache for loading modules and creating streams. The assumption
// is that we never unload modules or delete streams again during the lifetime
// of a tensorflow runtime process.
struct CudaRuntimeCache {
 public:
  CUmodule loadModule(void *data) {
    tensorflow::mutex_lock lock(module_handle_mutex);
    auto &module = module_handles[data];
    if (!module) {
      CUDA_REPORT_IF_ERROR(cuModuleLoadData(&module, data));
    }
    return module;
  }

  CUstream createStream() {
    tensorflow::mutex_lock lock(stream_handle_mutex);
    CUstream stream = nullptr;
    if (stream_handles.empty()) {
      CUDA_REPORT_IF_ERROR(cuStreamCreate(&stream, CU_STREAM_NON_BLOCKING));
    } else {
      stream = stream_handles.back();
      stream_handles.pop_back();
    }
    return stream;
  }

  void releaseStream(CUstream stream) {
    tensorflow::mutex_lock lock(stream_handle_mutex);
    stream_handles.push_back(stream);
  }

  // Returns the runtime cache for the current context.
  static CudaRuntimeCache *get() {
    using CacheWithLock =
        std::pair<tensorflow::mutex,
                  absl::flat_hash_map<CUcontext, CudaRuntimeCache *>>;
    static auto *cache_with_lock = new CacheWithLock();
    tensorflow::mutex_lock lock(cache_with_lock->first);
    CUcontext context;
    CUDA_REPORT_IF_ERROR(cuCtxGetCurrent(&context));
    auto &runtime_cache = cache_with_lock->second[context];
    if (!runtime_cache) {
      runtime_cache = new CudaRuntimeCache();
    }
    return runtime_cache;
  }

 private:
  CudaRuntimeCache() = default;

  tensorflow::mutex stream_handle_mutex;
  std::vector<CUstream> stream_handles TF_GUARDED_BY(stream_handle_mutex);
  tensorflow::mutex module_handle_mutex;
  absl::flat_hash_map<void *, CUmodule> module_handles
      TF_GUARDED_BY(module_handle_mutex);
};
}  // namespace

extern "C" CUmodule mgpuModuleLoad(void *data) {
  return CudaRuntimeCache::get()->loadModule(data);
}

extern "C" void mgpuModuleUnload(CUmodule module) {
  // We never unload modules.
}

extern "C" CUfunction mgpuModuleGetFunction(CUmodule module, const char *name) {
  CUfunction function = nullptr;
  CUDA_REPORT_IF_ERROR(cuModuleGetFunction(&function, module, name));
  return function;
}

// The wrapper uses intptr_t instead of CUDA's unsigned int to match
// the type of MLIR's index type. This avoids the need for casts in the
// generated MLIR code.
extern "C" void mgpuLaunchKernel(CUfunction function, intptr_t gridX,
                                 intptr_t gridY, intptr_t gridZ,
                                 intptr_t blockX, intptr_t blockY,
                                 intptr_t blockZ, int32_t smem, CUstream stream,
                                 void **params, void **extra) {
  CUDA_REPORT_IF_ERROR(cuLaunchKernel(function, gridX, gridY, gridZ, blockX,
                                      blockY, blockZ, smem, stream, params,
                                      extra));
}

extern "C" CUstream mgpuStreamCreate() {
  return CudaRuntimeCache::get()->createStream();
}

extern "C" void mgpuStreamDestroy(CUstream stream) {
  return CudaRuntimeCache::get()->releaseStream(stream);
}

extern "C" void mgpuStreamSynchronize(CUstream stream) {
  CUDA_REPORT_IF_ERROR(cuStreamSynchronize(stream));
}

extern "C" void mgpuStreamWaitEvent(CUstream stream, CUevent event) {
  CUDA_REPORT_IF_ERROR(cuStreamWaitEvent(stream, event, /*flags=*/0));
}

extern "C" CUevent mgpuEventCreate() {
  CUevent event = nullptr;
  CUDA_REPORT_IF_ERROR(cuEventCreate(&event, CU_EVENT_DISABLE_TIMING));
  return event;
}

extern "C" void mgpuEventDestroy(CUevent event) {
  CUDA_REPORT_IF_ERROR(cuEventDestroy(event));
}

extern "C" void mgpuEventSynchronize(CUevent event) {
  CUDA_REPORT_IF_ERROR(cuEventSynchronize(event));
}

extern "C" void mgpuEventRecord(CUevent event, CUstream stream) {
  CUDA_REPORT_IF_ERROR(cuEventRecord(event, stream));
}

#endif
<|endoftext|>