<commit_before>#include "pcapplaybacksender.h"
#ifdef Q_OS_LINUX
#include <linux/socket.h>
#include <linux/in.h>
#endif
#ifdef Q_OS_UNIX
#include <sys/socket.h>
#endif
#include <pcap.h>
#include <QDebug>
#include <QtEndian>
#include "preferences.h"
#include "sacn/streamingacn.h"
#include "sacn/sacnlistener.h"
#include "ethernetstrut.h"

pcapplaybacksender::pcapplaybacksender(QString FileName) :
    m_filename(FileName),
    m_pcap_in(Q_NULLPTR),
    m_pcap_out(Q_NULLPTR),
    m_running(false),
    m_shutdown(false)
{
    if (!openFile()) {
        closeFile();
    }
}

pcapplaybacksender::~pcapplaybacksender()
{
    m_running = false;

    closeFile();

    QMutexLocker mutexOut(&m_pcap_out_Mutex);
    if (m_pcap_out) {
        pcap_close(m_pcap_out);
        m_pcap_out = Q_NULLPTR;
    }
}

void pcapplaybacksender::run()
{
    /* Open output adapter */
    {
        QMutexLocker mutexOut(&m_pcap_out_Mutex);

        char errbuf[PCAP_ERRBUF_SIZE];

        // Get required interface
        QNetworkInterface iface = Preferences::getInstance()->networkInterface();

        // Find all usable interfaces
        pcap_if_t *alldevs;
        if (pcap_findalldevs(&alldevs, errbuf) == -1)
        {
            emit error(tr("%1").arg(errbuf));
            return;
        }

        // See which avaliable interface matches required interface
        for(pcap_if_t *dev = alldevs; dev != NULL; dev = dev->next)
        {
            // Already have an interface
            if (m_pcap_out) { break; }

            for (pcap_addr *addr = dev->addresses; addr != NULL; addr = addr->next)
            {
                // Already have an interface
                if (m_pcap_out) { break; }

                if (addr->addr->sa_family == AF_INET) {
                    // IPv4
                    struct sockaddr_in *ipv4 = (struct sockaddr_in *)addr->addr;

                    // Is this address assigned to the interface required?
                    foreach (QNetworkAddressEntry ifaceAddr, iface.addressEntries())
                    {
                        // Already have an interface
                        if (m_pcap_out) { break; }

                        if (ifaceAddr.ip().protocol() == QAbstractSocket::IPv4Protocol)
                        {
                            // Selected interface contains the IP of the required interface
                            #ifdef Q_OS_UNIX
                                QHostAddress requiredIP(qFromBigEndian<quint32>(ipv4->sin_addr.s_addr));
                            #else
                                QHostAddress requiredIP(qFromBigEndian<quint32>(ipv4->sin_addr.S_un.S_addr));
                            #endif
                            if (requiredIP == ifaceAddr.ip())
                            {
                               qDebug() << "PCap Playback: Output" << dev->name << requiredIP.toString();

                               // Yes this interface!
                               m_pcap_out = pcap_open_live(dev->name, 0, 1, 0, errbuf);
                               if (!m_pcap_out)
                               {
                                   emit error(tr("%1\n%2").arg(errbuf).arg(iface.humanReadableName()));
                                   return;
                               }
                            }
                        }
                    }
                }
            }
        }

        // Clean up
        pcap_freealldevs(alldevs);

        // Did we get an interface?
        if (!m_pcap_out) {
            error(tr("Unable to open required interface\n%1").arg(iface.humanReadableName()));
            return;
        }
    }

    while (!m_shutdown)
    {
        if (m_running && m_pcap_out && m_pcap_in)
        {
            QMutexLocker mutexIn(&m_pcap_in_Mutex);
            QMutexLocker mutexOut(&m_pcap_out_Mutex);

            /* Get next packet and send at correct interval */
            struct pcap_pkthdr *pkt_header;
            const u_char *pkt_data;
            if (pcap_next_ex(m_pcap_in, &pkt_header, &pkt_data) == 1)
            {
                // Create QT datagram to send to self
                QNetworkDatagram pkt_datagram = createDatagram(m_pcap_in, pkt_header, pkt_data);

                // Wait until time
                if (!m_pktLastTime.isNull())
                {
                    QTime pkt_time(0,0,0);
                    pkt_time = pkt_time.addSecs(pkt_header->ts.tv_sec);
                    pkt_time = pkt_time.addMSecs((pkt_header->ts.tv_usec / 1000));
                    QThread::msleep(m_pktLastTime.msecsTo(pkt_time));
                }

                if (!m_running) { continue; }
                /*
                 * Send to wire
                 *
                 * We use libpcap to retain sender IP and MAC when sending on the wire
                 * MULITICAST_LOOP is not enabled, so this is not recived by me.
                 * we need a seperate action to display this locally
                */
                if (pcap_sendpacket(m_pcap_out, pkt_data, pkt_header->caplen) == 0) {
                    emit packetSent();
                } else {
                    error(QString("%1").arg(pcap_geterr(m_pcap_out)));
                    m_running = false;
                    emit sendingFinished();
                    return;
                }
                /* Send to me
                 *
                 * Send to any local listener, but set the always pass flag
                 *
                 */
                {
                    const QHash<int, QWeakPointer<sACNListener> > listenerList = sACNManager::getInstance()->getListenerList();
                    QSharedPointer<sACNListener> listener = listenerList.begin().value().toStrongRef();
                    if (listener)
                        listener->processDatagram(
                            pkt_datagram.data(),
                            pkt_datagram.destinationAddress(),
                            pkt_datagram.senderAddress(),
                            true);
                }

                // Save time
                m_pktLastTime = QTime(0,0,0);
                m_pktLastTime = m_pktLastTime.addSecs(pkt_header->ts.tv_sec);
                m_pktLastTime = m_pktLastTime.addMSecs((pkt_header->ts.tv_usec / 1000));
            } else
            {
                // Done!
                m_running = false;
                emit sendingFinished();
            }
        } else {
            // Noop
            QThread::msleep(100);
        }
    }
}

void pcapplaybacksender::quit()
{
    m_running = false;
    m_shutdown = true;
}

bool pcapplaybacksender::openFile()
{
    // Ensure already closed
    closeFile();

    /* Open the capture file */
    QMutexLocker mutexIn(&m_pcap_in_Mutex);
    char errbuf[PCAP_ERRBUF_SIZE];
    m_pcap_in = pcap_open_offline(m_filename.toUtf8(), errbuf);
    if (!m_pcap_in) {
        emit error(tr("Error opening %1\n%2").arg(QDir::toNativeSeparators(m_filename)).arg(errbuf));
        return false;
    }

    qDebug() << "PCap Playback: Input" << m_filename;

    /* Filter to only include sACN packets */
    struct bpf_program fcode;
    const char packet_filter[] = sacn_packet_filter;
    if (pcap_compile(m_pcap_in, &fcode, packet_filter, 1, 0xffffff) != 0)
    {
        closeFile();
        emit error(tr("Error opening %1\npcap_compile failed").arg(QDir::toNativeSeparators(m_filename)));
        return false;
    }
    if (pcap_setfilter(m_pcap_in, &fcode)<0)
    {
        closeFile();
        emit error(tr("Error opening %1\npcap_setfilter failed").arg(QDir::toNativeSeparators(m_filename)));
        return false;
    }

    return true;
}

void pcapplaybacksender::closeFile()
{
    m_running = false;
    QMutexLocker mutexIn(&m_pcap_in_Mutex);
    m_pktLastTime = QTime();
    if (m_pcap_in) {
        pcap_close(m_pcap_in);
        m_pcap_in = Q_NULLPTR;
    }

    emit sendingClosed();
}

bool pcapplaybacksender::isRunning()
{
    return m_running;
}

void pcapplaybacksender::play()
{
    m_running = true;
}

void pcapplaybacksender::pause()
{
    m_running = false;
}

void pcapplaybacksender::reset()
{
    closeFile();
    openFile();
}

QNetworkDatagram pcapplaybacksender::createDatagram(pcap_t *hpcap, pcap_pkthdr_t *pkt_header, const unsigned char *pkt_data)
{
    /*
     * Disect packet and create QNetworkDatagram
     * Hardware addresses are lost
    */

    int linkType = pcap_datalink(hpcap);
    switch (linkType)
    {
        case DLT_EN10MB: // Ethernet
        {
            // Layer 2
            const struct sniff_ethernet *ethernet;
            if (pkt_header->caplen < sizeof(ethernet))
            {
                qDebug() << "PCapPlayback: Missing complete layer 2";
                return QNetworkDatagram();;
            }
            ethernet = (struct sniff_ethernet*)(pkt_data);
            if (qFromBigEndian(ethernet->ether_type) != 0x0800)
            {
                qDebug() << "PCapPlayback: Layer 2 ethertype not IPv4";
                return QNetworkDatagram();;
            }; // IPv4, no vlan

            // Layer 3
            const struct sniff_ip *ip;
            if (pkt_header->caplen < (sizeof(ethernet) + sizeof(ip)))
            {
                qDebug() << "PCapPlayback: Missing complete layer 3";
                return QNetworkDatagram();;
            }
            ip = (struct sniff_ip*)(ethernet + 1);

            // Layer 4
            const struct sniff_udp *udp;
            if (pkt_header->caplen < (sizeof(ethernet) + sizeof(ip) + sizeof(udp)))
            {
                qDebug() << "PCapPlayback: Missing layer 4";
                return QNetworkDatagram();;
            }
            udp = (struct sniff_udp*)(ip + 1);

            // Payload
            const char *payload;
            unsigned int payload_len = 0;
            payload = (const char *)(udp + 1);
            payload_len = qFromBigEndian(udp->uh_ulen) - sizeof(udp);
            if (pkt_header->caplen < (sizeof(ethernet) + sizeof(ip) + sizeof(udp) + payload_len))
            {
                qDebug() << "PCapPlayback: Missing Payload";
                return QNetworkDatagram();;
            }

            // Create Datagram
            /*
             * Remember: network byte order = big endian
            */
            QNetworkDatagram ret;
            #ifdef Q_OS_UNIX
                const QHostAddress senderHost = QHostAddress(qFromBigEndian<quint32>(ip->ip_src.s_addr));
            #else
                const QHostAddress senderHost = QHostAddress(qFromBigEndian<quint32>(ip->ip_src.S_un.S_addr));
            #endif
            quint16 senderPort = qFromBigEndian<quint16>(udp->uh_sport);
            ret.setSender(senderHost, senderPort);

            #ifdef Q_OS_UNIX
                const QHostAddress destHost = QHostAddress(qFromBigEndian<quint32>(ip->ip_dst.s_addr));
            #else
                const QHostAddress destHost = QHostAddress(qFromBigEndian<quint32>(ip->ip_dst.S_un.S_addr));
            #endif

            quint16 destPort = qFromBigEndian<quint16>(udp->uh_dport);
            ret.setDestination(destHost, destPort);

            ret.setData(QByteArray(payload, payload_len));

            return ret;
        }

        default:
            // Other, can not handle
            return QNetworkDatagram();
    }
}
<commit_msg>[MacOS] Missing include<commit_after>#include "pcapplaybacksender.h"
#ifdef Q_OS_LINUX
#include <linux/socket.h>
#include <linux/in.h>
#endif
#ifdef Q_OS_UNIX
#include <sys/socket.h>
#endif
#ifdef Q_OS_MACOS
#include <netinet/in.h>
#endif
#include <pcap.h>
#include <QDebug>
#include <QtEndian>
#include "preferences.h"
#include "sacn/streamingacn.h"
#include "sacn/sacnlistener.h"
#include "ethernetstrut.h"

