<commit_before>#include <QCoreApplication>
#include <QDebug>
#include "wakeproto.h"

const unsigned char crc8Table[256] = {
	0x00, 0x31, 0x62, 0x53, 0xC4, 0xF5, 0xA6, 0x97,
	0xB9, 0x88, 0xDB, 0xEA, 0x7D, 0x4C, 0x1F, 0x2E,
	0x43, 0x72, 0x21, 0x10, 0x87, 0xB6, 0xE5, 0xD4,
	0xFA, 0xCB, 0x98, 0xA9, 0x3E, 0x0F, 0x5C, 0x6D,
	0x86, 0xB7, 0xE4, 0xD5, 0x42, 0x73, 0x20, 0x11,
	0x3F, 0x0E, 0x5D, 0x6C, 0xFB, 0xCA, 0x99, 0xA8,
	0xC5, 0xF4, 0xA7, 0x96, 0x01, 0x30, 0x63, 0x52,
	0x7C, 0x4D, 0x1E, 0x2F, 0xB8, 0x89, 0xDA, 0xEB,
	0x3D, 0x0C, 0x5F, 0x6E, 0xF9, 0xC8, 0x9B, 0xAA,
	0x84, 0xB5, 0xE6, 0xD7, 0x40, 0x71, 0x22, 0x13,
	0x7E, 0x4F, 0x1C, 0x2D, 0xBA, 0x8B, 0xD8, 0xE9,
	0xC7, 0xF6, 0xA5, 0x94, 0x03, 0x32, 0x61, 0x50,
	0xBB, 0x8A, 0xD9, 0xE8, 0x7F, 0x4E, 0x1D, 0x2C,
	0x02, 0x33, 0x60, 0x51, 0xC6, 0xF7, 0xA4, 0x95,
	0xF8, 0xC9, 0x9A, 0xAB, 0x3C, 0x0D, 0x5E, 0x6F,
	0x41, 0x70, 0x23, 0x12, 0x85, 0xB4, 0xE7, 0xD6,
	0x7A, 0x4B, 0x18, 0x29, 0xBE, 0x8F, 0xDC, 0xED,
	0xC3, 0xF2, 0xA1, 0x90, 0x07, 0x36, 0x65, 0x54,
	0x39, 0x08, 0x5B, 0x6A, 0xFD, 0xCC, 0x9F, 0xAE,
	0x80, 0xB1, 0xE2, 0xD3, 0x44, 0x75, 0x26, 0x17,
	0xFC, 0xCD, 0x9E, 0xAF, 0x38, 0x09, 0x5A, 0x6B,
	0x45, 0x74, 0x27, 0x16, 0x81, 0xB0, 0xE3, 0xD2,
	0xBF, 0x8E, 0xDD, 0xEC, 0x7B, 0x4A, 0x19, 0x28,
	0x06, 0x37, 0x64, 0x55, 0xC2, 0xF3, 0xA0, 0x91,
	0x47, 0x76, 0x25, 0x14, 0x83, 0xB2, 0xE1, 0xD0,
	0xFE, 0xCF, 0x9C, 0xAD, 0x3A, 0x0B, 0x58, 0x69,
	0x04, 0x35, 0x66, 0x57, 0xC0, 0xF1, 0xA2, 0x93,
	0xBD, 0x8C, 0xDF, 0xEE, 0x79, 0x48, 0x1B, 0x2A,
	0xC1, 0xF0, 0xA3, 0x92, 0x05, 0x34, 0x67, 0x56,
	0x78, 0x49, 0x1A, 0x2B, 0xBC, 0x8D, 0xDE, 0xEF,
	0x82, 0xB3, 0xE0, 0xD1, 0x46, 0x77, 0x24, 0x15,
	0x3B, 0x0A, 0x59, 0x68, 0xFF, 0xCE, 0x9D, 0xAC
};

Wakeproto::Wakeproto()
{
	packet_started = 0;
	data_started = 0;
	bytes = 0;
	num_of_bytes = 0;
	qDebug() << "Wakeproto module loaded" << endl;
}

void Wakeproto::test() {
	qDebug() << "Wakeproto init completed" << endl;
}

QByteArray Wakeproto::createpacket(unsigned char address, unsigned char cmd, QByteArray data) {
	QByteArray packet;
	unsigned char tx_crc = 0xFF;
	tx_crc = crc8Table[tx_crc ^ FEND];
	tx_crc = crc8Table[tx_crc ^ address];
	tx_crc = crc8Table[tx_crc ^ cmd];
	tx_crc = crc8Table[tx_crc ^ data.size()];
	foreach (unsigned char k, data) {
		tx_crc = crc8Table[tx_crc ^ k];
	}

	packet.append(address); // Addr
	packet.append(cmd); // CMD
	packet.append(data.size()); // N
	packet.append(data); // data
	packet.append(tx_crc); // CRC
	packet = stuffing(packet);
	packet.prepend(FEND); // FEND

	return packet;
}

int Wakeproto::getpacket(QByteArray data) {
	QByteArray rx_buffer = data;
	QByteArray rx_data;
	unsigned char rx_crc_calculated = 0xFF;
	unsigned char rx_crc_actual = 0xFF;

	foreach (unsigned char rx_byte, rx_buffer) {
		if (rx_byte == FEND && packet_started == 1) {
			//  FEND,   ݣ   -
			bytes.clear();
			bytes.append(rx_byte);
			num_of_bytes = 0;
			rx_data.clear();
			rx_buffer.clear();

		} else if (packet_started) {
			// Bytes destuffing
			if(rx_byte == TFEND && bytes.endsWith(FESC)){
				bytes.chop(1);
				bytes.append(FEND);
			} else if (rx_byte == TFESC && bytes.endsWith(FESC)) {
				bytes.chop(1);
				bytes.append(FESC);
			} else {
				bytes.append(rx_byte);
			}
			// We received full header?
			if (bytes.size() == 4) {
				// TODO: implement ADDR & CMD check
				// fixme: what is 'n' ?
				//num_of_bytes = bytes.at(n);
				data_started = 1;
			}
			if(data_started && bytes.size() == 1 + 1 + 1 + 1 + num_of_bytes + 1) { // FEND + ADDR + CMD + N + DATA + CRC
				//rx_data = bytes.mid(datastream,bytes.size()-5);
				rx_data = bytes.mid(datastream,5);
				foreach (unsigned char k, rx_data) {
					rx_crc_calculated = crc8Table[rx_crc_calculated ^ k];
				}
				rx_crc_actual = bytes.right(1).at(0);
				if (rx_crc_actual != rx_crc_calculated) {
					// TODO: inform on CRC error
					//qDebug() << "[RX] CRC error" << QString::number(rx_crc_actual) << " (" << QString::number(rx_crc_calculated) << ")" << endl;
					//rx_crc_error_count++;
					// Send NACK
					//bytes.clear();
					//bytes.append(0xAE);
					//send_packet(201,60,bytes);
				} else {
					// TODO: Handle received packet
					//                    qDebug() << "[RX] FEND" << endl
					//                             << "[RX] ADDR: " << QString::number(static_cast<unsigned char>(bytes.at(addr))) << endl
					//                             << "[RX] CMD: " << QString::number(static_cast<unsigned char>(bytes.at(cmd))) << endl
					//                             << "[RX] N: " << QString::number(static_cast<unsigned char>(bytes.at(n))) << endl
					//                             << "[RX] DATA: " << rx_data.toHex() << endl
					//                             << "[RX] CRC: " << QString::number(rx_crc_actual) << " (" << QString::number(rx_crc_calculated) << ")" << endl
					//                             << "----------------------------" << endl;
					//process_packet(bytes.at(cmd), rx_data);
				}
				data_started = 0;
				packet_started = 0;
				num_of_bytes = 0;
				bytes.clear();
				rx_data.clear();
				rx_buffer.clear();
			}
		} else if (rx_byte == FEND) {
			bytes.append(rx_byte);
			packet_started = 1;
		}
	}
	return 0;
}

QByteArray Wakeproto::stuffing(QByteArray packet) {
	QByteArray stuffed_packet;
	foreach (unsigned char byte, packet) {
		switch (byte) {
			case FEND:
				stuffed_packet.append(FESC);
				stuffed_packet.append(TFEND);
				break;
			case FESC:
				stuffed_packet.append(FESC);
				stuffed_packet.append(TFESC);
				break;
			default:
				stuffed_packet.append(byte);
				break;
		}
	}
	return stuffed_packet;
}

<commit_msg>Fixed bux in rx_buff<commit_after>#include <QCoreApplication>
#include <QDebug>
#include "wakeproto.h"

