<commit_before>/*
 * Copyright (C) 2012 Arthur O'Dwyer
 *
 * 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.
 */

#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <cassert>
#include <set>
#include <string>
#include <vector>

#include "diffn.h"

void do_print_ifdefs_recursively(std::vector<FileInfo> &files,
                                 const std::vector<std::string> &macro_names,
                                 const std::string &output_name)
{
    const size_t num_files = files.size();

    /* If what's in "files" is all regular files, diff them.
     * Otherwise, try stepping through each directory in parallel. */
    FileInfo *sample_regular = NULL;
    FileInfo *sample_directory = NULL;
    for (size_t i=0; i < num_files; ++i) {
        if (files[i].fp == NULL) {
            files[i].fp = fopen(files[i].name.c_str(), "r");
            if (files[i].fp == NULL)
                continue;
        }
        fstat(fileno(files[i].fp), &files[i].stat);
        if (S_ISDIR(files[i].stat.st_mode)) {
            sample_directory = &files[i];
        } else if (S_ISREG(files[i].stat.st_mode)) {
            sample_regular = &files[i];
        }
    }

    if (sample_regular != NULL && sample_directory != NULL) {
        do_error("Input paths '%s' and '%s' cannot be merged because one is a directory\n"
                 "and the other is a regular file.\n"
                 "Incomplete output may have been left in the output directory.",
                 sample_directory->name.c_str(), sample_regular->name.c_str());
    }

    if (sample_regular != NULL) {
        /* Let's diff these files! */
        Difdef difdef(num_files);
        for (size_t i=0; i < num_files; ++i) {
            if (files[i].fp == NULL) {
                /* This file couldn't be opened, above. */
                continue;
            }
            assert(!S_ISDIR(files[i].stat.st_mode));
            if (S_ISREG(files[i].stat.st_mode)) {
                difdef.replace_file(i, files[i].fp);
            } else {
                difdef.replace_file(i, NULL);
            }
            fclose(files[i].fp);
        }

        Difdef::Diff diff = difdef.merge();

        /* Try to open the output file. */
        FILE *out = fopen(output_name.c_str(), "w");
        if (out == NULL) {
            do_error("Output file '%s': Cannot create file", output_name.c_str());
        }

        /* Print out the diff. */
        verify_properly_nested_directives(diff, &files[0]);
        do_print_using_ifdefs(diff, macro_names, out);
        fclose(out);

    } else {
        /* Recursively diff the contents of these directories. */
        if (mkdir(output_name.c_str(), 0777)) {
            do_error("Output path '%s': Cannot create directory", output_name.c_str());
        }
        std::set<std::string> processed_filenames;
        processed_filenames.insert(".");
        processed_filenames.insert("..");
        for (size_t i=0; i < num_files; ++i) {
            if (files[i].fp == NULL)
                continue;
#if (_POSIX_C_SOURCE >= 200809L)
            DIR *dir = fdopendir(fileno(files[i].fp));
#else
            DIR *dir = opendir(files[i].name.c_str());
#endif /* __GNUC__ */
            while (struct dirent *file = readdir(dir)) {
                std::string relative_name = file->d_name;
                if (processed_filenames.find(relative_name) != processed_filenames.end()) {
                    /* This filename was matched and handled earlier. */
                    continue;
                }
                processed_filenames.insert(relative_name);

                std::vector<FileInfo> subfiles(files.size());
                for (size_t j=0; j < num_files; ++j) {
                    subfiles[j].name = files[j].name + "/" + relative_name;
                }
                std::string suboutput_name = output_name + "/" + relative_name;
                do_print_ifdefs_recursively(subfiles, macro_names, suboutput_name);
            }
        }
    }
}
<commit_msg>Remove the #if protecting fdopendir()/opendir().<commit_after>/*
 * Copyright (C) 2012 Arthur O'Dwyer
 *
 * 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.
 */

#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <cassert>
#include <set>
#include <string>
#include <vector>

#include "diffn.h"

void do_print_ifdefs_recursively(std::vector<FileInfo> &files,
                                 const std::vector<std::string> &macro_names,
                                 const std::string &output_name)
{
    const size_t num_files = files.size();

    /* If what's in "files" is all regular files, diff them.
     * Otherwise, try stepping through each directory in parallel. */
    FileInfo *sample_regular = NULL;
    FileInfo *sample_directory = NULL;
    for (size_t i=0; i < num_files; ++i) {
        if (files[i].fp == NULL) {
            files[i].fp = fopen(files[i].name.c_str(), "r");
            if (files[i].fp == NULL)
                continue;
        }
        fstat(fileno(files[i].fp), &files[i].stat);
        if (S_ISDIR(files[i].stat.st_mode)) {
            sample_directory = &files[i];
        } else if (S_ISREG(files[i].stat.st_mode)) {
            sample_regular = &files[i];
        }
    }

    if (sample_regular != NULL && sample_directory != NULL) {
        do_error("Input paths '%s' and '%s' cannot be merged because one is a directory\n"
                 "and the other is a regular file.\n"
                 "Incomplete output may have been left in the output directory.",
                 sample_directory->name.c_str(), sample_regular->name.c_str());
    }

    if (sample_regular != NULL) {
        /* Let's diff these files! */
        Difdef difdef(num_files);
        for (size_t i=0; i < num_files; ++i) {
            if (files[i].fp == NULL) {
                /* This file couldn't be opened, above. */
                continue;
            }
            assert(!S_ISDIR(files[i].stat.st_mode));
            if (S_ISREG(files[i].stat.st_mode)) {
                difdef.replace_file(i, files[i].fp);
            } else {
                difdef.replace_file(i, NULL);
            }
            fclose(files[i].fp);
        }

        Difdef::Diff diff = difdef.merge();

        /* Try to open the output file. */
        FILE *out = fopen(output_name.c_str(), "w");
        if (out == NULL) {
            do_error("Output file '%s': Cannot create file", output_name.c_str());
        }

        /* Print out the diff. */
        verify_properly_nested_directives(diff, &files[0]);
        do_print_using_ifdefs(diff, macro_names, out);
        fclose(out);

    } else {
        /* Recursively diff the contents of these directories. */
        if (mkdir(output_name.c_str(), 0777)) {
            do_error("Output path '%s': Cannot create directory", output_name.c_str());
        }
        std::set<std::string> processed_filenames;
        processed_filenames.insert(".");
        processed_filenames.insert("..");
        for (size_t i=0; i < num_files; ++i) {
            if (files[i].fp == NULL)
                continue;
            DIR *dir = opendir(files[i].name.c_str());
            while (struct dirent *file = readdir(dir)) {
                std::string relative_name = file->d_name;
                if (processed_filenames.find(relative_name) != processed_filenames.end()) {
                    /* This filename was matched and handled earlier. */
                    continue;
                }
                processed_filenames.insert(relative_name);

                std::vector<FileInfo> subfiles(files.size());
                for (size_t j=0; j < num_files; ++j) {
                    subfiles[j].name = files[j].name + "/" + relative_name;
                }
                std::string suboutput_name = output_name + "/" + relative_name;
                do_print_ifdefs_recursively(subfiles, macro_names, suboutput_name);
            }
        }
    }
}
<|endoftext|>


<commit_before>#include <falcon/ctmatch.hpp>

#include <iostream>
#include <type_traits>

template<int i> struct i_ : std::integral_constant<int, i> {};

class my_true_type {};
std::true_type normalize_branch_value(my_true_type) { return {}; }

template<class T, int i> struct Fi { i_<i> operator()(T) const { return {}; } };

template<class T> struct type_ {
  template<class U>
  std::enable_if_t<std::is_same<std::decay_t<U>, T>::value, std::true_type>
  operator()(U const &) const { return {}; }
};

int main() {

using namespace falcon::ctmatch;

i_<1> a;
i_<2> b;

Fi<int, 1> fa;
Fi<int, 2> fb;

type_<int> only_int;
type_<bool> only_bool;

std::true_type true_;
std::false_type false_;

auto dyn_error = [](auto &&) { throw 1; };

a = match_invoke(1, fa);
a = match_invoke(1, match_if(fa, fa));
a = match_invoke(1, match_if(fa) >> fa);
a = 1 >>= match | match_if([](int) { return my_true_type{}; }, fa);

match_invoke(1, match_value(1, fa), dyn_error);
match_invoke(1, match_value(1) >> fa, dyn_error);

b = match_invoke(1, match_if(only_bool, fa), match_if(only_int, fb));
b = match_invoke(1, match_if(only_bool) >> fa, match_if(only_int) >> fb);

b = 1 >>= match
| match_if(only_bool) >> fa
| match_if(only_int) >> fb
;

3 >>= match | match_always;
true_ = 3 >>= match | only_int;

only_bool(
  1 >>= match.result<bool>()
  | match_value(only_int, []() { return 1; })
  | match_value(only_int, []() { return 2; })
  | [](int){ return 3; }
);

a = pmatch_invoke(1,
  [](auto x) -> std::enable_if_t<std::is_pointer<decltype(x)>::value> {
#ifndef _MSC_VER
    static_assert(!sizeof(x), "");
#endif
    return x; // msvc
  },
  [a](int) { return a; },
  [](auto x) { static_assert(!sizeof(x), ""); }
);
true_ = (pmatch(1) | match_always | match_error).is_invoked();
true_ = (pmatch(1) | only_bool | only_int | match_error).is_invoked();
false_ = (pmatch(1) | only_bool).is_invoked();

}
<commit_msg>[msvc] fixed compilation<commit_after>#include <falcon/ctmatch.hpp>

#include <iostream>
#include <type_traits>

template<int i> struct i_ : std::integral_constant<int, i> {};

class my_true_type {};
std::true_type normalize_branch_value(my_true_type) { return {}; }

template<class T, int i> struct Fi { i_<i> operator()(T) const { return {}; } };

template<class T> struct type_ {
  template<class U>
  std::enable_if_t<std::is_same<std::decay_t<U>, T>::value, std::true_type>
  operator()(U const &) const { return {}; }
};

int main() {

using namespace falcon::ctmatch;

i_<1> a;
i_<2> b;

Fi<int, 1> fa;
Fi<int, 2> fb;

type_<int> only_int;
type_<bool> only_bool;

std::true_type true_;
std::false_type false_;

auto dyn_error = [](auto &&) { throw 1; };

a = match_invoke(1, fa);
a = match_invoke(1, match_if(fa, fa));
a = match_invoke(1, match_if(fa) >> fa);
a = 1 >>= match | match_if([](int) { return my_true_type{}; }, fa);

match_invoke(1, match_value(1, fa), dyn_error);
match_invoke(1, match_value(1) >> fa, dyn_error);

b = match_invoke(1, match_if(only_bool, fa), match_if(only_int, fb));
b = match_invoke(1, match_if(only_bool) >> fa, match_if(only_int) >> fb);

b = 1 >>= match
| match_if(only_bool) >> fa
| match_if(only_int) >> fb
;

3 >>= match | match_always;
true_ = 3 >>= match | only_int;

only_bool(
  1 >>= match.result<bool>()
  | match_value(only_int, []() { return 1; })
  | match_value(only_int, []() { return 2; })
  | [](int){ return 3; }
);

a = pmatch_invoke(1,
  [](auto x) -> std::enable_if_t<std::is_pointer<decltype(x)>::value> {
  },
  [a](int) { return a; },
  [](auto x) { static_assert(!sizeof(x), ""); }
);
true_ = (pmatch(1) | match_always | match_error).is_invoked();
true_ = (pmatch(1) | only_bool | only_int | match_error).is_invoked();
false_ = (pmatch(1) | only_bool).is_invoked();

}
<|endoftext|>


<commit_before>#include "audio_player.h"
#include <QDebug>

void endTrackSync(HSYNC handle, DWORD channel, DWORD data, void * user) {
//    BASS_ChannelStop(channel);
//    BASS_ChannelRemoveSync(channel, handle);
    AudioPlayer * player = static_cast<AudioPlayer *>(user);
    emit player -> playbackEnded();
}