pcapplaybacksender::pcapplaybacksender(QString FileName) :
    m_filename(FileName),
    m_pcap_in(Q_NULLPTR),
    m_pcap_out(Q_NULLPTR),
    m_running(false),
    m_shutdown(false)
{
    if (!openFile()) {
        closeFile();
    }
}

pcapplaybacksender::~pcapplaybacksender()
{
    m_running = false;

    closeFile();

    QMutexLocker mutexOut(&m_pcap_out_Mutex);
    if (m_pcap_out) {
        pcap_close(m_pcap_out);
        m_pcap_out = Q_NULLPTR;
    }
}

void pcapplaybacksender::run()
{
    /* Open output adapter */
    {
        QMutexLocker mutexOut(&m_pcap_out_Mutex);

        char errbuf[PCAP_ERRBUF_SIZE];

        // Get required interface
        QNetworkInterface iface = Preferences::getInstance()->networkInterface();

        // Find all usable interfaces
        pcap_if_t *alldevs;
        if (pcap_findalldevs(&alldevs, errbuf) == -1)
        {
            emit error(tr("%1").arg(errbuf));
            return;
        }

        // See which avaliable interface matches required interface
        for(pcap_if_t *dev = alldevs; dev != NULL; dev = dev->next)
        {
            // Already have an interface
            if (m_pcap_out) { break; }

            for (pcap_addr *addr = dev->addresses; addr != NULL; addr = addr->next)
            {
                // Already have an interface
                if (m_pcap_out) { break; }

                if (addr->addr->sa_family == AF_INET) {
                    // IPv4
                    struct sockaddr_in *ipv4 = (struct sockaddr_in *)addr->addr;

                    // Is this address assigned to the interface required?
                    foreach (QNetworkAddressEntry ifaceAddr, iface.addressEntries())
                    {
                        // Already have an interface
                        if (m_pcap_out) { break; }

                        if (ifaceAddr.ip().protocol() == QAbstractSocket::IPv4Protocol)
                        {
                            // Selected interface contains the IP of the required interface
                            #ifdef Q_OS_UNIX
                                QHostAddress requiredIP(qFromBigEndian<quint32>(ipv4->sin_addr.s_addr));
                            #else
                                QHostAddress requiredIP(qFromBigEndian<quint32>(ipv4->sin_addr.S_un.S_addr));
                            #endif
                            if (requiredIP == ifaceAddr.ip())
                            {
                               qDebug() << "PCap Playback: Output" << dev->name << requiredIP.toString();

                               // Yes this interface!
                               m_pcap_out = pcap_open_live(dev->name, 0, 1, 0, errbuf);
                               if (!m_pcap_out)
                               {
                                   emit error(tr("%1\n%2").arg(errbuf).arg(iface.humanReadableName()));
                                   return;
                               }
                            }
                        }
                    }
                }
            }
        }

        // Clean up
        pcap_freealldevs(alldevs);

        // Did we get an interface?
        if (!m_pcap_out) {
            error(tr("Unable to open required interface\n%1").arg(iface.humanReadableName()));
            return;
        }
    }

    while (!m_shutdown)
    {
        if (m_running && m_pcap_out && m_pcap_in)
        {
            QMutexLocker mutexIn(&m_pcap_in_Mutex);
            QMutexLocker mutexOut(&m_pcap_out_Mutex);

            /* Get next packet and send at correct interval */
            struct pcap_pkthdr *pkt_header;
            const u_char *pkt_data;
            if (pcap_next_ex(m_pcap_in, &pkt_header, &pkt_data) == 1)
            {
                // Create QT datagram to send to self
                QNetworkDatagram pkt_datagram = createDatagram(m_pcap_in, pkt_header, pkt_data);

                // Wait until time
                if (!m_pktLastTime.isNull())
                {
                    QTime pkt_time(0,0,0);
                    pkt_time = pkt_time.addSecs(pkt_header->ts.tv_sec);
                    pkt_time = pkt_time.addMSecs((pkt_header->ts.tv_usec / 1000));
                    QThread::msleep(m_pktLastTime.msecsTo(pkt_time));
                }

                if (!m_running) { continue; }
                /*
                 * Send to wire
                 *
                 * We use libpcap to retain sender IP and MAC when sending on the wire
                 * MULITICAST_LOOP is not enabled, so this is not recived by me.
                 * we need a seperate action to display this locally
                */
                if (pcap_sendpacket(m_pcap_out, pkt_data, pkt_header->caplen) == 0) {
                    emit packetSent();
                } else {
                    error(QString("%1").arg(pcap_geterr(m_pcap_out)));
                    m_running = false;
                    emit sendingFinished();
                    return;
                }
                /* Send to me
                 *
                 * Send to any local listener, but set the always pass flag
                 *
                 */
                {
                    const QHash<int, QWeakPointer<sACNListener> > listenerList = sACNManager::getInstance()->getListenerList();
                    QSharedPointer<sACNListener> listener = listenerList.begin().value().toStrongRef();
                    if (listener)
                        listener->processDatagram(
                            pkt_datagram.data(),
                            pkt_datagram.destinationAddress(),
                            pkt_datagram.senderAddress(),
                            true);
                }

                // Save time
                m_pktLastTime = QTime(0,0,0);
                m_pktLastTime = m_pktLastTime.addSecs(pkt_header->ts.tv_sec);
                m_pktLastTime = m_pktLastTime.addMSecs((pkt_header->ts.tv_usec / 1000));
            } else
            {
                // Done!
                m_running = false;
                emit sendingFinished();
            }
        } else {
            // Noop
            QThread::msleep(100);
        }
    }
}

void pcapplaybacksender::quit()
{
    m_running = false;
    m_shutdown = true;
}

bool pcapplaybacksender::openFile()
{
    // Ensure already closed
    closeFile();

    /* Open the capture file */
    QMutexLocker mutexIn(&m_pcap_in_Mutex);
    char errbuf[PCAP_ERRBUF_SIZE];
    m_pcap_in = pcap_open_offline(m_filename.toUtf8(), errbuf);
    if (!m_pcap_in) {
        emit error(tr("Error opening %1\n%2").arg(QDir::toNativeSeparators(m_filename)).arg(errbuf));
        return false;
    }

    qDebug() << "PCap Playback: Input" << m_filename;

    /* Filter to only include sACN packets */
    struct bpf_program fcode;
    const char packet_filter[] = sacn_packet_filter;
    if (pcap_compile(m_pcap_in, &fcode, packet_filter, 1, 0xffffff) != 0)
    {
        closeFile();
        emit error(tr("Error opening %1\npcap_compile failed").arg(QDir::toNativeSeparators(m_filename)));
        return false;
    }
    if (pcap_setfilter(m_pcap_in, &fcode)<0)
    {
        closeFile();
        emit error(tr("Error opening %1\npcap_setfilter failed").arg(QDir::toNativeSeparators(m_filename)));
        return false;
    }

    return true;
}

void pcapplaybacksender::closeFile()
{
    m_running = false;
    QMutexLocker mutexIn(&m_pcap_in_Mutex);
    m_pktLastTime = QTime();
    if (m_pcap_in) {
        pcap_close(m_pcap_in);
        m_pcap_in = Q_NULLPTR;
    }

    emit sendingClosed();
}

bool pcapplaybacksender::isRunning()
{
    return m_running;
}

void pcapplaybacksender::play()
{
    m_running = true;
}

void pcapplaybacksender::pause()
{
    m_running = false;
}

void pcapplaybacksender::reset()
{
    closeFile();
    openFile();
}