const unsigned char crc8Table[256] = {
	0x00, 0x31, 0x62, 0x53, 0xC4, 0xF5, 0xA6, 0x97,
	0xB9, 0x88, 0xDB, 0xEA, 0x7D, 0x4C, 0x1F, 0x2E,
	0x43, 0x72, 0x21, 0x10, 0x87, 0xB6, 0xE5, 0xD4,
	0xFA, 0xCB, 0x98, 0xA9, 0x3E, 0x0F, 0x5C, 0x6D,
	0x86, 0xB7, 0xE4, 0xD5, 0x42, 0x73, 0x20, 0x11,
	0x3F, 0x0E, 0x5D, 0x6C, 0xFB, 0xCA, 0x99, 0xA8,
	0xC5, 0xF4, 0xA7, 0x96, 0x01, 0x30, 0x63, 0x52,
	0x7C, 0x4D, 0x1E, 0x2F, 0xB8, 0x89, 0xDA, 0xEB,
	0x3D, 0x0C, 0x5F, 0x6E, 0xF9, 0xC8, 0x9B, 0xAA,
	0x84, 0xB5, 0xE6, 0xD7, 0x40, 0x71, 0x22, 0x13,
	0x7E, 0x4F, 0x1C, 0x2D, 0xBA, 0x8B, 0xD8, 0xE9,
	0xC7, 0xF6, 0xA5, 0x94, 0x03, 0x32, 0x61, 0x50,
	0xBB, 0x8A, 0xD9, 0xE8, 0x7F, 0x4E, 0x1D, 0x2C,
	0x02, 0x33, 0x60, 0x51, 0xC6, 0xF7, 0xA4, 0x95,
	0xF8, 0xC9, 0x9A, 0xAB, 0x3C, 0x0D, 0x5E, 0x6F,
	0x41, 0x70, 0x23, 0x12, 0x85, 0xB4, 0xE7, 0xD6,
	0x7A, 0x4B, 0x18, 0x29, 0xBE, 0x8F, 0xDC, 0xED,
	0xC3, 0xF2, 0xA1, 0x90, 0x07, 0x36, 0x65, 0x54,
	0x39, 0x08, 0x5B, 0x6A, 0xFD, 0xCC, 0x9F, 0xAE,
	0x80, 0xB1, 0xE2, 0xD3, 0x44, 0x75, 0x26, 0x17,
	0xFC, 0xCD, 0x9E, 0xAF, 0x38, 0x09, 0x5A, 0x6B,
	0x45, 0x74, 0x27, 0x16, 0x81, 0xB0, 0xE3, 0xD2,
	0xBF, 0x8E, 0xDD, 0xEC, 0x7B, 0x4A, 0x19, 0x28,
	0x06, 0x37, 0x64, 0x55, 0xC2, 0xF3, 0xA0, 0x91,
	0x47, 0x76, 0x25, 0x14, 0x83, 0xB2, 0xE1, 0xD0,
	0xFE, 0xCF, 0x9C, 0xAD, 0x3A, 0x0B, 0x58, 0x69,
	0x04, 0x35, 0x66, 0x57, 0xC0, 0xF1, 0xA2, 0x93,
	0xBD, 0x8C, 0xDF, 0xEE, 0x79, 0x48, 0x1B, 0x2A,
	0xC1, 0xF0, 0xA3, 0x92, 0x05, 0x34, 0x67, 0x56,
	0x78, 0x49, 0x1A, 0x2B, 0xBC, 0x8D, 0xDE, 0xEF,
	0x82, 0xB3, 0xE0, 0xD1, 0x46, 0x77, 0x24, 0x15,
	0x3B, 0x0A, 0x59, 0x68, 0xFF, 0xCE, 0x9D, 0xAC
};

Wakeproto::Wakeproto()
{
	packet_started = 0;
	data_started = 0;
	bytes = 0;
	num_of_bytes = 0;
	qDebug() << "Wakeproto module loaded" << endl;
}

void Wakeproto::test() {
	qDebug() << "Wakeproto init completed" << endl;
}

QByteArray Wakeproto::createpacket(unsigned char address, unsigned char cmd, QByteArray data) {
	QByteArray packet;
	unsigned char tx_crc = 0xFF;
	tx_crc = crc8Table[tx_crc ^ FEND];
	tx_crc = crc8Table[tx_crc ^ address];
	tx_crc = crc8Table[tx_crc ^ cmd];
	tx_crc = crc8Table[tx_crc ^ data.size()];
	foreach (unsigned char k, data) {
		tx_crc = crc8Table[tx_crc ^ k];
	}

	packet.append(address); // Addr
	packet.append(cmd); // CMD
	packet.append(data.size()); // N
	packet.append(data); // data
	packet.append(tx_crc); // CRC
	packet = stuffing(packet);
	packet.prepend(FEND); // FEND

	return packet;
}

int Wakeproto::getpacket(QByteArray data) {
	QByteArray rx_buffer = data;
	QByteArray rx_data;
	unsigned char rx_crc_calculated = 0xFF;
	unsigned char rx_crc_actual = 0xFF;

	foreach (unsigned char rx_byte, rx_buffer) {
		if (rx_byte == FEND && packet_started == 1) {
			//  FEND,   ݣ   -
			bytes.clear();
			bytes.append(rx_byte);
			num_of_bytes = 0;
			rx_data.clear();
			rx_buffer.clear();

		} else if (packet_started) {
			// Bytes destuffing
			if(rx_byte == TFEND && bytes.endsWith(FESC)){
				bytes.chop(1);
				bytes.append(FEND);
			} else if (rx_byte == TFESC && bytes.endsWith(FESC)) {
				bytes.chop(1);
				bytes.append(FESC);
			} else {
				bytes.append(rx_byte);
			}
			// We received full header?
			if (bytes.size() == 4) {
				// TODO: implement ADDR & CMD check
				// fixme: what is 'n' ?
				//num_of_bytes = bytes.at(n);
				data_started = 1;
			}
			if(data_started && bytes.size() == 1 + 1 + 1 + 1 + num_of_bytes + 1) { // FEND + ADDR + CMD + N + DATA + CRC
				rx_data = bytes.mid(datastream,bytes.size()-5);
				foreach (unsigned char k, rx_data) {
					rx_crc_calculated = crc8Table[rx_crc_calculated ^ k];
				}
				rx_crc_actual = bytes.right(1).at(0);
				if (rx_crc_actual != rx_crc_calculated) {
					// TODO: inform on CRC error
					//qDebug() << "[RX] CRC error" << QString::number(rx_crc_actual) << " (" << QString::number(rx_crc_calculated) << ")" << endl;
					//rx_crc_error_count++;
					// Send NACK
					//bytes.clear();
					//bytes.append(0xAE);
					//send_packet(201,60,bytes);
				} else {
					// TODO: Handle received packet
					//                    qDebug() << "[RX] FEND" << endl
					//                             << "[RX] ADDR: " << QString::number(static_cast<unsigned char>(bytes.at(addr))) << endl
					//                             << "[RX] CMD: " << QString::number(static_cast<unsigned char>(bytes.at(cmd))) << endl
					//                             << "[RX] N: " << QString::number(static_cast<unsigned char>(bytes.at(n))) << endl
					//                             << "[RX] DATA: " << rx_data.toHex() << endl
					//                             << "[RX] CRC: " << QString::number(rx_crc_actual) << " (" << QString::number(rx_crc_calculated) << ")" << endl
					//                             << "----------------------------" << endl;
					//process_packet(bytes.at(cmd), rx_data);
				}
				data_started = 0;
				packet_started = 0;
				num_of_bytes = 0;
				bytes.clear();
				rx_data.clear();
				rx_buffer.clear();
			}
		} else if (rx_byte == FEND) {
			bytes.append(rx_byte);
			packet_started = 1;
		}
	}
	return 0;
}

QByteArray Wakeproto::stuffing(QByteArray packet) {
	QByteArray stuffed_packet;
	foreach (unsigned char byte, packet) {
		switch (byte) {
			case FEND:
				stuffed_packet.append(FESC);
				stuffed_packet.append(TFEND);
				break;
			case FESC:
				stuffed_packet.append(FESC);
				stuffed_packet.append(TFESC);
				break;
			default:
				stuffed_packet.append(byte);
				break;
		}
	}
	return stuffed_packet;
}

<|endoftext|>


<commit_before>/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Data Differential YATL (i.e. libtest)  library
 *
 *  Copyright (C) 2012 Data Differential, http://datadifferential.com/
 *
 *  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.
 *
 *      * The names of its contributors may not 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.
 *
 */

#pragma once

#include <typeinfo>

#if defined(HAVE_LIBMEMCACHED) && HAVE_LIBMEMCACHED
#include <libmemcached-1.0/memcached.h>
#include <libmemcachedutil-1.0/ostream.hpp>
#include <libtest/memcached.hpp>
#endif

#if defined(HAVE_LIBGEARMAN) && HAVE_LIBGEARMAN
#include <libgearman-1.0/ostream.hpp>
#endif

namespace libtest {

LIBTEST_API
bool jenkins_is_caller(void);

LIBTEST_API
bool gdb_is_caller(void);

LIBTEST_API
bool _in_valgrind(const char *file, int line, const char *func);

LIBTEST_API
bool helgrind_is_caller(void);

template <class T_comparable>
bool _compare_truth(const char *file, int line, const char *func, T_comparable __expected, const char *assertation_label)
{
  if (__expected == false)
  {
    libtest::stream::make_cerr(file, line, func) << "Assertation  \"" << assertation_label << "\"";
    return false;
  }

  return true;
}

template <class T1_comparable, class T2_comparable>
bool _compare(const char *file, int line, const char *func, const T1_comparable& __expected, const T2_comparable& __actual, bool use_io)
{
  if (__expected != __actual)
  {
    if (use_io)
    {
      libtest::stream::make_cerr(file, line, func) << "Expected \"" << __expected << "\" got \"" << __actual << "\"";
    }

    return false;
  }

  return true;
}

template <class T1_comparable, class T2_comparable>
bool _compare_strcmp(const char *file, int line, const char *func, const T1_comparable& __expected, const T2_comparable& __actual)
{
  if (__expected == NULL)
  {
    FATAL("Expected value was NULL, programmer error");
  }

  if (__actual == NULL)
  {
    libtest::stream::make_cerr(file, line, func) << "Expected " << __expected << " but got NULL";
    return false;
  }

  if (strncmp(__expected, __actual, strlen(__expected)))
  {
    libtest::stream::make_cerr(file, line, func) << "Expected " << __expected << " passed \"" << __actual << "\"";
    return false;
  }

  return true;
}

template <class T_comparable>
bool _compare_zero(const char *file, int line, const char *func, T_comparable __actual)
{
  if (T_comparable(0) != __actual)
  {
    libtest::stream::make_cerr(file, line, func) << "Expected 0 got \"" << __actual << "\"";
    return false;
  }

  return true;
}

template <class T1_comparable, class T2_comparable>
bool _ne_compare(const char *file, int line, const char *func, T1_comparable __expected, T2_comparable __actual, bool io_error= true)
{
  if (__expected == __actual)
  {
    if (io_error)
    {
      libtest::stream::make_cerr(file, line, func) << "Expected \"" << __expected << "\" got \"" << __actual << "\"";
    }

    return false;
  }

  return true;
}

template <class T_comparable, class T_expression_string>
bool _assert_truth(const char *file, int line, const char *func, T_comparable __truth, T_expression_string __expression, const char* __explain= NULL)
{
  if (__truth)
  {
    return true;
  }

  if (__explain)
  {
    libtest::stream::make_cerr(file, line, func) << "Assertion \"" << __expression << "\" warning:" << __explain;
  }

  return false;
}

} // namespace libtest
<commit_msg>Fixes NULL comparisons issue.<commit_after>/*  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Data Differential YATL (i.e. libtest)  library
 *
 *  Copyright (C) 2012 Data Differential, http://datadifferential.com/
 *
 *  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.
 *
 *      * The names of its contributors may not 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.
 *
 */