AudioPlayer::AudioPlayer(QObject * parent) : QObject(parent) {
    qRegisterMetaType<AudioPlayer::MediaStatus>("MediaStatus");
    qRegisterMetaType<AudioPlayer::MediaState>("MediaState");

    // cheat for cross treadhing
    connect(this, SIGNAL(playbackEnded()), this, SLOT(endOfPlayback()));

    duration = -1;
    notifyInterval = 100;

    currentState = StoppedState;

    if (HIWORD(BASS_GetVersion()) != BASSVERSION) {
        throw "An incorrect version of BASS.DLL was loaded";
    }

    if (HIWORD(BASS_FX_GetVersion()) != BASSVERSION) {
        throw "An incorrect version of BASS_FX.DLL was loaded";
    }

    if (!BASS_Init(-1, 44100, 0, NULL, NULL))
        qDebug() << "Init error: " << BASS_ErrorGetCode();
//        throw "Cannot initialize device";

    ///////////////////////////////////////////////
    /// load plugins
    ///////////////////////////////////////////////
    QFileInfoList list = QDir(QCoreApplication::applicationDirPath() + "/libs/bass/plugins").entryInfoList(QDir::Files | QDir::NoDotAndDotDot | QDir::Hidden);

    foreach(QFileInfo file, list) {
        /*int res = */BASS_PluginLoad(file.filePath().toLatin1(), 0);

//        if (res == 0)
//            qDebug() << file.filePath() << BASS_ErrorGetCode();
//        else
//            qDebug() << file.filePath() << res;
    }
    ///////////////////////////////////////////////

    notifyTimer = new NotifyTimer(this);
    connect(notifyTimer, SIGNAL(timeout()), this, SLOT(signalUpdate()));
    connect(notifyTimer, SIGNAL(started()), this, SLOT(started()));
    connect(notifyTimer, SIGNAL(stoped()), this, SLOT(stoped()));
}

AudioPlayer::~AudioPlayer() {
    BASS_PluginFree(0);
    notifyTimer -> stop();
    delete notifyTimer;
}

int AudioPlayer::getDuration() const {
    return duration;
}

int AudioPlayer::getNotifyInterval() {
    return notifyInterval;
}
void AudioPlayer::setNotifyInterval(signed int milis) {
    notifyInterval = milis;
    if (notifyTimer -> isActive())
        notifyTimer -> setInterval(notifyInterval);
}

void AudioPlayer::setMedia(QUrl mediaPath) {
    mediaUri = mediaPath;
}

AudioPlayer::MediaState AudioPlayer::state() const {
    return currentState;
}

////////////////////////////////////////////////////////////////////////
/// PRIVATE
////////////////////////////////////////////////////////////////////////

int AudioPlayer::openRemoteChannel(QString path) {
    BASS_ChannelStop(chan);
    chan = BASS_StreamCreateURL(path.toStdWString().c_str(), 0, 0, NULL, 0);

//    BASS_Encode_Start(channel, "output.wav", BASS_ENCODE_PCM, NULL, 0);

//    BASS_Encode_StartCAFile(channel, 'mp4f', 'aac ', 0, 128000, "output.mp4"); // only macos
//    BASS_Encode_StartCAFile(channel, 'm4af', 'alac', 0, 0, "output.m4a"); // only macos

    if (!chan)
        qDebug() << "Can't play stream" <<  BASS_ErrorGetCode() << path.toUtf8();
    return chan;
}

int AudioPlayer::openChannel(QString path) {
    BASS_ChannelStop(chan);
    if (!(chan = BASS_StreamCreateFile(false, path.toStdWString().c_str(), 0, 0, BASS_SAMPLE_FLOAT | BASS_ASYNCFILE)))
//    if (!(stream = BASS_StreamCreateFile(false, path.toStdWString().c_str(), 0, 0, BASS_SAMPLE_LOOP))
//        && !(chan = BASS_MusicLoad(false, path.toStdWString().c_str(), 0, 0, BASS_SAMPLE_LOOP | BASS_MUSIC_RAMP | BASS_MUSIC_POSRESET | BASS_MUSIC_STOPBACK | BASS_STREAM_PRESCAN | BASS_MUSIC_AUTOFREE, 1)))
        qDebug() << "Can't play file " <<  BASS_ErrorGetCode() << path.toUtf8();
    return chan;
}

void AudioPlayer::closeChannel() {
    qDebug() << "close channel";
    BASS_ChannelStop(chan);
    BASS_ChannelRemoveSync(chan, syncHandle);
    BASS_StreamFree(chan);
//    BASS_MusicFree(chan);
}

////////////////////////////////////////////////////////////////////////
/// SLOTS
////////////////////////////////////////////////////////////////////////

void AudioPlayer::started() {
    currentState = PlayingState;
    emit stateChanged(PlayingState);
}

void AudioPlayer::stoped() {
    currentState = StoppedState;
    closeChannel();
}

void AudioPlayer::signalUpdate() {
    int curr_pos = BASS_ChannelBytes2Seconds(chan, BASS_ChannelGetPosition(chan, BASS_POS_BYTE)) * 1000;

    emit positionChanged(curr_pos);
//    if (duration - curr_pos < 500)
//        endOfPlayback();
}

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

void AudioPlayer::play() {
    if (currentState == PausedState) {
        resume();
    } else {
        closeChannel();
        if (mediaUri.isEmpty()) {
            emit mediaStatusChanged(NoMedia);
        } else {
            if (openChannel(mediaUri.toLocalFile())) {
                duration = BASS_ChannelBytes2Seconds(chan, BASS_ChannelGetLength(chan, BASS_POS_BYTE)) * 1000;
                durationChanged(duration);
                BASS_ChannelPlay(chan, true);
                notifyTimer -> start(notifyInterval);
                //TODO: remove sync and check end of file by timer
                syncHandle = BASS_ChannelSetSync(chan, BASS_SYNC_END, 0, &endTrackSync, this);
            } else {
                qDebug() << "Can't play file";
            }
        }
    }
}

void AudioPlayer::pause() {
    notifyTimer -> stop();
    BASS_ChannelPause(chan);
    emit stateChanged(PausedState);
    currentState = PausedState;
}

void AudioPlayer::resume() {
    if (!BASS_ChannelPlay(chan, false)) {
        emit mediaStatusChanged(StalledMedia);
        qDebug() << "Error resuming";
    } else {
        notifyTimer -> start(notifyInterval);
    }
}

void AudioPlayer::stop() {
    BASS_ChannelStop(chan);
    notifyTimer -> stop();
    emit stateChanged(StoppedState);
}

void AudioPlayer::endOfPlayback() {
    stop();
    closeChannel();
    emit mediaStatusChanged(EndOfMedia);
}

void AudioPlayer::setPosition(int position) {
    BASS_ChannelSetPosition(chan, BASS_ChannelSeconds2Bytes(chan, position / 1000.0), BASS_POS_BYTE);
}
<commit_msg>fix pause state<commit_after>#include "audio_player.h"
#include <QDebug>

void endTrackSync(HSYNC handle, DWORD channel, DWORD data, void * user) {
//    BASS_ChannelStop(channel);
//    BASS_ChannelRemoveSync(channel, handle);
    AudioPlayer * player = static_cast<AudioPlayer *>(user);
    emit player -> playbackEnded();
}

AudioPlayer::AudioPlayer(QObject * parent) : QObject(parent) {
    qRegisterMetaType<AudioPlayer::MediaStatus>("MediaStatus");
    qRegisterMetaType<AudioPlayer::MediaState>("MediaState");

    // cheat for cross treadhing
    connect(this, SIGNAL(playbackEnded()), this, SLOT(endOfPlayback()));

    duration = -1;
    notifyInterval = 100;

    currentState = StoppedState;

    if (HIWORD(BASS_GetVersion()) != BASSVERSION) {
        throw "An incorrect version of BASS.DLL was loaded";
    }

    if (HIWORD(BASS_FX_GetVersion()) != BASSVERSION) {
        throw "An incorrect version of BASS_FX.DLL was loaded";
    }

    if (!BASS_Init(-1, 44100, 0, NULL, NULL))
        qDebug() << "Init error: " << BASS_ErrorGetCode();
//        throw "Cannot initialize device";

    ///////////////////////////////////////////////
    /// load plugins
    ///////////////////////////////////////////////
    QFileInfoList list = QDir(QCoreApplication::applicationDirPath() + "/libs/bass/plugins").entryInfoList(QDir::Files | QDir::NoDotAndDotDot | QDir::Hidden);

    foreach(QFileInfo file, list) {
        /*int res = */BASS_PluginLoad(file.filePath().toLatin1(), 0);

//        if (res == 0)
//            qDebug() << file.filePath() << BASS_ErrorGetCode();
//        else
//            qDebug() << file.filePath() << res;
    }
    ///////////////////////////////////////////////

    notifyTimer = new NotifyTimer(this);
    connect(notifyTimer, SIGNAL(timeout()), this, SLOT(signalUpdate()));
    connect(notifyTimer, SIGNAL(started()), this, SLOT(started()));
    connect(notifyTimer, SIGNAL(stoped()), this, SLOT(stoped()));
}

AudioPlayer::~AudioPlayer() {
    BASS_PluginFree(0);
    notifyTimer -> stop();
    delete notifyTimer;
}

int AudioPlayer::getDuration() const {
    return duration;
}

int AudioPlayer::getNotifyInterval() {
    return notifyInterval;
}
void AudioPlayer::setNotifyInterval(signed int milis) {
    notifyInterval = milis;
    if (notifyTimer -> isActive())
        notifyTimer -> setInterval(notifyInterval);
}

void AudioPlayer::setMedia(QUrl mediaPath) {
    mediaUri = mediaPath;
}

AudioPlayer::MediaState AudioPlayer::state() const {
    return currentState;
}

////////////////////////////////////////////////////////////////////////
/// PRIVATE
////////////////////////////////////////////////////////////////////////

int AudioPlayer::openRemoteChannel(QString path) {
    BASS_ChannelStop(chan);
    chan = BASS_StreamCreateURL(path.toStdWString().c_str(), 0, 0, NULL, 0);

//    BASS_Encode_Start(channel, "output.wav", BASS_ENCODE_PCM, NULL, 0);

//    BASS_Encode_StartCAFile(channel, 'mp4f', 'aac ', 0, 128000, "output.mp4"); // only macos
//    BASS_Encode_StartCAFile(channel, 'm4af', 'alac', 0, 0, "output.m4a"); // only macos

    if (!chan)
        qDebug() << "Can't play stream" <<  BASS_ErrorGetCode() << path.toUtf8();
    return chan;
}

int AudioPlayer::openChannel(QString path) {
    BASS_ChannelStop(chan);
    if (!(chan = BASS_StreamCreateFile(false, path.toStdWString().c_str(), 0, 0, BASS_SAMPLE_FLOAT | BASS_ASYNCFILE)))
//    if (!(stream = BASS_StreamCreateFile(false, path.toStdWString().c_str(), 0, 0, BASS_SAMPLE_LOOP))
//        && !(chan = BASS_MusicLoad(false, path.toStdWString().c_str(), 0, 0, BASS_SAMPLE_LOOP | BASS_MUSIC_RAMP | BASS_MUSIC_POSRESET | BASS_MUSIC_STOPBACK | BASS_STREAM_PRESCAN | BASS_MUSIC_AUTOFREE, 1)))
        qDebug() << "Can't play file " <<  BASS_ErrorGetCode() << path.toUtf8();
    return chan;
}

void AudioPlayer::closeChannel() {
    qDebug() << "close channel";
    BASS_ChannelStop(chan);
    BASS_ChannelRemoveSync(chan, syncHandle);
    BASS_StreamFree(chan);
//    BASS_MusicFree(chan);
}

////////////////////////////////////////////////////////////////////////
/// SLOTS
////////////////////////////////////////////////////////////////////////

void AudioPlayer::started() {
    currentState = PlayingState;
    emit stateChanged(PlayingState);
}

void AudioPlayer::stoped() {
    currentState = StoppedState;
}

void AudioPlayer::signalUpdate() {
    int curr_pos = BASS_ChannelBytes2Seconds(chan, BASS_ChannelGetPosition(chan, BASS_POS_BYTE)) * 1000;

    emit positionChanged(curr_pos);
//    if (duration - curr_pos < 500)
//        endOfPlayback();
}

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

void AudioPlayer::play() {
    if (currentState == PausedState) {
        resume();
    } else {
        closeChannel();
        if (mediaUri.isEmpty()) {
            emit mediaStatusChanged(NoMedia);
        } else {
            if (openChannel(mediaUri.toLocalFile())) {
                duration = BASS_ChannelBytes2Seconds(chan, BASS_ChannelGetLength(chan, BASS_POS_BYTE)) * 1000;
                durationChanged(duration);
                BASS_ChannelPlay(chan, true);
                notifyTimer -> start(notifyInterval);
                //TODO: remove sync and check end of file by timer
                syncHandle = BASS_ChannelSetSync(chan, BASS_SYNC_END, 0, &endTrackSync, this);
            } else {
                qDebug() << "Can't play file";
            }
        }
    }
}

void AudioPlayer::pause() {
    notifyTimer -> stop();
    BASS_ChannelPause(chan);
    emit stateChanged(PausedState);
    currentState = PausedState;
}

void AudioPlayer::resume() {
    if (!BASS_ChannelPlay(chan, false)) {
        emit mediaStatusChanged(StalledMedia);
        qDebug() << "Error resuming";
    } else {
        notifyTimer -> start(notifyInterval);
    }
}