QNetworkDatagram pcapplaybacksender::createDatagram(pcap_t *hpcap, pcap_pkthdr_t *pkt_header, const unsigned char *pkt_data)
{
    /*
     * Disect packet and create QNetworkDatagram
     * Hardware addresses are lost
    */

    int linkType = pcap_datalink(hpcap);
    switch (linkType)
    {
        case DLT_EN10MB: // Ethernet
        {
            // Layer 2
            const struct sniff_ethernet *ethernet;
            if (pkt_header->caplen < sizeof(ethernet))
            {
                qDebug() << "PCapPlayback: Missing complete layer 2";
                return QNetworkDatagram();;
            }
            ethernet = (struct sniff_ethernet*)(pkt_data);
            if (qFromBigEndian(ethernet->ether_type) != 0x0800)
            {
                qDebug() << "PCapPlayback: Layer 2 ethertype not IPv4";
                return QNetworkDatagram();;
            }; // IPv4, no vlan

            // Layer 3
            const struct sniff_ip *ip;
            if (pkt_header->caplen < (sizeof(ethernet) + sizeof(ip)))
            {
                qDebug() << "PCapPlayback: Missing complete layer 3";
                return QNetworkDatagram();;
            }
            ip = (struct sniff_ip*)(ethernet + 1);

            // Layer 4
            const struct sniff_udp *udp;
            if (pkt_header->caplen < (sizeof(ethernet) + sizeof(ip) + sizeof(udp)))
            {
                qDebug() << "PCapPlayback: Missing layer 4";
                return QNetworkDatagram();;
            }
            udp = (struct sniff_udp*)(ip + 1);

            // Payload
            const char *payload;
            unsigned int payload_len = 0;
            payload = (const char *)(udp + 1);
            payload_len = qFromBigEndian(udp->uh_ulen) - sizeof(udp);
            if (pkt_header->caplen < (sizeof(ethernet) + sizeof(ip) + sizeof(udp) + payload_len))
            {
                qDebug() << "PCapPlayback: Missing Payload";
                return QNetworkDatagram();;
            }

            // Create Datagram
            /*
             * Remember: network byte order = big endian
            */
            QNetworkDatagram ret;
            #ifdef Q_OS_UNIX
                const QHostAddress senderHost = QHostAddress(qFromBigEndian<quint32>(ip->ip_src.s_addr));
            #else
                const QHostAddress senderHost = QHostAddress(qFromBigEndian<quint32>(ip->ip_src.S_un.S_addr));
            #endif
            quint16 senderPort = qFromBigEndian<quint16>(udp->uh_sport);
            ret.setSender(senderHost, senderPort);

            #ifdef Q_OS_UNIX
                const QHostAddress destHost = QHostAddress(qFromBigEndian<quint32>(ip->ip_dst.s_addr));
            #else
                const QHostAddress destHost = QHostAddress(qFromBigEndian<quint32>(ip->ip_dst.S_un.S_addr));
            #endif

            quint16 destPort = qFromBigEndian<quint16>(udp->uh_dport);
            ret.setDestination(destHost, destPort);

            ret.setData(QByteArray(payload, payload_len));

            return ret;
        }

        default:
            // Other, can not handle
            return QNetworkDatagram();
    }
}
<|endoftext|>


<commit_before>#include <plasp/utils/Logger.h>

#include <plasp/utils/Formatting.h>
#include <plasp/utils/ParserWarning.h>

namespace plasp
{
namespace utils
{

////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Logger
//
////////////////////////////////////////////////////////////////////////////////////////////////////

Logger::Logger()
:	m_warningLevel{Logger::WarningLevel::Normal}
{
}

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

Logger::Logger(const Logger &other)
:	m_warningLevel{other.m_warningLevel}
{
}

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

Logger &Logger::operator=(const Logger &other)
{
	m_warningLevel = other.m_warningLevel;

	return *this;
}

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

Logger::Logger(Logger &&other)
:	m_warningLevel{other.m_warningLevel}
{
	other.m_warningLevel = WarningLevel::Normal;
}

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

Logger &Logger::operator=(Logger &&other)
{
	m_warningLevel = other.m_warningLevel;
	other.m_warningLevel = WarningLevel::Normal;

	return *this;
}

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

void Logger::setWarningLevel(WarningLevel warningLevel)
{
	m_warningLevel = warningLevel;
}

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

void Logger::exception(const std::string &errorType, const std::string &message)
{
	if (isatty(STDERR_FILENO))
	{
		std::cerr
			<< Format(Color::Red, FontWeight::Bold) << "error:"
			<< ResetFormat() << " "
			<< Format(Color::White, FontWeight::Bold) << message
			<< ResetFormat() << std::endl;
	}
	else
	{
		std::cerr
			<< "error:"
			<< " "
			<< message
			<< std::endl;
	}
}

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

void Logger::parserException(const Parser::Coordinate &coordinate, const std::string &message)
{
	if (isatty(STDERR_FILENO))
	{
		std::cerr
			<< Format(Color::White, FontWeight::Bold) << coordinate.sectionName << ":"
			<< std::to_string(coordinate.row) + ":" + std::to_string(coordinate.column) << ":"
			<< ResetFormat() << " "
			<< Format(Color::Red, FontWeight::Bold) << "error:"
			<< ResetFormat() << " "
			<< Format(Color::White, FontWeight::Bold) << message
			<< ResetFormat() << std::endl;
	}
	else
	{
		std::cerr
			<< coordinate.sectionName << ":"
			<< std::to_string(coordinate.row) + ":" + std::to_string(coordinate.column) << ":"
			<< " "
			<< "error:"
			<< " "
			<< message
			<< std::endl;
	}
}

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

void Logger::parserWarning(const Parser &parser, const std::string &message)
{
	if (m_warningLevel == WarningLevel::Ignore)
		return;

	if (m_warningLevel == WarningLevel::Error)
		throw ParserWarning(parser, message);

	const auto coordinate = parser.coordinate();

	if (isatty(STDERR_FILENO))
	{
		std::cerr
			<< Format(Color::White, FontWeight::Bold) << coordinate.sectionName << ":"
			<< std::to_string(coordinate.row) + ":" + std::to_string(coordinate.column) << ":"
			<< ResetFormat() << " "
			<< Format(Color::Magenta, FontWeight::Bold) << "warning:"
			<< ResetFormat() << " "
			<< Format(Color::White, FontWeight::Bold) << message
			<< ResetFormat() << std::endl;
	}
	else
	{
		std::cerr
			<< coordinate.sectionName << ":"
			<< std::to_string(coordinate.row) + ":" + std::to_string(coordinate.column) << ":"
			<< " "
			<< "warning:"
			<< " "
			<< message
			<< std::endl;
	}
}

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

}
}
<commit_msg>Fixed missing error message prefix.<commit_after>#include <plasp/utils/Logger.h>

#include <plasp/utils/Formatting.h>
#include <plasp/utils/ParserWarning.h>

namespace plasp
{
namespace utils
{

////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Logger
//
////////////////////////////////////////////////////////////////////////////////////////////////////

Logger::Logger()
:	m_warningLevel{Logger::WarningLevel::Normal}
{
}

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

Logger::Logger(const Logger &other)
:	m_warningLevel{other.m_warningLevel}
{
}

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

Logger &Logger::operator=(const Logger &other)
{
	m_warningLevel = other.m_warningLevel;

	return *this;
}

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

Logger::Logger(Logger &&other)
:	m_warningLevel{other.m_warningLevel}
{
	other.m_warningLevel = WarningLevel::Normal;
}

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

Logger &Logger::operator=(Logger &&other)
{
	m_warningLevel = other.m_warningLevel;
	other.m_warningLevel = WarningLevel::Normal;

	return *this;
}

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

void Logger::setWarningLevel(WarningLevel warningLevel)
{
	m_warningLevel = warningLevel;
}

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

void Logger::exception(const std::string &errorType, const std::string &message)
{
	if (isatty(STDERR_FILENO))
	{
		std::cerr
			<< Format(Color::Red, FontWeight::Bold) << errorType << ":"
			<< ResetFormat() << " "
			<< Format(Color::White, FontWeight::Bold) << message
			<< ResetFormat() << std::endl;
	}
	else
	{
		std::cerr
			<< "error:"
			<< " "
			<< message
			<< std::endl;
	}
}

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

void Logger::parserException(const Parser::Coordinate &coordinate, const std::string &message)
{
	if (isatty(STDERR_FILENO))
	{
		std::cerr
			<< Format(Color::White, FontWeight::Bold) << coordinate.sectionName << ":"
			<< std::to_string(coordinate.row) + ":" + std::to_string(coordinate.column) << ":"
			<< ResetFormat() << " "
			<< Format(Color::Red, FontWeight::Bold) << "error:"
			<< ResetFormat() << " "
			<< Format(Color::White, FontWeight::Bold) << message
			<< ResetFormat() << std::endl;
	}
	else
	{
		std::cerr
			<< coordinate.sectionName << ":"
			<< std::to_string(coordinate.row) + ":" + std::to_string(coordinate.column) << ":"
			<< " "
			<< "error:"
			<< " "
			<< message
			<< std::endl;
	}
}

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

void Logger::parserWarning(const Parser &parser, const std::string &message)
{
	if (m_warningLevel == WarningLevel::Ignore)
		return;

	if (m_warningLevel == WarningLevel::Error)
		throw ParserWarning(parser, message);

	const auto coordinate = parser.coordinate();

	if (isatty(STDERR_FILENO))
	{
		std::cerr
			<< Format(Color::White, FontWeight::Bold) << coordinate.sectionName << ":"
			<< std::to_string(coordinate.row) + ":" + std::to_string(coordinate.column) << ":"
			<< ResetFormat() << " "
			<< Format(Color::Magenta, FontWeight::Bold) << "warning:"
			<< ResetFormat() << " "
			<< Format(Color::White, FontWeight::Bold) << message
			<< ResetFormat() << std::endl;
	}
	else
	{
		std::cerr
			<< coordinate.sectionName << ":"
			<< std::to_string(coordinate.row) + ":" + std::to_string(coordinate.column) << ":"
			<< " "
			<< "warning:"
			<< " "
			<< message
			<< std::endl;
	}
}

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

}
}
<|endoftext|>


<commit_before>// Copyright(c) 2016 Jounayd Id Salah
// Distributed under the MIT License (See accompanying file LICENSE.md file or copy at http://opensource.org/licenses/MIT).
#include "prebuild/pch.h"
#include "prebuild/coAppImpl.h"
#include "prebuild/generator/coProjectGenerator.h"
#include "prebuild/generator/plugins/coCppTypesGeneratorPlugin.h"
#include "prebuild/generator/plugins/coMainEntryPointGeneratorPlugin.h"
#include "lang/result/coResult_f.h"
#include "io/path/coPathStatus.h"
#include "io/path/coPath_f.h"
#include "app/coCommandLineArgs.h"
#include "app/coProject_f.h"
#include "parser/project/coParsedProject.h"

