<commit_before>#include "TextWindow.h"
#include <string.h>
#include <errno.h>

using namespace input;

namespace video{
    void TextWindow::newLine(){
        _curs.x = 0;
        if(_curs.y + 1 == _lineBuffer.size()){
            if(_lineBuffer.size() == LineNum){
                _lineBuffer.pop_front();
            }
            else{
                ++_curs.y;
            }
            _lineBuffer.push_back(Line());
        }
        else ++_curs.y;
    }

    void TextWindow::addPrintableChar(char c){
        assert(_curs.x <= _width);
        if(_curs.x == _width) newLine();
        //fprintf(stderr,"pos %d %d %d %d %d\n",_curs.x, _curs.y,_cursFormat.fg.R,
        //_cursFormat.fg.G,_cursFormat.fg.B);
        _lineBuffer.at(_curs.y).write(_curs.x,FormatedChar(c,_cursFormat));
        ++_curs.x;
    }

    size_t TextWindow::write(const void* buf, size_t count){
        fprintf(stderr,"write TextWindow\n");
        const char* buf2 = reinterpret_cast<const char*>(buf);
        const size_t limit = 1024;
        if(count > limit) count = limit;
        for(size_t i = 0 ; i < count ; ++i){
            putChar(buf2[i]);
        }
        return count;
    }

    void TextWindow::error(){
        _state = NORMAL;
        putChar('~');
        putChar('~');
    }

    void TextWindow::putChar(char c){
        fprintf(stderr,"putChar('%c'); with %d in win %d\n",c,_state,getWID());
        switch(_state){
            case WAITINGOB:
                if(c != '['){
                    error();
                    putChar(c);
                }
                else {
                    _stack.clear();
                    _stack.push_back(0);
                    _state = ESCAPE;
                }
                return;

            case ESCAPE:
                if(c < 32 or c > 126) {
                    error();
                    putChar(c);
                    return;
                }

                if(c >= '0' and c <= '9'){
                    _stack.back() *=10;
                    _stack.back() += (c - '0');
                    return;
                }

                switch(c){
                    case ';':
                        _stack.push_back(0);
                        return;
                    case 'm':
                        SGR();
                        _state = NORMAL;
                        return;
                    default:
                        error();
                        putChar(c);
                        return;
                }

            case NORMAL:
                if(c == 27){
                    _state = WAITINGOB;
                    return;
                }

                uint val;
                switch(c){
                    case '\n':
                        //fprintf(stderr," new line \n");
                        newLine();
                        return;

                    case '\t':
                        // A clean way to do it.
                        val = _curs.x%4;
                        for(uint i = 0 ; i < 4-val ; ++i){
                            addPrintableChar(' ');
                        }
                        return;

                    case '\b':
                        if(_curs.x == 0){
                            if(_curs.y > 0) --_curs.y;
                            _curs.x = _width -1;
                        }
                        else --_curs.x;
                        return;

                    case '\r':
                        _curs.x = 0;
                        return;

                    case '\f':
                        val = _curs.x;
                        newLine();
                        _curs.x = val;
                        return;

                    default:
                        if(c < 32 and c >= EOF){
                            error();
                            return;
                        }
                        addPrintableChar(c);
                        return;
                }
        }
    }

    /**
       @brief Handles SGR Commands

       @todo Add Blinking.
     */

    void TextWindow::SGR(){
        //fprintf(stderr,"SGR %d\n",_stack.size());
        if(_stack.size() == 0){
            _cursFormat = Format();
            return;
        }

        uint command = _stack[0];
        if(command == 0){
            _cursFormat = Format();
        }
        else if(command == 1){
            _bright = true;
        }
        else if(command == 2){
            _bright = false;
        }
        else if(command == 4){
            _cursFormat.underline = true;
        }
        else if(command == 7){
            std::swap(_cursFormat.fg,_cursFormat.bg);
        }
        else if(command == 24){
            _cursFormat.underline = false;
        }

        else if(command >=30 and command <= 37){
            _cursFormat.fg = getByNum(command -30);
        }
        else if(command == 38){
            if(_stack.size() < 5){
                error();
                return;
            }
            if(_stack[1] != 2){
                error();
                return;
            }
            _cursFormat.fg.R = _stack[3];
            _cursFormat.fg.G = _stack[4];
            _cursFormat.fg.B = _stack[5];
        }
        else if(command == 39){
            _cursFormat.fg = Color24::lwhite;
        }

        else if(command >=40 and command <= 47){
            _cursFormat.bg = getByNum(command -40);
        }
        else if(command == 48){
            if(_stack.size() < 5){
                error();
                return;
            }
            if(_stack[1] != 2){
                error();
                return;
            }
            _cursFormat.bg.R = _stack[3];
            _cursFormat.bg.G = _stack[4];
            _cursFormat.bg.B = _stack[5];
        }
        else if(command == 49){
            _cursFormat.bg = Color24::black;
        }
    }

    void TextWindow::send() const{
        //fprintf(stderr,"hey !\n");
        if(!_active) return;
        //fprintf(stderr,"hoy !\n");
        size_t s = _lineBuffer.size();
        size_t offset = max(i64(s - _height),i64(0));
        //if(getWID()>=2) fprintf(stderr,"number line %llu and height %llu and offset \n",s,_height);
        for(size_t i =  0; i < min(s,(size_t)_height) ; ++i){
            //fprintf(stderr,"printing line %llu \n",i + offset);
            size_t j = 0;
            //fprintf(stderr,"of size %d \n",_lineBuffer[i + offset].data.size());
            for(auto fmc : _lineBuffer[i + offset].data){
                //fprintf(stderr,"printing %llu %llu\n",i,j);
                drawFMC({j,i},fmc);
                ++j;
            }
        }

    }
    void TextWindow::drawFMC(Vec2u pos, FormatedChar fmc) const{
        screen.putChar(fmc.c,_offset.x + pos.x*8+1,_offset.y + pos.y*16 + 1,*_font,fmc.fg,fmc.bg);
        if(fmc.underline){
            for(uint k = 0 ; k < 8 ; ++k){
                screen.set(_offset.x + pos.x*8+1+k, _offset.y + pos.y*16+16,fmc.fg);
            }
        }
    }

    bool TextWindow::handleEvent(input::Event e){
        if(e.type == Event::KEYBOARD){
            if(e.kcode.symbol and !e.kcode.scanCode.release and allowInput){
                char sym = e.kcode.symbol;
                if(sym == '\b' ){
                    if(!_keyboardBuffer.empty()){
                        _keyboardBuffer.pop_back();
                        putChar('\b');
                        putChar(' ');
                        putChar('\b');
                    }
                }
                else if(sym == '\n'){
                    for(auto c : _keyboardBuffer){
                        _inputBuffer.push_back(c);
                    }
                    _keyboardBuffer.clear();
                    _inputBuffer.push_back('\n');
                    putChar('\n');
                }
                else{
                    _keyboardBuffer.push_back(sym);
                    putChar(sym);
                }
            }
        }
        return true;
    }

    size_t TextWindow::read(void* buf, size_t count){
        char* buf2 = reinterpret_cast<char*>(buf);
        if(count > 1000) count = 1000;
        size_t reallyRead =0;
        while(!_inputBuffer.empty() and reallyRead < count){
            *buf2 = _inputBuffer.front();
            _inputBuffer.pop_front();
            ++reallyRead;
            ++buf2;
        }
        return reallyRead;
    }

};
<commit_msg>Removed TextWindow debug logs<commit_after>#include "TextWindow.h"
#include <string.h>
#include <errno.h>

using namespace input;

namespace video{
    void TextWindow::newLine(){
        _curs.x = 0;
        if(_curs.y + 1 == _lineBuffer.size()){
            if(_lineBuffer.size() == LineNum){
                _lineBuffer.pop_front();
            }
            else{
                ++_curs.y;
            }
            _lineBuffer.push_back(Line());
        }
        else ++_curs.y;
    }

    void TextWindow::addPrintableChar(char c){
        assert(_curs.x <= _width);
        if(_curs.x == _width) newLine();
        //fprintf(stderr,"pos %d %d %d %d %d\n",_curs.x, _curs.y,_cursFormat.fg.R,
        //_cursFormat.fg.G,_cursFormat.fg.B);
        _lineBuffer.at(_curs.y).write(_curs.x,FormatedChar(c,_cursFormat));
        ++_curs.x;
    }

    size_t TextWindow::write(const void* buf, size_t count){
        //fprintf(stderr,"write TextWindow\n");
        const char* buf2 = reinterpret_cast<const char*>(buf);
        const size_t limit = 1024;
        if(count > limit) count = limit;
        for(size_t i = 0 ; i < count ; ++i){
            putChar(buf2[i]);
        }
        return count;
    }

    void TextWindow::error(){
        _state = NORMAL;
        putChar('~');
        putChar('~');
    }

    void TextWindow::putChar(char c){
        //fprintf(stderr,"putChar('%c'); with %d in win %d\n",c,_state,getWID());
        switch(_state){
            case WAITINGOB:
                if(c != '['){
                    error();
                    putChar(c);
                }
                else {
                    _stack.clear();
                    _stack.push_back(0);
                    _state = ESCAPE;
                }
                return;

            case ESCAPE:
                if(c < 32 or c > 126) {
                    error();
                    putChar(c);
                    return;
                }

                if(c >= '0' and c <= '9'){
                    _stack.back() *=10;
                    _stack.back() += (c - '0');
                    return;
                }

                switch(c){
                    case ';':
                        _stack.push_back(0);
                        return;
                    case 'm':
                        SGR();
                        _state = NORMAL;
                        return;
                    default:
                        error();
                        putChar(c);
                        return;
                }

            case NORMAL:
                if(c == 27){
                    _state = WAITINGOB;
                    return;
                }

                uint val;
                switch(c){
                    case '\n':
                        //fprintf(stderr," new line \n");
                        newLine();
                        return;

                    case '\t':
                        // A clean way to do it.
                        val = _curs.x%4;
                        for(uint i = 0 ; i < 4-val ; ++i){
                            addPrintableChar(' ');
                        }
                        return;

                    case '\b':
                        if(_curs.x == 0){
                            if(_curs.y > 0) --_curs.y;
                            _curs.x = _width -1;
                        }
                        else --_curs.x;
                        return;

                    case '\r':
                        _curs.x = 0;
                        return;

                    case '\f':
                        val = _curs.x;
                        newLine();
                        _curs.x = val;
                        return;

                    default:
                        if(c < 32 and c >= EOF){
                            error();
                            return;
                        }
                        addPrintableChar(c);
                        return;
                }
        }
    }

    /**
       @brief Handles SGR Commands

       @todo Add Blinking.
     */