void AudioPlayer::stop() {
    closeChannel();
    notifyTimer -> stop();
    emit stateChanged(StoppedState);
}

void AudioPlayer::endOfPlayback() {
    stop();
    closeChannel();
    emit mediaStatusChanged(EndOfMedia);
}

void AudioPlayer::setPosition(int position) {
    BASS_ChannelSetPosition(chan, BASS_ChannelSeconds2Bytes(chan, position / 1000.0), BASS_POS_BYTE);
}
<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/

#include "itk{{cookiecutter.filter_name}}.h"

#include "itkCommand.h"
#include "itkImageFileWriter.h"
#include "itkTestingMacros.h"

namespace{
class ShowProgress : public itk::Command
{
public:
  itkNewMacro( ShowProgress );

  void
  Execute( itk::Object* caller, const itk::EventObject& event ) override
  {
    Execute( (const itk::Object*)caller, event );
  }

  void
  Execute( const itk::Object* caller, const itk::EventObject& event ) override
  {
    if ( !itk::ProgressEvent().CheckEvent( &event ) )
      {
      return;
      }
    const auto* processObject = dynamic_cast< const itk::ProcessObject* >( caller );
    if ( !processObject )
      {
      return;
      }
    std::cout << " " << processObject->GetProgress();
  }
};
}

int itk{{cookiecutter.filter_name}}Test( int argc, char * argv[] )
{
  if( argc < 2 )
    {
    std::cerr << "Usage: " << argv[0];
    std::cerr << " outputImage";
    std::cerr << std::endl;
    return EXIT_FAILURE;
    }
  const char * outputImageFileName  = argv[1];

  const unsigned int Dimension = 2;
  using PixelType = float;
  using ImageType = itk::Image< PixelType, Dimension >;

  using FilterType = itk::{{cookiecutter.filter_name}}< ImageType, ImageType >;
  FilterType::Pointer filter = FilterType::New();

  EXERCISE_BASIC_OBJECT_METHODS( filter, {{cookiecutter.filter_name}}, ImageToImageFilter );

  // Create input image to avoid test dependencies.
  ImageType::SizeType size;
  size.Fill( 128 );
  ImageType::Pointer image = ImageType::New();
  image->SetRegions( size );
  image->Allocate();
  image->FillBuffer(1.1f);

  ShowProgress::Pointer showProgress = ShowProgress::New();
  filter->AddObserver( itk::ProgressEvent(), showProgress );
  filter->SetInput(image);

  typedef itk::ImageFileWriter< ImageType > WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName( outputImageFileName );
  writer->SetInput( filter->GetOutput() );
  writer->SetUseCompression(true);

  TRY_EXPECT_NO_EXCEPTION( writer->Update() );

  return EXIT_SUCCESS;
}
<commit_msg>STYLE: Conform to the ITK SW Guide when reporting in tests.<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/

#include "itk{{cookiecutter.filter_name}}.h"

#include "itkCommand.h"
#include "itkImageFileWriter.h"
#include "itkTestingMacros.h"

namespace{
class ShowProgress : public itk::Command
{
public:
  itkNewMacro( ShowProgress );

  void
  Execute( itk::Object* caller, const itk::EventObject& event ) override
  {
    Execute( (const itk::Object*)caller, event );
  }

  void
  Execute( const itk::Object* caller, const itk::EventObject& event ) override
  {
    if ( !itk::ProgressEvent().CheckEvent( &event ) )
      {
      return;
      }
    const auto* processObject = dynamic_cast< const itk::ProcessObject* >( caller );
    if ( !processObject )
      {
      return;
      }
    std::cout << " " << processObject->GetProgress();
  }
};
}