coAppImpl::coAppImpl()
{

}

coAppImpl::~coAppImpl()
{
}

coResult coAppImpl::ParseArgs(const InitConfig& _config)
{
	coCommandLineArgs argParser;

	{
		coCommandLineArgs::InitConfig c;
		c.commandName = coPROJECT_NAME_WITH_VERSION_STRING;
		coTRY(argParser.Init(c), nullptr);
	}

	{
		coCommandLineArgs::ArgConfig c;
		c.name = "srcReferenceDir";
		coTRY(argParser.Add(c), nullptr);
	}

	{
		coCommandLineArgs::ArgConfig c;
		c.name = "outReferenceDir";
		coTRY(argParser.Add(c), nullptr);
	}

	{
		coCommandLineArgs::ArgConfig c;
		c.name = "projectRelativePath";
		coTRY(argParser.Add(c), nullptr);
	}

	{
		coCommandLineArgs::ArgConfig c;
		c.name = "pchRelativePath";
		//c.optional = true;
		coTRY(argParser.Add(c), nullptr);
	}

	coTRY(argParser.Parse(_config.argv, _config.nbArgs), nullptr);

	// Src reference dir
	{
		srcReferenceDir = argParser.GetArgValue("srcReferenceDir");
		coNormalizePath(srcReferenceDir);
		coTRY(srcReferenceDir.count, "Src reference dir is null");
		coTRY(coIsDirectory(srcReferenceDir), "Path is not a directory: " << srcReferenceDir);
	}

	// Out reference dir
	{
		outReferenceDir = argParser.GetArgValue("outReferenceDir");
		coNormalizePath(outReferenceDir);
		coTRY(outReferenceDir.count, "The out reference dir is null");
	}

	// Project path
	{
		projectRelativePath = argParser.GetArgValue("projectRelativePath");
		coNormalizePath(projectRelativePath);
		coTRY(projectRelativePath.count, "The project path is null");
	}

	// Pch path
	{
		pchRelativePath = argParser.GetArgValue("pchRelativePath");
		if (pchRelativePath != "")
		{
			coNormalizePath(pchRelativePath);
		}
	}

	return true;
}

coResult coAppImpl::OnInit(const coObject::InitConfig& _config)
{
	coTRY(Super::OnInit(_config), nullptr);
	const InitConfig& config = static_cast<const InitConfig&>(_config);

	coTRY(ParseArgs(config), "Failed to parse args");

	{
		coProjectParser::InitConfig c;
		coTRY(projectParser.Init(c), nullptr);
	}

	return true;
}

coResult coAppImpl::OnStart()
{
	coParsedProject parsedProject;
	coINFO("Parsing project...");
	coTRY(ParseProject(parsedProject), "Failed to parse the project: "<<projectRelativePath);
	coINFO("Parsing project done.");
	coINFO("Generating source files...");
	coTRY(GenerateProject(parsedProject), "Failed to generate the project: " << projectRelativePath);
	coINFO("Generating source files done.");

	return true;
}

coResult coAppImpl::ParseProject(coParsedProject& _parsedProject)
{
	coProjectParser::ParseConfig parseConfig;
	parseConfig.srcReferenceDir = srcReferenceDir;
	parseConfig.outReferenceDir = outReferenceDir;
	parseConfig.projectRelativePath = projectRelativePath;
	parseConfig.precompiledHeaderPath = pchRelativePath;
	coTRY(projectParser.Parse(_parsedProject, parseConfig), "Failed to parse the project: " << projectRelativePath);

	return true;
}

coResult coAppImpl::GenerateProject(const coParsedProject& _parsedProject)
{
	coCppTypesGeneratorPlugin cppTypesPlugin;
	{
		coCppTypesGeneratorPlugin::InitConfig c;
		coTRY(cppTypesPlugin.Init(c), "Failed to init the plugin: " << cppTypesPlugin);
	}

	coMainEntryPointGeneratorPlugin mainEntryPointPlugin;
	{
		coMainEntryPointGeneratorPlugin::InitConfig c;
		coTRY(mainEntryPointPlugin.Init(c), "Failed to init the plugin: " << mainEntryPointPlugin);
	}

	coProjectGenerator projectGenerator;
	{
		coProjectGenerator::InitConfig c;
		c.outReferenceDir = outReferenceDir;
		c.projectRelativePath = projectRelativePath;
		c.srcReferenceDir = srcReferenceDir;
		c.precompiledHeaderRelativePath = pchRelativePath;
		/*c.projectDir = projectDir;
		c.outDir = outputDir;
		c.precompiledHeaderPath = co_pchPath;*/
		coHACK("Direct assignation seems to fail in release for some reason.");
		// Seems to be a bug with VS2015 : https://social.msdn.microsoft.com/Forums/expression/en-US/9c58a750-b424-4d65-bf99-b7a29d0e3965/initializer-list-bug-in-vc-2015-the-following-program-crashes-in-64bit-release-optimized?forum=vcgeneral
		//c.plugins = {&cppTypesPlugin, &mainEntryPointPlugin};
		coDynamicArray<coProjectGeneratorPlugin*> a;
		coPushBack(a, &cppTypesPlugin);
		coPushBack(a, &mainEntryPointPlugin);
		c.plugins = a;
		coTRY(projectGenerator.Init(c), "Failed to init the project generator.");
	}

	coTRY(projectGenerator.Generate(_parsedProject), nullptr);
	return true;
}
<commit_msg>Removed some space.<commit_after>// Copyright(c) 2016 Jounayd Id Salah
// Distributed under the MIT License (See accompanying file LICENSE.md file or copy at http://opensource.org/licenses/MIT).
#include "prebuild/pch.h"
#include "prebuild/coAppImpl.h"
#include "prebuild/generator/coProjectGenerator.h"
#include "prebuild/generator/plugins/coCppTypesGeneratorPlugin.h"
#include "prebuild/generator/plugins/coMainEntryPointGeneratorPlugin.h"
#include "lang/result/coResult_f.h"
#include "io/path/coPathStatus.h"
#include "io/path/coPath_f.h"
#include "app/coCommandLineArgs.h"
#include "app/coProject_f.h"
#include "parser/project/coParsedProject.h"

coAppImpl::coAppImpl()
{
}

coAppImpl::~coAppImpl()
{
}

coResult coAppImpl::ParseArgs(const InitConfig& _config)
{
	coCommandLineArgs argParser;

	{
		coCommandLineArgs::InitConfig c;
		c.commandName = coPROJECT_NAME_WITH_VERSION_STRING;
		coTRY(argParser.Init(c), nullptr);
	}

	{
		coCommandLineArgs::ArgConfig c;
		c.name = "srcReferenceDir";
		coTRY(argParser.Add(c), nullptr);
	}

	{
		coCommandLineArgs::ArgConfig c;
		c.name = "outReferenceDir";
		coTRY(argParser.Add(c), nullptr);
	}

	{
		coCommandLineArgs::ArgConfig c;
		c.name = "projectRelativePath";
		coTRY(argParser.Add(c), nullptr);
	}

	{
		coCommandLineArgs::ArgConfig c;
		c.name = "pchRelativePath";
		//c.optional = true;
		coTRY(argParser.Add(c), nullptr);
	}

	coTRY(argParser.Parse(_config.argv, _config.nbArgs), nullptr);

	// Src reference dir
	{
		srcReferenceDir = argParser.GetArgValue("srcReferenceDir");
		coNormalizePath(srcReferenceDir);
		coTRY(srcReferenceDir.count, "Src reference dir is null");
		coTRY(coIsDirectory(srcReferenceDir), "Path is not a directory: " << srcReferenceDir);
	}

	// Out reference dir
	{
		outReferenceDir = argParser.GetArgValue("outReferenceDir");
		coNormalizePath(outReferenceDir);
		coTRY(outReferenceDir.count, "The out reference dir is null");
	}

	// Project path
	{
		projectRelativePath = argParser.GetArgValue("projectRelativePath");
		coNormalizePath(projectRelativePath);
		coTRY(projectRelativePath.count, "The project path is null");
	}

	// Pch path
	{
		pchRelativePath = argParser.GetArgValue("pchRelativePath");
		if (pchRelativePath != "")
		{
			coNormalizePath(pchRelativePath);
		}
	}

	return true;
}

coResult coAppImpl::OnInit(const coObject::InitConfig& _config)
{
	coTRY(Super::OnInit(_config), nullptr);
	const InitConfig& config = static_cast<const InitConfig&>(_config);

	coTRY(ParseArgs(config), "Failed to parse args");

	{
		coProjectParser::InitConfig c;
		coTRY(projectParser.Init(c), nullptr);
	}

	return true;
}

coResult coAppImpl::OnStart()
{
	coParsedProject parsedProject;
	coINFO("Parsing project...");
	coTRY(ParseProject(parsedProject), "Failed to parse the project: "<<projectRelativePath);
	coINFO("Parsing project done.");
	coINFO("Generating source files...");
	coTRY(GenerateProject(parsedProject), "Failed to generate the project: " << projectRelativePath);
	coINFO("Generating source files done.");

	return true;
}

coResult coAppImpl::ParseProject(coParsedProject& _parsedProject)
{
	coProjectParser::ParseConfig parseConfig;
	parseConfig.srcReferenceDir = srcReferenceDir;
	parseConfig.outReferenceDir = outReferenceDir;
	parseConfig.projectRelativePath = projectRelativePath;
	parseConfig.precompiledHeaderPath = pchRelativePath;
	coTRY(projectParser.Parse(_parsedProject, parseConfig), "Failed to parse the project: " << projectRelativePath);

	return true;
}