    void TextWindow::SGR(){
        //fprintf(stderr,"SGR %d\n",_stack.size());
        if(_stack.size() == 0){
            _cursFormat = Format();
            return;
        }

        uint command = _stack[0];
        if(command == 0){
            _cursFormat = Format();
        }
        else if(command == 1){
            _bright = true;
        }
        else if(command == 2){
            _bright = false;
        }
        else if(command == 4){
            _cursFormat.underline = true;
        }
        else if(command == 7){
            std::swap(_cursFormat.fg,_cursFormat.bg);
        }
        else if(command == 24){
            _cursFormat.underline = false;
        }

        else if(command >=30 and command <= 37){
            _cursFormat.fg = getByNum(command -30);
        }
        else if(command == 38){
            if(_stack.size() < 5){
                error();
                return;
            }
            if(_stack[1] != 2){
                error();
                return;
            }
            _cursFormat.fg.R = _stack[3];
            _cursFormat.fg.G = _stack[4];
            _cursFormat.fg.B = _stack[5];
        }
        else if(command == 39){
            _cursFormat.fg = Color24::lwhite;
        }

        else if(command >=40 and command <= 47){
            _cursFormat.bg = getByNum(command -40);
        }
        else if(command == 48){
            if(_stack.size() < 5){
                error();
                return;
            }
            if(_stack[1] != 2){
                error();
                return;
            }
            _cursFormat.bg.R = _stack[3];
            _cursFormat.bg.G = _stack[4];
            _cursFormat.bg.B = _stack[5];
        }
        else if(command == 49){
            _cursFormat.bg = Color24::black;
        }
    }

    void TextWindow::send() const{
        //fprintf(stderr,"hey !\n");
        if(!_active) return;
        //fprintf(stderr,"hoy !\n");
        size_t s = _lineBuffer.size();
        size_t offset = max(i64(s - _height),i64(0));
        //if(getWID()>=2) fprintf(stderr,"number line %llu and height %llu and offset \n",s,_height);
        for(size_t i =  0; i < min(s,(size_t)_height) ; ++i){
            //fprintf(stderr,"printing line %llu \n",i + offset);
            size_t j = 0;
            //fprintf(stderr,"of size %d \n",_lineBuffer[i + offset].data.size());
            for(auto fmc : _lineBuffer[i + offset].data){
                //fprintf(stderr,"printing %llu %llu\n",i,j);
                drawFMC({j,i},fmc);
                ++j;
            }
        }

    }
    void TextWindow::drawFMC(Vec2u pos, FormatedChar fmc) const{
        screen.putChar(fmc.c,_offset.x + pos.x*8+1,_offset.y + pos.y*16 + 1,*_font,fmc.fg,fmc.bg);
        if(fmc.underline){
            for(uint k = 0 ; k < 8 ; ++k){
                screen.set(_offset.x + pos.x*8+1+k, _offset.y + pos.y*16+16,fmc.fg);
            }
        }
    }

    bool TextWindow::handleEvent(input::Event e){
        if(e.type == Event::KEYBOARD){
            if(e.kcode.symbol and !e.kcode.scanCode.release and allowInput){
                char sym = e.kcode.symbol;
                if(sym == '\b' ){
                    if(!_keyboardBuffer.empty()){
                        _keyboardBuffer.pop_back();
                        putChar('\b');
                        putChar(' ');
                        putChar('\b');
                    }
                }
                else if(sym == '\n'){
                    for(auto c : _keyboardBuffer){
                        _inputBuffer.push_back(c);
                    }
                    _keyboardBuffer.clear();
                    _inputBuffer.push_back('\n');
                    putChar('\n');
                }
                else{
                    _keyboardBuffer.push_back(sym);
                    putChar(sym);
                }
            }
        }
        return true;
    }

    size_t TextWindow::read(void* buf, size_t count){
        char* buf2 = reinterpret_cast<char*>(buf);
        if(count > 1000) count = 1000;
        size_t reallyRead =0;
        while(!_inputBuffer.empty() and reallyRead < count){
            *buf2 = _inputBuffer.front();
            _inputBuffer.pop_front();
            ++reallyRead;
            ++buf2;
        }
        return reallyRead;
    }

};
<|endoftext|>


<commit_before>
/*

    poedit, a wxWindows i18n catalogs editor

    ---------------
      chooselang.cpp

      Language chooser

      (c) Vaclav Slavik, 2003, 2004

*/

#include <wx/wxprec.h>

#include <wx/wx.h>
#include <wx/config.h>

#include "chooselang.h"

static void SaveUILanguage(wxLanguage lang)
{
    if (lang == wxLANGUAGE_UNKNOWN)
        return;
    if (lang == wxLANGUAGE_DEFAULT)
        wxConfig::Get()->Write(_T("ui_language"), _T("default"));
    else
        wxConfig::Get()->Write(_T("ui_language"),
                               wxLocale::GetLanguageInfo(lang)->CanonicalName);
}

wxLanguage GetUILanguage()
{
#if defined(__UNIX__) || !wxCHECK_VERSION(2,5,0)
    return wxLANGUAGE_DEFAULT;
#else
    wxLanguage lang(wxLANGUAGE_DEFAULT);
    wxString lng = wxConfig::Get()->Read(_T("ui_language"));
    if (lng.empty())
    {
        lang = ChooseLanguage();
        if (lang != wxLANGUAGE_UNKNOWN)
            SaveUILanguage(lang);
        else
            lang = wxLANGUAGE_DEFAULT;
    }
    else if (lng != _T("default"))
    {
        const wxLanguageInfo *info = wxLocale::FindLanguageInfo(lng);
        if (info != NULL)
            lang = (wxLanguage)info->Language;
        else
            wxLogError(_("Uknown locale code '%s' in registry."), lng.c_str());
    }
    return lang;
#endif
}

#ifndef __UNIX__
wxLanguage ChooseLanguage()
{
    struct LangInfo
    {
        const wxChar *name;
        wxLanguage code;
    };

    LangInfo langs[] =
    {
        { _("(Use default language)"), wxLANGUAGE_DEFAULT },

        { _T("Afrikaans"), wxLANGUAGE_AFRIKAANS },
        { _T("Albanian"), wxLANGUAGE_ALBANIAN },
        { _T("Amharic"), wxLANGUAGE_AMHARIC },
        { _T("Bangla"), wxLANGUAGE_BENGALI },
        { _T("Belarusian"), wxLANGUAGE_BELARUSIAN },
        { _T("Breton"), wxLANGUAGE_BRETON },
        { _T("Bulgarian"), wxLANGUAGE_BULGARIAN },
        { _T("Catalan"), wxLANGUAGE_CATALAN },
        { _T("Chinese (Traditional)"), wxLANGUAGE_CHINESE_TRADITIONAL },
        { _T("Chinese (Simplified)"), wxLANGUAGE_CHINESE_SIMPLIFIED },
        { _T("Croatian"), wxLANGUAGE_CROATIAN },
        { _T("Czech"), wxLANGUAGE_CZECH },
        { _T("Danish"), wxLANGUAGE_DANISH },
        { _T("Dutch"), wxLANGUAGE_DUTCH },
        { _T("English"), wxLANGUAGE_ENGLISH },
        { _T("Estonian"), wxLANGUAGE_ESTONIAN },
        { _T("Esperanto"), wxLANGUAGE_ESPERANTO },
        { _T("Farsi"), wxLANGUAGE_FARSI },
        { _T("French"), wxLANGUAGE_FRENCH },
        { _T("Georgian"), wxLANGUAGE_GEORGIAN },
        { _T("German"), wxLANGUAGE_GERMAN },
        { _T("Greek"), wxLANGUAGE_GREEK },
        { _T("Hebrew"), wxLANGUAGE_HEBREW },
        { _T("Hindi"), wxLANGUAGE_HINDI },
        { _T("Hungarian"), wxLANGUAGE_HUNGARIAN },
        { _T("Icelandic"), wxLANGUAGE_ICELANDIC },
        { _T("Italian"), wxLANGUAGE_ITALIAN },
        { _T("Japanese"), wxLANGUAGE_JAPANESE },
        { _T("Korean"), wxLANGUAGE_KOREAN },
        { _T("Kyrgyz"), wxLANGUAGE_KIRGHIZ },
        { _T("Latvian"), wxLANGUAGE_LATVIAN },
        { _T("Lithuanian"), wxLANGUAGE_LITHUANIAN },
        { _T("Mongolian"), wxLANGUAGE_MONGOLIAN },
        { _T("Norwegian Nynorsk"), wxLANGUAGE_NORWEGIAN_NYNORSK },
        { _T("Norwegian Bokmal"), wxLANGUAGE_NORWEGIAN_BOKMAL },
        { _T("Polish"), wxLANGUAGE_POLISH },
        { _T("Portuguese"), wxLANGUAGE_PORTUGUESE },
        { _T("Portuguese (Brazilian)"), wxLANGUAGE_PORTUGUESE_BRAZILIAN },
        { _T("Punjabi"), wxLANGUAGE_PUNJABI },
        { _T("Romanian"), wxLANGUAGE_ROMANIAN },
        { _T("Russian"), wxLANGUAGE_RUSSIAN },
        { _T("Serbian"), wxLANGUAGE_SERBIAN },
        { _T("Slovak"), wxLANGUAGE_SLOVAK },
        { _T("Slovenian"), wxLANGUAGE_SLOVENIAN },
        { _T("Spanish"), wxLANGUAGE_SPANISH },
        { _T("Spanish (Puerto Rico)"), wxLANGUAGE_SPANISH_PUERTO_RICO },
        { _T("Swedish"), wxLANGUAGE_SWEDISH },
        { _T("Turkish"), wxLANGUAGE_TURKISH },
        { _T("Tamil"), wxLANGUAGE_TAMIL },
        { _T("Ukrainian"), wxLANGUAGE_UKRAINIAN },

        { NULL, wxLANGUAGE_UNKNOWN }
    };

    wxArrayString arr;
    for (int i = 0; langs[i].name; i++)
        arr.Add(langs[i].name);

    int choice = wxGetSingleChoiceIndex(
            _("Select your prefered language"),
            _("Language selection"),
            arr);
    if (choice == -1)
        return wxLANGUAGE_UNKNOWN;
    else
        return langs[choice].code;
}

void ChangeUILanguage()
{
    wxLanguage lang = ChooseLanguage();
    if (lang == wxLANGUAGE_UNKNOWN)
        return;
    SaveUILanguage(lang);
    wxMessageBox(_("You must restart poEdit for this change to take effect."),
                 _T("poEdit"),
                 wxOK | wxCENTRE | wxICON_INFORMATION);
}

#endif
<commit_msg>Basque was missing<commit_after>
/*

    poedit, a wxWindows i18n catalogs editor

    ---------------
      chooselang.cpp

      Language chooser

      (c) Vaclav Slavik, 2003-2005

*/

#include <wx/wxprec.h>

#include <wx/wx.h>
#include <wx/config.h>

#include "chooselang.h"

static void SaveUILanguage(wxLanguage lang)
{
    if (lang == wxLANGUAGE_UNKNOWN)
        return;
    if (lang == wxLANGUAGE_DEFAULT)
        wxConfig::Get()->Write(_T("ui_language"), _T("default"));
    else
        wxConfig::Get()->Write(_T("ui_language"),
                               wxLocale::GetLanguageInfo(lang)->CanonicalName);
}