#pragma once

#include <typeinfo>

#if defined(HAVE_LIBMEMCACHED) && HAVE_LIBMEMCACHED
#include <libmemcached-1.0/memcached.h>
#include <libmemcachedutil-1.0/ostream.hpp>
#include <libtest/memcached.hpp>
#endif

#if defined(HAVE_LIBGEARMAN) && HAVE_LIBGEARMAN
#include <libgearman-1.0/ostream.hpp>
#endif

namespace libtest {

LIBTEST_API
bool jenkins_is_caller(void);

LIBTEST_API
bool gdb_is_caller(void);

LIBTEST_API
bool _in_valgrind(const char *file, int line, const char *func);

LIBTEST_API
bool helgrind_is_caller(void);

template <class T_comparable>
bool _compare_truth(const char *file, int line, const char *func, T_comparable __expected, const char *assertation_label)
{
  if (__expected == false)
  {
    libtest::stream::make_cerr(file, line, func) << "Assertation  \"" << assertation_label << "\"";
    return false;
  }

  return true;
}

template <class T1_comparable, class T2_comparable>
bool _compare(const char *file, int line, const char *func, const T1_comparable& __expected, const T2_comparable& __actual, bool use_io)
{
  if (__expected != __actual)
  {
    if (use_io)
    {
      libtest::stream::make_cerr(file, line, func) << "Expected \"" << __expected << "\" got \"" << __actual << "\"";
    }

    return false;
  }

  return true;
}

template <class T1_comparable, class T2_comparable>
bool _compare_strcmp(const char *file, int line, const char *func, const T1_comparable& __expected, const T2_comparable& __actual)
{
  if (strncmp(__expected, __actual, strlen(__expected)))
  {
    libtest::stream::make_cerr(file, line, func) << "Expected " << __expected << " passed \"" << __actual << "\"";
    return false;
  }

  return true;
}

template <class T_comparable>
bool _compare_zero(const char *file, int line, const char *func, T_comparable __actual)
{
  if (T_comparable(0) != __actual)
  {
    libtest::stream::make_cerr(file, line, func) << "Expected 0 got \"" << __actual << "\"";
    return false;
  }

  return true;
}

template <class T1_comparable, class T2_comparable>
bool _ne_compare(const char *file, int line, const char *func, T1_comparable __expected, T2_comparable __actual, bool io_error= true)
{
  if (__expected == __actual)
  {
    if (io_error)
    {
      libtest::stream::make_cerr(file, line, func) << "Expected \"" << __expected << "\" got \"" << __actual << "\"";
    }

    return false;
  }

  return true;
}

template <class T_comparable, class T_expression_string>
bool _assert_truth(const char *file, int line, const char *func, T_comparable __truth, T_expression_string __expression, const char* __explain= NULL)
{
  if (__truth)
  {
    return true;
  }

  if (__explain)
  {
    libtest::stream::make_cerr(file, line, func) << "Assertion \"" << __expression << "\" warning:" << __explain;
  }

  return false;
}

} // namespace libtest
<|endoftext|>


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

#include "gpu/command_buffer/service/mailbox_synchronizer.h"

#include "base/bind.h"
#include "gpu/command_buffer/service/mailbox_manager.h"
#include "gpu/command_buffer/service/texture_manager.h"
#include "ui/gl/gl_implementation.h"

namespace gpu {
namespace gles2 {

namespace {

MailboxSynchronizer* g_instance = NULL;

}  // anonymous namespace

// static
bool MailboxSynchronizer::Initialize() {
  DCHECK(!g_instance);
  DCHECK(gfx::GetGLImplementation() != gfx::kGLImplementationNone)
      << "GL bindings not initialized";
  switch (gfx::GetGLImplementation()) {
    case gfx::kGLImplementationMockGL:
      break;
    case gfx::kGLImplementationEGLGLES2:
#if !defined(OS_MACOSX)
      {
        if (!gfx::g_driver_egl.ext.b_EGL_KHR_image_base ||
            !gfx::g_driver_egl.ext.b_EGL_KHR_gl_texture_2D_image ||
            !gfx::g_driver_gl.ext.b_GL_OES_EGL_image ||
            !gfx::g_driver_egl.ext.b_EGL_KHR_fence_sync) {
          LOG(WARNING) << "MailboxSync not supported due to missing EGL "
                          "image/fence support";
          return false;
        }
      }
      break;
#endif
    default:
      NOTREACHED();
      return false;
  }
  g_instance = new MailboxSynchronizer;
  return true;
}

// static
void MailboxSynchronizer::Terminate() {
  DCHECK(g_instance);
  delete g_instance;
  g_instance = NULL;
}

// static
MailboxSynchronizer* MailboxSynchronizer::GetInstance() {
  return g_instance;
}

MailboxSynchronizer::TargetName::TargetName(unsigned target,
                                            const Mailbox& mailbox)
    : target(target), mailbox(mailbox) {}

MailboxSynchronizer::TextureGroup::TextureGroup(
    const TextureDefinition& definition)
    : definition(definition) {}

MailboxSynchronizer::TextureGroup::~TextureGroup() {}

MailboxSynchronizer::TextureVersion::TextureVersion(
    linked_ptr<TextureGroup> group)
    : version(group->definition.version()), group(group) {}

MailboxSynchronizer::TextureVersion::~TextureVersion() {}

MailboxSynchronizer::MailboxSynchronizer() {}

MailboxSynchronizer::~MailboxSynchronizer() {
  DCHECK_EQ(0U, textures_.size());
}

void MailboxSynchronizer::ReassociateMailboxLocked(
    const TargetName& target_name,
    TextureGroup* group) {
  lock_.AssertAcquired();
  for (TextureMap::iterator it = textures_.begin(); it != textures_.end();
       it++) {
    std::set<TargetName>::iterator mb_it =
        it->second.group->mailboxes.find(target_name);
    if (it->second.group != group &&
        mb_it != it->second.group->mailboxes.end()) {
      it->second.group->mailboxes.erase(mb_it);
    }
  }
  group->mailboxes.insert(target_name);
}

linked_ptr<MailboxSynchronizer::TextureGroup>
MailboxSynchronizer::GetGroupForMailboxLocked(const TargetName& target_name) {
  lock_.AssertAcquired();
  for (TextureMap::iterator it = textures_.begin(); it != textures_.end();
       it++) {
    std::set<TargetName>::const_iterator mb_it =
        it->second.group->mailboxes.find(target_name);
    if (mb_it != it->second.group->mailboxes.end())
      return it->second.group;
  }
  return make_linked_ptr<MailboxSynchronizer::TextureGroup>(NULL);
}

Texture* MailboxSynchronizer::CreateTextureFromMailbox(unsigned target,
                                                       const Mailbox& mailbox) {
  base::AutoLock lock(lock_);
  TargetName target_name(target, mailbox);
  linked_ptr<TextureGroup> group = GetGroupForMailboxLocked(target_name);
  if (group.get()) {
    Texture* new_texture = group->definition.CreateTexture();
    if (new_texture)
      textures_.insert(std::make_pair(new_texture, TextureVersion(group)));
    return new_texture;
  }

  return NULL;
}

void MailboxSynchronizer::TextureDeleted(Texture* texture) {
  base::AutoLock lock(lock_);
  TextureMap::iterator it = textures_.find(texture);
  if (it != textures_.end()) {
    // TODO: We could avoid the update if this was the last ref.
    UpdateTextureLocked(it->first, it->second);
    textures_.erase(it);
  }
}

void MailboxSynchronizer::PushTextureUpdates(MailboxManager* manager) {
  base::AutoLock lock(lock_);
  for (MailboxManager::MailboxToTextureMap::const_iterator texture_it =
           manager->mailbox_to_textures_.begin();
       texture_it != manager->mailbox_to_textures_.end();
       texture_it++) {
    TargetName target_name(texture_it->first.target, texture_it->first.mailbox);
    Texture* texture = texture_it->second->first;
    // TODO(sievers): crbug.com/352274
    // Should probably only fail if it already *has* mipmaps, while allowing
    // incomplete textures here. Also reconsider how to fail otherwise.
    bool needs_mips = texture->min_filter() != GL_NEAREST &&
                      texture->min_filter() != GL_LINEAR;
    if (target_name.target != GL_TEXTURE_2D || needs_mips)
      continue;

    TextureMap::iterator it = textures_.find(texture);
    if (it != textures_.end()) {
      TextureVersion& texture_version = it->second;
      TextureGroup* group = texture_version.group.get();
      std::set<TargetName>::const_iterator mb_it =
          group->mailboxes.find(target_name);
      if (mb_it == group->mailboxes.end()) {
        // We previously did not associate this texture with the given mailbox.
        // Unlink other texture groups from the mailbox.
        ReassociateMailboxLocked(target_name, group);
      }
      UpdateTextureLocked(texture, texture_version);

    } else {
      linked_ptr<TextureGroup> group = make_linked_ptr(new TextureGroup(
          TextureDefinition(target_name.target, texture, 1, NULL)));

      // Unlink other textures from this mailbox in case the name is not new.
      ReassociateMailboxLocked(target_name, group.get());
      textures_.insert(std::make_pair(texture, TextureVersion(group)));
    }
  }
}

void MailboxSynchronizer::UpdateTextureLocked(Texture* texture,
                                              TextureVersion& texture_version) {
  lock_.AssertAcquired();
  gfx::GLImage* gl_image = texture->GetLevelImage(texture->target(), 0);
  TextureGroup* group = texture_version.group.get();
  scoped_refptr<NativeImageBuffer> image_buffer = group->definition.image();

  // Make sure we don't clobber with an older version
  if (!group->definition.IsOlderThan(texture_version.version))
    return;

  // Also don't push redundant updates. Note that it would break the
  // versioning.
  if (group->definition.Matches(texture))
    return;

  if (gl_image && !image_buffer->IsClient(gl_image)) {
    LOG(ERROR) << "MailboxSync: Incompatible attachment";
    return;
  }

  group->definition = TextureDefinition(texture->target(),
                                        texture,
                                        ++texture_version.version,
                                        gl_image ? image_buffer : NULL);
}

void MailboxSynchronizer::PullTextureUpdates(MailboxManager* manager) {
  base::AutoLock lock(lock_);
  for (MailboxManager::MailboxToTextureMap::const_iterator texture_it =
           manager->mailbox_to_textures_.begin();
       texture_it != manager->mailbox_to_textures_.end();
       texture_it++) {
    Texture* texture = texture_it->second->first;
    TextureMap::iterator it = textures_.find(texture);
    if (it != textures_.end()) {
      TextureDefinition& definition = it->second.group->definition;
      if (it->second.version == definition.version() ||
          definition.IsOlderThan(it->second.version))
        continue;
      it->second.version = definition.version();
      definition.UpdateTexture(texture);
    }
  }
}

}  // namespace gles2
}  // namespace gpu
<commit_msg>Cherry-pick: Android Webview: Skip managed resources in mailbox sync<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "gpu/command_buffer/service/mailbox_synchronizer.h"