coResult coAppImpl::GenerateProject(const coParsedProject& _parsedProject)
{
	coCppTypesGeneratorPlugin cppTypesPlugin;
	{
		coCppTypesGeneratorPlugin::InitConfig c;
		coTRY(cppTypesPlugin.Init(c), "Failed to init the plugin: " << cppTypesPlugin);
	}

	coMainEntryPointGeneratorPlugin mainEntryPointPlugin;
	{
		coMainEntryPointGeneratorPlugin::InitConfig c;
		coTRY(mainEntryPointPlugin.Init(c), "Failed to init the plugin: " << mainEntryPointPlugin);
	}

	coProjectGenerator projectGenerator;
	{
		coProjectGenerator::InitConfig c;
		c.outReferenceDir = outReferenceDir;
		c.projectRelativePath = projectRelativePath;
		c.srcReferenceDir = srcReferenceDir;
		c.precompiledHeaderRelativePath = pchRelativePath;
		/*c.projectDir = projectDir;
		c.outDir = outputDir;
		c.precompiledHeaderPath = co_pchPath;*/
		coHACK("Direct assignation seems to fail in release for some reason.");
		// Seems to be a bug with VS2015 : https://social.msdn.microsoft.com/Forums/expression/en-US/9c58a750-b424-4d65-bf99-b7a29d0e3965/initializer-list-bug-in-vc-2015-the-following-program-crashes-in-64bit-release-optimized?forum=vcgeneral
		//c.plugins = {&cppTypesPlugin, &mainEntryPointPlugin};
		coDynamicArray<coProjectGeneratorPlugin*> a;
		coPushBack(a, &cppTypesPlugin);
		coPushBack(a, &mainEntryPointPlugin);
		c.plugins = a;
		coTRY(projectGenerator.Init(c), "Failed to init the project generator.");
	}

	coTRY(projectGenerator.Generate(_parsedProject), nullptr);
	return true;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012
 * Alessio Sclocco <a.sclocco@vu.nl>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
#include <limits>
#include <CImg.h>
using std::cout;
using std::cerr;
using std::endl;
using std::ios;
using std::ifstream;
using std::ofstream;
using std::vector;
using std::fixed;
using std::setprecision;
using std::string;
using std::numeric_limits;
using cimg_library::CImg;

#include <ArgumentList.hpp>
#include <GPUData.hpp>
#include <Exceptions.hpp>
#include <ReadData.hpp>
#include <Observation.hpp>
using isa::utils::ArgumentList;
using isa::OpenCL::GPUData;
using AstroData::readLOFAR;
using AstroData::Observation;

int main(int argc, char *argv[]) {
	string headerFilename;
	string rawFilename;
	unsigned int paddedSecond = 0;
	unsigned int nrOutputSeconds = 0;
	unsigned int channelMagnifyingFactor = 0;
	unsigned int timeIntegrationFactor = 0;

	// Parse command line
	if ( argc != 11 ) {
		cerr << "Usage: " << argv[0] << " -hf <header_file> -rf <raw_file> -os <output_seconds> -cm <channel_magnifying_factor> -if <time_integration_factor>" << endl;
		return 1;
	}
	try {
		ArgumentList args(argc, argv);

		headerFilename = args.getSwitchArgument< string >("-hf");
		rawFilename = args.getSwitchArgument< string >("-rf");
		nrOutputSeconds = args.getSwitchArgument< unsigned int >("-os");
		channelMagnifyingFactor = args.getSwitchArgument< unsigned int >("-cm");
		timeIntegrationFactor = args.getSwitchArgument< unsigned int >("-if");
	}
	catch ( exception &err ) {
		cerr << err.what() << endl;
		return 1;
	}

	// Load input
	Observation observation("LOFAR", "float");
	vector< GPUData< float > * > *input = new vector< GPUData< float > * >(1);
	readLOFAR(headerFilename, rawFilename, observation, &paddedSecond, *input);

	// Plot the output
	float maxSample = numeric_limits< float >::min();
	float minSample = numeric_limits< float >::max();
	float diffMinMax = 0.0f;
	CImg< unsigned char > oImage(nrOutputSeconds * (observation.getNrSamplesPerSecond() / timeIntegrationFactor), observation.getNrChannels() * channelMagnifyingFactor, 1, 1);

	for ( unsigned int second = 0; second < nrOutputSeconds; second++ ) {
		for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
			for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) {
				float value = (input->at(second)->getHostData())[(channel * paddedSecond) + sample];

				if ( value < minSample ) {
					minSample = value;
				}
				if ( value > maxSample ) {
					maxSample = value;
				}
			}
		}
	}
	diffMinMax = maxSample - minSample;

	for ( unsigned int second = 0; second < nrOutputSeconds; second++ ) {
		for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample += timeIntegrationFactor ) {
			for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) {
				unsigned int counter = 0;
				float value = 0.0f;

				for ( unsigned int time = 0; time < timeIntegrationFactor; time++ ) {
					if ( (sample + time) < observation.getNrSamplesPerSecond() ) {
						value += (input->at(second)->getHostData())[(channel * paddedSecond) + (sample + time)] - minSample;
						counter++;
					}
					else {
						break;
					}
				}
				value /= couter;

				for ( unsigned int magnifier = 0; magnifier < channelMagnifyingFactor; magnifier++ ) {
					oImage(((second * observation.getNrSamplesPerSecond()) + sample) / timeIntegrationFactor, (channel * channelMagnifyingFactor) + magnifier, 0, 0) = (value * 256) / diffMinMax;
				}
			}
		}
	}
	oImage.save("./rawLOFARChannels.jpg");

	return 0;
}