wxLanguage GetUILanguage()
{
#if defined(__UNIX__) || !wxCHECK_VERSION(2,5,0)
    return wxLANGUAGE_DEFAULT;
#else
    wxLanguage lang(wxLANGUAGE_DEFAULT);
    wxString lng = wxConfig::Get()->Read(_T("ui_language"));
    if (lng.empty())
    {
        lang = ChooseLanguage();
        if (lang != wxLANGUAGE_UNKNOWN)
            SaveUILanguage(lang);
        else
            lang = wxLANGUAGE_DEFAULT;
    }
    else if (lng != _T("default"))
    {
        const wxLanguageInfo *info = wxLocale::FindLanguageInfo(lng);
        if (info != NULL)
            lang = (wxLanguage)info->Language;
        else
            wxLogError(_("Uknown locale code '%s' in registry."), lng.c_str());
    }
    return lang;
#endif
}

#ifndef __UNIX__
wxLanguage ChooseLanguage()
{
    struct LangInfo
    {
        const wxChar *name;
        wxLanguage code;
    };

    LangInfo langs[] =
    {
        { _("(Use default language)"), wxLANGUAGE_DEFAULT },

        { _T("Afrikaans"), wxLANGUAGE_AFRIKAANS },
        { _T("Albanian"), wxLANGUAGE_ALBANIAN },
        { _T("Amharic"), wxLANGUAGE_AMHARIC },
        { _T("Bangla"), wxLANGUAGE_BENGALI },
        { _T("Basque"), wxLANGUAGE_BASQUE },
        { _T("Belarusian"), wxLANGUAGE_BELARUSIAN },
        { _T("Breton"), wxLANGUAGE_BRETON },
        { _T("Bulgarian"), wxLANGUAGE_BULGARIAN },
        { _T("Catalan"), wxLANGUAGE_CATALAN },
        { _T("Chinese (Traditional)"), wxLANGUAGE_CHINESE_TRADITIONAL },
        { _T("Chinese (Simplified)"), wxLANGUAGE_CHINESE_SIMPLIFIED },
        { _T("Croatian"), wxLANGUAGE_CROATIAN },
        { _T("Czech"), wxLANGUAGE_CZECH },
        { _T("Danish"), wxLANGUAGE_DANISH },
        { _T("Dutch"), wxLANGUAGE_DUTCH },
        { _T("English"), wxLANGUAGE_ENGLISH },
        { _T("Estonian"), wxLANGUAGE_ESTONIAN },
        { _T("Esperanto"), wxLANGUAGE_ESPERANTO },
        { _T("Farsi"), wxLANGUAGE_FARSI },
        { _T("French"), wxLANGUAGE_FRENCH },
        { _T("Georgian"), wxLANGUAGE_GEORGIAN },
        { _T("German"), wxLANGUAGE_GERMAN },
        { _T("Greek"), wxLANGUAGE_GREEK },
        { _T("Hebrew"), wxLANGUAGE_HEBREW },
        { _T("Hindi"), wxLANGUAGE_HINDI },
        { _T("Hungarian"), wxLANGUAGE_HUNGARIAN },
        { _T("Icelandic"), wxLANGUAGE_ICELANDIC },
        { _T("Italian"), wxLANGUAGE_ITALIAN },
        { _T("Japanese"), wxLANGUAGE_JAPANESE },
        { _T("Korean"), wxLANGUAGE_KOREAN },
        { _T("Kyrgyz"), wxLANGUAGE_KIRGHIZ },
        { _T("Latvian"), wxLANGUAGE_LATVIAN },
        { _T("Lithuanian"), wxLANGUAGE_LITHUANIAN },
        { _T("Mongolian"), wxLANGUAGE_MONGOLIAN },
        { _T("Norwegian Nynorsk"), wxLANGUAGE_NORWEGIAN_NYNORSK },
        { _T("Norwegian Bokmal"), wxLANGUAGE_NORWEGIAN_BOKMAL },
        { _T("Polish"), wxLANGUAGE_POLISH },
        { _T("Portuguese"), wxLANGUAGE_PORTUGUESE },
        { _T("Portuguese (Brazilian)"), wxLANGUAGE_PORTUGUESE_BRAZILIAN },
        { _T("Punjabi"), wxLANGUAGE_PUNJABI },
        { _T("Romanian"), wxLANGUAGE_ROMANIAN },
        { _T("Russian"), wxLANGUAGE_RUSSIAN },
        { _T("Serbian"), wxLANGUAGE_SERBIAN },
        { _T("Slovak"), wxLANGUAGE_SLOVAK },
        { _T("Slovenian"), wxLANGUAGE_SLOVENIAN },
        { _T("Spanish"), wxLANGUAGE_SPANISH },
        { _T("Spanish (Puerto Rico)"), wxLANGUAGE_SPANISH_PUERTO_RICO },
        { _T("Swedish"), wxLANGUAGE_SWEDISH },
        { _T("Turkish"), wxLANGUAGE_TURKISH },
        { _T("Tamil"), wxLANGUAGE_TAMIL },
        { _T("Ukrainian"), wxLANGUAGE_UKRAINIAN },

        { NULL, wxLANGUAGE_UNKNOWN }
    };

    wxArrayString arr;
    for (int i = 0; langs[i].name; i++)
        arr.Add(langs[i].name);

    int choice = wxGetSingleChoiceIndex(
            _("Select your prefered language"),
            _("Language selection"),
            arr);
    if (choice == -1)
        return wxLANGUAGE_UNKNOWN;
    else
        return langs[choice].code;
}

void ChangeUILanguage()
{
    wxLanguage lang = ChooseLanguage();
    if (lang == wxLANGUAGE_UNKNOWN)
        return;
    SaveUILanguage(lang);
    wxMessageBox(_("You must restart poEdit for this change to take effect."),
                 _T("poEdit"),
                 wxOK | wxCENTRE | wxICON_INFORMATION);
}

#endif
<|endoftext|>


<commit_before>#ifndef DISSENT_MESSAGING_RPC_HANDLER_H_GUARD
#define DISSENT_MESSAGING_RPC_HANDLER_H_GUARD

#include <QByteArray>
#include <QDebug>
#include <QHash>
#include <QObject>
#include <QString>
#include <QSharedPointer>

#include "Utils/TimerCallback.hpp"
#include "Utils/TimerEvent.hpp"

#include "ISender.hpp"
#include "ISinkObject.hpp"
#include "Request.hpp"
#include "RequestHandler.hpp"
#include "RequestResponder.hpp"
#include "Response.hpp"
#include "ResponseHandler.hpp"

namespace Dissent {
namespace Messaging {
  class RequestState;

  /**
   * Rpc mechanism assumes a reliable sending mechanism
   */
  class RpcHandler : public ISinkObject {
    Q_OBJECT

    public:
      typedef Utils::TimerMethod<RpcHandler, int> TimerCallback;
      static const int TimeoutDelta = 60000;

      inline static QSharedPointer<RpcHandler> GetEmpty()
      {
        static QSharedPointer<RpcHandler> handler(new RpcHandler());
        return handler;
      }

      /**
       * The constructor
       */
      explicit RpcHandler();

      /**
       * The destructor
       */
      virtual ~RpcHandler();

      /**
       * Handle an incoming Rpc request
       * @param from a return path to the requestor
       * @param data serialized request message
       */
      virtual void HandleData(const QSharedPointer<ISender> &from,
          const QByteArray &data);

      /**
       * Handle an incoming Rpc request
       * @param from a return path to the requestor
       * @param container deserialized request message
       */
      void HandleData(const QSharedPointer<ISender> &from,
          const QVariantList &container);

      /**
       * Send a request
       * @param to the destination for the notification
       * @param method the remote method
       * @param data the input data for that method
       * @returns the id of the request so that the callback can be cancelled
       */
      void SendNotification(const QSharedPointer<ISender> &to,
          const QString &method, const QVariant &data);

      /**
       * Send a request
       * @param to the destination for the request
       * @param method the remote method
       * @param data the input data for that method
       * @param callback called when the request is complete
       * @param timeout specifies whether or not to let the request timeout.
       * It is a temporary parameter that will be phased out in the future,
       * all future Rpc Methods should be implemented with potential timeouts
       * in mind.
       * @returns the id of the request so that the callback can be cancelled
       */
      int SendRequest(const QSharedPointer<ISender> &to, const QString &method,
          const QVariant &data, const QSharedPointer<ResponseHandler> &callback,
          bool timeout = false);

      /**
       * Register a callback
       * @param name The string to match it with
       * @param cb Method callback to register
       */
      bool Register(const QString &name,
          const QSharedPointer<RequestHandler> &cb);

      /**
       * Register a callback into the specified object
       * @param name The string to match it with
       * @param obj with the method name
       */
      bool Register(const QString &name, const QObject *obj,
          const char *method);

      /**
       * Unregister a callback
       * @param name name of method to remove
       */
      bool Unregister(const QString &name);

      /**
       * Used to cancel handling a request result
       * @param id the id of the request
       */
      bool CancelRequest(int id)
      {
        return _requests.remove(id) != 0;
      }

    public slots:
      /**
       * Send a response for a request
       * @param request the original request
       * @param data the data for the remote side
       */
      void SendResponse(const Request &request, const QVariant &data);

      /**
       * Send a response for a request
       * @param request the original request
       * @param reason the reason for the failure
       */
      void SendFailedResponse(const Request &request,
          Response::ErrorTypes error, const QString &reason,
          const QVariant &error_data = QVariant());

    private:
      void StartTimer();
      void Timeout(const int &);

      /**
       * Handle an incoming request
       * @param request the request
       */
      void HandleRequest(const Request &request);

      /**
       * Handle an incoming response
       * @param response the response
       */
      void HandleResponse(const Response &response);

      /**
       * Returns the _current_id and increments it to the next
       */
      inline int IncrementId();

      /**
       * Maps a string to a method to call
       */
      QHash<QString, QSharedPointer<RequestHandler> > _callbacks;

      /**
       * Maps id to a callback method to handle responses
       */
      QMap<int, QSharedPointer<RequestState> > _requests;

      /**
       * Next request id
       */
      int _current_id;

      /**
       * Used to asynchronously respond to requests
       */
      QSharedPointer<RequestResponder> _responder;

      QSharedPointer<TimerCallback> _timer_callback;
      Utils::TimerEvent _next_call;
  };

  class RequestState {
    public:
      RequestState(const QSharedPointer<ISender> sender,
          const QSharedPointer<ResponseHandler> &res_h,
          qint64 start_time, const Utils::TimerEvent &timer, bool timeout) :
        _sender(sender),
        _res_h(res_h),
        _start_time(start_time),
        _timer(timer),
        _timeout(timeout)
      {
      }

      ~RequestState()
      {
        _timer.Stop();
      }

      inline QSharedPointer<ISender> GetSender() const { return _sender; }

      inline QSharedPointer<ResponseHandler> GetResponseHandler() const
      {
        return _res_h;
      }

      inline qint64 GetStartTime() const { return _start_time; }

      void StopTimer() { _timer.Stop(); }

      bool TimeoutCapable() const { return _timeout; }

    private:
      QSharedPointer<ISender> _sender;
      QSharedPointer<ResponseHandler> _res_h;
      qint64 _start_time;
      Utils::TimerEvent _timer;
      bool _timeout;
  };
}
}

#endif
<commit_msg>[Messaging] Updated comments<commit_after>#ifndef DISSENT_MESSAGING_RPC_HANDLER_H_GUARD
#define DISSENT_MESSAGING_RPC_HANDLER_H_GUARD