#include "base/bind.h"
#include "gpu/command_buffer/service/mailbox_manager.h"
#include "gpu/command_buffer/service/texture_manager.h"
#include "ui/gl/gl_implementation.h"

namespace gpu {
namespace gles2 {

namespace {

MailboxSynchronizer* g_instance = NULL;

}  // anonymous namespace

// static
bool MailboxSynchronizer::Initialize() {
  DCHECK(!g_instance);
  DCHECK(gfx::GetGLImplementation() != gfx::kGLImplementationNone)
      << "GL bindings not initialized";
  switch (gfx::GetGLImplementation()) {
    case gfx::kGLImplementationMockGL:
      break;
    case gfx::kGLImplementationEGLGLES2:
#if !defined(OS_MACOSX)
      {
        if (!gfx::g_driver_egl.ext.b_EGL_KHR_image_base ||
            !gfx::g_driver_egl.ext.b_EGL_KHR_gl_texture_2D_image ||
            !gfx::g_driver_gl.ext.b_GL_OES_EGL_image ||
            !gfx::g_driver_egl.ext.b_EGL_KHR_fence_sync) {
          LOG(WARNING) << "MailboxSync not supported due to missing EGL "
                          "image/fence support";
          return false;
        }
      }
      break;
#endif
    default:
      NOTREACHED();
      return false;
  }
  g_instance = new MailboxSynchronizer;
  return true;
}

// static
void MailboxSynchronizer::Terminate() {
  DCHECK(g_instance);
  delete g_instance;
  g_instance = NULL;
}

// static
MailboxSynchronizer* MailboxSynchronizer::GetInstance() {
  return g_instance;
}

MailboxSynchronizer::TargetName::TargetName(unsigned target,
                                            const Mailbox& mailbox)
    : target(target), mailbox(mailbox) {}

MailboxSynchronizer::TextureGroup::TextureGroup(
    const TextureDefinition& definition)
    : definition(definition) {}

MailboxSynchronizer::TextureGroup::~TextureGroup() {}

MailboxSynchronizer::TextureVersion::TextureVersion(
    linked_ptr<TextureGroup> group)
    : version(group->definition.version()), group(group) {}

MailboxSynchronizer::TextureVersion::~TextureVersion() {}

MailboxSynchronizer::MailboxSynchronizer() {}

MailboxSynchronizer::~MailboxSynchronizer() {
  DCHECK_EQ(0U, textures_.size());
}

void MailboxSynchronizer::ReassociateMailboxLocked(
    const TargetName& target_name,
    TextureGroup* group) {
  lock_.AssertAcquired();
  for (TextureMap::iterator it = textures_.begin(); it != textures_.end();
       it++) {
    std::set<TargetName>::iterator mb_it =
        it->second.group->mailboxes.find(target_name);
    if (it->second.group != group &&
        mb_it != it->second.group->mailboxes.end()) {
      it->second.group->mailboxes.erase(mb_it);
    }
  }
  group->mailboxes.insert(target_name);
}

linked_ptr<MailboxSynchronizer::TextureGroup>
MailboxSynchronizer::GetGroupForMailboxLocked(const TargetName& target_name) {
  lock_.AssertAcquired();
  for (TextureMap::iterator it = textures_.begin(); it != textures_.end();
       it++) {
    std::set<TargetName>::const_iterator mb_it =
        it->second.group->mailboxes.find(target_name);
    if (mb_it != it->second.group->mailboxes.end())
      return it->second.group;
  }
  return make_linked_ptr<MailboxSynchronizer::TextureGroup>(NULL);
}

Texture* MailboxSynchronizer::CreateTextureFromMailbox(unsigned target,
                                                       const Mailbox& mailbox) {
  base::AutoLock lock(lock_);
  TargetName target_name(target, mailbox);
  linked_ptr<TextureGroup> group = GetGroupForMailboxLocked(target_name);
  if (group.get()) {
    Texture* new_texture = group->definition.CreateTexture();
    if (new_texture)
      textures_.insert(std::make_pair(new_texture, TextureVersion(group)));
    return new_texture;
  }

  return NULL;
}

void MailboxSynchronizer::TextureDeleted(Texture* texture) {
  base::AutoLock lock(lock_);
  TextureMap::iterator it = textures_.find(texture);
  if (it != textures_.end()) {
    // TODO: We could avoid the update if this was the last ref.
    UpdateTextureLocked(it->first, it->second);
    textures_.erase(it);
  }
}

void MailboxSynchronizer::PushTextureUpdates(MailboxManager* manager) {
  base::AutoLock lock(lock_);
  for (MailboxManager::MailboxToTextureMap::const_iterator texture_it =
           manager->mailbox_to_textures_.begin();
       texture_it != manager->mailbox_to_textures_.end();
       texture_it++) {
    TargetName target_name(texture_it->first.target, texture_it->first.mailbox);
    Texture* texture = texture_it->second->first;
    // TODO(sievers): crbug.com/352274
    // Should probably only fail if it already *has* mipmaps, while allowing
    // incomplete textures here. Also reconsider how to fail otherwise.
    bool needs_mips = texture->min_filter() != GL_NEAREST &&
                      texture->min_filter() != GL_LINEAR;
    if (target_name.target != GL_TEXTURE_2D || needs_mips)
      continue;

    TextureMap::iterator it = textures_.find(texture);
    if (it != textures_.end()) {
      TextureVersion& texture_version = it->second;
      TextureGroup* group = texture_version.group.get();
      std::set<TargetName>::const_iterator mb_it =
          group->mailboxes.find(target_name);
      if (mb_it == group->mailboxes.end()) {
        // We previously did not associate this texture with the given mailbox.
        // Unlink other texture groups from the mailbox.
        ReassociateMailboxLocked(target_name, group);
      }
      UpdateTextureLocked(texture, texture_version);

    } else {
      // Skip compositor resources/tile textures.
      // TODO: Remove this, see crbug.com/399226.
      if (texture->pool() == GL_TEXTURE_POOL_MANAGED_CHROMIUM)
        continue;

      linked_ptr<TextureGroup> group = make_linked_ptr(new TextureGroup(
          TextureDefinition(target_name.target, texture, 1, NULL)));

      // Unlink other textures from this mailbox in case the name is not new.
      ReassociateMailboxLocked(target_name, group.get());
      textures_.insert(std::make_pair(texture, TextureVersion(group)));
    }
  }
}

void MailboxSynchronizer::UpdateTextureLocked(Texture* texture,
                                              TextureVersion& texture_version) {
  lock_.AssertAcquired();
  gfx::GLImage* gl_image = texture->GetLevelImage(texture->target(), 0);
  TextureGroup* group = texture_version.group.get();
  scoped_refptr<NativeImageBuffer> image_buffer = group->definition.image();

  // Make sure we don't clobber with an older version
  if (!group->definition.IsOlderThan(texture_version.version))
    return;

  // Also don't push redundant updates. Note that it would break the
  // versioning.
  if (group->definition.Matches(texture))
    return;

  if (gl_image && !image_buffer->IsClient(gl_image)) {
    LOG(ERROR) << "MailboxSync: Incompatible attachment";
    return;
  }

  group->definition = TextureDefinition(texture->target(),
                                        texture,
                                        ++texture_version.version,
                                        gl_image ? image_buffer : NULL);
}

void MailboxSynchronizer::PullTextureUpdates(MailboxManager* manager) {
  base::AutoLock lock(lock_);
  for (MailboxManager::MailboxToTextureMap::const_iterator texture_it =
           manager->mailbox_to_textures_.begin();
       texture_it != manager->mailbox_to_textures_.end();
       texture_it++) {
    Texture* texture = texture_it->second->first;
    TextureMap::iterator it = textures_.find(texture);
    if (it != textures_.end()) {
      TextureDefinition& definition = it->second.group->definition;
      if (it->second.version == definition.version() ||
          definition.IsOlderThan(it->second.version))
        continue;
      it->second.version = definition.version();
      definition.UpdateTexture(texture);
    }
  }
}

}  // namespace gles2
}  // namespace gpu
<|endoftext|>


<commit_before>/*=========================================================================

  Copyright (c) Kitware Inc.
  All rights reserved.

=========================================================================*/
// .SECTION Thanks
// This test was written by Philippe Pebay and Charles Law, Kitware 2012
// This work was supported in part by Commissariat a l'Energie Atomique (CEA/DIF)

#include "vtkHyperTreeGridGeometry.h"
#include "vtkHyperTreeGridSource.h"

#include "vtkCamera.h"
#include "vtkCellData.h"
#include "vtkNew.h"
#include "vtkPolyDataMapper.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"