<commit_msg>Typo ("couter" instead of "counter") :|<commit_after>/*
 * Copyright (C) 2012
 * Alessio Sclocco <a.sclocco@vu.nl>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
#include <limits>
#include <CImg.h>
using std::cout;
using std::cerr;
using std::endl;
using std::ios;
using std::ifstream;
using std::ofstream;
using std::vector;
using std::fixed;
using std::setprecision;
using std::string;
using std::numeric_limits;
using cimg_library::CImg;

#include <ArgumentList.hpp>
#include <GPUData.hpp>
#include <Exceptions.hpp>
#include <ReadData.hpp>
#include <Observation.hpp>
using isa::utils::ArgumentList;
using isa::OpenCL::GPUData;
using AstroData::readLOFAR;
using AstroData::Observation;

int main(int argc, char *argv[]) {
	string headerFilename;
	string rawFilename;
	unsigned int paddedSecond = 0;
	unsigned int nrOutputSeconds = 0;
	unsigned int channelMagnifyingFactor = 0;
	unsigned int timeIntegrationFactor = 0;

	// Parse command line
	if ( argc != 11 ) {
		cerr << "Usage: " << argv[0] << " -hf <header_file> -rf <raw_file> -os <output_seconds> -cm <channel_magnifying_factor> -if <time_integration_factor>" << endl;
		return 1;
	}
	try {
		ArgumentList args(argc, argv);

		headerFilename = args.getSwitchArgument< string >("-hf");
		rawFilename = args.getSwitchArgument< string >("-rf");
		nrOutputSeconds = args.getSwitchArgument< unsigned int >("-os");
		channelMagnifyingFactor = args.getSwitchArgument< unsigned int >("-cm");
		timeIntegrationFactor = args.getSwitchArgument< unsigned int >("-if");
	}
	catch ( exception &err ) {
		cerr << err.what() << endl;
		return 1;
	}

	// Load input
	Observation observation("LOFAR", "float");
	vector< GPUData< float > * > *input = new vector< GPUData< float > * >(1);
	readLOFAR(headerFilename, rawFilename, observation, &paddedSecond, *input);

	// Plot the output
	float maxSample = numeric_limits< float >::min();
	float minSample = numeric_limits< float >::max();
	float diffMinMax = 0.0f;
	CImg< unsigned char > oImage(nrOutputSeconds * (observation.getNrSamplesPerSecond() / timeIntegrationFactor), observation.getNrChannels() * channelMagnifyingFactor, 1, 1);

	for ( unsigned int second = 0; second < nrOutputSeconds; second++ ) {
		for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
			for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) {
				float value = (input->at(second)->getHostData())[(channel * paddedSecond) + sample];

				if ( value < minSample ) {
					minSample = value;
				}
				if ( value > maxSample ) {
					maxSample = value;
				}
			}
		}
	}
	diffMinMax = maxSample - minSample;

	for ( unsigned int second = 0; second < nrOutputSeconds; second++ ) {
		for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample += timeIntegrationFactor ) {
			for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) {
				unsigned int counter = 0;
				float value = 0.0f;

				for ( unsigned int time = 0; time < timeIntegrationFactor; time++ ) {
					if ( (sample + time) < observation.getNrSamplesPerSecond() ) {
						value += (input->at(second)->getHostData())[(channel * paddedSecond) + (sample + time)] - minSample;
						counter++;
					}
					else {
						break;
					}
				}
				value /= counter;

				for ( unsigned int magnifier = 0; magnifier < channelMagnifyingFactor; magnifier++ ) {
					oImage(((second * observation.getNrSamplesPerSecond()) + sample) / timeIntegrationFactor, (channel * channelMagnifyingFactor) + magnifier, 0, 0) = (value * 256) / diffMinMax;
				}
			}
		}
	}
	oImage.save("./rawLOFARChannels.jpg");

	return 0;
}

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012
 * Alessio Sclocco <a.sclocco@vu.nl>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
#include <limits>
#include <CImg.h>
using std::cout;
using std::cerr;
using std::endl;
using std::ios;
using std::ifstream;
using std::ofstream;
using std::vector;
using std::fixed;
using std::setprecision;
using std::string;
using std::numeric_limits;
using cimg_library::CImg;

#include <ArgumentList.hpp>
#include <GPUData.hpp>
#include <Exceptions.hpp>
#include <ReadData.hpp>
#include <Observation.hpp>
using isa::utils::ArgumentList;
using isa::OpenCL::GPUData;
using AstroData::readLOFAR;
using AstroData::Observation;

int main(int argc, char *argv[]) {
	string headerFilename;
	string rawFilename;
	unsigned int paddedSecond = 0;
	unsigned int nrOutputSeconds = 0;

	// Parse command line
	if ( argc != 7 ) {
		cerr << "Usage: " << argv[0] << " -hf <header_file> -rf <raw_file> -os <output_seconds>" << endl;
		return 1;
	}
	try {
		ArgumentList args(argc, argv);

		headerFilename = args.getSwitchArgument< string >("-hf");
		rawFilename = args.getSwitchArgument< string >("-rf");
		nrOutputSeconds = args.getSwitchArgument< unsigned int >("-os");
	}
	catch ( exception &err ) {
		cerr << err.what() << endl;
		return 1;
	}

	// Load input
	Observation observation("LOFAR", "float");
	vector< GPUData< float > * > *input = new vector< GPUData< float > * >(1);
	readLOFAR(headerFilename, rawFilename, observation, &paddedSecond, *input);

	// Plot the output
	float maxSample = numeric_limits< float >::min();
	float minSample = numeric_limits< float >::max();
	float diffMinMax = 0.0f;
	CImg< unsigned char > oImage(nrOutputSeconds * observation.getNrSamplesPerSecond(), observation.getNrChannels(), 1, 1);

	for ( unsigned int second = 0; second < nrOutputSeconds; second++ ) {
		for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
			for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) {
				float value = (input->at(second)->getHostData())[(channel * paddedSecond) + sample];

				if ( value < minSample ) {
					minSample = value;
				}
				if ( value > maxSample ) {
					maxSample = value;
				}
			}
		}
	}
	diffMinMax = maxSample - minSample;

	for ( unsigned int second = 0; second < nrOutputSeconds; second++ ) {
		for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
			for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) {
				float value = (input->at(second)->getHostData())[(channel * paddedSecond) + sample] - minSample;

				oImage((second * observation.getNrSamplesPerSecond()) + sample, channel, 0, 0) = (value * 256) / diffMinMax;
			}
		}
	}
	oImage.save("./rawLOFARChannels.bmp");

	return 0;
}

<commit_msg>Reducing the size of the produced image, and make it more readable.<commit_after>/*
 * Copyright (C) 2012
 * Alessio Sclocco <a.sclocco@vu.nl>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
#include <limits>
#include <CImg.h>
using std::cout;
using std::cerr;
using std::endl;
using std::ios;
using std::ifstream;
using std::ofstream;
using std::vector;
using std::fixed;
using std::setprecision;
using std::string;
using std::numeric_limits;
using cimg_library::CImg;

#include <ArgumentList.hpp>
#include <GPUData.hpp>
#include <Exceptions.hpp>
#include <ReadData.hpp>
#include <Observation.hpp>
using isa::utils::ArgumentList;
using isa::OpenCL::GPUData;
using AstroData::readLOFAR;
using AstroData::Observation;

int main(int argc, char *argv[]) {
	string headerFilename;
	string rawFilename;
	unsigned int paddedSecond = 0;
	unsigned int nrOutputSeconds = 0;
	unsigned int channelMagnifyingFactor = 0;
	unsigned int timeIntegrationFactor = 0;

	// Parse command line
	if ( argc != 11 ) {
		cerr << "Usage: " << argv[0] << " -hf <header_file> -rf <raw_file> -os <output_seconds> -cm <channel_magnifying_factor> -if <time_integration_factor>" << endl;
		return 1;
	}
	try {
		ArgumentList args(argc, argv);

		headerFilename = args.getSwitchArgument< string >("-hf");
		rawFilename = args.getSwitchArgument< string >("-rf");
		nrOutputSeconds = args.getSwitchArgument< unsigned int >("-os");
		channelMagnifyingFactor = args.getSwitchArgument< unsigned int >("-cm");
		timeIntegrationFactor = args.getSwitchArgument< unsigned int >("-if");
	}
	catch ( exception &err ) {
		cerr << err.what() << endl;
		return 1;
	}

	// Load input
	Observation observation("LOFAR", "float");
	vector< GPUData< float > * > *input = new vector< GPUData< float > * >(1);
	readLOFAR(headerFilename, rawFilename, observation, &paddedSecond, *input);

	// Plot the output
	float maxSample = numeric_limits< float >::min();
	float minSample = numeric_limits< float >::max();
	float diffMinMax = 0.0f;
	CImg< unsigned char > oImage(nrOutputSeconds * (observation.getNrSamplesPerSecond() / timeIntegrationFactor), observation.getNrChannels() * channelMagnifyingFactor, 1, 1);

	for ( unsigned int second = 0; second < nrOutputSeconds; second++ ) {
		for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample++ ) {
			for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) {
				float value = (input->at(second)->getHostData())[(channel * paddedSecond) + sample];

				if ( value < minSample ) {
					minSample = value;
				}
				if ( value > maxSample ) {
					maxSample = value;
				}
			}
		}
	}
	diffMinMax = maxSample - minSample;

	for ( unsigned int second = 0; second < nrOutputSeconds; second++ ) {
		for ( unsigned int sample = 0; sample < observation.getNrSamplesPerSecond(); sample += timeIntegrationFactor ) {
			for ( unsigned int channel = 0; channel < observation.getNrChannels(); channel++ ) {
				unsigned int counter = 0;
				float value = 0.0f;

				for ( unsigned int time = 0; time < timeIntegrationFactor; time++ ) {
					if ( (sample + time) < observation.getNrSamplesPerSecond() ) {
						value += (input->at(second)->getHostData())[(channel * paddedSecond) + (sample + time)] - minSample;
						counter++;
					}
					else {
						break;
					}
				}
				value /= couter;

				for ( unsigned int magnifier = 0; magnifier < channelMagnifyingFactor; magnifier++ ) {
					oImage(((second * observation.getNrSamplesPerSecond()) + sample) / timeIntegrationFactor, (channel * channelMagnifyingFactor) + magnifier, 0, 0) = (value * 256) / diffMinMax;
				}
			}
		}
	}
	oImage.save("./rawLOFARChannels.jpg");

	return 0;
}

<|endoftext|>


<commit_before>/*
** Copyright 2011 Merethis
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include "exceptions/basic.hh"
#include "logging/logging.hh"
#include "multiplexing/publisher.hh"
#include "multiplexing/subscriber.hh"
#include "processing/failover.hh"

using namespace com::centreon::broker;
using namespace com::centreon::broker::processing;

/**************************************
*                                     *
*           Public Methods            *
*                                     *
**************************************/

/**
 *  Constructor.
 *
 *  @param[in] is_out true if the failover thread is an output thread.
 */
failover::failover(bool is_out) : _is_out(is_out), _should_exit(false) {
  if (_is_out)
    _source = QSharedPointer<io::stream>(new multiplexing::subscriber);
  else
    _destination = QSharedPointer<io::stream>(new multiplexing::publisher);
}

/**
 *  Copy constructor.
 *
 *  @param[in] f Object to copy.
 */
failover::failover(failover const& f)
  :  QThread(),
     io::stream(f),
     _destination(f._destination),
     _endpoint(f._endpoint),
     _failover(f._failover),
     _is_out(f._is_out),
     _should_exit(false),
     _source(f._source) {}

/**
 *  Destructor.
 */
failover::~failover() {}

/**
 *  Assignment operator.
 *
 *  @param[in] f Object to copy.
 *
 *  @return This object.
 */
failover& failover::operator=(failover const& f) {
  _destination = f._destination;
  _endpoint = f._endpoint;
  _failover = f._failover;
  _is_out = f._is_out;
  _source = f._source;
  return (*this);
}

/**
 *  Request thread termination.
 */
void failover::exit() {
  _should_exit = true;
  _feeder.exit();
  return ;
}

/**
 *  Read data.
 *
 *  @param[out] data Data buffer.
 *  @param[out] type Data type.
 */
QSharedPointer<io::data> failover::read() {
  QSharedPointer<io::data> data;
  if (isRunning() && QThread::currentThread() != this) {
    logging::debug << logging::LOW << "failover: reading event from a different thread";
    bool caught(false);
    try {
      data = _stream->read();
      logging::debug << logging::LOW << "failover: got event from remote thread";
    }
    catch (...) {
      caught = true;
    }
    if (caught || data.isNull() || !data->size()) {
      logging::debug << logging::LOW << "failover: could not get event from remote thread";
      logging::info << logging::MEDIUM << "failover: requesting failover thread termination";
      this->exit();
      this->wait();
      _stream.clear();
      data = this->read();
    }
  }
  else {
    data = _source->read();
    logging::debug << logging::LOW << "failover: got event from thread source";
  }
  return (data);
}

/**
 *  Thread core function.
 */
void failover::run() {
  // Failover should continue as long as not exit request was received.
  logging::debug << logging::MEDIUM << "failover: launching loop";
  _should_exit = false;
  while (!_should_exit) {
    // Check endpoint.
    if (_endpoint.isNull()) {
      logging::error << logging::HIGH << "attempt to run a failover " \
        "thread with a non-existent endpoint";
      return ;
    }

    try {
      // Open endpoint.
      logging::debug << logging::MEDIUM << "failover: opening endpoint";
      _stream = _endpoint->open();
      if (_stream.isNull()) { // Retry connection.
        logging::debug << logging::MEDIUM << "failover: resulting stream is nul, retrying";
        continue ;
      }
      if (_is_out)
        _destination = _stream;
      else
        _source = _stream;

      // Process input and output.
      logging::debug << logging::MEDIUM << "failover: launching feeder";
      _feeder.prepare(_source, _destination);
      _feeder.run(); // Yes run(), we do not want to start another thread.
    }
    catch (exceptions::basic const& e) {
      logging::error << logging::HIGH << e.what();
    }
    catch (...) {
      logging::error << logging::HIGH << "failover: unknown error caught in processing thread";
    }
    if (_is_out)
      _destination.clear();
    else
      _source.clear();
    if (!_failover.isNull() && !_failover->isRunning())
      _failover->start();
    logging::info << logging::MEDIUM << "failover: sleeping a while before reconnection";
    QThread::sleep(5);
  }
  return ;
}

/**
 *  Set thread endpoint.
 *
 *  @param[in] endp Thread endpoint.
 */
void failover::set_endpoint(QSharedPointer<io::endpoint> endp) {
  _endpoint = endp;
  return ;
}

/**
 *  Set the thread's failover.
 *
 *  @param[in] fo Thread's failover.
 */