#include <QByteArray>
#include <QDebug>
#include <QHash>
#include <QObject>
#include <QString>
#include <QSharedPointer>

#include "Utils/TimerCallback.hpp"
#include "Utils/TimerEvent.hpp"

#include "ISender.hpp"
#include "ISinkObject.hpp"
#include "Request.hpp"
#include "RequestHandler.hpp"
#include "RequestResponder.hpp"
#include "Response.hpp"
#include "ResponseHandler.hpp"

namespace Dissent {
namespace Messaging {
  class RequestState;

  /**
   * Rpc mechanism assumes a reliable sending mechanism
   */
  class RpcHandler : public ISinkObject {
    Q_OBJECT

    public:
      typedef Utils::TimerMethod<RpcHandler, int> TimerCallback;
      static const int TimeoutDelta = 60000;

      inline static QSharedPointer<RpcHandler> GetEmpty()
      {
        static QSharedPointer<RpcHandler> handler(new RpcHandler());
        return handler;
      }

      /**
       * The constructor
       */
      explicit RpcHandler();

      /**
       * The destructor
       */
      virtual ~RpcHandler();

      /**
       * Handle an incoming Rpc request
       * @param from a return path to the requestor
       * @param data serialized request message
       */
      virtual void HandleData(const QSharedPointer<ISender> &from,
          const QByteArray &data);

      /**
       * Handle an incoming Rpc request
       * @param from a return path to the requestor
       * @param container deserialized request message
       */
      void HandleData(const QSharedPointer<ISender> &from,
          const QVariantList &container);

      /**
       * Send a request
       * @param to the destination for the notification
       * @param method the remote method
       * @param data the input data for that method
       * @returns the id of the request so that the callback can be cancelled
       */
      void SendNotification(const QSharedPointer<ISender> &to,
          const QString &method, const QVariant &data);

      /**
       * Send a request
       * @param to the destination for the request
       * @param method the remote method
       * @param data the input data for that method
       * @param callback called when the request is complete
       * @param timeout specifies whether or not to let the request timeout.
       * It is a temporary parameter that will be phased out in the future,
       * all future Rpc Methods should be implemented with potential timeouts
       * in mind.
       * @returns the id of the request so that the callback can be cancelled
       */
      int SendRequest(const QSharedPointer<ISender> &to, const QString &method,
          const QVariant &data, const QSharedPointer<ResponseHandler> &callback,
          bool timeout = false);

      /**
       * Register a callback
       * @param name The string to match it with
       * @param cb Method callback to register
       */
      bool Register(const QString &name,
          const QSharedPointer<RequestHandler> &cb);

      /**
       * Register a callback into the specified object
       * @param name The string to match it with
       * @param obj with the method name
       * @param method name of method
       */
      bool Register(const QString &name, const QObject *obj,
          const char *method);

      /**
       * Unregister a callback
       * @param name name of method to remove
       */
      bool Unregister(const QString &name);

      /**
       * Used to cancel handling a request result
       * @param id the id of the request
       */
      bool CancelRequest(int id)
      {
        return _requests.remove(id) != 0;
      }

    public slots:
      /**
       * Send a response for a request
       * @param request the original request
       * @param data the data for the remote side
       */
      void SendResponse(const Request &request, const QVariant &data);

      /**
       * Send a response for a request
       * @param request the original request
       * @param reason the reason for the failure
       */
      void SendFailedResponse(const Request &request,
          Response::ErrorTypes error, const QString &reason,
          const QVariant &error_data = QVariant());

    private:
      void StartTimer();
      void Timeout(const int &);

      /**
       * Handle an incoming request
       * @param request the request
       */
      void HandleRequest(const Request &request);

      /**
       * Handle an incoming response
       * @param response the response
       */
      void HandleResponse(const Response &response);

      /**
       * Returns the _current_id and increments it to the next
       */
      inline int IncrementId();

      /**
       * Maps a string to a method to call
       */
      QHash<QString, QSharedPointer<RequestHandler> > _callbacks;

      /**
       * Maps id to a callback method to handle responses
       */
      QMap<int, QSharedPointer<RequestState> > _requests;

      /**
       * Next request id
       */
      int _current_id;

      /**
       * Used to asynchronously respond to requests
       */
      QSharedPointer<RequestResponder> _responder;

      QSharedPointer<TimerCallback> _timer_callback;
      Utils::TimerEvent _next_call;
  };

  class RequestState {
    public:
      RequestState(const QSharedPointer<ISender> sender,
          const QSharedPointer<ResponseHandler> &res_h,
          qint64 start_time, const Utils::TimerEvent &timer, bool timeout) :
        _sender(sender),
        _res_h(res_h),
        _start_time(start_time),
        _timer(timer),
        _timeout(timeout)
      {
      }

      ~RequestState()
      {
        _timer.Stop();
      }

      inline QSharedPointer<ISender> GetSender() const { return _sender; }

      inline QSharedPointer<ResponseHandler> GetResponseHandler() const
      {
        return _res_h;
      }

      inline qint64 GetStartTime() const { return _start_time; }

      void StopTimer() { _timer.Stop(); }

      bool TimeoutCapable() const { return _timeout; }

    private:
      QSharedPointer<ISender> _sender;
      QSharedPointer<ResponseHandler> _res_h;
      qint64 _start_time;
      Utils::TimerEvent _timer;
      bool _timeout;
  };
}
}

#endif
<|endoftext|>


<commit_before>/**
 * This file is part of the CernVM File System.
 */
#include "helpers.h"

#ifdef __GLIBC__
#include <gnu/libc-version.h>
#endif
#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <utime.h>

// #include <attr/xattr.h>  // NOLINT
// Necessary because xattr.h does not import sys/types.h

#include <string>
#include <vector>

#include "data_dir_mgmt.h"
#include "garbage_collector.h"
#include "logging.h"
#include "platform.h"
#include "shrinkwrap/fs_traversal_interface.h"
#include "util/posix.h"
#include "xattr.h"

#ifdef __GLIBC__
  #if __GLIBC_MINOR__ < 6
    #warning No lutimes support, glibc >= 2.6 required
  #else
    #define CVMFS_HAS_LUTIMES 1
  #endif
#else
  #define CVMFS_HAS_LUTIMES 1
#endif

void InitialFsOperations(struct fs_traversal_context *ctx) {
  InitializeDataDirectory(ctx);
  InitializeWarningFile(ctx);
  InitializeGarbageCollection(ctx);
}

void FinalizeFsOperations(struct fs_traversal_context *ctx) {
  FinalizeGarbageCollection(ctx);
}

void InitializeWarningFile(struct fs_traversal_context *ctx) {
  const char *warning = WARNING_FILE_NAME;
  FILE *f = fopen(BuildPath(ctx, "/" WARNING_FILE_NAME).c_str(), "w");
  if (f != NULL) {
    fwrite(warning, sizeof(char), strlen(warning), f);
    fclose(f);
  } else {
    LogCvmfs(kLogCvmfs, kLogStderr,
      "Could not write warning file for posix file system!");
  }
}

std::string BuildPath(struct fs_traversal_context *ctx,
  const char *dir) {
  std::string result = ctx->base;
  result += ctx->repo;
  if (dir[0] != '/') {
    result += "/";
  }
  result += dir;
  return result;
}

std::string BuildHiddenPath(struct fs_traversal_context *ctx,
  const char *ident) {
  std::string cur_path = ctx->data;
  cur_path += ident;
  return cur_path;
}

int PosixSetMeta(const char *path,
  const struct cvmfs_attr *stat_info, bool set_permissions/* = true*/) {
  int res = 0;
  if (set_permissions) {
    res = chmod(path, stat_info->st_mode);
    if (res != 0) return -1;
    res = chown(path, stat_info->st_uid, stat_info->st_gid);
    if (res != 0) return -1;
  }
  std::string path_str = std::string(path);
  if (stat_info->cvm_xattrs != NULL) {
    XattrList *xlist = reinterpret_cast<XattrList *>(stat_info->cvm_xattrs);
    if (xlist) {
      std::vector<std::string> v = xlist->ListKeys();
      std::string val;
      if (set_permissions) {
        for (std::vector<std::string>::iterator it = v.begin();
              it != v.end();
              ++it) {
          xlist->Get(*it, &val);
          bool res = platform_lsetxattr(path_str, *it, val);
          if (!res) return -1;
        }
      }
    }
  }
#ifdef CVMFS_HAS_LUTIMES
  const struct timeval times[2] = {
    {stat_info->mtime, 0},
    {stat_info->mtime, 0}
  };
  res = utimes(path, times);
  if (res != 0) return -1;
#endif
  return 0;
}

bool BackupMtimes(std::string path, struct utimbuf *mtimes) {
  // According to valgrind this is necessary due to struct paddings here...
  struct stat stat_buf;
  int res = stat(path.c_str(), &stat_buf);
  if (res != 0) return false;
  mtimes->actime = stat_buf.st_mtime;
  mtimes->modtime = stat_buf.st_mtime;
  return true;
}
<commit_msg>fix typo<commit_after>/**
 * This file is part of the CernVM File System.
 */
#include "helpers.h"

#ifdef __GLIBC__
#include <gnu/libc-version.h>
#endif
#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <utime.h>

// #include <attr/xattr.h>  // NOLINT
// Necessary because xattr.h does not import sys/types.h

#include <string>
#include <vector>

#include "data_dir_mgmt.h"
#include "garbage_collector.h"
#include "logging.h"
#include "platform.h"
#include "shrinkwrap/fs_traversal_interface.h"
#include "util/posix.h"
#include "xattr.h"

#ifdef __GLIBC__
  #if __GLIBC_MINOR__ < 6
    #warning No lutimes support, glibc >= 2.6 required
  #else
    #define CVMFS_HAS_LUTIMES 1
  #endif
#else
  #define CVMFS_HAS_LUTIMES 1
#endif

void InitialFsOperations(struct fs_traversal_context *ctx) {
  InitializeDataDirectory(ctx);
  InitializeWarningFile(ctx);
  InitializeGarbageCollection(ctx);
}

void FinalizeFsOperations(struct fs_traversal_context *ctx) {
  FinalizeGarbageCollection(ctx);
}

void InitializeWarningFile(struct fs_traversal_context *ctx) {
  const char *warning = WARNING_FILE_NAME;
  FILE *f = fopen(BuildPath(ctx, "/" WARNING_FILE_NAME).c_str(), "w");
  if (f != NULL) {
    fwrite(warning, sizeof(char), strlen(warning), f);
    fclose(f);
  } else {
    LogCvmfs(kLogCvmfs, kLogStderr,
      "Could not write warning file for posix file system!");
  }
}

std::string BuildPath(struct fs_traversal_context *ctx,
  const char *dir) {
  std::string result = ctx->base;
  result += ctx->repo;
  if (dir[0] != '/') {
    result += "/";
  }
  result += dir;
  return result;
}

std::string BuildHiddenPath(struct fs_traversal_context *ctx,
  const char *ident) {
  std::string cur_path = ctx->data;
  cur_path += ident;
  return cur_path;
}