int TestHyperTreeGridTernary3DGeometry( int argc, char* argv[] )
{
  vtkNew<vtkHyperTreeGridSource> fractal;
  fractal->SetMaximumLevel( 3 );
  fractal->SetGridSize( 3, 4, 2 );
  fractal->SetDimension( 3 );
  fractal->SetAxisBranchFactor( 3 );

  vtkNew<vtkHyperTreeGridGeometry> geometry;
  geometry->SetInputConnection( fractal->GetOutputPort() );
  geometry->Update();
  vtkPolyData* pd = geometry->GetOutput();

  vtkNew<vtkPolyDataMapper> mapper;
  mapper->SetInputConnection( geometry->GetOutputPort() );
  mapper->SetScalarRange( pd->GetCellData()->GetScalars()->GetRange() );

  vtkNew<vtkActor> actor;
  actor->SetMapper( mapper.GetPointer() );

  // Create camera
  double bd[6];
  pd->GetBounds( bd );
  vtkNew<vtkCamera> camera;
  camera->SetClippingRange( 1., 100. );
  camera->SetFocalPoint( pd->GetCenter() );
  camera->SetPosition( -.8 * bd[1], 2.1 * bd[3], -4.8 * bd[5] );

  // Create a renderer, add actors to it
  vtkNew<vtkRenderer> renderer;
  renderer->SetActiveCamera( camera.GetPointer() );
  renderer->SetBackground( 1., 1., 1. );
  renderer->AddActor( actor.GetPointer() );

  // Create a renderWindow
  vtkNew<vtkRenderWindow> renWin;
  renWin->AddRenderer( renderer.GetPointer() );
  renWin->SetSize( 300, 300 );
  renWin->SetMultiSamples( 0 );

  // Create interactor
  vtkNew<vtkRenderWindowInteractor> iren;
  iren->SetRenderWindow( renWin.GetPointer() );

  // Render and test
  renWin->Render();

  int retVal = vtkRegressionTestImage( renWin.GetPointer() );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR )
    {
    iren->Start();
    }

  return !retVal;
}
<commit_msg>A very challenging test for the 3D hyper tree geometry filter<commit_after>/*=========================================================================

  Copyright (c) Kitware Inc.
  All rights reserved.

=========================================================================*/
// .SECTION Thanks
// This test was written by Philippe Pebay and Charles Law, Kitware 2012
// This work was supported in part by Commissariat a l'Energie Atomique (CEA/DIF)

#include "vtkHyperTreeGridGeometry.h"
#include "vtkHyperTreeGridSource.h"

#include "vtkCamera.h"
#include "vtkCellData.h"
#include "vtkNew.h"
#include "vtkProperty.h"
#include "vtkPolyDataMapper.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"

int TestHyperTreeGridTernary3DGeometry( int argc, char* argv[] )
{
  // Hyper tree grid
  vtkNew<vtkHyperTreeGridSource> htGrid;
  int maxLevel = 5;
  htGrid->SetMaximumLevel( maxLevel );
  htGrid->SetGridSize( 3, 3, 2 );
  htGrid->SetDimension( 3 );
  htGrid->SetAxisBranchFactor( 3 );
  htGrid->DualOn();
  htGrid->SetDescriptor( "RRR .R. .RR ..R ..R .R.|R.......................... ........................... ........................... .............R............. ....RR.RR........R......... .....RRRR.....R.RR......... ........................... ........................... ...........................|........................... ........................... ........................... ...RR.RR.......RR.......... ........................... RR......................... ........................... ........................... ........................... ........................... ........................... ........................... ........................... ............RRR............|........................... ........................... .......RR.................. ........................... ........................... ........................... ........................... ........................... ........................... ........................... ...........................|........................... ..........................." );

  // Geometry
  vtkNew<vtkHyperTreeGridGeometry> geometry;
  geometry->SetInputConnection( htGrid->GetOutputPort() );
  geometry->Update();
  vtkPolyData* pd = geometry->GetOutput();

  // Mappers
  vtkNew<vtkPolyDataMapper> mapper1;
  mapper1->SetInputConnection( geometry->GetOutputPort() );
  mapper1->SetScalarRange( pd->GetCellData()->GetScalars()->GetRange() );
  mapper1->SetResolveCoincidentTopologyToPolygonOffset();
  mapper1->SetResolveCoincidentTopologyPolygonOffsetParameters( 0, 1 );
  vtkNew<vtkPolyDataMapper> mapper2;
  mapper2->SetInputConnection( geometry->GetOutputPort() );
  mapper2->ScalarVisibilityOff();
  mapper2->SetResolveCoincidentTopologyToPolygonOffset();
  mapper2->SetResolveCoincidentTopologyPolygonOffsetParameters( 1, 1 );

  // Actors
  vtkNew<vtkActor> actor1;
  actor1->SetMapper( mapper1.GetPointer() );
  vtkNew<vtkActor> actor2;
  actor2->SetMapper( mapper2.GetPointer() );
  actor2->GetProperty()->SetRepresentationToWireframe();
  actor2->GetProperty()->SetColor( .7, .7, .7 );

  // Camera
  double bd[6];
  pd->GetBounds( bd );
  vtkNew<vtkCamera> camera;
  camera->SetClippingRange( 1., 100. );
  camera->SetFocalPoint( pd->GetCenter() );
  camera->SetPosition( -.8 * bd[1], 2.1 * bd[3], -4.8 * bd[5] );

  // Renderer
  vtkNew<vtkRenderer> renderer;
  renderer->SetActiveCamera( camera.GetPointer() );
  renderer->SetBackground( 1., 1., 1. );
  renderer->AddActor( actor1.GetPointer() );
  renderer->AddActor( actor2.GetPointer() );

  // Render window
  vtkNew<vtkRenderWindow> renWin;
  renWin->AddRenderer( renderer.GetPointer() );
  renWin->SetSize( 300, 300 );
  renWin->SetMultiSamples( 0 );

  // Interactor
  vtkNew<vtkRenderWindowInteractor> iren;
  iren->SetRenderWindow( renWin.GetPointer() );

  // Render and test
  renWin->Render();

  int retVal = vtkRegressionTestImage( renWin.GetPointer() );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR )
    {
    iren->Start();
    }

  return !retVal;
}
<|endoftext|>


<commit_before>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <stdlib.h>
#include <QtGlobal>
#include <QtWidgets>

int main(int argc, char *argv[])
{
    // Global menubar is broken for qt5 apps in Ubuntu Unity, see:
    // https://bugs.launchpad.net/ubuntu/+source/appmenu-qt5/+bug/1323853
    // This workaround enables a local menubar.
    qputenv("UBUNTU_MENUPROXY","0");

    // Don't write .pyc files.
    qputenv("PYTHONDONTWRITEBYTECODE", "1");

    QApplication app(argc, argv);

    QString app_dir = app.applicationDirPath();
    QString main_qml = "/qml/main.qml";
    QString path_prefix;
    QString url_prefix;

    app.setApplicationName("YubiKey Manager");
    app.setOrganizationName("Yubico");
    app.setOrganizationDomain("com.yubico");

    // A lock file is used, to ensure only one running instance at the time.
    QString tmpDir = QDir::tempPath();
    QLockFile lockFile(tmpDir + "/ykman-gui.lock");
    if(!lockFile.tryLock(100)) {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText("YubiKey Manager is already running.");
        msgBox.exec();
        return 1;
    }

    if (QFileInfo::exists(":" + main_qml)) {
        // Embedded resources
        path_prefix = ":";
        url_prefix = "qrc://";
    } else if (QFileInfo::exists(app_dir + main_qml)) {
        // Try relative to executable
        path_prefix = app_dir;
        url_prefix = app_dir;
    } else {  //Assume qml/main.qml in cwd.
        app_dir = ".";
        path_prefix = ".";
        url_prefix = ".";
    }

    app.setWindowIcon(QIcon(path_prefix + "/images/windowicon.png"));

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("appDir", app_dir);
    engine.rootContext()->setContextProperty("urlPrefix", url_prefix);
    engine.rootContext()->setContextProperty("appVersion", APP_VERSION);

    engine.load(QUrl(url_prefix + main_qml));

    if (argc > 2 && strcmp(argv[1], "--log-level") == 0) {
        if (argc > 4 && strcmp(argv[3], "--log-file") == 0) {
            QMetaObject::invokeMethod(engine.rootObjects().first(), "enableLoggingToFile", Q_ARG(QVariant, argv[2]), Q_ARG(QVariant, argv[4]));
        } else {
            QMetaObject::invokeMethod(engine.rootObjects().first(), "enableLogging", Q_ARG(QVariant, argv[2]));
        }
    } else {
        QMetaObject::invokeMethod(engine.rootObjects().first(), "disableLogging");
    }

    return app.exec();
}
<commit_msg>Use QCommandLineParser instead of raw argv inspection<commit_after>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <stdlib.h>
#include <QtGlobal>
#include <QtWidgets>

int main(int argc, char *argv[])
{
    // Global menubar is broken for qt5 apps in Ubuntu Unity, see:
    // https://bugs.launchpad.net/ubuntu/+source/appmenu-qt5/+bug/1323853
    // This workaround enables a local menubar.
    qputenv("UBUNTU_MENUPROXY","0");

    // Don't write .pyc files.
    qputenv("PYTHONDONTWRITEBYTECODE", "1");

    QApplication app(argc, argv);

    QString app_dir = app.applicationDirPath();
    QString main_qml = "/qml/main.qml";
    QString path_prefix;
    QString url_prefix;

    app.setApplicationName("YubiKey Manager");
    app.setApplicationVersion(APP_VERSION);
    app.setOrganizationName("Yubico");
    app.setOrganizationDomain("com.yubico");

    // A lock file is used, to ensure only one running instance at the time.
    QString tmpDir = QDir::tempPath();
    QLockFile lockFile(tmpDir + "/ykman-gui.lock");
    if(!lockFile.tryLock(100)) {
        QMessageBox msgBox;
        msgBox.setIcon(QMessageBox::Warning);
        msgBox.setText("YubiKey Manager is already running.");
        msgBox.exec();
        return 1;
    }

    if (QFileInfo::exists(":" + main_qml)) {
        // Embedded resources
        path_prefix = ":";
        url_prefix = "qrc://";
    } else if (QFileInfo::exists(app_dir + main_qml)) {
        // Try relative to executable
        path_prefix = app_dir;
        url_prefix = app_dir;
    } else {  //Assume qml/main.qml in cwd.
        app_dir = ".";
        path_prefix = ".";
        url_prefix = ".";
    }

    app.setWindowIcon(QIcon(path_prefix + "/images/windowicon.png"));

    QQmlApplicationEngine engine;
    engine.rootContext()->setContextProperty("appDir", app_dir);
    engine.rootContext()->setContextProperty("urlPrefix", url_prefix);
    engine.rootContext()->setContextProperty("appVersion", APP_VERSION);

    engine.load(QUrl(url_prefix + main_qml));

    QCommandLineParser parser;
    parser.setApplicationDescription("Cross-platform application for YubiKey configuration");
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addOptions({
        {"log-level", QCoreApplication::translate("main", "Set log level to <LEVEL>"), QCoreApplication::translate("main", "LEVEL")},
        {"log-file", QCoreApplication::translate("main", "Print logs to <FILE> instead of standard output; ignored without --log-level"), QCoreApplication::translate("main", "FILE")},
    });

    parser.process(app);

    if (parser.isSet("log-level")) {
        if (parser.isSet("log-file")) {
            QMetaObject::invokeMethod(engine.rootObjects().first(), "enableLoggingToFile", Q_ARG(QVariant, parser.value("log-level")), Q_ARG(QVariant, parser.value("log-file")));
        } else {
            QMetaObject::invokeMethod(engine.rootObjects().first(), "enableLogging", Q_ARG(QVariant, parser.value("log-level")));
        }
    } else {
        QMetaObject::invokeMethod(engine.rootObjects().first(), "disableLogging");
    }

    return app.exec();
}
<|endoftext|>