void failover::set_failover(QSharedPointer<failover> fo) {
  _failover = fo;
  if (!fo.isNull() && _is_out) // failover object will act as input for output threads.
    _source = _failover;
  return ;
}

/**
 *  Write data.
 *
 *  @param[in] d Unused.
 *
 *  @return Does not return, throw an exception.
 */
void failover::write(QSharedPointer<io::data> d) {
  (void)d;
  throw (exceptions::basic() << "attempt to use a failover thread as a destination (software bug)");
  return ;
}
<commit_msg>In failover thread, close previous endpoint before reopening.<commit_after>/*
** Copyright 2011 Merethis
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker 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
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/

#include "exceptions/basic.hh"
#include "logging/logging.hh"
#include "multiplexing/publisher.hh"
#include "multiplexing/subscriber.hh"
#include "processing/failover.hh"

using namespace com::centreon::broker;
using namespace com::centreon::broker::processing;

/**************************************
*                                     *
*           Public Methods            *
*                                     *
**************************************/

/**
 *  Constructor.
 *
 *  @param[in] is_out true if the failover thread is an output thread.
 */
failover::failover(bool is_out) : _is_out(is_out), _should_exit(false) {
  if (_is_out)
    _source = QSharedPointer<io::stream>(new multiplexing::subscriber);
  else
    _destination = QSharedPointer<io::stream>(new multiplexing::publisher);
}

/**
 *  Copy constructor.
 *
 *  @param[in] f Object to copy.
 */
failover::failover(failover const& f)
  :  QThread(),
     io::stream(f),
     _destination(f._destination),
     _endpoint(f._endpoint),
     _failover(f._failover),
     _is_out(f._is_out),
     _should_exit(false),
     _source(f._source) {}

/**
 *  Destructor.
 */
failover::~failover() {}

/**
 *  Assignment operator.
 *
 *  @param[in] f Object to copy.
 *
 *  @return This object.
 */
failover& failover::operator=(failover const& f) {
  _destination = f._destination;
  _endpoint = f._endpoint;
  _failover = f._failover;
  _is_out = f._is_out;
  _source = f._source;
  return (*this);
}

/**
 *  Request thread termination.
 */
void failover::exit() {
  _should_exit = true;
  _feeder.exit();
  return ;
}

/**
 *  Read data.
 *
 *  @param[out] data Data buffer.
 *  @param[out] type Data type.
 */
QSharedPointer<io::data> failover::read() {
  QSharedPointer<io::data> data;
  if (isRunning() && QThread::currentThread() != this) {
    logging::debug << logging::LOW << "failover: reading event from a different thread";
    bool caught(false);
    try {
      data = _stream->read();
      logging::debug << logging::LOW << "failover: got event from remote thread";
    }
    catch (...) {
      caught = true;
    }
    if (caught || data.isNull() || !data->size()) {
      logging::debug << logging::LOW << "failover: could not get event from remote thread";
      logging::info << logging::MEDIUM << "failover: requesting failover thread termination";
      this->exit();
      this->wait();
      _stream.clear();
      data = this->read();
    }
  }
  else {
    data = _source->read();
    logging::debug << logging::LOW << "failover: got event from thread source";
  }
  return (data);
}

/**
 *  Thread core function.
 */
void failover::run() {
  // Failover should continue as long as not exit request was received.
  logging::debug << logging::MEDIUM << "failover: launching loop";
  _should_exit = false;
  while (!_should_exit) {
    // Check endpoint.
    if (_endpoint.isNull()) {
      logging::error << logging::HIGH << "attempt to run a failover " \
        "thread with a non-existent endpoint";
      return ;
    }

    try {
      // Close previous endpoint if any.
      _stream.clear();

      // Open endpoint.
      logging::debug << logging::MEDIUM << "failover: opening endpoint";
      _stream = _endpoint->open();
      if (_stream.isNull()) { // Retry connection.
        logging::debug << logging::MEDIUM << "failover: resulting stream is nul, retrying";
        continue ;
      }
      if (_is_out)
        _destination = _stream;
      else
        _source = _stream;

      // Process input and output.
      logging::debug << logging::MEDIUM << "failover: launching feeder";
      _feeder.prepare(_source, _destination);
      _feeder.run(); // Yes run(), we do not want to start another thread.
    }
    catch (exceptions::basic const& e) {
      logging::error << logging::HIGH << e.what();
    }
    catch (std::exception const& e) {
      logging::error << logging::HIGH << "failover: standard library error: " << e.what();
    }
    catch (...) {
      logging::error << logging::HIGH << "failover: unknown error caught in processing thread";
    }
    if (_is_out)
      _destination.clear();
    else
      _source.clear();
    if (!_failover.isNull() && !_failover->isRunning())
      _failover->start();
    logging::info << logging::MEDIUM << "failover: sleeping a while before reconnection";
    QThread::sleep(5);
  }
  return ;
}

/**
 *  Set thread endpoint.
 *
 *  @param[in] endp Thread endpoint.
 */
void failover::set_endpoint(QSharedPointer<io::endpoint> endp) {
  _endpoint = endp;
  return ;
}

/**
 *  Set the thread's failover.
 *
 *  @param[in] fo Thread's failover.
 */
void failover::set_failover(QSharedPointer<failover> fo) {
  _failover = fo;
  if (!fo.isNull() && _is_out) // failover object will act as input for output threads.
    _source = _failover;
  return ;
}

/**
 *  Write data.
 *
 *  @param[in] d Unused.
 *
 *  @return Does not return, throw an exception.
 */
void failover::write(QSharedPointer<io::data> d) {
  (void)d;
  throw (exceptions::basic() << "attempt to use a failover thread as a destination (software bug)");
  return ;
}
<|endoftext|>


<commit_before>#include "api/plugin_instance.h"
#include "core/core.h"
#include "core/log.h"
#include "core/math.h"
#include "core/plugin_handler.h"
#include "session/session.h"
#include "settings.h"
#include "ui/imgui/imgui.h"
#include "ui/imgui_setup.h"
#include "ui/menu.h"

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

#ifdef PRODBG_WIN
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif

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

struct Context
{
    int width;
    int height;
    float mouseX;
    float mouseY;
    int mouseLmb;
    Session* session;   // one session right now
};

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

static Context s_context;

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

static const char* s_plugins[] =
{
    "sourcecode_plugin",
    "disassembly_plugin",
    "locals_plugin",
    "callstack_plugin",
    "registers_plugin",
#ifdef PRODBG_MAC
    "lldb_plugin",
#endif
};

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

void ProDBG_create(void* window, int width, int height)
{
    Context* context = &s_context;
    Rect settingsRect;

    context->session = Session_create();

    Settings_getWindowRect(&settingsRect);

    width = settingsRect.width;
    height = settingsRect.height;

    (void)window;

    for (uint32_t i = 0; i < sizeof_array(s_plugins); ++i)
    {
        if (!PluginHandler_addPlugin(OBJECT_DIR, s_plugins[i]))
            return;
    }

#if BX_PLATFORM_OSX
    bgfx::osxSetNSWindow(window);
#elif BX_PLATFORM_WINDOWS
    bgfx::winSetHwnd((HWND)window);
#else
    //bgfx::winSetHwnd(0);
#endif

    bgfx::init();
    bgfx::reset(width, height);
    bgfx::setViewSeq(0, true);

    context->width = width;
    context->height = height;

    IMGUI_setup(width, height);
}

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

void ProDBG_update()
{
    Context* context = &s_context;

    bgfx::setViewRect(0, 0, 0, (uint16_t)context->width, (uint16_t)context->height);
    bgfx::setViewClear(0, BGFX_CLEAR_COLOR_BIT | BGFX_CLEAR_DEPTH_BIT, 0x303030ff, 1.0f, 0);
    bgfx::submit(0);

    IMGUI_preUpdate(context->mouseX, context->mouseY, context->mouseLmb);

    // TODO: Support multiple sessions

    Session_update(context->session);

    /*

    bool show = true;

    ImGui::Begin("ImGui Test", &show, ImVec2(550, 480), true, ImGuiWindowFlags_ShowBorders);

    if (ImGui::Button("Test0r testing!"))
    {
        printf("test\n");
    }

    ImGui::End();
    */

    IMGUI_postUpdate();

    bgfx::frame();
}

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

void ProDBG_setWindowSize(int width, int height)
{
    Context* context = &s_context;

    context->width = width;
    context->height = height;

    bgfx::reset(width, height);
    IMGUI_setup(width, height);
    ProDBG_update();
}

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

void ProDBG_destroy()
{
    Settings_save();
}

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