int PosixSetMeta(const char *path,
  const struct cvmfs_attr *stat_info, bool set_permissions/* = true*/) {
  int res = 0;
  if (set_permissions) {
    res = chmod(path, stat_info->st_mode);
    if (res != 0) return -1;
    res = chown(path, stat_info->st_uid, stat_info->st_gid);
    if (res != 0) return -1;
  }
  std::string path_str = std::string(path);
  if (stat_info->cvm_xattrs != NULL) {
    XattrList *xlist = reinterpret_cast<XattrList *>(stat_info->cvm_xattrs);
    if (xlist) {
      std::vector<std::string> v = xlist->ListKeys();
      std::string val;
      if (set_permissions) {
        for (std::vector<std::string>::iterator it = v.begin();
              it != v.end();
              ++it) {
          xlist->Get(*it, &val);
          bool res = platform_lsetxattr(path_str, *it, val);
          if (!res) return -1;
        }
      }
    }
  }
#ifdef CVMFS_HAS_LUTIMES
  const struct timeval times[2] = {
    {stat_info->mtime, 0},
    {stat_info->mtime, 0}
  };
  res = lutimes(path, times);
  if (res != 0) return -1;
#endif
  return 0;
}

bool BackupMtimes(std::string path, struct utimbuf *mtimes) {
  // According to valgrind this is necessary due to struct paddings here...
  struct stat stat_buf;
  int res = stat(path.c_str(), &stat_buf);
  if (res != 0) return false;
  mtimes->actime = stat_buf.st_mtime;
  mtimes->modtime = stat_buf.st_mtime;
  return true;
}
<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2014-2015 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <modules/python3/pythonincluder.h>
#include <inviwo/core/common/inviwoapplication.h>
#include "pyinviwo.h"

#include <modules/python3/python3module.h>

#include <modules/python3/pythonscript.h>
#include <modules/python3/pythonexecutionoutputobservable.h>

#include <modules/python3/pythoninterface/pymodule.h>

#include <modules/python3/pyinviwoobserver.h>

#include "defaultinterface/pyproperties.h"
#include "defaultinterface/pycamera.h"
#include "defaultinterface/pycanvas.h"
#include "defaultinterface/pylist.h"
#include "defaultinterface/pyutil.h"
#include "defaultinterface/pyvolume.h"

namespace inviwo {
static PyObject* py_stdout(PyObject* /*self*/, PyObject* args);
class PyStdOutCatcher : public PyMethod {
public:
    virtual std::string getName() const override { return "ivwPrint"; }
    virtual std::string getDesc() const override {
        return " Only for internal use. Redirect std output to python editor widget.";
    }
    virtual PyCFunction getFunc() override { return py_stdout; }
};

static PyObject* py_stdout(PyObject* /*self*/, PyObject* args) {
    char* msg;
    int len;
    int isStderr;

    if (!PyArg_ParseTuple(args, "s#i", &msg, &len, &isStderr)) {
        LogWarnCustom("inviwo.Python.py_print", "failed to parse log message");
    } else {
        if (len != 0) {
            if (!(len == 1 && (msg[0] == '\n' || msg[0] == '\r' || msg[0] == '\0')))
                PythonExecutionOutputObservable::getPtr()->pythonExecutionOutputEvent(
                    msg, (isStderr == 0) ? sysstdout : sysstderr);
        }
    }

    Py_RETURN_NONE;
}

PyInviwo::PyInviwo()
    : isInit_(false)
    , inviwoPyModule_(nullptr)
    , inviwoInternalPyModule_(nullptr)
    , mainDict_(nullptr)
    , modulesDict_(nullptr) {
    init(this);

    initPythonCInterface();
}

PyInviwo::~PyInviwo() {
    delete inviwoPyModule_;
    delete inviwoInternalPyModule_;
}

void PyInviwo::registerPyModule(PyModule* pyModule) {
    if (Py_IsInitialized()) {
        struct PyModuleDef moduleDef = {PyModuleDef_HEAD_INIT, pyModule->getModuleName(), nullptr,
                                        -1, pyModule->getPyMethodDefs()};

        PyObject* obj = PyModule_Create(&moduleDef);

        if (!obj) {
            LogWarn("Failed to init python module '" << pyModule->getModuleName() << "' ");
        }
        PyDict_SetItemString(modulesDict_, pyModule->getModuleName(), obj);

        pyModule->setPyObject(obj);
        registeredModules_.push_back(pyModule);

        for (ObserverSet::reverse_iterator it = observers_->rbegin(); it != observers_->rend();
             ++it) {
            static_cast<PyInviwoObserver*>(*it)->onModuleRegistered(pyModule);
        }
    } else {
        LogError("Python environment not initialized");
    }
}

void PyInviwo::addModulePath(const std::string& path) {
    if (!Py_IsInitialized()) {
        LogWarn("addModulePath(): not initialized");
        return;
    }

    std::string pathConv = path;
    replaceInString(pathConv, "\\", "/");
    std::string runString = "import sys\n";
    runString.append(std::string("sys.path.append('") + pathConv + std::string("')"));
    int ret = PyRun_SimpleString(runString.c_str());

    if (ret != 0) LogWarn("Failed to add '" + pathConv + "' to Python module search path");
}

void PyInviwo::initPythonCInterface() {
    if (isInit_) return;

    isInit_ = true;
    LogInfo("Python version: " + toString(Py_GetVersion()));
    wchar_t programName[] = L"PyInviwo";
    Py_SetProgramName(programName);
#ifdef WIN32
    Py_NoSiteFlag = 1;
#endif
    Py_InitializeEx(false);

    if (!Py_IsInitialized()) {
        LogError("Python is not Initialized");
        return;
    }

    PyEval_InitThreads();
    mainDict_ = PyDict_New();
    modulesDict_ = PyImport_GetModuleDict();
    importModule("builtins");
    importModule("sys");
    importModule("os");
    importModule("glob");
    importModule("random");

    addModulePath(InviwoApplication::getPtr()->getBasePath() + "/modules/python3/scripts");

    initDefaultInterfaces();

    initOutputRedirector();
}

void PyInviwo::importModule(const std::string &moduleName){
    const static std::string __key__ = "__";
    char * key = new char[moduleName.size() + 5];
    sprintf(key,"__%s__", moduleName.c_str());
    if (PyDict_GetItemString(mainDict_, key) == nullptr) {
        PyObject* pMod = PyImport_ImportModule(moduleName.c_str());
        if (nullptr != pMod) {
            PyDict_SetItemString(mainDict_, key, pMod);
            LogInfo("Imported python module: " << moduleName);
        }
        else{
            LogWarn("Failed to import python module: " << moduleName);
        }
    }
    delete [] key;
}

void PyInviwo::initDefaultInterfaces() {
    inviwoInternalPyModule_ = new PyModule("inviwo_internal");
    inviwoInternalPyModule_->addMethod(new PyStdOutCatcher());

    inviwoPyModule_ = new PyModule("inviwo");
    inviwoPyModule_->addMethod(new PySetPropertyValueMethod());
    inviwoPyModule_->addMethod(new PySetPropertyMaxValueMethod());
    inviwoPyModule_->addMethod(new PySetPropertyMinValueMethod());
    inviwoPyModule_->addMethod(new PyGetPropertyValueMethod());
    inviwoPyModule_->addMethod(new PyGetPropertyMaxValueMethod());
    inviwoPyModule_->addMethod(new PyGetPropertyMinValueMethod());
    inviwoPyModule_->addMethod(new PyClickButtonMethod());
    inviwoPyModule_->addMethod(new PySetCameraFocusMethod());
    inviwoPyModule_->addMethod(new PySetCameraUpMethod());
    inviwoPyModule_->addMethod(new PySetCameraPosMethod());
    inviwoPyModule_->addMethod(new PyListPropertiesMethod());
    inviwoPyModule_->addMethod(new PyListProcessorsMethod());
    inviwoPyModule_->addMethod(new PyCanvasCountMethod());
    inviwoPyModule_->addMethod(new PyResizeCanvasMethod());
    inviwoPyModule_->addMethod(new PySnapshotMethod());
    inviwoPyModule_->addMethod(new PySnapshotCanvasMethod());
    inviwoPyModule_->addMethod(new PyGetBasePathMethod());
    inviwoPyModule_->addMethod(new PyGetWorkspaceSavePathMethod());
    inviwoPyModule_->addMethod(new PyGetVolumePathMethod());
    inviwoPyModule_->addMethod(new PyGetDataPathMethod());
    inviwoPyModule_->addMethod(new PyGetImagePathMethod());
    inviwoPyModule_->addMethod(new PyGetModulePathMethod());
    inviwoPyModule_->addMethod(new PyGetTransferFunctionPath());
    inviwoPyModule_->addMethod(new PyGetMemoryUsage());
    inviwoPyModule_->addMethod(new PyClearResourceManage());
    inviwoPyModule_->addMethod(new PyEnableEvaluation());
    inviwoPyModule_->addMethod(new PyDisableEvaluation());
    inviwoPyModule_->addMethod(new PySaveTransferFunction());
    inviwoPyModule_->addMethod(new PyLoadTransferFunction());
    inviwoPyModule_->addMethod(new PyClearTransferfunction());
    inviwoPyModule_->addMethod(new PyAddTransferFunction());

    registerPyModule(inviwoPyModule_);
    registerPyModule(inviwoInternalPyModule_);
}

void PyInviwo::initOutputRedirector() {
    std::string directorFileName =
        InviwoApplication::getPtr()->getModuleByType<Python3Module>()->getPath() +
        "/scripts/outputredirector.py";

    if (!filesystem::fileExists(directorFileName)) {
        LogError("Could not open outputredirector.py");
        return;
    }

    std::ifstream file(directorFileName.c_str());
    std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
    file.close();

    PythonScript outputCatcher;
    outputCatcher.setSource(text);

    if (!outputCatcher.run(false)) {
        LogWarn("Python init script failed to run");
    }
}

}  // namespace
<commit_msg>Python: Removed info message<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2014-2015 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <modules/python3/pythonincluder.h>
#include <inviwo/core/common/inviwoapplication.h>
#include "pyinviwo.h"

#include <modules/python3/python3module.h>

#include <modules/python3/pythonscript.h>
#include <modules/python3/pythonexecutionoutputobservable.h>

#include <modules/python3/pythoninterface/pymodule.h>

#include <modules/python3/pyinviwoobserver.h>

#include "defaultinterface/pyproperties.h"
#include "defaultinterface/pycamera.h"
#include "defaultinterface/pycanvas.h"
#include "defaultinterface/pylist.h"
#include "defaultinterface/pyutil.h"
#include "defaultinterface/pyvolume.h"