<commit_before>/*
 * feature suite - Feature detection suite
 *
 * Copyright (c) 2013-2015 FOXEL SA - http://foxel.ch
 * Please read <http://foxel.ch/license> for more information.
 *
 *
 * Author(s):
 *
 *      Nils Hamel <n.hamel@foxel.ch>
 *
 *
 * This file is part of the FOXEL project <http://foxel.ch>.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * Additional Terms:
 *
 *      You are required to preserve legal notices and author attributions in
 *      that material or in the Appropriate Legal Notices displayed by works
 *      containing it.
 *
 *      You are required to attribute the work as explained in the "Usage and
 *      Attribution" section of <http://foxel.ch/license>.
 */

/*
    Source - Includes
 */

    # include "feature-image-expose.hpp"

/*
    Source - Entry point
 */

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

        /* Path variables */
        char fsImgIPath[256] = { 0 };
        char fsImgOPath[256] = { 0 };

        /* Parameters variables */
        float fsFixMean ( 0.0 );
        float fsFixStdd ( 0.0 );

        /* Statistical variables */
        float fsMean ( 0.0 );
        float fsStdd ( 0.0 );

        /* Image variable */
        cv::Mat fsImage;

        /* Search in parameters */
        lc_stdp( lc_stda( argc, argv, "--input" , "-i" ), argv,   fsImgIPath, LC_STRING );
        lc_stdp( lc_stda( argc, argv, "--output", "-o" ), argv,   fsImgOPath, LC_STRING );
        lc_stdp( lc_stda( argc, argv, "--mean"  , "-m" ), argv, & fsFixMean , LC_FLOAT  );
        lc_stdp( lc_stda( argc, argv, "--stdd"  , "-s" ), argv, & fsFixStdd , LC_FLOAT  );

        /* Software swicth */
        if ( ( lc_stda( argc, argv, "--help", "-h" ) ) || ( argc <= 1 ) ) {

            /* Display message */
            std::cout << FS_HELP;

        } else {

            /* Read input image */
            fsImage = cv::imread( fsImgIPath, CV_LOAD_IMAGE_COLOR );

            /* Verify image reading */
            if ( fsImage.data != NULL ) {

                /* Create array on image bytes */
                std::vector < char > fsBytes( fsImage.data, fsImage.data + fsImage.rows * fsImage.cols * fsImage.channels() );

                /* Compute histogram mean */
                fsMean = LC_VMEAN( fsBytes );

                /* Compute histogram standard deviation */
                fsStdd = LC_VSTDD( fsBytes, fsMean );

                /* Software switch */
                if ( lc_stda( argc, argv, "--set", "-e" ) ) {

                    /* Apply exposure correction */
                    fsImage = ( ( fsImage - fsMean ) / fsStdd ) * fsFixStdd + fsFixMean;

                    /* Write result image */
                    if ( imwrite( fsImgOPath, fsImage ) ) {

                        /* Display message */
                        std::cout << "Exported " << fsImgOPath << std::endl;

                    /* Display message */
                    } else { std::cout << "Error : Unable to write output image" << std::endl; }

                } else if ( lc_stda( argc, argv, "--get", "-g" ) ) {

                    /* Display image histogramm mean and standard deviation */
                    std::cout << fsMean << " " << fsStdd << std::endl;

                }

            /* Display message */
            } else { std::cout << "Error : Unable to read input image" << std::endl; }

        }

        /* Return to system */
        return( EXIT_SUCCESS );

    }

<commit_msg>Adding mean and standard deviation separate management in feature-image-expose<commit_after>/*
 * feature suite - Feature detection suite
 *
 * Copyright (c) 2013-2015 FOXEL SA - http://foxel.ch
 * Please read <http://foxel.ch/license> for more information.
 *
 *
 * Author(s):
 *
 *      Nils Hamel <n.hamel@foxel.ch>
 *
 *
 * This file is part of the FOXEL project <http://foxel.ch>.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * 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.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * Additional Terms:
 *
 *      You are required to preserve legal notices and author attributions in
 *      that material or in the Appropriate Legal Notices displayed by works
 *      containing it.
 *
 *      You are required to attribute the work as explained in the "Usage and
 *      Attribution" section of <http://foxel.ch/license>.
 */

/*
    Source - Includes
 */

    # include "feature-image-expose.hpp"

/*
    Source - Entry point
 */

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

        /* Path variables */
        char fsImgIPath[256] = { 0 };
        char fsImgOPath[256] = { 0 };

        /* Execution mode variables */
        char fsMode[256] = { 0 };

        /* Parameters variables */
        float fsFixMean ( 0.0 );
        float fsFixStdd ( 0.0 );

        /* Statistical variables */
        float fsMean ( 0.0 );
        float fsStdD ( 0.0 );

        /* Image variable */
        cv::Mat fsImage;

        /* Search in parameters */
        lc_stdp( lc_stda( argc, argv, "--input" , "-i" ), argv,   fsImgIPath, LC_STRING );
        lc_stdp( lc_stda( argc, argv, "--output", "-o" ), argv,   fsImgOPath, LC_STRING );
        lc_stdp( lc_stda( argc, argv, "--mode"  , "-d" ), argv,   fsMode    , LC_STRING );
        lc_stdp( lc_stda( argc, argv, "--mean"  , "-m" ), argv, & fsFixMean , LC_FLOAT  );
        lc_stdp( lc_stda( argc, argv, "--stdd"  , "-s" ), argv, & fsFixStdd , LC_FLOAT  );

        /* Software swicth */
        if ( ( lc_stda( argc, argv, "--help", "-h" ) ) || ( argc <= 1 ) ) {

            /* Display message */
            std::cout << FS_HELP;

        } else {

            /* Read input image */
            fsImage = cv::imread( fsImgIPath, CV_LOAD_IMAGE_COLOR );

            /* Verify image reading */
            if ( fsImage.data != NULL ) {

                /* Create array on image bytes */
                std::vector < char > fsBytes( fsImage.data, fsImage.data + fsImage.rows * fsImage.cols * fsImage.channels() );

                /* Software switch */
                if ( lc_stda( argc, argv, "--get", "-g" ) ) {

                    /* Check execution mode */
                    if ( ( strcmp( fsMode, "mean" ) == 0 ) || ( strcmp( fsMode, "both" ) == 0 ) ) {

                        /* Compute histogram mean */
                        fsMean = LC_VMEAN( fsBytes );

                        /* Display mean value */
                        std::cout << fsMean << std::endl;

                    }

                    if ( ( strcmp( fsMode, "std" ) == 0 ) || ( strcmp( fsMode, "both" ) == 0 ) ) {

                        /* Compute histogram standard deviation */
                        fsStdD = LC_VSTDD( fsBytes, fsMean );

                        /* Display standard deviation value */
                        std::cout << fsStdD << std::endl;

                    }

                } else if ( lc_stda( argc, argv, "--set", "-e" ) ) {

                    /* Check execution mode */
                    if ( ( strcmp( fsMode, "mean" ) == 0 ) || ( strcmp( fsMode, "both" ) == 0 ) ) {

                        /* Compute histogram mean */
                        fsMean = LC_VMEAN( fsBytes );

                        /* Check execution mode */
                        if ( strcmp( fsMode, "both" ) != 0 ) {

                            /* Exposure correction */
                            fsImage = ( fsImage - fsMean ) + fsFixMean;

                        }

                    }

                    if ( ( strcmp( fsMode, "std" ) == 0 ) || ( strcmp( fsMode, "both" ) == 0 ) ) {

                        /* Compute histogram standard deviation */
                        fsStdD = LC_VSTDD( fsBytes, fsMean );

                        /* Check execution mode */
                        if ( strcmp( fsMode, "both" ) != 0 ) {

                            /* Exposure correction */
                            fsImage = ( fsImage / fsStdD ) * fsFixStdd;

                        }

                    }

                    /* Check execution mode */
                    if ( strcmp( fsMode, "both" ) == 0 ) {

                        /* Exposure correction */
                        fsImage = ( ( fsImage - fsMean ) / fsStdD ) * fsFixStdd + fsFixMean;

                    }

                    /* Write result image */
                    if ( imwrite( fsImgOPath, fsImage ) == false ) {

                        /* Display message */
                        std::cout << "Error : Unable to write output image" << std::endl;

                    }

                /* Display message */
                } else { std::cout << "Error : Execution switch not provided" << std::endl; }

            /* Display message */
            } else { std::cout << "Error : Unable to read input image" << std::endl; }

        }

        /* Return to system */
        return( EXIT_SUCCESS );

    }

<|endoftext|>


<commit_before>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2019 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/

#pragma once

#include <Tensile/Predicates.hpp>
#include <Tensile/ContractionProblem.hpp>

#include <array>
#include <cstddef>
#include <vector>

namespace Tensile
{
    namespace Predicates
    {
        /**
         * \addtogroup Predicates
         * @{
         */
        /**
         * @brief ContractionProblem predicates
         */
        namespace Contraction
        {
            struct FreeSizeAMultiple: public Predicate_CRTP<FreeSizeAMultiple, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                FreeSizeAMultiple() = default;
                FreeSizeAMultiple(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "FreeSizeAMultiple"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.freeSizeA(index) % value == 0;
                }
            };

            struct FreeSizeBMultiple: public Predicate_CRTP<FreeSizeBMultiple, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                FreeSizeBMultiple() = default;
                FreeSizeBMultiple(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "FreeSizeBMultiple"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.freeSizeA(index) % value == 0;
                }
            };