int itk{{cookiecutter.filter_name}}Test( int argc, char * argv[] )
{
  if( argc < 2 )
    {
    std::cerr << "Missing parameters." << std::endl;
    std::cerr << "Usage: " << argv[0];
    std::cerr << " outputImage";
    std::cerr << std::endl;
    return EXIT_FAILURE;
    }
  const char * outputImageFileName  = argv[1];

  const unsigned int Dimension = 2;
  using PixelType = float;
  using ImageType = itk::Image< PixelType, Dimension >;

  using FilterType = itk::{{cookiecutter.filter_name}}< ImageType, ImageType >;
  FilterType::Pointer filter = FilterType::New();

  EXERCISE_BASIC_OBJECT_METHODS( filter, {{cookiecutter.filter_name}}, ImageToImageFilter );

  // Create input image to avoid test dependencies.
  ImageType::SizeType size;
  size.Fill( 128 );
  ImageType::Pointer image = ImageType::New();
  image->SetRegions( size );
  image->Allocate();
  image->FillBuffer(1.1f);

  ShowProgress::Pointer showProgress = ShowProgress::New();
  filter->AddObserver( itk::ProgressEvent(), showProgress );
  filter->SetInput(image);

  typedef itk::ImageFileWriter< ImageType > WriterType;
  WriterType::Pointer writer = WriterType::New();
  writer->SetFileName( outputImageFileName );
  writer->SetInput( filter->GetOutput() );
  writer->SetUseCompression(true);

  TRY_EXPECT_NO_EXCEPTION( writer->Update() );

  std::cout << "Test finished." << std::endl;
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <boost/noncopyable.hpp>
#include <boost/python.hpp>

#include <Box2D/Collision/Shapes/b2CircleShape.h>
#include <Box2D/Collision/Shapes/b2PolygonShape.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2Fixture.h>
#include <Box2D/Dynamics/b2World.h>
#include <Box2D/Dynamics/Contacts/b2Contact.h>
#include <Box2D/Dynamics/Joints/b2Joint.h>

using namespace boost::python;

b2Fixture* (b2Body::*b2BodyCreateFixture1)(const b2FixtureDef*) = &b2Body::CreateFixture;
b2Fixture* (b2Body::*b2BodyCreateFixture2)(const b2Shape*, float32) = &b2Body::CreateFixture;
b2Fixture* (b2Body::*b2BodyGetFixtureList)() = &b2Body::GetFixtureList;
b2JointEdge* (b2Body::*b2BodyGetJointList)() = &b2Body::GetJointList;
b2ContactEdge* (b2Body::*b2BodyGetContactList)() = &b2Body::GetContactList;
b2Body* (b2Body::*b2BodyGetNext)() = &b2Body::GetNext;
b2World* (b2Body::*b2BodyGetWorld)() = &b2Body::GetWorld;

BOOST_PYTHON_MODULE(box2d)
{
	class_<b2World>("World", init<const b2Vec2&, bool>())
        .def("create_body", &b2World::CreateBody, return_internal_reference<>())
		.def("destroy_body", &b2World::DestroyBody)
    ;

    class_<b2Vec2>("Vec2", init<float32, float32>())
        .def_readwrite("x", &b2Vec2::x)
        .def_readwrite("y", &b2Vec2::y)
    ;

	enum_<b2BodyType>("BodyType")
		.value("static_body", b2_staticBody)
		.value("kinematic_body", b2_kinematicBody)
		.value("dynamic_body", b2_dynamicBody)
		.export_values()
    ;

	class_<b2BodyDef>("BodyDef")
		.def_readwrite("user_data", &b2BodyDef::userData)
		.def_readwrite("position", &b2BodyDef::position)
		.def_readwrite("angle", &b2BodyDef::angle)
		.def_readwrite("linear_velocity", &b2BodyDef::linearVelocity)
		.def_readwrite("angular_velocity", &b2BodyDef::angularVelocity)
		.def_readwrite("linear_damping", &b2BodyDef::linearDamping)
		.def_readwrite("angular_damping", &b2BodyDef::angularDamping)
		.def_readwrite("allow_sleep", &b2BodyDef::allowSleep)
		.def_readwrite("awake", &b2BodyDef::awake)
		.def_readwrite("fixed_rotation", &b2BodyDef::fixedRotation)
		.def_readwrite("bullet", &b2BodyDef::bullet)
		.def_readwrite("type", &b2BodyDef::type)
		.def_readwrite("active", &b2BodyDef::active)
		.def_readwrite("inertia_scale", &b2BodyDef::inertiaScale)
	;

	class_<b2Body, boost::noncopyable>("Body", no_init)
		.def("CreateFixture", b2BodyCreateFixture1, return_internal_reference<>())
		.def("CreateFixture", b2BodyCreateFixture2, return_internal_reference<>())
		.def("DestroyFixture", &b2Body::DestroyFixture)
		.def("SetTransform", &b2Body::SetTransform)
		.def("GetTransform", &b2Body::GetTransform, return_value_policy<copy_const_reference>())
		.def("GetPosition", &b2Body::GetPosition, return_value_policy<copy_const_reference>())
		.def("GetAngle", &b2Body::GetAngle)
		.def("GetWorldCenter", &b2Body::GetWorldCenter, return_value_policy<copy_const_reference>())
		.def("GetLocalCenter", &b2Body::GetLocalCenter, return_value_policy<copy_const_reference>())
		.def("SetLinearVelocity", &b2Body::SetLinearVelocity)
		.def("GetLinearVelocity", &b2Body::GetLinearVelocity)
		.def("SetAngularVelocity", &b2Body::SetAngularVelocity)
		.def("GetAngularVelocity", &b2Body::GetAngularVelocity)
		.def("ApplyForce", &b2Body::ApplyForce)
		.def("ApplyTorque", &b2Body::ApplyTorque)
		// .def("ApplyImpulse", &b2Body::ApplyImpulse)
		.def("GetMass", &b2Body::GetMass)
		.def("GetInertia", &b2Body::GetInertia)
		.def("GetMassData", &b2Body::GetMassData)
		.def("SetMassData", &b2Body::SetMassData)
		.def("ResetMassData", &b2Body::ResetMassData)
		.def("GetWorldPoint", &b2Body::GetWorldPoint)
		.def("GetWorldVector", &b2Body::GetWorldVector)
		.def("GetLocalPoint", &b2Body::GetLocalPoint)
		.def("GetLocalVector", &b2Body::GetLocalVector)
		.def("GetLinearVelocityFromWorldPoint", &b2Body::GetLinearVelocityFromWorldPoint)
		.def("GetLinearVelocityFromLocalPoint", &b2Body::GetLinearVelocityFromLocalPoint)
		.def("GetLinearDamping", &b2Body::GetLinearDamping)
		.def("SetLinearDamping", &b2Body::SetLinearDamping)
		.def("GetAngularDamping", &b2Body::GetAngularDamping)
		.def("SetAngularDamping", &b2Body::SetAngularDamping)
		.def("SetType", &b2Body::SetType)
		.def("GetType", &b2Body::GetType)
		.def("SetBullet", &b2Body::SetBullet)
		.def("IsBullet", &b2Body::IsBullet)
		.def("SetSleepingAllowed", &b2Body::SetSleepingAllowed)
		.def("IsSleepingAllowed", &b2Body::IsSleepingAllowed)
		.def("SetAwake", &b2Body::SetAwake)
		.def("IsAwake", &b2Body::IsAwake)
		.def("SetActive", &b2Body::SetActive)
		.def("IsActive", &b2Body::IsActive)
		.def("SetFixedRotation", &b2Body::SetFixedRotation)
		.def("IsFixedRotation", &b2Body::IsFixedRotation)
		.def("GetFixtureList", b2BodyGetFixtureList, return_internal_reference<>())
		.def("GetJointList", b2BodyGetJointList, return_internal_reference<>())
		.def("GetContactList", b2BodyGetContactList, return_internal_reference<>())
		.def("GetNext", b2BodyGetNext, return_internal_reference<>())
		// .def("GetUserData", &b2Body::GetUserData)
		// .def("SetUserData", &b2Body::SetUserData)
		.def("GetWorld", b2BodyGetWorld, return_internal_reference<>())
	;

	class_<b2FixtureDef>("FixtureDef")
	;

	class_<b2Fixture, boost::noncopyable>("Fixture", no_init)
	;

	class_<b2CircleShape>("CircleShape")
	;

	class_<b2PolygonShape>("PolygonShape")
	;
}
<commit_msg>made wrapper declarations more pythonic<commit_after>#include <boost/noncopyable.hpp>
#include <boost/python.hpp>

#include <Box2D/Collision/Shapes/b2CircleShape.h>
#include <Box2D/Collision/Shapes/b2PolygonShape.h>
#include <Box2D/Dynamics/b2Body.h>
#include <Box2D/Dynamics/b2Fixture.h>
#include <Box2D/Dynamics/b2World.h>
#include <Box2D/Dynamics/Contacts/b2Contact.h>
#include <Box2D/Dynamics/Joints/b2Joint.h>

using namespace boost::python;

b2Fixture* (b2Body::*b2BodyCreateFixture1)(const b2FixtureDef*) = &b2Body::CreateFixture;
b2Fixture* (b2Body::*b2BodyCreateFixture2)(const b2Shape*, float32) = &b2Body::CreateFixture;
b2Fixture* (b2Body::*b2BodyGetFixtureList)() = &b2Body::GetFixtureList;
b2JointEdge* (b2Body::*b2BodyGetJointList)() = &b2Body::GetJointList;
b2ContactEdge* (b2Body::*b2BodyGetContactList)() = &b2Body::GetContactList;
b2Body* (b2Body::*b2BodyGetNext)() = &b2Body::GetNext;
b2World* (b2Body::*b2BodyGetWorld)() = &b2Body::GetWorld;

BOOST_PYTHON_MODULE(box2d)
{
	class_<b2World>("World", init<const b2Vec2&, bool>())
        .def("create_body", &b2World::CreateBody, return_internal_reference<>())
		.def("destroy_body", &b2World::DestroyBody)
    ;

    class_<b2Vec2>("Vec2", init<float32, float32>())
        .def_readwrite("x", &b2Vec2::x)
        .def_readwrite("y", &b2Vec2::y)
    ;

	enum_<b2BodyType>("BodyType")
		.value("static_body", b2_staticBody)
		.value("kinematic_body", b2_kinematicBody)
		.value("dynamic_body", b2_dynamicBody)
		.export_values()
    ;

	class_<b2BodyDef>("BodyDef")
		.def_readwrite("user_data", &b2BodyDef::userData)
		.def_readwrite("position", &b2BodyDef::position)
		.def_readwrite("angle", &b2BodyDef::angle)
		.def_readwrite("linear_velocity", &b2BodyDef::linearVelocity)
		.def_readwrite("angular_velocity", &b2BodyDef::angularVelocity)
		.def_readwrite("linear_damping", &b2BodyDef::linearDamping)
		.def_readwrite("angular_damping", &b2BodyDef::angularDamping)
		.def_readwrite("allow_sleep", &b2BodyDef::allowSleep)
		.def_readwrite("awake", &b2BodyDef::awake)
		.def_readwrite("fixed_rotation", &b2BodyDef::fixedRotation)
		.def_readwrite("bullet", &b2BodyDef::bullet)
		.def_readwrite("type", &b2BodyDef::type)
		.def_readwrite("active", &b2BodyDef::active)
		.def_readwrite("inertia_scale", &b2BodyDef::inertiaScale)
	;

	class_<b2Body, boost::noncopyable>("Body", no_init)
		.def("create_fixture", b2BodyCreateFixture1, return_internal_reference<>())
		.def("create_fixture", b2BodyCreateFixture2, return_internal_reference<>())
		.def("destroy_fixture", &b2Body::DestroyFixture)
		.add_property("transform", make_function(&b2Body::GetTransform, return_value_policy<copy_const_reference>()), &b2Body::SetTransform)
		.add_property("position", make_function(&b2Body::GetPosition, return_value_policy<copy_const_reference>()))
		.add_property("angle", &b2Body::GetAngle)
		.add_property("world_center", make_function(&b2Body::GetWorldCenter, return_value_policy<copy_const_reference>()))
		.add_property("local_center", make_function(&b2Body::GetLocalCenter, return_value_policy<copy_const_reference>()))
		.add_property("linear_velocity", &b2Body::GetLinearVelocity, &b2Body::SetLinearVelocity)
		.add_property("angular_velocity", &b2Body::GetAngularVelocity, &b2Body::SetAngularVelocity)
		.def("apply_force", &b2Body::ApplyForce)
		.def("apply_torque", &b2Body::ApplyTorque)
		// .def("ApplyImpulse", &b2Body::ApplyImpulse)
		.add_property("mass", &b2Body::GetMass)
		.add_property("inertia", &b2Body::GetInertia)
		.add_property("mass_data", &b2Body::GetMassData, &b2Body::SetMassData)
		.def("reset_mass_data", &b2Body::ResetMassData)
		.def("get_world_point", &b2Body::GetWorldPoint)
		.def("get_world_vector", &b2Body::GetWorldVector)
		.def("get_local_point", &b2Body::GetLocalPoint)
		.def("get_local_vector", &b2Body::GetLocalVector)
		.def("get_linear_velocity_from_world_point", &b2Body::GetLinearVelocityFromWorldPoint)
		.def("get_linear_velocity_from_local_point", &b2Body::GetLinearVelocityFromLocalPoint)
		.add_property("linear_damping", &b2Body::GetLinearDamping, &b2Body::SetLinearDamping)
		.add_property("angular_damping", &b2Body::GetAngularDamping, &b2Body::SetAngularDamping)
		.add_property("type", &b2Body::GetType, &b2Body::SetType)
		.add_property("bullet", &b2Body::IsBullet, &b2Body::SetBullet)
		.add_property("sleeping_allowed", &b2Body::IsSleepingAllowed, &b2Body::SetSleepingAllowed)
		.add_property("awake", &b2Body::IsAwake, &b2Body::SetAwake)
		.add_property("active", &b2Body::IsActive, &b2Body::SetActive)
		.add_property("fixed_rotation", &b2Body::IsFixedRotation, &b2Body::SetFixedRotation)
		.add_property("fixture_list", make_function(b2BodyGetFixtureList, return_internal_reference<>()))
		.add_property("joint_list", make_function(b2BodyGetJointList, return_internal_reference<>()))
		.add_property("contact_list", make_function(b2BodyGetContactList, return_internal_reference<>()))
		.add_property("next", make_function(b2BodyGetNext, return_internal_reference<>()))
		// .def("GetUserData", &b2Body::GetUserData)
		// .def("SetUserData", &b2Body::SetUserData)
		.add_property("world", make_function(b2BodyGetWorld, return_internal_reference<>()))
	;

	class_<b2FixtureDef>("FixtureDef")
	;

	class_<b2Fixture, boost::noncopyable>("Fixture", no_init)
	;

	class_<b2CircleShape>("CircleShape")
	;

	class_<b2PolygonShape>("PolygonShape")
	;
}
<|endoftext|>


<commit_before>// Copyright (c) 2013, Adam Simpkins
#include "keyboard_v2.h"

#include <avrpp/progmem.h>
#include <avrpp/usb_hid_keyboard.h>
#include <avrpp/util.h>

#include <util/delay.h>

#if 0
/*
 * Maltron's standard QWERTY layout used by recent (2013) 89-series keyboards
 */
static const uint8_t PROGMEM factory_key_table[18 * 8] = {
    // Row 0
    KEY_RIGHT, KEY_NONE, KEY_LEFT_GUI, KEY_BACKSLASH,
    KEY_LEFT_BRACE, KEY_MINUS, KEY_BACKSPACE, KEY_LEFT,
    // Row 1
    KEY_END, KEY_N, KEY_M, KEY_COMMA,
    KEY_PERIOD, KEY_QUOTE, KEY_RIGHT_SHIFT, KEY_NONE,
    // Row 2
    KEY_NONE, KEY_Y, KEY_U, KEY_I,
    KEY_O, KEY_P, KEY_MUTE, KEY_NONE,
    // Row 3
    KEY_NONE, KEY_F7, KEY_F8, KEY_F9,
    KEY_F10, KEY_F11, KEY_F12, KEY_NONE,
    // Row 4
    KEY_MENU, KEYPAD_MINUS, KEYPAD_1, KEYPAD_2,
    KEYPAD_3, KEYPAD_PLUS, KEY_RIGHT_ALT, KEY_NONE,
    // Row 5
    KEY_CAPS_LOCK, KEY_NUM_LOCK, KEYPAD_7, KEYPAD_8,
    KEYPAD_9, KEYPAD_ASTERIX, KEY_F14, KEY_NONE,
    // Row 6
    KEY_NONE, KEY_VOLUME_UP, KEY_A, KEY_S,
    KEY_D, KEY_F, KEY_G, KEY_ENTER,
    // Row 7
    KEY_NONE, KEY_ESC, KEY_1, KEY_2,
    KEY_3, KEY_4, KEY_5, KEY_NONE,
    // Row 8
    KEY_SPACE, KEY_DELETE, KEY_EQUAL, KEY_RIGHT_BRACE,
    KEY_SLASH, KEY_RIGHT_GUI, KEY_NONE, KEY_UP,
    // Row 9
    KEY_DOWN, KEY_H, KEY_J, KEY_K,
    KEY_L, KEY_SEMICOLON, KEY_VOLUME_DOWN, KEY_NONE,
    // Row 10
    KEY_NONE, KEY_6, KEY_7, KEY_8,
    KEY_9, KEY_0, KEY_TILDE, KEY_NONE,
    // Row 11
    KEY_PAGE_UP, KEYPAD_ENTER, KEYPAD_0, KEY_INSERT,
    KEY_BACKSPACE, KEYPAD_PERIOD, KEY_PAGE_DOWN, KEY_NONE,
    // Row 12
    KEY_F13, KEYPAD_EQUAL, KEYPAD_4, KEYPAD_5,
    KEYPAD_6, KEYPAD_SLASH, KEY_F15, KEY_NONE,
    // Row 13
    KEY_NONE, KEY_LEFT_SHIFT, KEY_Z, KEY_X,
    KEY_C, KEY_V, KEY_B, KEY_TAB,
    // Row 14
    KEY_NONE, KEY_NON_US_BACKSLASH, KEY_Q, KEY_W,
    KEY_E, KEY_R, KEY_T, KEY_NONE,
    // Row 15
    KEY_NONE, KEY_F1, KEY_F2, KEY_F3,
    KEY_F4, KEY_F5, KEY_F6, KEY_NONE,
    // Row 16
    KEY_ENTER, KEY_NONE, KEY_NONE, KEY_LEFT_CTRL,
    KEY_NONE, KEY_NONE, KEY_NONE, KEY_RIGHT_CTRL,
    // Row 17
    KEY_LEFT_ALT, KEY_NONE, KEY_NONE, KEY_NONE,
    KEY_RIGHT_ALT, KEY_NONE, KEY_NONE, KEY_HOME,
};
static const uint8_t PROGMEM factory_modifier_table[18 * 8] = {
    0, 0, MOD_LEFT_GUI, 0, 0, 0, 0, 0,  // Row 0
    0, 0, 0, 0, 0, 0, MOD_RIGHT_SHIFT, 0,  // Row 1
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 2
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 3
    0, 0, 0, 0, 0, 0, MOD_RIGHT_ALT, 0,  // Row 4
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 5
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 6
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 7
    0, 0, 0, 0, 0, MOD_RIGHT_GUI, 0, 0,  // Row 8
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 9
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 10
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 11
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 12
    0, MOD_LEFT_SHIFT, 0, 0, 0, 0, 0, 0,  // Row 13
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 14
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 15
    0, 0, 0, MOD_LEFT_CTRL, 0, 0, 0, MOD_RIGHT_CTRL,  // Row 16
    MOD_LEFT_ALT, 0, 0, 0, MOD_RIGHT_ALT, 0, 0, 0,  // Row 17
};
#endif

/*
 * My preferred keyboard layout
 */
static const uint8_t PROGMEM default_key_table[18 * 8] = {
    // Row 0
    KEY_TAB, KEY_NONE, KEY_HOME, KEY_BACKSLASH,
    KEY_LEFT_BRACE, KEY_MINUS, KEY_BACKSPACE, KEY_LEFT_GUI,
    // Row 1
    KEY_RIGHT, KEY_N, KEY_M, KEY_COMMA,
    KEY_PERIOD, KEY_QUOTE, KEY_RIGHT_SHIFT, KEY_NONE,
    // Row 2
    KEY_NONE, KEY_Y, KEY_U, KEY_I,
    KEY_O, KEY_P, KEY_RIGHT_GUI, KEY_NONE,
    // Row 3
    KEY_NONE, KEY_F7, KEY_F8, KEY_F9,
    KEY_F10, KEY_F11, KEY_F12, KEY_NONE,
    // Row 4
    KEY_APPLICATION, KEYPAD_MINUS, KEYPAD_1, KEYPAD_2,
    KEYPAD_3, KEYPAD_PLUS, KEY_RIGHT_ALT, KEY_NONE,
    // Row 5
    KEY_CAPS_LOCK, KEY_NUM_LOCK, KEYPAD_7, KEYPAD_8,
    KEYPAD_9, KEYPAD_ASTERIX, KEY_F14, KEY_NONE,
    // Row 6
    KEY_NONE, KEY_LEFT_CTRL, KEY_A, KEY_S,
    KEY_D, KEY_F, KEY_G, KEY_ENTER,
    // Row 7
    KEY_NONE, KEY_MENU, KEY_1, KEY_2,
    KEY_3, KEY_4, KEY_5, KEY_NONE,
    // Row 8
    KEY_SPACE, KEY_DELETE, KEY_EQUAL, KEY_RIGHT_BRACE,
    KEY_SLASH, KEY_END, KEY_NONE, KEY_UP,
    // Row 9
    KEY_DOWN, KEY_H, KEY_J, KEY_K,
    KEY_L, KEY_SEMICOLON, KEY_RIGHT_CTRL, KEY_NONE,
    // Row 10
    KEY_NONE, KEY_6, KEY_7, KEY_8,
    KEY_9, KEY_0, KEY_TILDE, KEY_NONE,
    // Row 11
    KEY_PAGE_UP, KEYPAD_ENTER, KEYPAD_0, KEY_INSERT,
    KEY_BACKSPACE, KEYPAD_PERIOD, KEY_PAGE_DOWN, KEY_NONE,
    // Row 12
    KEY_F13, KEYPAD_EQUAL, KEYPAD_4, KEYPAD_5,
    KEYPAD_6, KEYPAD_SLASH, KEY_F15, KEY_NONE,
    // Row 13
    KEY_NONE, KEY_LEFT_SHIFT, KEY_Z, KEY_X,
    KEY_C, KEY_V, KEY_B, KEY_ESC,
    // Row 14
    KEY_NONE, KEY_RIGHT_ALT, KEY_Q, KEY_W,
    KEY_E, KEY_R, KEY_T, KEY_NONE,
    // Row 15
    KEY_NONE, KEY_F1, KEY_F2, KEY_F3,
    KEY_F4, KEY_F5, KEY_F6, KEY_NONE,
    // Row 16
    KEY_ENTER, KEY_NONE, KEY_NONE, KEY_VOLUME_UP,
    KEY_NONE, KEY_NONE, KEY_NONE, KEY_VOLUME_DOWN,
    // Row 17
    KEY_LEFT_ALT, KEY_NONE, KEY_NONE, KEY_NONE,
    KEY_MUTE, KEY_NONE, KEY_NONE, KEY_LEFT,
};
static const uint8_t PROGMEM default_modifier_table[18 * 8] = {
    0, 0, 0, 0, 0, 0, 0, MOD_LEFT_GUI,  // Row 0
    0, 0, 0, 0, 0, 0, MOD_RIGHT_SHIFT, 0,  // Row 1
    0, 0, 0, 0, 0, 0, MOD_RIGHT_GUI, 0,  // Row 2
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 3
    0, 0, 0, 0, 0, 0, MOD_RIGHT_ALT, 0,  // Row 4
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 5
    0, MOD_LEFT_CTRL, 0, 0, 0, 0, 0, 0,  // Row 6
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 7
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 8
    0, 0, 0, 0, 0, 0, MOD_RIGHT_CTRL, 0,  // Row 9
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 10
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 11
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 12
    0, MOD_LEFT_SHIFT, 0, 0, 0, 0, 0, 0,  // Row 13
    0, MOD_RIGHT_ALT, 0, 0, 0, 0, 0, 0,  // Row 14
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 15
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 16
    MOD_LEFT_ALT, 0, 0, 0, 0, 0, 0, 0,  // Row 17
};

void
KeyboardV2::prepareLoop() {
    // Set LEDs to output, high (which is off for my LEDs)
    DDRC = 0x3f;
    PORTC = 0xff;

    // Set columns to output, low
    DDRB = 0xff;
    PORTB = 0x00;

    // Set rows to input, with pull-up resistors
    DDRD = 0x00;
    PORTD = 0xff;
    DDRF = 0x00;
    PORTF = 0xff;
    DDRE = 0x00;
    PORTE = 0xc0;

    _numCols = 8;
    _keyTable = default_key_table;
    _modifierTable = default_modifier_table;
}

void
KeyboardV2::scanImpl() {
    for (uint8_t col = 0; col < 8; ++col) {
        // Turn the specified column pin into an output pin, and bring it low.
        //
        // It is important that the other column pins are configured as inputs.
        // If multiple keys are pressed down, they may create a circuit
        // connecting to other column pins as well.  We don't want an output
        // voltage on these pins to affect our reading on the column currently
        // being scanned.
        DDRB = 0x01 << col;
        PORTB = 0xff & ~(0x01 << col);

        // We need a very brief delay here to allow the signal
        // to propagate to the input pins.
        _delay_us(5);

        // Read which row pins are active
        uint8_t d = ~PIND;
        uint8_t f = ~PINF;
        uint8_t e = ~PINE;

        if (UNLIKELY(d)) {
            for (uint8_t n = 0; n < 8; ++n) {
                if (d & (0x1 << n)) {
                    keyPressed(col, n);
                }
            }
        }
        if (UNLIKELY(f)) {
            for (uint8_t n = 0; n < 8; ++n) {
                if (f & (0x1 << n)) {
                    keyPressed(col, n + 8);
                }
            }
        }
        if (e & 0x40) {
            keyPressed(col, 16);
        }
        if (e & 0x80) {
            keyPressed(col, 17);
        }
    }
    DDRB = 0x00;
    PORTB = 0xff;
}
<commit_msg>[kbd_v2] Delete the factory standard keyboard layout<commit_after>// Copyright (c) 2013, Adam Simpkins
#include "keyboard_v2.h"

#include <avrpp/progmem.h>
#include <avrpp/usb_hid_keyboard.h>
#include <avrpp/util.h>

#include <util/delay.h>

static const uint8_t PROGMEM default_key_table[18 * 8] = {
    // Row 0
    KEY_TAB, KEY_NONE, KEY_HOME, KEY_BACKSLASH,
    KEY_LEFT_BRACE, KEY_MINUS, KEY_BACKSPACE, KEY_LEFT_GUI,
    // Row 1
    KEY_RIGHT, KEY_N, KEY_M, KEY_COMMA,
    KEY_PERIOD, KEY_QUOTE, KEY_RIGHT_SHIFT, KEY_NONE,
    // Row 2
    KEY_NONE, KEY_Y, KEY_U, KEY_I,
    KEY_O, KEY_P, KEY_RIGHT_GUI, KEY_NONE,
    // Row 3
    KEY_NONE, KEY_F7, KEY_F8, KEY_F9,
    KEY_F10, KEY_F11, KEY_F12, KEY_NONE,
    // Row 4
    KEY_APPLICATION, KEYPAD_MINUS, KEYPAD_1, KEYPAD_2,
    KEYPAD_3, KEYPAD_PLUS, KEY_RIGHT_ALT, KEY_NONE,
    // Row 5
    KEY_CAPS_LOCK, KEY_NUM_LOCK, KEYPAD_7, KEYPAD_8,
    KEYPAD_9, KEYPAD_ASTERIX, KEY_F14, KEY_NONE,
    // Row 6
    KEY_NONE, KEY_LEFT_CTRL, KEY_A, KEY_S,
    KEY_D, KEY_F, KEY_G, KEY_ENTER,
    // Row 7
    KEY_NONE, KEY_MENU, KEY_1, KEY_2,
    KEY_3, KEY_4, KEY_5, KEY_NONE,
    // Row 8
    KEY_SPACE, KEY_DELETE, KEY_EQUAL, KEY_RIGHT_BRACE,
    KEY_SLASH, KEY_END, KEY_NONE, KEY_UP,
    // Row 9
    KEY_DOWN, KEY_H, KEY_J, KEY_K,
    KEY_L, KEY_SEMICOLON, KEY_RIGHT_CTRL, KEY_NONE,
    // Row 10
    KEY_NONE, KEY_6, KEY_7, KEY_8,
    KEY_9, KEY_0, KEY_TILDE, KEY_NONE,
    // Row 11
    KEY_PAGE_UP, KEYPAD_ENTER, KEYPAD_0, KEY_INSERT,
    KEY_BACKSPACE, KEYPAD_PERIOD, KEY_PAGE_DOWN, KEY_NONE,
    // Row 12
    KEY_F13, KEYPAD_EQUAL, KEYPAD_4, KEYPAD_5,
    KEYPAD_6, KEYPAD_SLASH, KEY_F15, KEY_NONE,
    // Row 13
    KEY_NONE, KEY_LEFT_SHIFT, KEY_Z, KEY_X,
    KEY_C, KEY_V, KEY_B, KEY_ESC,
    // Row 14
    KEY_NONE, KEY_RIGHT_ALT, KEY_Q, KEY_W,
    KEY_E, KEY_R, KEY_T, KEY_NONE,
    // Row 15
    KEY_NONE, KEY_F1, KEY_F2, KEY_F3,
    KEY_F4, KEY_F5, KEY_F6, KEY_NONE,
    // Row 16
    KEY_ENTER, KEY_NONE, KEY_NONE, KEY_VOLUME_UP,
    KEY_NONE, KEY_NONE, KEY_NONE, KEY_VOLUME_DOWN,
    // Row 17
    KEY_LEFT_ALT, KEY_NONE, KEY_NONE, KEY_NONE,
    KEY_MUTE, KEY_NONE, KEY_NONE, KEY_LEFT,
};
static const uint8_t PROGMEM default_modifier_table[18 * 8] = {
    0, 0, 0, 0, 0, 0, 0, MOD_LEFT_GUI,  // Row 0
    0, 0, 0, 0, 0, 0, MOD_RIGHT_SHIFT, 0,  // Row 1
    0, 0, 0, 0, 0, 0, MOD_RIGHT_GUI, 0,  // Row 2
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 3
    0, 0, 0, 0, 0, 0, MOD_RIGHT_ALT, 0,  // Row 4
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 5
    0, MOD_LEFT_CTRL, 0, 0, 0, 0, 0, 0,  // Row 6
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 7
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 8
    0, 0, 0, 0, 0, 0, MOD_RIGHT_CTRL, 0,  // Row 9
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 10
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 11
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 12
    0, MOD_LEFT_SHIFT, 0, 0, 0, 0, 0, 0,  // Row 13
    0, MOD_RIGHT_ALT, 0, 0, 0, 0, 0, 0,  // Row 14
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 15
    0, 0, 0, 0, 0, 0, 0, 0,  // Row 16
    MOD_LEFT_ALT, 0, 0, 0, 0, 0, 0, 0,  // Row 17
};

void
KeyboardV2::prepareLoop() {
    // Set LEDs to output, high (which is off for my LEDs)
    DDRC = 0x3f;
    PORTC = 0xff;

    // Set columns to output, low
    DDRB = 0xff;
    PORTB = 0x00;

    // Set rows to input, with pull-up resistors
    DDRD = 0x00;
    PORTD = 0xff;
    DDRF = 0x00;
    PORTF = 0xff;
    DDRE = 0x00;
    PORTE = 0xc0;

    _numCols = 8;
    _keyTable = default_key_table;
    _modifierTable = default_modifier_table;
}

void
KeyboardV2::scanImpl() {
    for (uint8_t col = 0; col < 8; ++col) {
        // Turn the specified column pin into an output pin, and bring it low.
        //
        // It is important that the other column pins are configured as inputs.
        // If multiple keys are pressed down, they may create a circuit
        // connecting to other column pins as well.  We don't want an output
        // voltage on these pins to affect our reading on the column currently
        // being scanned.
        DDRB = 0x01 << col;
        PORTB = 0xff & ~(0x01 << col);

        // We need a very brief delay here to allow the signal
        // to propagate to the input pins.
        _delay_us(5);

        // Read which row pins are active
        uint8_t d = ~PIND;
        uint8_t f = ~PINF;
        uint8_t e = ~PINE;

        if (UNLIKELY(d)) {
            for (uint8_t n = 0; n < 8; ++n) {
                if (d & (0x1 << n)) {
                    keyPressed(col, n);
                }
            }
        }
        if (UNLIKELY(f)) {
            for (uint8_t n = 0; n < 8; ++n) {
                if (f & (0x1 << n)) {
                    keyPressed(col, n + 8);
                }
            }
        }
        if (e & 0x40) {
            keyPressed(col, 16);
        }
        if (e & 0x80) {
            keyPressed(col, 17);
        }
    }
    DDRB = 0x00;
    PORTB = 0xff;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/kernel/bltohbdatamgr.C $                                  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include <kernel/bltohbdatamgr.H>
#include <util/align.H>
#include <kernel/console.H>
#include <assert.h>
#include <arch/memorymap.H>
#include <bootloader/bootloaderif.H>

// Global and only BlToHbDataManager instance
BlToHbDataManager g_BlToHbDataManager;

////////////////////////////////////////////////////////////////////////////////
//--------------------------------- Private ----------------------------------//
////////////////////////////////////////////////////////////////////////////////

// Set static variables to control use
Bootloader::BlToHbData BlToHbDataManager::iv_data;
bool BlToHbDataManager::iv_instantiated = false;
bool BlToHbDataManager::iv_initialized = false;
bool BlToHbDataManager::iv_dataValid = false;
size_t BlToHbDataManager::iv_preservedSize = 0;

void BlToHbDataManager::validAssert() const
{
    if(!iv_dataValid)
    {
        printk("E> BlToHbDataManager is invalid, cannot access\n");
        kassert(iv_dataValid);
    }
}

void BlToHbDataManager::print() const
{
    printkd("\nBlToHbData (all addr HRMOR relative):\n");

    if(iv_data.version >= Bootloader::BLTOHB_SAB)
    {
        printkd("-- secureSettings: SAB=%d, SecOvrd=%d, AllowAttrOvrd=%d\n",
                iv_data.secureAccessBit, iv_data.securityOverride,
                iv_data.allowAttrOverrides);
    }
    if(iv_dataValid)
    {
        printkd("-- eyeCatch = 0x%lX (%s)\n", iv_data.eyeCatch,
                                    reinterpret_cast<char*>(&iv_data.eyeCatch));
        printkd("-- version = 0x%lX\n", iv_data.version);
        printkd("-- branchtableOffset = 0x%lX\n", iv_data.branchtableOffset);
        printkd("-- SecureRom Addr = 0x%lX Size = 0x%lX\n", getSecureRomAddr(),
               iv_data.secureRomSize);
        printkd("-- HW keys' Hash Addr = 0x%lX Size = 0x%lX\n",
                getHwKeysHashAddr(),
                iv_data.hwKeysHashSize);
        printkd("-- HBB header Addr = 0x%lX Size = 0x%lX\n", getHbbHeaderAddr(),
               iv_data.hbbHeaderSize);
        printkd("-- Reserved Size = 0x%lX\n", iv_preservedSize);
        printkd("\n");
    }
}

////////////////////////////////////////////////////////////////////////////////
//---------------------------------- Public ----------------------------------//
////////////////////////////////////////////////////////////////////////////////

BlToHbDataManager::BlToHbDataManager()
{
    // Allow only one instantiation
    if (iv_instantiated)
    {
        printk("E> A BlToHbDataManager class instance already exists\n");
        kassert(!iv_instantiated);
    }
    iv_instantiated = true;
}

void BlToHbDataManager::initValid (const Bootloader::BlToHbData& i_data)
{
    // Allow only one initializer call
    if (iv_initialized)
    {
        printk("E> BlToHbDataManager class previously initialized\n");
        kassert(!iv_initialized);
    }

    // Simple assertion checks
    kassert(i_data.eyeCatch>0);
    kassert(i_data.version>0);
    kassert(i_data.branchtableOffset>0);
    kassert(i_data.secureRom!=nullptr);
    kassert(i_data.hwKeysHash!=nullptr);
    kassert(i_data.hbbHeader!=nullptr);
    kassert(i_data.secureRomSize>0);
    kassert(i_data.hwKeysHashSize>0);
    kassert(i_data.hbbHeaderSize>0);

    // Set internal static data
    iv_data.eyeCatch = i_data.eyeCatch;
    iv_data.version = i_data.version;
    iv_data.branchtableOffset = i_data.branchtableOffset;
    iv_data.secureRom = i_data.secureRom;
    iv_data.secureRomSize = i_data.secureRomSize;
    iv_data.hwKeysHash = i_data.hwKeysHash;
    iv_data.hwKeysHashSize = i_data.hwKeysHashSize;
    iv_data.hbbHeader = i_data.hbbHeader;
    iv_data.hbbHeaderSize = i_data.hbbHeaderSize;

printk("Version=%lX\n",i_data.version);
    // Ensure Bootloader to HB structure has the Secure Settings
    if(iv_data.version >= Bootloader::BLTOHB_SAB)
    {
        iv_data.secureAccessBit = i_data.secureAccessBit;
    }

    if(iv_data.version >= Bootloader::BLTOHB_SECURE_OVERRIDES)
    {
        iv_data.securityOverride   = i_data.securityOverride;
        iv_data.allowAttrOverrides = i_data.allowAttrOverrides;
    }
    else
    {
        iv_data.securityOverride   = 0;
        iv_data.allowAttrOverrides = 0;
    }

    // Ensure Bootloader to HB structure has the MMIO members
    if( iv_data.version >= Bootloader::BLTOHB_MMIOBARS )
    {
printk("lpc=%lX, xscom=%lX\n", i_data.lpcBAR, i_data.xscomBAR );
        kassert(i_data.lpcBAR>0);
        kassert(i_data.xscomBAR>0);
        iv_data.lpcBAR = i_data.lpcBAR;
        iv_data.xscomBAR = i_data.xscomBAR;
    }
    else
    {
        //default to group0-proc0 values for down-level SBE
        iv_data.lpcBAR = MMIO_GROUP0_CHIP0_LPC_BASE_ADDR;
        iv_data.xscomBAR = MMIO_GROUP0_CHIP0_XSCOM_BASE_ADDR;

    }

    //@fixme-RTC:149250-Remove this hack
    iv_data.lpcBAR = MMIO_GROUP0_CHIP0_LPC_BASE_ADDR;
    iv_data.xscomBAR = MMIO_GROUP0_CHIP0_XSCOM_BASE_ADDR;
    printk( "Use default LPC/XSCOM\n" );

    // Size of data that needs to be preserved and pinned.
    iv_preservedSize = ALIGN_PAGE(iv_data.secureRomSize +
                                 iv_data.hwKeysHashSize +
                                 iv_data.hbbHeaderSize );
    iv_initialized = true;
    iv_dataValid = true;
    print();
}

void BlToHbDataManager::initInvalid ()
{
    printkd("BlToHbDataManager::initInvalid\n");
    // Allow only one initializer call
    if (iv_initialized)
    {
        printk("E> BlToHbDataManager class previously initialized\n");
        kassert(!iv_initialized);
    }

    //default to group0-proc0 values for down-level SBE
    iv_data.lpcBAR = MMIO_GROUP0_CHIP0_LPC_BASE_ADDR;
    iv_data.xscomBAR = MMIO_GROUP0_CHIP0_XSCOM_BASE_ADDR;

    iv_initialized = true;
    iv_dataValid = false;
    print();
}

const uint64_t BlToHbDataManager::getBranchtableOffset() const
{
    validAssert();
    return iv_data.branchtableOffset;
}

const void* BlToHbDataManager::getSecureRom() const
{
    validAssert();
    return iv_data.secureRom;
}

const uint64_t BlToHbDataManager::getSecureRomAddr() const
{
    validAssert();
    return reinterpret_cast<uint64_t>(iv_data.secureRom);
}

const size_t BlToHbDataManager::getSecureRomSize() const
{
    validAssert();
    return iv_data.secureRomSize;
}

const void* BlToHbDataManager::getHwKeysHash() const
{
    validAssert();
    return iv_data.hwKeysHash;
}

const uint64_t BlToHbDataManager::getHwKeysHashAddr() const
{
    validAssert();
    return reinterpret_cast<uint64_t>(iv_data.hwKeysHash);
}

const size_t BlToHbDataManager::getHwKeysHashSize() const
{
    validAssert();
    return iv_data.hwKeysHashSize;
}

const void* BlToHbDataManager::getHbbHeader() const
{
    validAssert();
    return iv_data.hbbHeader;
}

const uint64_t BlToHbDataManager::getHbbHeaderAddr() const
{
    validAssert();
    return reinterpret_cast<uint64_t>(iv_data.hbbHeader);
}

const size_t BlToHbDataManager::getHbbHeaderSize() const
{
    validAssert();
    return iv_data.hbbHeaderSize;
}

const bool BlToHbDataManager::getSecureAccessBit() const
{
    validAssert();
    return iv_data.secureAccessBit;
}

const bool BlToHbDataManager::getSecurityOverride() const
{
    validAssert();
    return iv_data.securityOverride;
}

const bool BlToHbDataManager::getAllowAttrOverrides() const
{
    validAssert();
    return iv_data.allowAttrOverrides;
}

const size_t BlToHbDataManager::getPreservedSize() const
{
    validAssert();
    return iv_preservedSize;
}

const bool BlToHbDataManager::isValid() const
{
    return iv_dataValid;
}

const uint64_t BlToHbDataManager::getLpcBAR() const
{
    return reinterpret_cast<uint64_t>(iv_data.lpcBAR);
}

const uint64_t BlToHbDataManager::getXscomBAR() const
{
    return reinterpret_cast<uint64_t>(iv_data.xscomBAR);
}

<commit_msg>Remove asserts on variables that have valid default values<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/kernel/bltohbdatamgr.C $                                  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include <kernel/bltohbdatamgr.H>
#include <util/align.H>
#include <kernel/console.H>
#include <assert.h>
#include <arch/memorymap.H>
#include <bootloader/bootloaderif.H>

// Global and only BlToHbDataManager instance
BlToHbDataManager g_BlToHbDataManager;

////////////////////////////////////////////////////////////////////////////////
//--------------------------------- Private ----------------------------------//
////////////////////////////////////////////////////////////////////////////////

// Set static variables to control use
Bootloader::BlToHbData BlToHbDataManager::iv_data;
bool BlToHbDataManager::iv_instantiated = false;
bool BlToHbDataManager::iv_initialized = false;
bool BlToHbDataManager::iv_dataValid = false;
size_t BlToHbDataManager::iv_preservedSize = 0;

void BlToHbDataManager::validAssert() const
{
    if(!iv_dataValid)
    {
        printk("E> BlToHbDataManager is invalid, cannot access\n");
        kassert(iv_dataValid);
    }
}

void BlToHbDataManager::print() const
{
    if(iv_dataValid)
    {
        printkd("\nBlToHbData (all addr HRMOR relative):\n");
        if(iv_data.version >= Bootloader::BLTOHB_SAB)
        {
            printkd("-- secureSettings: SAB=%d, SecOvrd=%d, AllowAttrOvrd=%d\n",
                    iv_data.secureAccessBit, iv_data.securityOverride,
                    iv_data.allowAttrOverrides);
        }

        printkd("-- eyeCatch = 0x%lX (%s)\n", iv_data.eyeCatch,
                                    reinterpret_cast<char*>(&iv_data.eyeCatch));
        printkd("-- version = 0x%lX\n", iv_data.version);
        printkd("-- branchtableOffset = 0x%lX\n", iv_data.branchtableOffset);
        printkd("-- SecureRom Addr = 0x%lX Size = 0x%lX\n", getSecureRomAddr(),
               iv_data.secureRomSize);
        printkd("-- HW keys' Hash Addr = 0x%lX Size = 0x%lX\n",
                getHwKeysHashAddr(),
                iv_data.hwKeysHashSize);
        printkd("-- HBB header Addr = 0x%lX Size = 0x%lX\n", getHbbHeaderAddr(),
               iv_data.hbbHeaderSize);
        printkd("-- Reserved Size = 0x%lX\n", iv_preservedSize);
        printkd("\n");
    }
}

////////////////////////////////////////////////////////////////////////////////
//---------------------------------- Public ----------------------------------//
////////////////////////////////////////////////////////////////////////////////

BlToHbDataManager::BlToHbDataManager()
{
    // Allow only one instantiation
    if (iv_instantiated)
    {
        printk("E> A BlToHbDataManager class instance already exists\n");
        kassert(!iv_instantiated);
    }
    iv_instantiated = true;
}

void BlToHbDataManager::initValid (const Bootloader::BlToHbData& i_data)
{
    // Allow only one initializer call
    if (iv_initialized)
    {
        printk("E> BlToHbDataManager class previously initialized\n");
        kassert(!iv_initialized);
    }

    // Simple assertion checks
    kassert(i_data.eyeCatch>0);
    kassert(i_data.version>0);
    kassert(i_data.branchtableOffset>0);
    kassert(i_data.secureRom!=nullptr);
    kassert(i_data.hwKeysHash!=nullptr);
    kassert(i_data.hbbHeader!=nullptr);
    kassert(i_data.secureRomSize>0);
    kassert(i_data.hwKeysHashSize>0);
    kassert(i_data.hbbHeaderSize>0);

    // Set internal static data
    iv_data.eyeCatch = i_data.eyeCatch;
    iv_data.version = i_data.version;
    iv_data.branchtableOffset = i_data.branchtableOffset;
    iv_data.secureRom = i_data.secureRom;
    iv_data.secureRomSize = i_data.secureRomSize;
    iv_data.hwKeysHash = i_data.hwKeysHash;
    iv_data.hwKeysHashSize = i_data.hwKeysHashSize;
    iv_data.hbbHeader = i_data.hbbHeader;
    iv_data.hbbHeaderSize = i_data.hbbHeaderSize;

printk("Version=%lX\n",i_data.version);
    // Ensure Bootloader to HB structure has the Secure Settings
    if(iv_data.version >= Bootloader::BLTOHB_SAB)
    {
        iv_data.secureAccessBit = i_data.secureAccessBit;
    }

    if(iv_data.version >= Bootloader::BLTOHB_SECURE_OVERRIDES)
    {
        iv_data.securityOverride   = i_data.securityOverride;
        iv_data.allowAttrOverrides = i_data.allowAttrOverrides;
    }
    else
    {
        iv_data.securityOverride   = 0;
        iv_data.allowAttrOverrides = 0;
    }

    // Ensure Bootloader to HB structure has the MMIO members
    if( iv_data.version >= Bootloader::BLTOHB_MMIOBARS )
    {
printk("lpc=%lX, xscom=%lX\n", i_data.lpcBAR, i_data.xscomBAR );
        kassert(i_data.lpcBAR>0);
        kassert(i_data.xscomBAR>0);
        iv_data.lpcBAR = i_data.lpcBAR;
        iv_data.xscomBAR = i_data.xscomBAR;
    }
    else
    {
        //default to group0-proc0 values for down-level SBE
        iv_data.lpcBAR = MMIO_GROUP0_CHIP0_LPC_BASE_ADDR;
        iv_data.xscomBAR = MMIO_GROUP0_CHIP0_XSCOM_BASE_ADDR;

    }

    //@fixme-RTC:149250-Remove this hack
    iv_data.lpcBAR = MMIO_GROUP0_CHIP0_LPC_BASE_ADDR;
    iv_data.xscomBAR = MMIO_GROUP0_CHIP0_XSCOM_BASE_ADDR;
    printk( "Use default LPC/XSCOM\n" );

    // Size of data that needs to be preserved and pinned.
    iv_preservedSize = ALIGN_PAGE(iv_data.secureRomSize +
                                 iv_data.hwKeysHashSize +
                                 iv_data.hbbHeaderSize );
    iv_initialized = true;
    iv_dataValid = true;
    print();
}

void BlToHbDataManager::initInvalid ()
{
    printkd("BlToHbDataManager::initInvalid\n");
    // Allow only one initializer call
    if (iv_initialized)
    {
        printk("E> BlToHbDataManager class previously initialized\n");
        kassert(!iv_initialized);
    }

    //default to group0-proc0 values for down-level SBE
    iv_data.lpcBAR = MMIO_GROUP0_CHIP0_LPC_BASE_ADDR;
    iv_data.xscomBAR = MMIO_GROUP0_CHIP0_XSCOM_BASE_ADDR;

    iv_initialized = true;
    iv_dataValid = false;
    print();
}

const uint64_t BlToHbDataManager::getBranchtableOffset() const
{
    return iv_data.branchtableOffset;
}

const void* BlToHbDataManager::getSecureRom() const
{
    validAssert();
    return iv_data.secureRom;
}

const uint64_t BlToHbDataManager::getSecureRomAddr() const
{
    validAssert();
    return reinterpret_cast<uint64_t>(iv_data.secureRom);
}

const size_t BlToHbDataManager::getSecureRomSize() const
{
    return iv_data.secureRomSize;
}

const void* BlToHbDataManager::getHwKeysHash() const
{
    validAssert();
    return iv_data.hwKeysHash;
}

const uint64_t BlToHbDataManager::getHwKeysHashAddr() const
{
    validAssert();
    return reinterpret_cast<uint64_t>(iv_data.hwKeysHash);
}

const size_t BlToHbDataManager::getHwKeysHashSize() const
{
    return iv_data.hwKeysHashSize;
}

const void* BlToHbDataManager::getHbbHeader() const
{
    validAssert();
    return iv_data.hbbHeader;
}

const uint64_t BlToHbDataManager::getHbbHeaderAddr() const
{
    validAssert();
    return reinterpret_cast<uint64_t>(iv_data.hbbHeader);
}

const size_t BlToHbDataManager::getHbbHeaderSize() const
{
    return iv_data.hbbHeaderSize;
}

const bool BlToHbDataManager::getSecureAccessBit() const
{
    return iv_data.secureAccessBit;
}

const bool BlToHbDataManager::getSecurityOverride() const
{
    return iv_data.securityOverride;
}

const bool BlToHbDataManager::getAllowAttrOverrides() const
{
    return iv_data.allowAttrOverrides;
}

const size_t BlToHbDataManager::getPreservedSize() const
{
    return iv_preservedSize;
}

const bool BlToHbDataManager::isValid() const
{
    return iv_dataValid;
}

const uint64_t BlToHbDataManager::getLpcBAR() const
{
    return reinterpret_cast<uint64_t>(iv_data.lpcBAR);
}

const uint64_t BlToHbDataManager::getXscomBAR() const
{
    return reinterpret_cast<uint64_t>(iv_data.xscomBAR);
}

<|endoftext|>


<commit_before>/*
  Q Light Controller - Unit tests
  qlcphysical_test.cpp

  Copyright (C) Heikki Junnila

  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.txt

  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.
*/

#include <QtTest>
#include <QtXml>

#include "qlcphysical_test.h"
#include "qlcphysical.h"

void QLCPhysical_Test::bulbType()
{
    QVERIFY(p.bulbType().isEmpty());
    p.setBulbType("BulbType");
    QVERIFY(p.bulbType() == "BulbType");
}

void QLCPhysical_Test::bulbLumens()
{
    QVERIFY(p.bulbLumens() == 0);
    p.setBulbLumens(10000);
    QVERIFY(p.bulbLumens() == 10000);
}

void QLCPhysical_Test::bulbColourTemp()
{
    QVERIFY(p.bulbColourTemperature() == 0);
    p.setBulbColourTemperature(3200);
    QVERIFY(p.bulbColourTemperature() == 3200);
}

void QLCPhysical_Test::weight()
{
    QVERIFY(p.weight() == 0);
    p.setWeight(7);
    QVERIFY(p.weight() == 7);
    p.setWeight(5.02837);
    QCOMPARE(p.weight(), 5.02837);
}

void QLCPhysical_Test::width()
{
    QVERIFY(p.width() == 0);
    p.setWidth(600);
    QVERIFY(p.width() == 600);
}

void QLCPhysical_Test::height()
{
    QVERIFY(p.height() == 0);
    p.setHeight(1200);
    QVERIFY(p.height() == 1200);
}

void QLCPhysical_Test::depth()
{
    QVERIFY(p.depth() == 0);
    p.setDepth(250);
    QVERIFY(p.depth() == 250);
}

void QLCPhysical_Test::lensName()
{
    QVERIFY(p.lensName() == "Other");
    p.setLensName("Fresnel");
    QVERIFY(p.lensName() == "Fresnel");
}

void QLCPhysical_Test::lensDegreesMin()
{
    QVERIFY(p.lensDegreesMin() == 0);
    p.setLensDegreesMin(9.4);
    QVERIFY(p.lensDegreesMin() == 9.4);
}

void QLCPhysical_Test::lensDegreesMax()
{
    QVERIFY(p.lensDegreesMax() == 0);
    p.setLensDegreesMax(40.5);
    QVERIFY(p.lensDegreesMax() == 40.5);
}

void QLCPhysical_Test::focusType()
{
    QVERIFY(p.focusType() == "Fixed");
    p.setFocusType("Head");
    QVERIFY(p.focusType() == "Head");
}

void QLCPhysical_Test::focusPanMax()
{
    QVERIFY(p.focusPanMax() == 0);
    p.setFocusPanMax(540);
    QVERIFY(p.focusPanMax() == 540);
}

void QLCPhysical_Test::focusTiltMax()
{
    QVERIFY(p.focusTiltMax() == 0);
    p.setFocusTiltMax(270);
    QVERIFY(p.focusTiltMax() == 270);
}
void QLCPhysical_Test::powerConsumption()
{
    QVERIFY(p.powerConsumption() == 0);
    p.setPowerConsumption(24000);
    QVERIFY(p.powerConsumption() == 24000);
}
void QLCPhysical_Test::dmxConnector()
{
    QVERIFY(p.dmxConnector() == "5-pin");
    p.setDmxConnector("3-pin");
    QVERIFY(p.dmxConnector() == "3-pin");
}

void QLCPhysical_Test::copy()
{
    QLCPhysical c = p;
    QVERIFY(c.bulbType() == p.bulbType());
    QVERIFY(c.bulbLumens() == p.bulbLumens());
    QVERIFY(c.bulbColourTemperature() == p.bulbColourTemperature());
    QVERIFY(c.weight() == p.weight());
    QVERIFY(c.width() == p.width());
    QVERIFY(c.height() == p.height());
    QVERIFY(c.depth() == p.depth());
    QVERIFY(c.lensName() == p.lensName());
    QVERIFY(c.lensDegreesMin() == p.lensDegreesMin());
    QVERIFY(c.lensDegreesMax() == p.lensDegreesMax());
    QVERIFY(c.focusType() == p.focusType());
    QVERIFY(c.focusPanMax() == p.focusPanMax());
    QVERIFY(c.focusTiltMax() == p.focusTiltMax());
    QVERIFY(c.powerConsumption() == p.powerConsumption());
    QVERIFY(c.dmxConnector() == p.dmxConnector());
}

void QLCPhysical_Test::load()
{
    QDomDocument doc;

    QDomElement root = doc.createElement("Physical");
    doc.appendChild(root);

    /* Bulb */
    QDomElement bulb = doc.createElement("Bulb");
    bulb.setAttribute("Type", "LED");
    bulb.setAttribute("Lumens", 18000);
    bulb.setAttribute("ColourTemperature", 6500);
    root.appendChild(bulb);

    /* Dimensions */
    QDomElement dim = doc.createElement("Dimensions");
    dim.setAttribute("Weight", 39.4);
    dim.setAttribute("Width", 530);
    dim.setAttribute("Height", 320);
    dim.setAttribute("Depth", 260);
    root.appendChild(dim);

    /* Lens */
    QDomElement lens = doc.createElement("Lens");
    lens.setAttribute("Name", "Fresnel");
    lens.setAttribute("DegreesMin", 8);
    lens.setAttribute("DegreesMax", 38);
    root.appendChild(lens);

    /* Focus */
    QDomElement focus = doc.createElement("Focus");
    focus.setAttribute("Type", "Head");
    focus.setAttribute("PanMax", 520);
    focus.setAttribute("TiltMax", 270);
    root.appendChild(focus);

    /* Technical */
    QDomElement technical = doc.createElement("Technical");
    technical.setAttribute("PowerConsumption", 250);
    technical.setAttribute("DmxConnector", "5-pin");
    root.appendChild(technical);

    /* Unrecognized tag */
    QDomElement homer = doc.createElement("HomerSimpson");
    homer.setAttribute("BeerConsumption", 25000);
    homer.setAttribute("PreferredBrand", "Duff");
    root.appendChild(homer);

    QVERIFY(p.loadXML(root) == true);
    QVERIFY(p.bulbType() == "LED");
    QVERIFY(p.bulbLumens() == 18000);
    QVERIFY(p.bulbColourTemperature() == 6500);
    QCOMPARE(p.weight(), 39.4);
    QVERIFY(p.width() == 530);
    QVERIFY(p.height() == 320);
    QVERIFY(p.depth() == 260);
    QVERIFY(p.lensName() == "Fresnel");
    QVERIFY(p.lensDegreesMin() == 8);
    QVERIFY(p.lensDegreesMax() == 38);
    QVERIFY(p.focusType() == "Head");
    QVERIFY(p.focusPanMax() == 520);
    QVERIFY(p.focusTiltMax() == 270);
    QVERIFY(p.powerConsumption() == 250);
    QVERIFY(p.dmxConnector() == "5-pin");
}

void QLCPhysical_Test::loadWrongRoot()
{
    QDomDocument doc;

    QDomElement root = doc.createElement("Foosical");
    doc.appendChild(root);

    /* Bulb */
    QDomElement bulb = doc.createElement("Bulb");
    bulb.setAttribute("Type", "LED");
    bulb.setAttribute("Lumens", 18000);
    bulb.setAttribute("ColourTemperature", 6500);
    root.appendChild(bulb);

    /* Dimensions */
    QDomElement dim = doc.createElement("Dimensions");
    dim.setAttribute("Weight", 39.4);
    dim.setAttribute("Width", 530);
    dim.setAttribute("Height", 320);
    dim.setAttribute("Depth", 260);
    root.appendChild(dim);

    /* Lens */
    QDomElement lens = doc.createElement("Lens");
    lens.setAttribute("Name", "Fresnel");
    lens.setAttribute("DegreesMin", 8);
    lens.setAttribute("DegreesMax", 38);
    root.appendChild(lens);

    /* Focus */
    QDomElement focus = doc.createElement("Focus");
    focus.setAttribute("Type", "Head");
    focus.setAttribute("PanMax", 520);
    focus.setAttribute("TiltMax", 270);
    root.appendChild(focus);

    /* Technical */
    QDomElement technical=  doc.createElement("Technical");
    technical.setAttribute("PowerConsumption", 250);
    technical.setAttribute("DmxConnector", "5-pin");
    root.appendChild(technical);

    QVERIFY(p.loadXML(root) == false);
}

void QLCPhysical_Test::save()
{
    QDomDocument doc;
    QDomElement root = doc.createElement("Test Root");
    bool bulb = false, dim = false, lens = false, focus = false, technical = false;

    QVERIFY(p.saveXML(&doc, &root) == true);
    QVERIFY(root.firstChild().toElement().tagName() == "Physical");

    QDomNode node = root.firstChild().firstChild();
    while (node.isNull() == false)
    {
        QDomElement e = node.toElement();
        if (e.tagName() == "Bulb")
        {
            bulb = true;
            QVERIFY(e.attribute("Type") == "LED");
            QVERIFY(e.attribute("Lumens") == "18000");
            QVERIFY(e.attribute("ColourTemperature") == "6500");
        }
        else if (e.tagName() == "Dimensions")
        {
            dim = true;
            QVERIFY(e.attribute("Width") == "530");
            QVERIFY(e.attribute("Depth") == "260");
            QVERIFY(e.attribute("Height") == "320");
            QCOMPARE(e.attribute("Weight").toDouble(), 39.4);
        }
        else if (e.tagName() == "Lens")
        {
            lens = true;
            QVERIFY(e.attribute("Name") == "Fresnel");
            QVERIFY(e.attribute("DegreesMin") == "8");
            QVERIFY(e.attribute("DegreesMax") == "38");
        }
        else if (e.tagName() == "Focus")
        {
            focus = true;
            QVERIFY(e.attribute("Type") == "Head");
            QVERIFY(e.attribute("PanMax") == "520");
            QVERIFY(e.attribute("TiltMax") == "270");
        }
        else if (e.tagName() == "Technical")
        {
            technical = true;
            QVERIFY(e.attribute("PowerConsumption") == "250");
            QVERIFY(e.attribute("DmxConnector") == "5-pin");
        }
        else
        {
            QFAIL(QString("Unexpected tag: %1").arg(e.tagName())
                  .toLatin1());
        }

        node = node.nextSibling();
    }

    QVERIFY(bulb == true);
    QVERIFY(dim == true);
    QVERIFY(lens == true);
    QVERIFY(focus == true);
    QVERIFY(technical == true);
}

QTEST_MAIN(QLCPhysical_Test)
<commit_msg>Fix QLCPhysical test unit when building with Qt5<commit_after>/*
  Q Light Controller - Unit tests
  qlcphysical_test.cpp

  Copyright (C) Heikki Junnila

  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.txt

  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.
*/

#include <QtTest>
#include <QtXml>

#include "qlcphysical_test.h"
#include "qlcphysical.h"

void QLCPhysical_Test::bulbType()
{
    QVERIFY(p.bulbType().isEmpty());
    p.setBulbType("BulbType");
    QVERIFY(p.bulbType() == "BulbType");
}

void QLCPhysical_Test::bulbLumens()
{
    QVERIFY(p.bulbLumens() == 0);
    p.setBulbLumens(10000);
    QVERIFY(p.bulbLumens() == 10000);
}

void QLCPhysical_Test::bulbColourTemp()
{
    QVERIFY(p.bulbColourTemperature() == 0);
    p.setBulbColourTemperature(3200);
    QVERIFY(p.bulbColourTemperature() == 3200);
}

void QLCPhysical_Test::weight()
{
    QVERIFY(p.weight() == 0);
    p.setWeight(7);
    QVERIFY(p.weight() == 7);
    p.setWeight(5.02837);
    QCOMPARE(p.weight(), 5.02837);
}

void QLCPhysical_Test::width()
{
    QVERIFY(p.width() == 0);
    p.setWidth(600);
    QVERIFY(p.width() == 600);
}

void QLCPhysical_Test::height()
{
    QVERIFY(p.height() == 0);
    p.setHeight(1200);
    QVERIFY(p.height() == 1200);
}

void QLCPhysical_Test::depth()
{
    QVERIFY(p.depth() == 0);
    p.setDepth(250);
    QVERIFY(p.depth() == 250);
}

void QLCPhysical_Test::lensName()
{
    QVERIFY(p.lensName() == "Other");
    p.setLensName("Fresnel");
    QVERIFY(p.lensName() == "Fresnel");
}

void QLCPhysical_Test::lensDegreesMin()
{
    QVERIFY(p.lensDegreesMin() == 0);
    p.setLensDegreesMin(9.4);
    QVERIFY(p.lensDegreesMin() == 9.4);
}

void QLCPhysical_Test::lensDegreesMax()
{
    QVERIFY(p.lensDegreesMax() == 0);
    p.setLensDegreesMax(40.5);
    QVERIFY(p.lensDegreesMax() == 40.5);
}

void QLCPhysical_Test::focusType()
{
    QVERIFY(p.focusType() == "Fixed");
    p.setFocusType("Head");
    QVERIFY(p.focusType() == "Head");
}

void QLCPhysical_Test::focusPanMax()
{
    QVERIFY(p.focusPanMax() == 0);
    p.setFocusPanMax(540);
    QVERIFY(p.focusPanMax() == 540);
}

void QLCPhysical_Test::focusTiltMax()
{
    QVERIFY(p.focusTiltMax() == 0);
    p.setFocusTiltMax(270);
    QVERIFY(p.focusTiltMax() == 270);
}
void QLCPhysical_Test::powerConsumption()
{
    QVERIFY(p.powerConsumption() == 0);
    p.setPowerConsumption(24000);
    QVERIFY(p.powerConsumption() == 24000);
}
void QLCPhysical_Test::dmxConnector()
{
    QVERIFY(p.dmxConnector() == "5-pin");
    p.setDmxConnector("3-pin");
    QVERIFY(p.dmxConnector() == "3-pin");
}

void QLCPhysical_Test::copy()
{
    QLCPhysical c = p;
    QVERIFY(c.bulbType() == p.bulbType());
    QVERIFY(c.bulbLumens() == p.bulbLumens());
    QVERIFY(c.bulbColourTemperature() == p.bulbColourTemperature());
    QVERIFY(c.weight() == p.weight());
    QVERIFY(c.width() == p.width());
    QVERIFY(c.height() == p.height());
    QVERIFY(c.depth() == p.depth());
    QVERIFY(c.lensName() == p.lensName());
    QVERIFY(c.lensDegreesMin() == p.lensDegreesMin());
    QVERIFY(c.lensDegreesMax() == p.lensDegreesMax());
    QVERIFY(c.focusType() == p.focusType());
    QVERIFY(c.focusPanMax() == p.focusPanMax());
    QVERIFY(c.focusTiltMax() == p.focusTiltMax());
    QVERIFY(c.powerConsumption() == p.powerConsumption());
    QVERIFY(c.dmxConnector() == p.dmxConnector());
}

void QLCPhysical_Test::load()
{
    QDomDocument doc;

    QDomElement root = doc.createElement("Physical");
    doc.appendChild(root);

    /* Bulb */
    QDomElement bulb = doc.createElement("Bulb");
    bulb.setAttribute("Type", "LED");
    bulb.setAttribute("Lumens", 18000);
    bulb.setAttribute("ColourTemperature", 6500);
    root.appendChild(bulb);

    /* Dimensions */
    QDomElement dim = doc.createElement("Dimensions");
    dim.setAttribute("Weight", QString::number(39.4));
    dim.setAttribute("Width", 530);
    dim.setAttribute("Height", 320);
    dim.setAttribute("Depth", 260);
    root.appendChild(dim);

    /* Lens */
    QDomElement lens = doc.createElement("Lens");
    lens.setAttribute("Name", "Fresnel");
    lens.setAttribute("DegreesMin", 8);
    lens.setAttribute("DegreesMax", 38);
    root.appendChild(lens);

    /* Focus */
    QDomElement focus = doc.createElement("Focus");
    focus.setAttribute("Type", "Head");
    focus.setAttribute("PanMax", 520);
    focus.setAttribute("TiltMax", 270);
    root.appendChild(focus);

    /* Technical */
    QDomElement technical = doc.createElement("Technical");
    technical.setAttribute("PowerConsumption", 250);
    technical.setAttribute("DmxConnector", "5-pin");
    root.appendChild(technical);

    /* Unrecognized tag */
    QDomElement homer = doc.createElement("HomerSimpson");
    homer.setAttribute("BeerConsumption", 25000);
    homer.setAttribute("PreferredBrand", "Duff");
    root.appendChild(homer);

    QVERIFY(p.loadXML(root) == true);
    QVERIFY(p.bulbType() == "LED");
    QVERIFY(p.bulbLumens() == 18000);
    QVERIFY(p.bulbColourTemperature() == 6500);
    QCOMPARE(p.weight(), 39.4);
    QVERIFY(p.width() == 530);
    QVERIFY(p.height() == 320);
    QVERIFY(p.depth() == 260);
    QVERIFY(p.lensName() == "Fresnel");
    QVERIFY(p.lensDegreesMin() == 8);
    QVERIFY(p.lensDegreesMax() == 38);
    QVERIFY(p.focusType() == "Head");
    QVERIFY(p.focusPanMax() == 520);
    QVERIFY(p.focusTiltMax() == 270);
    QVERIFY(p.powerConsumption() == 250);
    QVERIFY(p.dmxConnector() == "5-pin");
}

void QLCPhysical_Test::loadWrongRoot()
{
    QDomDocument doc;

    QDomElement root = doc.createElement("Foosical");
    doc.appendChild(root);

    /* Bulb */
    QDomElement bulb = doc.createElement("Bulb");
    bulb.setAttribute("Type", "LED");
    bulb.setAttribute("Lumens", 18000);
    bulb.setAttribute("ColourTemperature", 6500);
    root.appendChild(bulb);

    /* Dimensions */
    QDomElement dim = doc.createElement("Dimensions");
    dim.setAttribute("Weight", 39.4);
    dim.setAttribute("Width", 530);
    dim.setAttribute("Height", 320);
    dim.setAttribute("Depth", 260);
    root.appendChild(dim);

    /* Lens */
    QDomElement lens = doc.createElement("Lens");
    lens.setAttribute("Name", "Fresnel");
    lens.setAttribute("DegreesMin", 8);
    lens.setAttribute("DegreesMax", 38);
    root.appendChild(lens);

    /* Focus */
    QDomElement focus = doc.createElement("Focus");
    focus.setAttribute("Type", "Head");
    focus.setAttribute("PanMax", 520);
    focus.setAttribute("TiltMax", 270);
    root.appendChild(focus);

    /* Technical */
    QDomElement technical=  doc.createElement("Technical");
    technical.setAttribute("PowerConsumption", 250);
    technical.setAttribute("DmxConnector", "5-pin");
    root.appendChild(technical);

    QVERIFY(p.loadXML(root) == false);
}

void QLCPhysical_Test::save()
{
    QDomDocument doc;
    QDomElement root = doc.createElement("Test Root");
    bool bulb = false, dim = false, lens = false, focus = false, technical = false;

    QVERIFY(p.saveXML(&doc, &root) == true);
    QVERIFY(root.firstChild().toElement().tagName() == "Physical");

    QDomNode node = root.firstChild().firstChild();
    while (node.isNull() == false)
    {
        QDomElement e = node.toElement();
        if (e.tagName() == "Bulb")
        {
            bulb = true;
            QVERIFY(e.attribute("Type") == "LED");
            QVERIFY(e.attribute("Lumens") == "18000");
            QVERIFY(e.attribute("ColourTemperature") == "6500");
        }
        else if (e.tagName() == "Dimensions")
        {
            dim = true;
            QVERIFY(e.attribute("Width") == "530");
            QVERIFY(e.attribute("Depth") == "260");
            QVERIFY(e.attribute("Height") == "320");
            QCOMPARE(e.attribute("Weight").toDouble(), 39.4);
        }
        else if (e.tagName() == "Lens")
        {
            lens = true;
            QVERIFY(e.attribute("Name") == "Fresnel");
            QVERIFY(e.attribute("DegreesMin") == "8");
            QVERIFY(e.attribute("DegreesMax") == "38");
        }
        else if (e.tagName() == "Focus")
        {
            focus = true;
            QVERIFY(e.attribute("Type") == "Head");
            QVERIFY(e.attribute("PanMax") == "520");
            QVERIFY(e.attribute("TiltMax") == "270");
        }
        else if (e.tagName() == "Technical")
        {
            technical = true;
            QVERIFY(e.attribute("PowerConsumption") == "250");
            QVERIFY(e.attribute("DmxConnector") == "5-pin");
        }
        else
        {
            QFAIL(QString("Unexpected tag: %1").arg(e.tagName())
                  .toLatin1());
        }

        node = node.nextSibling();
    }

    QVERIFY(bulb == true);
    QVERIFY(dim == true);
    QVERIFY(lens == true);
    QVERIFY(focus == true);
    QVERIFY(technical == true);
}

QTEST_MAIN(QLCPhysical_Test)
<|endoftext|>