namespace inviwo {
static PyObject* py_stdout(PyObject* /*self*/, PyObject* args);
class PyStdOutCatcher : public PyMethod {
public:
    virtual std::string getName() const override { return "ivwPrint"; }
    virtual std::string getDesc() const override {
        return " Only for internal use. Redirect std output to python editor widget.";
    }
    virtual PyCFunction getFunc() override { return py_stdout; }
};

static PyObject* py_stdout(PyObject* /*self*/, PyObject* args) {
    char* msg;
    int len;
    int isStderr;

    if (!PyArg_ParseTuple(args, "s#i", &msg, &len, &isStderr)) {
        LogWarnCustom("inviwo.Python.py_print", "failed to parse log message");
    } else {
        if (len != 0) {
            if (!(len == 1 && (msg[0] == '\n' || msg[0] == '\r' || msg[0] == '\0')))
                PythonExecutionOutputObservable::getPtr()->pythonExecutionOutputEvent(
                    msg, (isStderr == 0) ? sysstdout : sysstderr);
        }
    }

    Py_RETURN_NONE;
}

PyInviwo::PyInviwo()
    : isInit_(false)
    , inviwoPyModule_(nullptr)
    , inviwoInternalPyModule_(nullptr)
    , mainDict_(nullptr)
    , modulesDict_(nullptr) {
    init(this);

    initPythonCInterface();
}

PyInviwo::~PyInviwo() {
    delete inviwoPyModule_;
    delete inviwoInternalPyModule_;
}

void PyInviwo::registerPyModule(PyModule* pyModule) {
    if (Py_IsInitialized()) {
        struct PyModuleDef moduleDef = {PyModuleDef_HEAD_INIT, pyModule->getModuleName(), nullptr,
                                        -1, pyModule->getPyMethodDefs()};

        PyObject* obj = PyModule_Create(&moduleDef);

        if (!obj) {
            LogWarn("Failed to init python module '" << pyModule->getModuleName() << "' ");
        }
        PyDict_SetItemString(modulesDict_, pyModule->getModuleName(), obj);

        pyModule->setPyObject(obj);
        registeredModules_.push_back(pyModule);

        for (ObserverSet::reverse_iterator it = observers_->rbegin(); it != observers_->rend();
             ++it) {
            static_cast<PyInviwoObserver*>(*it)->onModuleRegistered(pyModule);
        }
    } else {
        LogError("Python environment not initialized");
    }
}

void PyInviwo::addModulePath(const std::string& path) {
    if (!Py_IsInitialized()) {
        LogWarn("addModulePath(): not initialized");
        return;
    }

    std::string pathConv = path;
    replaceInString(pathConv, "\\", "/");
    std::string runString = "import sys\n";
    runString.append(std::string("sys.path.append('") + pathConv + std::string("')"));
    int ret = PyRun_SimpleString(runString.c_str());

    if (ret != 0) LogWarn("Failed to add '" + pathConv + "' to Python module search path");
}

void PyInviwo::initPythonCInterface() {
    if (isInit_) return;

    isInit_ = true;
    LogInfo("Python version: " + toString(Py_GetVersion()));
    wchar_t programName[] = L"PyInviwo";
    Py_SetProgramName(programName);
#ifdef WIN32
    Py_NoSiteFlag = 1;
#endif
    Py_InitializeEx(false);

    if (!Py_IsInitialized()) {
        LogError("Python is not Initialized");
        return;
    }

    PyEval_InitThreads();
    mainDict_ = PyDict_New();
    modulesDict_ = PyImport_GetModuleDict();
    importModule("builtins");
    importModule("sys");
    importModule("os");
    importModule("glob");
    importModule("random");

    addModulePath(InviwoApplication::getPtr()->getBasePath() + "/modules/python3/scripts");

    initDefaultInterfaces();

    initOutputRedirector();
}

void PyInviwo::importModule(const std::string &moduleName){
    const static std::string __key__ = "__";
    char * key = new char[moduleName.size() + 5];
    sprintf(key,"__%s__", moduleName.c_str());
    if (PyDict_GetItemString(mainDict_, key) == nullptr) {
        PyObject* pMod = PyImport_ImportModule(moduleName.c_str());
        if (nullptr != pMod) {
            PyDict_SetItemString(mainDict_, key, pMod);
        }
        else{
            LogWarn("Failed to import python module: " << moduleName);
        }
    }
    delete [] key;
}

void PyInviwo::initDefaultInterfaces() {
    inviwoInternalPyModule_ = new PyModule("inviwo_internal");
    inviwoInternalPyModule_->addMethod(new PyStdOutCatcher());

    inviwoPyModule_ = new PyModule("inviwo");
    inviwoPyModule_->addMethod(new PySetPropertyValueMethod());
    inviwoPyModule_->addMethod(new PySetPropertyMaxValueMethod());
    inviwoPyModule_->addMethod(new PySetPropertyMinValueMethod());
    inviwoPyModule_->addMethod(new PyGetPropertyValueMethod());
    inviwoPyModule_->addMethod(new PyGetPropertyMaxValueMethod());
    inviwoPyModule_->addMethod(new PyGetPropertyMinValueMethod());
    inviwoPyModule_->addMethod(new PyClickButtonMethod());
    inviwoPyModule_->addMethod(new PySetCameraFocusMethod());
    inviwoPyModule_->addMethod(new PySetCameraUpMethod());
    inviwoPyModule_->addMethod(new PySetCameraPosMethod());
    inviwoPyModule_->addMethod(new PyListPropertiesMethod());
    inviwoPyModule_->addMethod(new PyListProcessorsMethod());
    inviwoPyModule_->addMethod(new PyCanvasCountMethod());
    inviwoPyModule_->addMethod(new PyResizeCanvasMethod());
    inviwoPyModule_->addMethod(new PySnapshotMethod());
    inviwoPyModule_->addMethod(new PySnapshotCanvasMethod());
    inviwoPyModule_->addMethod(new PyGetBasePathMethod());
    inviwoPyModule_->addMethod(new PyGetWorkspaceSavePathMethod());
    inviwoPyModule_->addMethod(new PyGetVolumePathMethod());
    inviwoPyModule_->addMethod(new PyGetDataPathMethod());
    inviwoPyModule_->addMethod(new PyGetImagePathMethod());
    inviwoPyModule_->addMethod(new PyGetModulePathMethod());
    inviwoPyModule_->addMethod(new PyGetTransferFunctionPath());
    inviwoPyModule_->addMethod(new PyGetMemoryUsage());
    inviwoPyModule_->addMethod(new PyClearResourceManage());
    inviwoPyModule_->addMethod(new PyEnableEvaluation());
    inviwoPyModule_->addMethod(new PyDisableEvaluation());
    inviwoPyModule_->addMethod(new PySaveTransferFunction());
    inviwoPyModule_->addMethod(new PyLoadTransferFunction());
    inviwoPyModule_->addMethod(new PyClearTransferfunction());
    inviwoPyModule_->addMethod(new PyAddTransferFunction());

    registerPyModule(inviwoPyModule_);
    registerPyModule(inviwoInternalPyModule_);
}

void PyInviwo::initOutputRedirector() {
    std::string directorFileName =
        InviwoApplication::getPtr()->getModuleByType<Python3Module>()->getPath() +
        "/scripts/outputredirector.py";

    if (!filesystem::fileExists(directorFileName)) {
        LogError("Could not open outputredirector.py");
        return;
    }

    std::ifstream file(directorFileName.c_str());
    std::string text((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
    file.close();

    PythonScript outputCatcher;
    outputCatcher.setSource(text);

    if (!outputCatcher.run(false)) {
        LogWarn("Python init script failed to run");
    }
}

}  // namespace
<|endoftext|>


<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "main.h"
#include <Eigen/Array>

template<typename MatrixType> void product_extra(const MatrixType& m)
{
  typedef typename MatrixType::Scalar Scalar;
  typedef typename NumTraits<Scalar>::FloatingPoint FloatingPoint;
  typedef Matrix<Scalar, 1, Dynamic> RowVectorType;
  typedef Matrix<Scalar, Dynamic, 1> ColVectorType;
  typedef Matrix<Scalar, Dynamic, Dynamic,
                         MatrixType::Flags&RowMajorBit> OtherMajorMatrixType;

  int rows = m.rows();
  int cols = m.cols();

  MatrixType m1 = MatrixType::Random(rows, cols),
             m2 = MatrixType::Random(rows, cols),
             m3(rows, cols),
             mzero = MatrixType::Zero(rows, cols),
             identity = MatrixType::Identity(rows, rows),
             square = MatrixType::Random(rows, rows),
             res = MatrixType::Random(rows, rows),
             square2 = MatrixType::Random(cols, cols),
             res2 = MatrixType::Random(cols, cols);
  RowVectorType v1 = RowVectorType::Random(rows), vrres(rows);
  ColVectorType vc2 = ColVectorType::Random(cols), vcres(cols);
  OtherMajorMatrixType tm1 = m1;

  Scalar s1 = ei_random<Scalar>(),
         s2 = ei_random<Scalar>(),
         s3 = ei_random<Scalar>();

//   int c0 = ei_random<int>(0,cols/2-1),
//       c1 = ei_random<int>(cols/2,cols),
//       r0 = ei_random<int>(0,rows/2-1),
//       r1 = ei_random<int>(rows/2,rows);

  VERIFY_IS_APPROX(m3.noalias() = m1 * m2.adjoint(),                 m1 * m2.adjoint().eval());
  VERIFY_IS_APPROX(m3.noalias() = m1.adjoint() * square.adjoint(),   m1.adjoint().eval() * square.adjoint().eval());
  VERIFY_IS_APPROX(m3.noalias() = m1.adjoint() * m2,                 m1.adjoint().eval() * m2);
  VERIFY_IS_APPROX(m3.noalias() = (s1 * m1.adjoint()) * m2,          (s1 * m1.adjoint()).eval() * m2);
  VERIFY_IS_APPROX(m3.noalias() = (- m1.adjoint() * s1) * (s3 * m2), (- m1.adjoint()  * s1).eval() * (s3 * m2).eval());
  VERIFY_IS_APPROX(m3.noalias() = (s2 * m1.adjoint() * s1) * m2,     (s2 * m1.adjoint()  * s1).eval() * m2);
  VERIFY_IS_APPROX(m3.noalias() = (-m1*s2) * s1*m2.adjoint(),        (-m1*s2).eval() * (s1*m2.adjoint()).eval());

  // a very tricky case where a scale factor has to be automatically conjugated:
  VERIFY_IS_APPROX( m1.adjoint() * (s1*m2).conjugate(), (m1.adjoint()).eval() * ((s1*m2).conjugate()).eval());

  // test all possible conjugate combinations for the four matrix-vector product cases:

  VERIFY_IS_APPROX((-m1.conjugate() * s2) * (s1 * vc2),
                   (-m1.conjugate()*s2).eval() * (s1 * vc2).eval());
  VERIFY_IS_APPROX((-m1 * s2) * (s1 * vc2.conjugate()),
                   (-m1*s2).eval() * (s1 * vc2.conjugate()).eval());
  VERIFY_IS_APPROX((-m1.conjugate() * s2) * (s1 * vc2.conjugate()),
                   (-m1.conjugate()*s2).eval() * (s1 * vc2.conjugate()).eval());

  VERIFY_IS_APPROX((s1 * vc2.transpose()) * (-m1.adjoint() * s2),
                   (s1 * vc2.transpose()).eval() * (-m1.adjoint()*s2).eval());
  VERIFY_IS_APPROX((s1 * vc2.adjoint()) * (-m1.transpose() * s2),
                   (s1 * vc2.adjoint()).eval() * (-m1.transpose()*s2).eval());
  VERIFY_IS_APPROX((s1 * vc2.adjoint()) * (-m1.adjoint() * s2),
                   (s1 * vc2.adjoint()).eval() * (-m1.adjoint()*s2).eval());

  VERIFY_IS_APPROX((-m1.adjoint() * s2) * (s1 * v1.transpose()),
                   (-m1.adjoint()*s2).eval() * (s1 * v1.transpose()).eval());
  VERIFY_IS_APPROX((-m1.transpose() * s2) * (s1 * v1.adjoint()),
                   (-m1.transpose()*s2).eval() * (s1 * v1.adjoint()).eval());
  VERIFY_IS_APPROX((-m1.adjoint() * s2) * (s1 * v1.adjoint()),
                   (-m1.adjoint()*s2).eval() * (s1 * v1.adjoint()).eval());

  VERIFY_IS_APPROX((s1 * v1) * (-m1.conjugate() * s2),
                   (s1 * v1).eval() * (-m1.conjugate()*s2).eval());
  VERIFY_IS_APPROX((s1 * v1.conjugate()) * (-m1 * s2),
                   (s1 * v1.conjugate()).eval() * (-m1*s2).eval());
  VERIFY_IS_APPROX((s1 * v1.conjugate()) * (-m1.conjugate() * s2),
                   (s1 * v1.conjugate()).eval() * (-m1.conjugate()*s2).eval());

  VERIFY_IS_APPROX((-m1.adjoint() * s2) * (s1 * v1.adjoint()),
                   (-m1.adjoint()*s2).eval() * (s1 * v1.adjoint()).eval());

}

void test_product_extra()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST( product_extra(MatrixXf(ei_random<int>(1,320), ei_random<int>(1,320))) );
    CALL_SUBTEST( product_extra(MatrixXcf(ei_random<int>(50,50), ei_random<int>(50,50))) );
    CALL_SUBTEST( product_extra(Matrix<std::complex<double>,Dynamic,Dynamic,RowMajor>(ei_random<int>(1,50), ei_random<int>(1,50))) );
  }
}
<commit_msg>improve coverage of matrix-vector product<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2006-2008 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.