            struct BatchSizeMultiple: public Predicate_CRTP<BatchSizeMultiple, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                BatchSizeMultiple() = default;
                BatchSizeMultiple(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "BatchSizeMultiple"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.batchSize(index) % value == 0;
                }
            };

            struct BatchSizeEqual: public Predicate_CRTP<BatchSizeEqual, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                BatchSizeEqual() = default;
                BatchSizeEqual(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "BatchSizeEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.batchSize(index) == value;
                }
            };

            struct BoundSizeMultiple: public Predicate_CRTP<BoundSizeMultiple, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                int64_t index;
                size_t value;

                BoundSizeMultiple() = default;
                BoundSizeMultiple(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "BoundSizeMultiple"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    if (index < 0)
                        return problem.boundSize(problem.boundIndices().size()+index) % value == 0;
                    else
                        return problem.boundSize(index) % value == 0;
                }
            };

            struct ProblemSizeEqual: public Predicate_CRTP<ProblemSizeEqual, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                ProblemSizeEqual() = default;
                ProblemSizeEqual(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "ProblemSizeEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.problemSizes()[index] == value;
                }
            };

            struct MaxProblemSizeGreaterThan: public Predicate_CRTP<MaxProblemSizeGreaterThan, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                size_t value;

                MaxProblemSizeGreaterThan() = default;
                MaxProblemSizeGreaterThan(size_t value): value(value) {}

                static std::string Type() { return "MaxProblemSizeGreaterThan"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.maxProblemSize() > value;
                }

                virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override
                {
                    bool rv = (*this)(problem);

                    stream << *this << ": (" << problem.maxProblemSize() << " > " << value << ") == " << rv;

                    return rv;
                }
            };

            struct LeadingFreeSizesGreaterOrEqual: public Predicate_CRTP<LeadingFreeSizesGreaterOrEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                size_t value;

                LeadingFreeSizesGreaterOrEqual() = default;
                LeadingFreeSizesGreaterOrEqual(size_t value): value(value) {}

                static std::string Type() { return "LeadingFreeSizesGreaterOrEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    // do we need this?
                    // this assert is not currenly used in rocblas
                    // enabling it is causing test failures
                    //return problem.freeSizeA(0) >= value
                    //    && problem.freeSizeB(0) >= value;
                    return true;
                }
            };

            struct StrideAEqual: public Predicate_CRTP<StrideAEqual, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                StrideAEqual() = default;
                StrideAEqual(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "StrideAEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.a().strides()[index] == value ;
                }

                virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override
                {
                    bool rv = (*this)(problem);

                    stream << *this << ": (" << problem.a().strides()[index] << " == " << value << ") == " << rv;

                    return rv;
                }
            };

            struct StrideBEqual: public Predicate_CRTP<StrideBEqual, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                StrideBEqual() = default;
                StrideBEqual(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "StrideBEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.b().strides()[index] == value ;
                }

                virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override
                {
                    bool rv = (*this)(problem);

                    stream << *this << ": (" << problem.b().strides()[index] << " == " << value << ") == " << rv;

                    return rv;
                }
            };

            struct CDStridesEqual: public Predicate_CRTP<CDStridesEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = false };
                static std::string Type() { return "CDStridesEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.c().strides() == problem.d().strides();
                }
            };

            struct LDCEqualsLDD: public Predicate_CRTP<LDCEqualsLDD, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = false };
                static std::string Type() { return "LDCEqualsLDD"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.c().strides()[1] == problem.d().strides()[1];
                }
            };

            struct BetaZero: public Predicate_CRTP<BetaZero, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = false };
                BetaZero() = default;

                static std::string Type() { return "BetaZero"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.beta() == 0.0;
                }
            };

            struct BetaOne: public Predicate_CRTP<BetaOne, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = false };
                BetaOne() = default;

                static std::string Type() { return "BetaOne"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.beta() == 1.0;
                }
            };

            struct HighPrecisionAccumulateEqual: public Predicate_CRTP<HighPrecisionAccumulateEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                bool value;

                HighPrecisionAccumulateEqual() = default;
                HighPrecisionAccumulateEqual(bool value): value(value) {}

                static std::string Type() { return "HighPrecisionAccumulate"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.highPrecisionAccumulate() == value;
                }
            };

            struct TypesEqual: public Predicate_CRTP<TypesEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                TypesEqual() = default;

                std::array<DataType, 4> value;

                static std::string Type() { return "TypesEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.a().dataType() == value[0]
                        && problem.b().dataType() == value[1]
                        && problem.c().dataType() == value[2]
                        && problem.d().dataType() == value[3];
                }

                virtual std::string toString() const override
                {
                    return concatenate(this->type(),
                                       "(a:",  value[0],
                                       ", b:", value[1],
                                       ", c:", value[2],
                                       ", d:", value[3],
                                       ")");
                }

                virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override
                {
                    bool rv = (*this)(problem);

                    stream << this->type()
                           <<   "(a:" << problem.a().dataType() << " == " << value[0]
                           << "&& b:" << problem.b().dataType() << " == " << value[1]
                           << "&& c:" << problem.c().dataType() << " == " << value[2]
                           << "&& d:" << problem.d().dataType() << " == " << value[3]
                           << "): " << rv;

                    return rv;
                }
            };

            struct OperationIdentifierEqual: public Predicate_CRTP<OperationIdentifierEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                OperationIdentifierEqual() = default;

                std::string value;

                static std::string Type() { return "OperationIdentifierEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.operationIdentifier() == value;
                }
            };
        }

        /**
         * @}
         */
    }
}

<commit_msg>fix for bug fixes<commit_after>/*******************************************************************************
 *
 * MIT License
 *
 * Copyright (c) 2019 Advanced Micro Devices, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *******************************************************************************/

#pragma once

#include <Tensile/Predicates.hpp>
#include <Tensile/ContractionProblem.hpp>

#include <array>
#include <cstddef>
#include <vector>

namespace Tensile
{
    namespace Predicates
    {
        /**
         * \addtogroup Predicates
         * @{
         */
        /**
         * @brief ContractionProblem predicates
         */
        namespace Contraction
        {
            struct FreeSizeAMultiple: public Predicate_CRTP<FreeSizeAMultiple, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                FreeSizeAMultiple() = default;
                FreeSizeAMultiple(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "FreeSizeAMultiple"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.freeSizeA(index) % value == 0;
                }
            };

            struct FreeSizeBMultiple: public Predicate_CRTP<FreeSizeBMultiple, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                FreeSizeBMultiple() = default;
                FreeSizeBMultiple(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "FreeSizeBMultiple"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.freeSizeA(index) % value == 0;
                }
            };

            struct BatchSizeMultiple: public Predicate_CRTP<BatchSizeMultiple, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                BatchSizeMultiple() = default;
                BatchSizeMultiple(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "BatchSizeMultiple"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.batchSize(index) % value == 0;
                }
            };

            struct BatchSizeEqual: public Predicate_CRTP<BatchSizeEqual, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                BatchSizeEqual() = default;
                BatchSizeEqual(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "BatchSizeEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.batchSize(index) == value;
                }
            };

            struct BoundSizeMultiple: public Predicate_CRTP<BoundSizeMultiple, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                int64_t index;
                size_t value;

                BoundSizeMultiple() = default;
                BoundSizeMultiple(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "BoundSizeMultiple"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    if (index < 0)
                        return problem.boundSize(problem.boundIndices().size()+index) % value == 0;
                    else
                        return problem.boundSize(index) % value == 0;
                }
            };

            struct ProblemSizeEqual: public Predicate_CRTP<ProblemSizeEqual, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                ProblemSizeEqual() = default;
                ProblemSizeEqual(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "ProblemSizeEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.problemSizes()[index] == value;
                }
            };

            struct MaxProblemSizeGreaterThan: public Predicate_CRTP<MaxProblemSizeGreaterThan, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                size_t value;

                MaxProblemSizeGreaterThan() = default;
                MaxProblemSizeGreaterThan(size_t value): value(value) {}

                static std::string Type() { return "MaxProblemSizeGreaterThan"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.maxProblemSize() > value;
                }

                virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override
                {
                    bool rv = (*this)(problem);

                    stream << *this << ": (" << problem.maxProblemSize() << " > " << value << ") == " << rv;

                    return rv;
                }
            };

            struct LeadingFreeSizesGreaterOrEqual: public Predicate_CRTP<LeadingFreeSizesGreaterOrEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                size_t value;

                LeadingFreeSizesGreaterOrEqual() = default;
                LeadingFreeSizesGreaterOrEqual(size_t value): value(value) {}

                static std::string Type() { return "LeadingFreeSizesGreaterOrEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    // do we need this?
                    // this assert is not currenly used in rocblas
                    // enabling it is causing test failures
                    return problem.freeSizeA(0) >= value
                        && problem.freeSizeB(0) >= value;
                }
            };

            struct StrideAEqual: public Predicate_CRTP<StrideAEqual, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                StrideAEqual() = default;
                StrideAEqual(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "StrideAEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.a().strides()[index] == value ;
                }

                virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override
                {
                    bool rv = (*this)(problem);

                    stream << *this << ": (" << problem.a().strides()[index] << " == " << value << ") == " << rv;

                    return rv;
                }
            };

            struct StrideBEqual: public Predicate_CRTP<StrideBEqual, ContractionProblem>
            {
                enum { HasIndex = true, HasValue = true };
                size_t index;
                size_t value;

                StrideBEqual() = default;
                StrideBEqual(size_t index, size_t value): index(index), value(value) {}

                static std::string Type() { return "StrideBEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.b().strides()[index] == value ;
                }

                virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override
                {
                    bool rv = (*this)(problem);

                    stream << *this << ": (" << problem.b().strides()[index] << " == " << value << ") == " << rv;

                    return rv;
                }
            };

            struct CDStridesEqual: public Predicate_CRTP<CDStridesEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = false };
                static std::string Type() { return "CDStridesEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.c().strides() == problem.d().strides();
                }
            };

            struct LDCEqualsLDD: public Predicate_CRTP<LDCEqualsLDD, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = false };
                static std::string Type() { return "LDCEqualsLDD"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.c().strides()[1] == problem.d().strides()[1];
                }
            };

            struct BetaZero: public Predicate_CRTP<BetaZero, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = false };
                BetaZero() = default;

                static std::string Type() { return "BetaZero"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.beta() == 0.0;
                }
            };

            struct BetaOne: public Predicate_CRTP<BetaOne, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = false };
                BetaOne() = default;

                static std::string Type() { return "BetaOne"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.beta() == 1.0;
                }
            };

            struct HighPrecisionAccumulateEqual: public Predicate_CRTP<HighPrecisionAccumulateEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                bool value;

                HighPrecisionAccumulateEqual() = default;
                HighPrecisionAccumulateEqual(bool value): value(value) {}

                static std::string Type() { return "HighPrecisionAccumulate"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.highPrecisionAccumulate() == value;
                }
            };

            struct TypesEqual: public Predicate_CRTP<TypesEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                TypesEqual() = default;

                std::array<DataType, 4> value;

                static std::string Type() { return "TypesEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.a().dataType() == value[0]
                        && problem.b().dataType() == value[1]
                        && problem.c().dataType() == value[2]
                        && problem.d().dataType() == value[3];
                }

                virtual std::string toString() const override
                {
                    return concatenate(this->type(),
                                       "(a:",  value[0],
                                       ", b:", value[1],
                                       ", c:", value[2],
                                       ", d:", value[3],
                                       ")");
                }

                virtual bool debugEval(ContractionProblem const& problem, std::ostream & stream) const override
                {
                    bool rv = (*this)(problem);

                    stream << this->type()
                           <<   "(a:" << problem.a().dataType() << " == " << value[0]
                           << "&& b:" << problem.b().dataType() << " == " << value[1]
                           << "&& c:" << problem.c().dataType() << " == " << value[2]
                           << "&& d:" << problem.d().dataType() << " == " << value[3]
                           << "): " << rv;

                    return rv;
                }
            };

            struct OperationIdentifierEqual: public Predicate_CRTP<OperationIdentifierEqual, ContractionProblem>
            {
                enum { HasIndex = false, HasValue = true };
                OperationIdentifierEqual() = default;

                std::string value;

                static std::string Type() { return "OperationIdentifierEqual"; }

                virtual bool operator()(ContractionProblem const& problem) const override
                {
                    return problem.operationIdentifier() == value;
                }
            };
        }

        /**
         * @}
         */
    }
}