void ProDBG_timedUpdate()
{
    ProDBG_update();
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Events

void ProDBG_event(int eventId)
{
	Context* context = &s_context;

	int count;

	Plugin* plugins = PluginHandler_getPlugins(&count);

	printf("%d pluginCount\n", count);

    switch (eventId)
    {
        case PRODBG_MENU_SOURCECODE:
        {
        	ViewPluginInstance* instance = PluginInstance_createViewPlugin((PDViewPlugin*)plugins[0].data);
        	Session_addViewPlugin(context->session, instance);
            log_info("create source code\n");
            break;
        }

        case PRODBG_MENU_DISASSEMBLY:
        {
            log_info("disassembly view\n");
            break;
        }

        case PRODBG_MENU_LOCALS:
        {
            log_info("disassembly view\n");
            break;
        }

        case PRODBG_MENU_CALLSTACK:
        {
            log_info("callstack view\n");
            break;
        }

        case PRODBG_MENU_REGISTERS:
        {
            log_info("registers view\n");
            break;
        }

        case PRODBG_MENU_WATCH:
        {
            log_info("watch view\n");
            break;
        }
    }
}

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

void ProDBG_scroll(float deltaX, float deltaY, int flags)
{
    (void)deltaX;
    (void)deltaY;
    (void)flags;
}

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

void ProDBG_setMousePos(float x, float y)
{
    Context* context = &s_context;

    context->mouseX = x;
    context->mouseY = y;

    ProDBG_update();
}

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

void ProDBG_setMouseState(int button, int state)
{
    Context* context = &s_context;
    (void)button;

    context->mouseLmb = state;

    ProDBG_update();
}

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

/*

   namespace prodbg
   {

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

   static const char* s_plugins[] =
   {
    "SourceCodePlugin",
    "CallStackPlugin",
    "Registers",
    "Locals",
    "Disassembly",
   #ifdef PRODBG_MAC
    "LLDBPlugin",
   #endif
   };

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

   int realMain(int argc, const char** argv)
   {
    (void)argc;
    (void)argv;

    for (uint32_t i = 0; i < sizeof_array(s_plugins); ++i)
    {
        if (!PluginHandler_addPlugin(OBJECT_DIR, s_plugins[i]))
            return 0;
    }

    uint32_t width = 1280;
    uint32_t height = 720;
    uint32_t debug = BGFX_DEBUG_TEXT;
    uint32_t reset = BGFX_RESET_VSYNC;

    bgfx::init();
    bgfx::reset(width, height, reset);

    // Enable debug text.
    bgfx::setDebug(debug);

    // Set view 0 clear state.
    bgfx::setViewClear(0
        , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT
        , 0x303030ff
        , 1.0f
        , 0
        );

    bgfx::setViewSeq(0, true);

    entry::MouseState mouseState;

    IMGUI_setup((int)width, (int)height);

    while (!entry::processEvents(width, height, debug, reset, &mouseState))
    {
        // Set view 0 default viewport.
        bgfx::setViewRect(0, 0, 0, (uint16_t)width, (uint16_t)height);

        // This dummy draw call is here to make sure that view 0 is cleared
        // if no other draw calls are submitted to view 0.
        bgfx::submit(0);

        IMGUI_preUpdate(&mouseState);

        bool show = true;

        ImGui::Begin("ImGui Test", &show, ImVec2(550,480), true, ImGuiWindowFlags_ShowBorders);

        if (ImGui::Button("Test0r testing!"))
        {
            printf("test\n");
        }

        ImGui::End();

        // Use debug font to print information about this example.
        //bgfx::dbgTextClear();
        //bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/00-helloworld");
        //bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Initialization and debug text.");

        IMGUI_postUpdate();

        // Advance to next frame. Rendering thread will be kicked to
        // process submitted rendering primitives.
        bgfx::frame();
    }

    // Shutdown bgfx.
    bgfx::shutdown();

    return 0; //Application_init(argc, argv);
   }

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

   }

   extern "C"
   {

   int _main_(int argc, char** argv)
   {
    return prodbg::realMain(argc, (const char**)argv);
   }

   }

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

   #ifdef WIN32

   extern "C" int main(int _argc, char** _argv);

   int CALLBACK WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
   {
    char* temp[] = { "foo" };
    main(1, temp);
   }

   #endif

 */

<commit_msg>Better bg color<commit_after>#include "api/plugin_instance.h"
#include "core/core.h"
#include "core/log.h"
#include "core/math.h"
#include "core/plugin_handler.h"
#include "session/session.h"
#include "settings.h"
#include "ui/imgui/imgui.h"
#include "ui/imgui_setup.h"
#include "ui/menu.h"

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

#ifdef PRODBG_WIN
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif

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

struct Context
{
    int width;
    int height;
    float mouseX;
    float mouseY;
    int mouseLmb;
    Session* session;   // one session right now
};

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

static Context s_context;

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

static const char* s_plugins[] =
{
    "sourcecode_plugin",
    "disassembly_plugin",
    "locals_plugin",
    "callstack_plugin",
    "registers_plugin",
#ifdef PRODBG_MAC
    "lldb_plugin",
#endif
};

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

void ProDBG_create(void* window, int width, int height)
{
    Context* context = &s_context;
    Rect settingsRect;

    context->session = Session_create();

    Settings_getWindowRect(&settingsRect);

    width = settingsRect.width;
    height = settingsRect.height;

    (void)window;

    for (uint32_t i = 0; i < sizeof_array(s_plugins); ++i)
    {
        if (!PluginHandler_addPlugin(OBJECT_DIR, s_plugins[i]))
            return;
    }

#if BX_PLATFORM_OSX
    bgfx::osxSetNSWindow(window);
#elif BX_PLATFORM_WINDOWS
    bgfx::winSetHwnd((HWND)window);
#else
    //bgfx::winSetHwnd(0);
#endif

    bgfx::init();
    bgfx::reset(width, height);
    bgfx::setViewSeq(0, true);

    context->width = width;
    context->height = height;

    IMGUI_setup(width, height);
}

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

void ProDBG_update()
{
    Context* context = &s_context;

    bgfx::setViewRect(0, 0, 0, (uint16_t)context->width, (uint16_t)context->height);
    bgfx::setViewClear(0, BGFX_CLEAR_COLOR_BIT | BGFX_CLEAR_DEPTH_BIT, 0x101010ff, 1.0f, 0);
    bgfx::submit(0);

    IMGUI_preUpdate(context->mouseX, context->mouseY, context->mouseLmb);

    // TODO: Support multiple sessions

    Session_update(context->session);

    /*

    bool show = true;

    ImGui::Begin("ImGui Test", &show, ImVec2(550, 480), true, ImGuiWindowFlags_ShowBorders);

    if (ImGui::Button("Test0r testing!"))
    {
        printf("test\n");
    }

    ImGui::End();
    */

    IMGUI_postUpdate();

    bgfx::frame();
}

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

void ProDBG_setWindowSize(int width, int height)
{
    Context* context = &s_context;

    context->width = width;
    context->height = height;

    bgfx::reset(width, height);
    IMGUI_setup(width, height);
    ProDBG_update();
}

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

void ProDBG_destroy()
{
    Settings_save();
}

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

void ProDBG_timedUpdate()
{
    ProDBG_update();
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Events

void ProDBG_event(int eventId)
{
	Context* context = &s_context;

	int count;

	Plugin* plugins = PluginHandler_getPlugins(&count);

	printf("%d pluginCount\n", count);

    switch (eventId)
    {
        case PRODBG_MENU_SOURCECODE:
        {
        	ViewPluginInstance* instance = PluginInstance_createViewPlugin((PDViewPlugin*)plugins[0].data);
        	Session_addViewPlugin(context->session, instance);
            log_info("create source code\n");
            break;
        }

        case PRODBG_MENU_DISASSEMBLY:
        {
            log_info("disassembly view\n");
            break;
        }

        case PRODBG_MENU_LOCALS:
        {
            log_info("disassembly view\n");
            break;
        }

        case PRODBG_MENU_CALLSTACK:
        {
            log_info("callstack view\n");
            break;
        }

        case PRODBG_MENU_REGISTERS:
        {
            log_info("registers view\n");
            break;
        }

        case PRODBG_MENU_WATCH:
        {
            log_info("watch view\n");
            break;
        }
    }
}

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

void ProDBG_scroll(float deltaX, float deltaY, int flags)
{
    (void)deltaX;
    (void)deltaY;
    (void)flags;
}

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

void ProDBG_setMousePos(float x, float y)
{
    Context* context = &s_context;

    context->mouseX = x;
    context->mouseY = y;

    ProDBG_update();
}

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

void ProDBG_setMouseState(int button, int state)
{
    Context* context = &s_context;
    (void)button;

    context->mouseLmb = state;

    ProDBG_update();
}

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

/*

   namespace prodbg
   {

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

   static const char* s_plugins[] =
   {
    "SourceCodePlugin",
    "CallStackPlugin",
    "Registers",
    "Locals",
    "Disassembly",
   #ifdef PRODBG_MAC
    "LLDBPlugin",
   #endif
   };

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

   int realMain(int argc, const char** argv)
   {
    (void)argc;
    (void)argv;

    for (uint32_t i = 0; i < sizeof_array(s_plugins); ++i)
    {
        if (!PluginHandler_addPlugin(OBJECT_DIR, s_plugins[i]))
            return 0;
    }

    uint32_t width = 1280;
    uint32_t height = 720;
    uint32_t debug = BGFX_DEBUG_TEXT;
    uint32_t reset = BGFX_RESET_VSYNC;

    bgfx::init();
    bgfx::reset(width, height, reset);

    // Enable debug text.
    bgfx::setDebug(debug);

    // Set view 0 clear state.
    bgfx::setViewClear(0
        , BGFX_CLEAR_COLOR_BIT|BGFX_CLEAR_DEPTH_BIT
        , 0x303030ff
        , 1.0f
        , 0
        );

    bgfx::setViewSeq(0, true);

    entry::MouseState mouseState;

    IMGUI_setup((int)width, (int)height);

    while (!entry::processEvents(width, height, debug, reset, &mouseState))
    {
        // Set view 0 default viewport.
        bgfx::setViewRect(0, 0, 0, (uint16_t)width, (uint16_t)height);

        // This dummy draw call is here to make sure that view 0 is cleared
        // if no other draw calls are submitted to view 0.
        bgfx::submit(0);

        IMGUI_preUpdate(&mouseState);

        bool show = true;

        ImGui::Begin("ImGui Test", &show, ImVec2(550,480), true, ImGuiWindowFlags_ShowBorders);

        if (ImGui::Button("Test0r testing!"))
        {
            printf("test\n");
        }

        ImGui::End();

        // Use debug font to print information about this example.
        //bgfx::dbgTextClear();
        //bgfx::dbgTextPrintf(0, 1, 0x4f, "bgfx/examples/00-helloworld");
        //bgfx::dbgTextPrintf(0, 2, 0x6f, "Description: Initialization and debug text.");

        IMGUI_postUpdate();

        // Advance to next frame. Rendering thread will be kicked to
        // process submitted rendering primitives.
        bgfx::frame();
    }

    // Shutdown bgfx.
    bgfx::shutdown();

    return 0; //Application_init(argc, argv);
   }

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

   }

   extern "C"
   {

   int _main_(int argc, char** argv)
   {
    return prodbg::realMain(argc, (const char**)argv);
   }

   }

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

   #ifdef WIN32

   extern "C" int main(int _argc, char** _argv);

   int CALLBACK WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
   {
    char* temp[] = { "foo" };
    main(1, temp);
   }

   #endif

 */

<|endoftext|>