#include "main.h"
#include <Eigen/Array>

template<typename MatrixType> void product_extra(const MatrixType& m)
{
  typedef typename MatrixType::Scalar Scalar;
  typedef typename NumTraits<Scalar>::FloatingPoint FloatingPoint;
  typedef Matrix<Scalar, 1, Dynamic> RowVectorType;
  typedef Matrix<Scalar, Dynamic, 1> ColVectorType;
  typedef Matrix<Scalar, Dynamic, Dynamic,
                         MatrixType::Flags&RowMajorBit> OtherMajorMatrixType;

  int rows = m.rows();
  int cols = m.cols();

  MatrixType m1 = MatrixType::Random(rows, cols),
             m2 = MatrixType::Random(rows, cols),
             m3(rows, cols),
             mzero = MatrixType::Zero(rows, cols),
             identity = MatrixType::Identity(rows, rows),
             square = MatrixType::Random(rows, rows),
             res = MatrixType::Random(rows, rows),
             square2 = MatrixType::Random(cols, cols),
             res2 = MatrixType::Random(cols, cols);
  RowVectorType v1 = RowVectorType::Random(rows), vrres(rows);
  ColVectorType vc2 = ColVectorType::Random(cols), vcres(cols);
  OtherMajorMatrixType tm1 = m1;

  Scalar s1 = ei_random<Scalar>(),
         s2 = ei_random<Scalar>(),
         s3 = ei_random<Scalar>();

//   int c0 = ei_random<int>(0,cols/2-1),
//       c1 = ei_random<int>(cols/2,cols),
//       r0 = ei_random<int>(0,rows/2-1),
//       r1 = ei_random<int>(rows/2,rows);

  VERIFY_IS_APPROX(m3.noalias() = m1 * m2.adjoint(),                 m1 * m2.adjoint().eval());
  VERIFY_IS_APPROX(m3.noalias() = m1.adjoint() * square.adjoint(),   m1.adjoint().eval() * square.adjoint().eval());
  VERIFY_IS_APPROX(m3.noalias() = m1.adjoint() * m2,                 m1.adjoint().eval() * m2);
  VERIFY_IS_APPROX(m3.noalias() = (s1 * m1.adjoint()) * m2,          (s1 * m1.adjoint()).eval() * m2);
  VERIFY_IS_APPROX(m3.noalias() = (- m1.adjoint() * s1) * (s3 * m2), (- m1.adjoint()  * s1).eval() * (s3 * m2).eval());
  VERIFY_IS_APPROX(m3.noalias() = (s2 * m1.adjoint() * s1) * m2,     (s2 * m1.adjoint()  * s1).eval() * m2);
  VERIFY_IS_APPROX(m3.noalias() = (-m1*s2) * s1*m2.adjoint(),        (-m1*s2).eval() * (s1*m2.adjoint()).eval());

  // a very tricky case where a scale factor has to be automatically conjugated:
  VERIFY_IS_APPROX( m1.adjoint() * (s1*m2).conjugate(), (m1.adjoint()).eval() * ((s1*m2).conjugate()).eval());

  // test all possible conjugate combinations for the four matrix-vector product cases:

  VERIFY_IS_APPROX((-m1.conjugate() * s2) * (s1 * vc2),
                   (-m1.conjugate()*s2).eval() * (s1 * vc2).eval());
  VERIFY_IS_APPROX((-m1 * s2) * (s1 * vc2.conjugate()),
                   (-m1*s2).eval() * (s1 * vc2.conjugate()).eval());
  VERIFY_IS_APPROX((-m1.conjugate() * s2) * (s1 * vc2.conjugate()),
                   (-m1.conjugate()*s2).eval() * (s1 * vc2.conjugate()).eval());

  VERIFY_IS_APPROX((s1 * vc2.transpose()) * (-m1.adjoint() * s2),
                   (s1 * vc2.transpose()).eval() * (-m1.adjoint()*s2).eval());
  VERIFY_IS_APPROX((s1 * vc2.adjoint()) * (-m1.transpose() * s2),
                   (s1 * vc2.adjoint()).eval() * (-m1.transpose()*s2).eval());
  VERIFY_IS_APPROX((s1 * vc2.adjoint()) * (-m1.adjoint() * s2),
                   (s1 * vc2.adjoint()).eval() * (-m1.adjoint()*s2).eval());

  VERIFY_IS_APPROX((-m1.adjoint() * s2) * (s1 * v1.transpose()),
                   (-m1.adjoint()*s2).eval() * (s1 * v1.transpose()).eval());
  VERIFY_IS_APPROX((-m1.transpose() * s2) * (s1 * v1.adjoint()),
                   (-m1.transpose()*s2).eval() * (s1 * v1.adjoint()).eval());
  VERIFY_IS_APPROX((-m1.adjoint() * s2) * (s1 * v1.adjoint()),
                   (-m1.adjoint()*s2).eval() * (s1 * v1.adjoint()).eval());

  VERIFY_IS_APPROX((s1 * v1) * (-m1.conjugate() * s2),
                   (s1 * v1).eval() * (-m1.conjugate()*s2).eval());
  VERIFY_IS_APPROX((s1 * v1.conjugate()) * (-m1 * s2),
                   (s1 * v1.conjugate()).eval() * (-m1*s2).eval());
  VERIFY_IS_APPROX((s1 * v1.conjugate()) * (-m1.conjugate() * s2),
                   (s1 * v1.conjugate()).eval() * (-m1.conjugate()*s2).eval());

  VERIFY_IS_APPROX((-m1.adjoint() * s2) * (s1 * v1.adjoint()),
                   (-m1.adjoint()*s2).eval() * (s1 * v1.adjoint()).eval());

  // test the vector-matrix product with non aligned starts
  int i = ei_random<int>(0,m1.rows()-2);
  int j = ei_random<int>(0,m1.cols()-2);
  int r = ei_random<int>(1,m1.rows()-i);
  int c = ei_random<int>(1,m1.cols()-j);
  int i2 = ei_random<int>(0,m1.rows()-1);
  int j2 = ei_random<int>(0,m1.cols()-1);

  VERIFY_IS_APPROX(m1.col(j2).adjoint() * m1.block(0,j,m1.rows(),c), m1.col(j2).adjoint().eval() * m1.block(0,j,m1.rows(),c).eval());
  VERIFY_IS_APPROX(m1.block(i,0,r,m1.cols()) * m1.row(i2).adjoint(), m1.block(i,0,r,m1.cols()).eval() * m1.row(i2).adjoint().eval());

}

void test_product_extra()
{
  for(int i = 0; i < g_repeat; i++) {
    CALL_SUBTEST( product_extra(MatrixXf(ei_random<int>(2,320), ei_random<int>(2,320))) );
    CALL_SUBTEST( product_extra(MatrixXcf(ei_random<int>(50,50), ei_random<int>(50,50))) );
    CALL_SUBTEST( product_extra(Matrix<std::complex<double>,Dynamic,Dynamic,RowMajor>(ei_random<int>(2,50), ei_random<int>(2,50))) );
  }
}
<|endoftext|>