<|endoftext|>


<commit_before>/*
 * Copyright 2020 Google Inc.
 *
 * 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.
 */

#pragma once

#include "data.hpp"
#include "internal/sys.hpp"
#include "pciaccess.hpp"

#include <linux/pci_regs.h>

#include <stdplus/types.hpp>

// Some versions of the linux/pci_regs.h header don't define this
#ifndef PCI_STD_NUM_BARS
#define PCI_STD_NUM_BARS 6
#endif // !PCI_STD_NUM_BARS

namespace host_tool
{

class PciBridgeIntf
{
  public:
    virtual ~PciBridgeIntf() = default;

    virtual void write(const stdplus::span<const std::uint8_t> data) = 0;
    virtual void configure(const ipmi_flash::PciConfigResponse& config) = 0;

    virtual std::size_t getDataLength() = 0;
};

class PciAccessBridge : public PciBridgeIntf
{
  public:
    virtual ~PciAccessBridge();

    virtual void write(const stdplus::span<const std::uint8_t> data) override;
    virtual void
        configure(const ipmi_flash::PciConfigResponse& configResp) override{};

    std::size_t getDataLength() override
    {
        return dataLength;
    }

  protected:
    /**
     * Finds the PCI device matching @a match and saves a reference to it in @a
     * dev. Also maps the memory region described in BAR number @a bar to
     * address @a addr,
     */
    PciAccessBridge(const struct pci_id_match* match, int bar,
                    std::size_t dataOffset, std::size_t dataLength,
                    const PciAccess* pci);

    struct pci_device* dev = nullptr;
    std::uint8_t* addr = nullptr;
    std::size_t size = 0;

  private:
    std::size_t dataOffset;
    std::size_t dataLength;

  protected:
    const PciAccess* pci;
};

class NuvotonPciBridge : public PciAccessBridge
{
  public:
    explicit NuvotonPciBridge(const PciAccess* pci,
                              bool skipBridgeDisable = false) :
        PciAccessBridge(&match, bar, dataOffset, dataLength, pci),
        skipBridgeDisable(skipBridgeDisable)
    {
        enableBridge();
    }

    ~NuvotonPciBridge()
    {
        if (!skipBridgeDisable)
            disableBridge();
    }

  private:
    static constexpr std::uint32_t vid = 0x1050;
    static constexpr std::uint32_t did = 0x0750;
    static constexpr int bar = 0;
    static constexpr struct pci_id_match match
    {
        vid, did, PCI_MATCH_ANY, PCI_MATCH_ANY
    };

    static constexpr pciaddr_t bridge = 0x04;
    static constexpr std::uint8_t bridgeEnabled = 0x02;

    static constexpr std::size_t dataOffset = 0x0;
    static constexpr std::size_t dataLength = 0x4000;

    void enableBridge();
    void disableBridge();

    bool skipBridgeDisable;
};

class AspeedPciBridge : public PciAccessBridge
{
  public:
    explicit AspeedPciBridge(const PciAccess* pci,
                             bool skipBridgeDisable = false) :
        PciAccessBridge(&match, bar, dataOffset, dataLength, pci),
        skipBridgeDisable(skipBridgeDisable)
    {
        enableBridge();
    }

    ~AspeedPciBridge()
    {
        if (!skipBridgeDisable)
            disableBridge();
    }

    void configure(const ipmi_flash::PciConfigResponse& configResp) override;

  private:
    static constexpr std::uint32_t vid = 0x1a03;
    static constexpr std::uint32_t did = 0x2000;
    static constexpr int bar = 1;
    static constexpr struct pci_id_match match
    {
        vid, did, PCI_MATCH_ANY, PCI_MATCH_ANY
    };

    static constexpr std::size_t config = 0x0f000;
    static constexpr std::size_t bridge = 0x0f004;
    static constexpr std::uint32_t bridgeEnabled = 0x1;

    static constexpr std::size_t dataOffset = 0x10000;
    static constexpr std::size_t dataLength = 0x10000;

    void enableBridge();
    void disableBridge();

    bool skipBridgeDisable;
};

} // namespace host_tool
<commit_msg>tools: remove shadow field<commit_after>/*
 * Copyright 2020 Google Inc.
 *
 * 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.
 */

#pragma once

#include "data.hpp"
#include "internal/sys.hpp"
#include "pciaccess.hpp"

#include <linux/pci_regs.h>

#include <stdplus/types.hpp>

// Some versions of the linux/pci_regs.h header don't define this
#ifndef PCI_STD_NUM_BARS
#define PCI_STD_NUM_BARS 6
#endif // !PCI_STD_NUM_BARS

namespace host_tool
{

class PciBridgeIntf
{
  public:
    virtual ~PciBridgeIntf() = default;

    virtual void write(const stdplus::span<const std::uint8_t> data) = 0;
    virtual void configure(const ipmi_flash::PciConfigResponse& config) = 0;

    virtual std::size_t getDataLength() = 0;
};

class PciAccessBridge : public PciBridgeIntf
{
  public:
    virtual ~PciAccessBridge();

    virtual void write(const stdplus::span<const std::uint8_t> data) override;
    virtual void
        configure(const ipmi_flash::PciConfigResponse& configResp) override{};

    std::size_t getDataLength() override
    {
        return dataLength;
    }

  protected:
    /**
     * Finds the PCI device matching @a match and saves a reference to it in @a
     * dev. Also maps the memory region described in BAR number @a bar to
     * address @a addr,
     */
    PciAccessBridge(const struct pci_id_match* match, int bar,
                    std::size_t dataOffset, std::size_t dataLength,
                    const PciAccess* pci);

    struct pci_device* dev = nullptr;
    std::uint8_t* addr = nullptr;
    std::size_t size = 0;

  private:
    std::size_t dataOffset;
    std::size_t dataLength;

  protected:
    const PciAccess* pci;
};

class NuvotonPciBridge : public PciAccessBridge
{
  public:
    explicit NuvotonPciBridge(const PciAccess* pciAccess,
                              bool skipBridgeDisable = false) :
        PciAccessBridge(&match, bar, dataOffset, dataLength, pciAccess),
        skipBridgeDisable(skipBridgeDisable)
    {
        enableBridge();
    }

    ~NuvotonPciBridge()
    {
        if (!skipBridgeDisable)
            disableBridge();
    }

  private:
    static constexpr std::uint32_t vid = 0x1050;
    static constexpr std::uint32_t did = 0x0750;
    static constexpr int bar = 0;
    static constexpr struct pci_id_match match
    {
        vid, did, PCI_MATCH_ANY, PCI_MATCH_ANY
    };

    static constexpr pciaddr_t bridge = 0x04;
    static constexpr std::uint8_t bridgeEnabled = 0x02;

    static constexpr std::size_t dataOffset = 0x0;
    static constexpr std::size_t dataLength = 0x4000;

    void enableBridge();
    void disableBridge();

    bool skipBridgeDisable;
};

class AspeedPciBridge : public PciAccessBridge
{
  public:
    explicit AspeedPciBridge(const PciAccess* pciAccess,
                             bool skipBridgeDisable = false) :
        PciAccessBridge(&match, bar, dataOffset, dataLength, pciAccess),
        skipBridgeDisable(skipBridgeDisable)
    {
        enableBridge();
    }

    ~AspeedPciBridge()
    {
        if (!skipBridgeDisable)
            disableBridge();
    }

    void configure(const ipmi_flash::PciConfigResponse& configResp) override;

  private:
    static constexpr std::uint32_t vid = 0x1a03;
    static constexpr std::uint32_t did = 0x2000;
    static constexpr int bar = 1;
    static constexpr struct pci_id_match match
    {
        vid, did, PCI_MATCH_ANY, PCI_MATCH_ANY
    };

    static constexpr std::size_t config = 0x0f000;
    static constexpr std::size_t bridge = 0x0f004;
    static constexpr std::uint32_t bridgeEnabled = 0x1;

    static constexpr std::size_t dataOffset = 0x10000;
    static constexpr std::size_t dataLength = 0x10000;

    void enableBridge();
    void disableBridge();

    bool skipBridgeDisable;
};

} // namespace host_tool
<|endoftext|>