<commit_before>/*
    OpenDeck MIDI platform firmware
    Copyright (C) 2015-2018 Igor Petrovic

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "board/Board.h"
#include "interface/Interface.h"
#include "Version.h"
#include "interface/midi/Handlers.h"

MIDI                midi;
bool                processingEnabled;
midiClockStatus_t   midiClockStatus;

void init()
{
    board.init();
    database.init();
    sysEx.init();

    #ifdef DIN_MIDI_SUPPORTED
    if (database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureDinEnabled))
    {
        setupMIDIoverUART(UART_MIDI_CHANNEL);

        //use recursive parsing when merging is active
        if (database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureMergeEnabled))
            midi.useRecursiveParsing(true);
        else
            midi.useRecursiveParsing(false);
    }
    #endif

    //enable uart-to-usb link when usb isn't supported directly
    #ifndef USB_SUPPORTED
    setupMIDIoverUART_OD(UART_USB_LINK_CHANNEL);
    #endif

    midi.setInputChannel(MIDI_CHANNEL_OMNI);
    midi.setNoteOffMode((noteOffType_t)database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureStandardNoteOff));
    midi.setRunningStatusState(database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureRunningStatus));
    midi.setChannelSendZeroStart(true);

    board.ledFlashStartup(board.checkNewRevision());

    //enable global interrupts
    sei();

    #ifdef LEDS_SUPPORTED
    leds.init();
    #endif

    #ifdef DISPLAY_SUPPORTED
    if (database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureEnable))
    {
        if (display.init((displayController_t)database.read(DB_BLOCK_DISPLAY, dbSection_display_hw, displayHwController), (displayResolution_t)database.read(DB_BLOCK_DISPLAY, dbSection_display_hw, displayHwResolution)))
        {
            display.setDirectWriteState(true);

            if (database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureWelcomeMsg))
                display.displayWelcomeMessage();

            if (database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureVInfoMsg))
                display.displayVinfo(false);

            display.setDirectWriteState(false);

            display.displayHome();
            display.setRetentionState(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDIeventRetention));
            display.setRetentionTime(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDIeventTime) * 1000);
            display.setAlternateNoteDisplay(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDInotesAlternate));
        }
    }
    #endif

    processingEnabled = true;
    midiClockStatus = midiClockStop;

    #ifdef BOARD_BERGAMOT
    touchscreen.init(ts_sdw);
    touchscreen.setPage(1);
    #endif
}

int main()
{
    init();

    #ifdef USB_SUPPORTED
    //wait a bit before checking if usb is connected
    wait_ms(1500);

    if (board.isUSBconnected())
    {
        //this board is connected to usb, check if din is enabled
        if (database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureDinEnabled) && !database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureMergeEnabled))
        {
            //start daisy-chain auto-config
            //format message as special request so that it's parsed on other boards
            sysExParameter_t daisyChainMessage[] =
            {
                SYSEX_CR_DAISY_CHAIN_MASTER,
            };

            sysEx.sendCustomMessage(usbMessage.sysexArray, daisyChainMessage, 1, false);
        }
    }
    #endif

    while(1)
    {
        //note: mega/uno
        //"fake" usbInterface - din data is stored as usb data so use usb callback to read the usb
        //packet stored in midi object
        if (midi.read(usbInterface))
        {
            //new message on usb
            midiMessageType_t messageType = midi.getType(usbInterface);
            #if defined(LEDS_SUPPORTED) || defined(DISPLAY_SUPPORTED)
            uint8_t data1 = midi.getData1(usbInterface);
            uint8_t data2 = midi.getData2(usbInterface);
            uint8_t channel = midi.getChannel(usbInterface);
            #endif

            switch(messageType)
            {
                case midiMessageSystemExclusive:
                //don't handle sysex on slave boards in daisy-chain setup
                #ifdef BOARD_OPEN_DECK
                if (board.isUSBconnected())
                #endif
                    sysEx.handleMessage(midi.getSysExArray(usbInterface), midi.getSysExArrayLength(usbInterface));
                break;

                case midiMessageNoteOn:
                case midiMessageNoteOff:
                case midiMessageControlChange:
                case midiMessageProgramChange:
                #if defined(LEDS_SUPPORTED) || defined(DISPLAY_SUPPORTED)
                if (messageType == midiMessageNoteOff)
                    data2 = 0;
                #endif
                #ifdef LEDS_SUPPORTED
                leds.midiToState(messageType, data1, data2, channel);
                #endif
                #ifdef DISPLAY_SUPPORTED
                display.displayMIDIevent(displayEventIn, midiMessageNoteOn_display, data1, data2, channel+1);
                #endif
                break;

                case midiMessageClock:
                midiClockStatus = midiClockChange;
                break;

                case midiMessageStart:
                midiClockStatus = midiClockReset;
                break;

                case midiMessageStop:
                midiClockStatus = midiClockStop;
                break;

                default:
                break;
            }
        }

        #ifdef BOARD_OPEN_DECK
        if (database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureDinEnabled))
        {
            //check for incoming MIDI messages on UART
            //merging is supported on opendeck board only at the moment
            if (!database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureMergeEnabled))
            {
                //daisy-chained opendeck boards
                if (!board.getUARTloopbackState(UART_MIDI_CHANNEL))
                {
                    if (!board.isUSBconnected())
                    {
                        //in this case, board is slave, check only for sysex from master
                        if (midi.read(dinInterface))
                        {
                            midiMessageType_t messageType = midi.getType(dinInterface);

                            if (messageType == midiMessageSystemExclusive)
                            {
                                sysEx.handleMessage(midi.getSysExArray(dinInterface), midi.getSysExArrayLength(dinInterface));
                            }
                        }
                    }
                    else
                    {
                        //master opendeck - dump everything from MIDI in to USB MIDI out
                        if (uartReadMIDI_OD(UART_MIDI_CHANNEL))
                            Board::usbWriteMIDI(usbMIDIpacket);
                    }
                }
                else
                {
                    //all incoming data is forwarded automatically (inner slave)
                }
            }
            else
            {
                switch(database.read(DB_BLOCK_MIDI, dbSection_midi_merge, midiMergeToInterface))
                {
                    case midiMergeToInterfaceUSB:
                    //dump everything from DIN MIDI in to USB MIDI out
                    midi.read(dinInterface, THRU_FULL_USB);
                    break;

                    default:
                    break;
                }
            }
        }
        #endif

        if (processingEnabled)
        {
            digitalInput.update();
            analog.update();
            #ifdef LEDS_SUPPORTED
            leds.update();
            #endif

            #ifdef DISPLAY_SUPPORTED
            display.update();
            #endif

            #ifdef TOUCHSCREEN_SUPPORTED
            touchscreen.update();
            #endif
        }
    }
}
<commit_msg>fix incorrect uart init order<commit_after>/*
    OpenDeck MIDI platform firmware
    Copyright (C) 2015-2018 Igor Petrovic

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "board/Board.h"
#include "interface/Interface.h"
#include "Version.h"
#include "interface/midi/Handlers.h"

MIDI                midi;
bool                processingEnabled;
midiClockStatus_t   midiClockStatus;

void init()
{
    board.init();
    database.init();
    sysEx.init();

    //enable uart-to-usb link when usb isn't supported directly
    #ifndef USB_SUPPORTED
    setupMIDIoverUART_OD(UART_USB_LINK_CHANNEL);
    #endif

    #ifdef DIN_MIDI_SUPPORTED
    if (database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureDinEnabled))
    {
        setupMIDIoverUART(UART_MIDI_CHANNEL);

        //use recursive parsing when merging is active
        if (database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureMergeEnabled))
            midi.useRecursiveParsing(true);
        else
            midi.useRecursiveParsing(false);
    }
    #endif

    midi.setInputChannel(MIDI_CHANNEL_OMNI);
    midi.setNoteOffMode((noteOffType_t)database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureStandardNoteOff));
    midi.setRunningStatusState(database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureRunningStatus));
    midi.setChannelSendZeroStart(true);

    board.ledFlashStartup(board.checkNewRevision());

    //enable global interrupts
    sei();

    #ifdef LEDS_SUPPORTED
    leds.init();
    #endif

    #ifdef DISPLAY_SUPPORTED
    if (database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureEnable))
    {
        if (display.init((displayController_t)database.read(DB_BLOCK_DISPLAY, dbSection_display_hw, displayHwController), (displayResolution_t)database.read(DB_BLOCK_DISPLAY, dbSection_display_hw, displayHwResolution)))
        {
            display.setDirectWriteState(true);

            if (database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureWelcomeMsg))
                display.displayWelcomeMessage();

            if (database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureVInfoMsg))
                display.displayVinfo(false);

            display.setDirectWriteState(false);

            display.displayHome();
            display.setRetentionState(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDIeventRetention));
            display.setRetentionTime(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDIeventTime) * 1000);
            display.setAlternateNoteDisplay(database.read(DB_BLOCK_DISPLAY, dbSection_display_features, displayFeatureMIDInotesAlternate));
        }
    }
    #endif

    processingEnabled = true;
    midiClockStatus = midiClockStop;

    #ifdef BOARD_BERGAMOT
    touchscreen.init(ts_sdw);
    touchscreen.setPage(1);
    #endif
}

int main()
{
    init();

    #ifdef USB_SUPPORTED
    //wait a bit before checking if usb is connected
    wait_ms(1500);

    if (board.isUSBconnected())
    {
        //this board is connected to usb, check if din is enabled
        if (database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureDinEnabled) && !database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureMergeEnabled))
        {
            //start daisy-chain auto-config
            //format message as special request so that it's parsed on other boards
            sysExParameter_t daisyChainMessage[] =
            {
                SYSEX_CR_DAISY_CHAIN_MASTER,
            };

            sysEx.sendCustomMessage(usbMessage.sysexArray, daisyChainMessage, 1, false);
        }
    }
    #endif

    while(1)
    {
        //note: mega/uno
        //"fake" usbInterface - din data is stored as usb data so use usb callback to read the usb
        //packet stored in midi object
        if (midi.read(usbInterface))
        {
            //new message on usb
            midiMessageType_t messageType = midi.getType(usbInterface);
            #if defined(LEDS_SUPPORTED) || defined(DISPLAY_SUPPORTED)
            uint8_t data1 = midi.getData1(usbInterface);
            uint8_t data2 = midi.getData2(usbInterface);
            uint8_t channel = midi.getChannel(usbInterface);
            #endif

            switch(messageType)
            {
                case midiMessageSystemExclusive:
                //don't handle sysex on slave boards in daisy-chain setup
                #ifdef BOARD_OPEN_DECK
                if (board.isUSBconnected())
                #endif
                    sysEx.handleMessage(midi.getSysExArray(usbInterface), midi.getSysExArrayLength(usbInterface));
                break;

                case midiMessageNoteOn:
                case midiMessageNoteOff:
                case midiMessageControlChange:
                case midiMessageProgramChange:
                #if defined(LEDS_SUPPORTED) || defined(DISPLAY_SUPPORTED)
                if (messageType == midiMessageNoteOff)
                    data2 = 0;
                #endif
                #ifdef LEDS_SUPPORTED
                leds.midiToState(messageType, data1, data2, channel);
                #endif
                #ifdef DISPLAY_SUPPORTED
                display.displayMIDIevent(displayEventIn, midiMessageNoteOn_display, data1, data2, channel+1);
                #endif
                break;

                case midiMessageClock:
                midiClockStatus = midiClockChange;
                break;

                case midiMessageStart:
                midiClockStatus = midiClockReset;
                break;

                case midiMessageStop:
                midiClockStatus = midiClockStop;
                break;

                default:
                break;
            }
        }

        #ifdef BOARD_OPEN_DECK
        if (database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureDinEnabled))
        {
            //check for incoming MIDI messages on UART
            //merging is supported on opendeck board only at the moment
            if (!database.read(DB_BLOCK_MIDI, dbSection_midi_feature, midiFeatureMergeEnabled))
            {
                //daisy-chained opendeck boards
                if (!board.getUARTloopbackState(UART_MIDI_CHANNEL))
                {
                    if (!board.isUSBconnected())
                    {
                        //in this case, board is slave, check only for sysex from master
                        if (midi.read(dinInterface))
                        {
                            midiMessageType_t messageType = midi.getType(dinInterface);

                            if (messageType == midiMessageSystemExclusive)
                            {
                                sysEx.handleMessage(midi.getSysExArray(dinInterface), midi.getSysExArrayLength(dinInterface));
                            }
                        }
                    }
                    else
                    {
                        //master opendeck - dump everything from MIDI in to USB MIDI out
                        if (uartReadMIDI_OD(UART_MIDI_CHANNEL))
                            Board::usbWriteMIDI(usbMIDIpacket);
                    }
                }
                else
                {
                    //all incoming data is forwarded automatically (inner slave)
                }
            }
            else
            {
                switch(database.read(DB_BLOCK_MIDI, dbSection_midi_merge, midiMergeToInterface))
                {
                    case midiMergeToInterfaceUSB:
                    //dump everything from DIN MIDI in to USB MIDI out
                    midi.read(dinInterface, THRU_FULL_USB);
                    break;

                    default:
                    break;
                }
            }
        }
        #endif

        if (processingEnabled)
        {
            digitalInput.update();
            analog.update();
            #ifdef LEDS_SUPPORTED
            leds.update();
            #endif

            #ifdef DISPLAY_SUPPORTED
            display.update();
            #endif

            #ifdef TOUCHSCREEN_SUPPORTED
            touchscreen.update();
            #endif
        }
    }
}
<|endoftext|>