<commit_before>// MediaInfo_Internal - All info about media files
// Copyright (C) 2002-2011 MediaArea.net SARL, Info@MediaArea.net
//
// This library 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
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// For user: you can disable or enable it
//#define MEDIAINFO_DEBUG
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Reader/Reader_File.h"
#include "MediaInfo/File__Analyze.h"
#include "ZenLib/FileName.h"
#ifdef WINDOWS
    #undef __TEXT
    #include "Windows.h"
#endif //WINDOWS
using namespace ZenLib;
using namespace std;
//---------------------------------------------------------------------------
// Debug stuff
#ifdef MEDIAINFO_DEBUG
    int64u Reader_File_Offset=0;
    int64u Reader_File_BytesRead_Total=0;
    int64u Reader_File_BytesRead=0;
    int64u Reader_File_Count=1;
    #include <iostream>
#endif // MEDIAINFO_DEBUG
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

const size_t Buffer_NoJump=128*1024;

//---------------------------------------------------------------------------
size_t Reader_File::Format_Test(MediaInfo_Internal* MI, const String &File_Name)
{
    //std::cout<<Ztring(File_Name).To_Local().c_str()<<std::endl;
    #if MEDIAINFO_EVENTS
        {
            struct MediaInfo_Event_General_Start_0 Event;
            Event.EventCode=MediaInfo_EventCode_Create(MediaInfo_Parser_None, MediaInfo_Event_General_Start, 0);
            Event.Stream_Size=File::Size_Get(File_Name);
            MI->Config.Event_Send((const int8u*)&Event, sizeof(MediaInfo_Event_General_Start_0));
        }
    #endif //MEDIAINFO_EVENTS

    //With Parser MultipleParsing
    /*
    MI->Open_Buffer_Init((int64u)-1, File_Name);
    if (Format_Test_PerParser(MI, File_Name))
         return 1;
    return 0; //There is a problem
    */

    //Get the Extension
    Ztring Extension=FileName::Extension_Get(File_Name);
    Extension.MakeLowerCase();

    //Search the theorical format from extension
    InfoMap &FormatList=MediaInfoLib::Config.Format_Get();
    InfoMap::iterator Format=FormatList.begin();
    while (Format!=FormatList.end())
    {
        const Ztring &Extensions=FormatList.Get(Format->first, InfoFormat_Extensions);
        if (Extensions.find(Extension)!=Error)
        {
            if(Extension.size()==Extensions.size())
                break; //Only one extenion in the list
            if(Extensions.find(Extension+_T(" "))!=Error
            || Extensions.find(_T(" ")+Extension)!=Error)
                break;
        }
        Format++;
    }
    if (Format!=FormatList.end())
    {
        const Ztring &Parser=Format->second(InfoFormat_Parser);
        if (MI->SelectFromExtension(Parser))
        {
            //Test the theorical format
            if (Format_Test_PerParser(MI, File_Name)>0)
                 return 1;
        }
    }

    size_t ToReturn=MI->ListFormats(File_Name);
    return ToReturn;
}

//---------------------------------------------------------------------------
size_t Reader_File::Format_Test_PerParser(MediaInfo_Internal* MI, const String &File_Name)
{
    //Opening the file
    F.Open(File_Name);
    if (!F.Opened_Get())
        return 0;

    //Info
    Status=0;
    MI->Config.File_Size=F.Size_Get();

    //Partial file handling
    Ztring Config_Partial_Begin=MI->Config.File_Partial_Begin_Get();
    if (!Config_Partial_Begin.empty() && Config_Partial_Begin[0]>=_T('0') && Config_Partial_Begin[0]<=_T('9'))
    {
        if (Config_Partial_Begin.find(_T('%'))==Config_Partial_Begin.size()-1)
            Partial_Begin=float64_int64s(MI->Config.File_Size*Config_Partial_Begin.To_float64()/100);
        else
            Partial_Begin=Config_Partial_Begin.To_int64u();
        if (Partial_Begin)
            F.GoTo(Partial_Begin);
    }
    else
        Partial_Begin=0;
    Ztring Config_Partial_End=MI->Config.File_Partial_End_Get();
    if (!Config_Partial_End.empty() && Config_Partial_End[0]>=_T('0') && Config_Partial_End[0]<=_T('9'))
    {
        if (Config_Partial_End.find(_T('%'))==Config_Partial_End.size()-1)
            Partial_End=float64_int64s(MI->Config.File_Size*Config_Partial_End.To_float64()/100);
        else
            Partial_End=Config_Partial_End.To_int64u();
    }
    else
        Partial_End=(int64u)-1;
    if (Partial_Begin>MI->Config.File_Size)
        Partial_Begin=0; //Wrong value
    if (Partial_Begin>Partial_End)
        Partial_Begin=0; //Wrong value

    //Parser
    MI->Open_Buffer_Init((Partial_End<=MI->Config.File_Size?Partial_End:MI->Config.File_Size)-Partial_Begin, File_Name);

    //Buffer
    MI->Option(_T("File_Buffer_Size_Hint_Pointer"), Ztring::ToZtring((size_t)(&MI->Config.File_Buffer_Size_ToRead)));
    MI->Config.File_Buffer_Repeat_IsSupported=true;

    //Test the format with buffer
    return Format_Test_PerParser_Continue(MI);
}

//---------------------------------------------------------------------------
size_t Reader_File::Format_Test_PerParser_Continue (MediaInfo_Internal* MI)
{
    bool StopAfterFilled=MI->Config.File_StopAfterFilled_Get();
    bool ShouldContinue=true;

    //Previous data
    if (MI->Config.File_Buffer_Repeat)
    {
        MI->Config.File_Buffer_Repeat=false;
        #if MEDIAINFO_DEMUX
            MI->Config.Demux_EventWasSent=false;
        #endif //MEDIAINFO_DEMUX

        Status=MI->Open_Buffer_Continue(MI->Config.File_Buffer, MI->Config.File_Buffer_Size);

        #if MEDIAINFO_DEMUX
            //Demux
            if (MI->Config.Demux_EventWasSent)
                return 2; //Must return immediately
        #endif //MEDIAINFO_DEMUX

        //Threading
        if (MI->IsTerminating())
            return 1; //Termination is requested

        if (Status[File__Analyze::IsFinished] || (StopAfterFilled && Status[File__Analyze::IsFilled]))
            ShouldContinue=false;
    }

    #if MEDIAINFO_DEMUX
    //PerPacket
    if (ShouldContinue && MI->Config.Demux_EventWasSent)
    {
        MI->Config.Demux_EventWasSent=false;

        Status=MI->Open_Buffer_Continue(NULL, 0);

        //Demux
        if (MI->Config.Demux_EventWasSent)
            return 2; //Must return immediately

        //Threading
        if (MI->IsTerminating())
            return 1; //Termination is requested

        if (Status[File__Analyze::IsFinished] || (StopAfterFilled && Status[File__Analyze::IsFilled]))
            ShouldContinue=false;
    }
    #endif //MEDIAINFO_DEMUX

    if (ShouldContinue)
    {
        //Test the format with buffer
        while (!(Status[File__Analyze::IsFinished] || (StopAfterFilled && Status[File__Analyze::IsFilled])))
        {
            //Seek (if needed)
            if (MI->Open_Buffer_Continue_GoTo_Get()!=(int64u)-1)
            {
                #ifdef MEDIAINFO_DEBUG
                    std::cout<<std::hex<<Reader_File_Offset<<" - "<<Reader_File_Offset+Reader_File_BytesRead<<" : "<<std::dec<<Reader_File_BytesRead<<" bytes"<<std::endl;
                    Reader_File_Offset=MI->Open_Buffer_Continue_GoTo_Get();
                    Reader_File_BytesRead=0;
                    Reader_File_Count++;
                #endif //MEDIAINFO_DEBUG

                if (MI->Open_Buffer_Continue_GoTo_Get()>=F.Size_Get())
                    break; //Seek requested, but on a file bigger in theory than what is in the real file, we can't do this
                if (!(MI->Open_Buffer_Continue_GoTo_Get()>F.Position_Get() && MI->Open_Buffer_Continue_GoTo_Get()<F.Position_Get()+Buffer_NoJump)) //No smal jumps
                {
                     if (!F.GoTo(Partial_Begin+MI->Open_Buffer_Continue_GoTo_Get()))
                        break; //File is not seekable

                    MI->Open_Buffer_Init((int64u)-1, F.Position_Get()-Partial_Begin);
                }
            }

            //Handling of hints
            if (MI->Config.File_Buffer_Size_ToRead==0)
                break; //Problem while config
            if (MI->Config.File_Buffer_Size_ToRead>MI->Config.File_Buffer_Size_Max)
            {
                delete[] MI->Config.File_Buffer;
                if (MI->Config.File_Buffer_Size_Max==0)
                    MI->Config.File_Buffer_Size_Max=1;
                while (MI->Config.File_Buffer_Size_ToRead>MI->Config.File_Buffer_Size_Max)
                    MI->Config.File_Buffer_Size_Max*=2;
                MI->Config.File_Buffer=new int8u[MI->Config.File_Buffer_Size_Max];
            }

            MI->Config.File_Buffer_Size=F.Read(MI->Config.File_Buffer, (F.Position_Get()+MI->Config.File_Buffer_Size_ToRead<(Partial_End<=MI->Config.File_Size?Partial_End:MI->Config.File_Size))?MI->Config.File_Buffer_Size_ToRead:((size_t)((Partial_End<=MI->Config.File_Size?Partial_End:MI->Config.File_Size)-F.Position_Get())));

            //Testing growing files
            if (!MI->Config.File_IsGrowing && F.Position_Get()>=MI->Config.File_Size)
            {
                if (MediaInfoLib::Config.ParseSpeed_Get()>=1.0) //Only if full parsing
                {
                    int64u FileSize_New=F.Size_Get();
                    if (MI->Config.File_Size!=FileSize_New)
                        MI->Config.File_IsGrowing=true;
                }
            }
            if (MI->Config.File_IsNotGrowingAnymore)
            {
                MI->Config.File_Size=F.Size_Get();;
                MI->Open_Buffer_Init(MI->Config.File_Size, F.Position_Get()-MI->Config.File_Buffer_Size);
                MI->Config.File_IsGrowing=false;
                MI->Config.File_IsNotGrowingAnymore=false;
            }
            if (MI->Config.File_IsGrowing && F.Position_Get()>=MI->Config.File_Size)
            {
                for (size_t CountOfSeconds=0; CountOfSeconds<10; CountOfSeconds++)
                {
                    int64u FileSize_New=F.Size_Get();
                    if (MI->Config.File_Size!=FileSize_New)
                    {
                        MI->Config.File_Size=FileSize_New;
                        MI->Open_Buffer_Init(MI->Config.File_Size, F.Position_Get()-MI->Config.File_Buffer_Size);
                        break;
                    }
                    #ifdef WINDOWS
                        Sleep(1000);
                    #endif //WINDOWS
                }
            }

            #ifdef MEDIAINFO_DEBUG
                Reader_File_BytesRead_Total+=MI->Config.File_Buffer_Size;
                Reader_File_BytesRead+=MI->Config.File_Buffer_Size;
            #endif //MEDIAINFO_DEBUG

            //Parser
            Status=MI->Open_Buffer_Continue(MI->Config.File_Buffer, MI->Config.File_Buffer_Size);
            if (MI->Config.File_Buffer_Size==0)
                break;

            #if MEDIAINFO_DEMUX
                if (MI->Config.Demux_EventWasSent)
                    return 2; //Must return immediately
            #endif //MEDIAINFO_DEMUX

            //Threading
            if (MI->IsTerminating())
                break; //Termination is requested
        }
    }

    #ifdef MEDIAINFO_DEBUG
        std::cout<<std::hex<<Reader_File_Offset<<" - "<<Reader_File_Offset+Reader_File_BytesRead<<" : "<<std::dec<<Reader_File_BytesRead<<" bytes"<<std::endl;
        std::cout<<"Total: "<<std::dec<<Reader_File_BytesRead_Total<<" bytes in "<<Reader_File_Count<<" blocks"<<std::endl;
    #endif //MEDIAINFO_DEBUG

    if (MI==NULL || !MI->Config.File_KeepInfo_Get())
    {
        //File
        F.Close();
    }

    //Is this file detected?
    if (!Status[File__Analyze::IsAccepted])
        return 0;

    MI->Open_Buffer_Finalize();

    #if MEDIAINFO_DEMUX
        if (MI->Config.Demux_EventWasSent)
            return 2; //Must return immediately
    #endif //MEDIAINFO_DEMUX

    return 1;
}

//---------------------------------------------------------------------------
#if MEDIAINFO_SEEK
size_t Reader_File::Format_Test_PerParser_Seek (MediaInfo_Internal* MI, size_t Method, int64u Value, int64u ID)
{
    size_t ToReturn=MI->Open_Buffer_Seek(Method, Value, ID);

    if (ToReturn==0 || ToReturn==1)
    {
        //Reset
        Status=0;
    }

    return ToReturn;
}
#endif //MEDIAINFO_SEEK

} //NameSpace
<commit_msg>+ Parser can be forced for files<commit_after>// MediaInfo_Internal - All info about media files
// Copyright (C) 2002-2011 MediaArea.net SARL, Info@MediaArea.net
//
// This library 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
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// For user: you can disable or enable it
//#define MEDIAINFO_DEBUG
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Reader/Reader_File.h"
#include "MediaInfo/File__Analyze.h"
#include "ZenLib/FileName.h"
#ifdef WINDOWS
    #undef __TEXT
    #include "Windows.h"
#endif //WINDOWS
using namespace ZenLib;
using namespace std;
//---------------------------------------------------------------------------
// Debug stuff
#ifdef MEDIAINFO_DEBUG
    int64u Reader_File_Offset=0;
    int64u Reader_File_BytesRead_Total=0;
    int64u Reader_File_BytesRead=0;
    int64u Reader_File_Count=1;
    #include <iostream>
#endif // MEDIAINFO_DEBUG
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

const size_t Buffer_NoJump=128*1024;

//---------------------------------------------------------------------------
size_t Reader_File::Format_Test(MediaInfo_Internal* MI, const String &File_Name)
{
    //std::cout<<Ztring(File_Name).To_Local().c_str()<<std::endl;
    #if MEDIAINFO_EVENTS
        {
            struct MediaInfo_Event_General_Start_0 Event;
            Event.EventCode=MediaInfo_EventCode_Create(MediaInfo_Parser_None, MediaInfo_Event_General_Start, 0);
            Event.Stream_Size=File::Size_Get(File_Name);
            MI->Config.Event_Send((const int8u*)&Event, sizeof(MediaInfo_Event_General_Start_0));
        }
    #endif //MEDIAINFO_EVENTS

    //With Parser MultipleParsing
    /*
    MI->Open_Buffer_Init((int64u)-1, File_Name);
    if (Format_Test_PerParser(MI, File_Name))
         return 1;
    return 0; //There is a problem
    */

    //Get the Extension
    Ztring Extension=FileName::Extension_Get(File_Name);
    Extension.MakeLowerCase();

    //Search the theorical format from extension
    InfoMap &FormatList=MediaInfoLib::Config.Format_Get();
    InfoMap::iterator Format=FormatList.end();
    if (!MI->Config.File_ForceParser_Get().empty())
        Format=FormatList.find(MI->Config.File_ForceParser_Get());
    if (Format==FormatList.end())
    {
        Format=FormatList.begin();
        while (Format!=FormatList.end())
        {
            const Ztring &Extensions=FormatList.Get(Format->first, InfoFormat_Extensions);
            if (Extensions.find(Extension)!=Error)
            {
                if(Extension.size()==Extensions.size())
                    break; //Only one extenion in the list
                if(Extensions.find(Extension+_T(" "))!=Error
                || Extensions.find(_T(" ")+Extension)!=Error)
                    break;
            }
            Format++;
        }
    }
    if (Format!=FormatList.end())
    {
        const Ztring &Parser=Format->second(InfoFormat_Parser);
        if (MI->SelectFromExtension(Parser))
        {
            //Test the theorical format
            if (Format_Test_PerParser(MI, File_Name)>0)
                 return 1;
        }
    }

    size_t ToReturn=MI->ListFormats(File_Name);
    return ToReturn;
}

//---------------------------------------------------------------------------
size_t Reader_File::Format_Test_PerParser(MediaInfo_Internal* MI, const String &File_Name)
{
    //Opening the file
    F.Open(File_Name);
    if (!F.Opened_Get())
        return 0;

    //Info
    Status=0;
    MI->Config.File_Size=F.Size_Get();

    //Partial file handling
    Ztring Config_Partial_Begin=MI->Config.File_Partial_Begin_Get();
    if (!Config_Partial_Begin.empty() && Config_Partial_Begin[0]>=_T('0') && Config_Partial_Begin[0]<=_T('9'))
    {
        if (Config_Partial_Begin.find(_T('%'))==Config_Partial_Begin.size()-1)
            Partial_Begin=float64_int64s(MI->Config.File_Size*Config_Partial_Begin.To_float64()/100);
        else
            Partial_Begin=Config_Partial_Begin.To_int64u();
        if (Partial_Begin)
            F.GoTo(Partial_Begin);
    }
    else
        Partial_Begin=0;
    Ztring Config_Partial_End=MI->Config.File_Partial_End_Get();
    if (!Config_Partial_End.empty() && Config_Partial_End[0]>=_T('0') && Config_Partial_End[0]<=_T('9'))
    {
        if (Config_Partial_End.find(_T('%'))==Config_Partial_End.size()-1)
            Partial_End=float64_int64s(MI->Config.File_Size*Config_Partial_End.To_float64()/100);
        else
            Partial_End=Config_Partial_End.To_int64u();
    }
    else
        Partial_End=(int64u)-1;
    if (Partial_Begin>MI->Config.File_Size)
        Partial_Begin=0; //Wrong value
    if (Partial_Begin>Partial_End)
        Partial_Begin=0; //Wrong value

    //Parser
    MI->Open_Buffer_Init((Partial_End<=MI->Config.File_Size?Partial_End:MI->Config.File_Size)-Partial_Begin, File_Name);

    //Buffer
    MI->Option(_T("File_Buffer_Size_Hint_Pointer"), Ztring::ToZtring((size_t)(&MI->Config.File_Buffer_Size_ToRead)));
    MI->Config.File_Buffer_Repeat_IsSupported=true;

    //Test the format with buffer
    return Format_Test_PerParser_Continue(MI);
}

//---------------------------------------------------------------------------
size_t Reader_File::Format_Test_PerParser_Continue (MediaInfo_Internal* MI)
{
    bool StopAfterFilled=MI->Config.File_StopAfterFilled_Get();
    bool ShouldContinue=true;

    //Previous data
    if (MI->Config.File_Buffer_Repeat)
    {
        MI->Config.File_Buffer_Repeat=false;
        #if MEDIAINFO_DEMUX
            MI->Config.Demux_EventWasSent=false;
        #endif //MEDIAINFO_DEMUX

        Status=MI->Open_Buffer_Continue(MI->Config.File_Buffer, MI->Config.File_Buffer_Size);

        #if MEDIAINFO_DEMUX
            //Demux
            if (MI->Config.Demux_EventWasSent)
                return 2; //Must return immediately
        #endif //MEDIAINFO_DEMUX

        //Threading
        if (MI->IsTerminating())
            return 1; //Termination is requested

        if (Status[File__Analyze::IsFinished] || (StopAfterFilled && Status[File__Analyze::IsFilled]))
            ShouldContinue=false;
    }

    #if MEDIAINFO_DEMUX
    //PerPacket
    if (ShouldContinue && MI->Config.Demux_EventWasSent)
    {
        MI->Config.Demux_EventWasSent=false;

        Status=MI->Open_Buffer_Continue(NULL, 0);

        //Demux
        if (MI->Config.Demux_EventWasSent)
            return 2; //Must return immediately

        //Threading
        if (MI->IsTerminating())
            return 1; //Termination is requested

        if (Status[File__Analyze::IsFinished] || (StopAfterFilled && Status[File__Analyze::IsFilled]))
            ShouldContinue=false;
    }
    #endif //MEDIAINFO_DEMUX

    if (ShouldContinue)
    {
        //Test the format with buffer
        while (!(Status[File__Analyze::IsFinished] || (StopAfterFilled && Status[File__Analyze::IsFilled])))
        {
            //Seek (if needed)
            if (MI->Open_Buffer_Continue_GoTo_Get()!=(int64u)-1)
            {
                #ifdef MEDIAINFO_DEBUG
                    std::cout<<std::hex<<Reader_File_Offset<<" - "<<Reader_File_Offset+Reader_File_BytesRead<<" : "<<std::dec<<Reader_File_BytesRead<<" bytes"<<std::endl;
                    Reader_File_Offset=MI->Open_Buffer_Continue_GoTo_Get();
                    Reader_File_BytesRead=0;
                    Reader_File_Count++;
                #endif //MEDIAINFO_DEBUG

                if (MI->Open_Buffer_Continue_GoTo_Get()>=F.Size_Get())
                    break; //Seek requested, but on a file bigger in theory than what is in the real file, we can't do this
                if (!(MI->Open_Buffer_Continue_GoTo_Get()>F.Position_Get() && MI->Open_Buffer_Continue_GoTo_Get()<F.Position_Get()+Buffer_NoJump)) //No smal jumps
                {
                     if (!F.GoTo(Partial_Begin+MI->Open_Buffer_Continue_GoTo_Get()))
                        break; //File is not seekable

                    MI->Open_Buffer_Init((int64u)-1, F.Position_Get()-Partial_Begin);
                }
            }

            //Handling of hints
            if (MI->Config.File_Buffer_Size_ToRead==0)
                break; //Problem while config
            if (MI->Config.File_Buffer_Size_ToRead>MI->Config.File_Buffer_Size_Max)
            {
                delete[] MI->Config.File_Buffer;
                if (MI->Config.File_Buffer_Size_Max==0)
                    MI->Config.File_Buffer_Size_Max=1;
                while (MI->Config.File_Buffer_Size_ToRead>MI->Config.File_Buffer_Size_Max)
                    MI->Config.File_Buffer_Size_Max*=2;
                MI->Config.File_Buffer=new int8u[MI->Config.File_Buffer_Size_Max];
            }

            MI->Config.File_Buffer_Size=F.Read(MI->Config.File_Buffer, (F.Position_Get()+MI->Config.File_Buffer_Size_ToRead<(Partial_End<=MI->Config.File_Size?Partial_End:MI->Config.File_Size))?MI->Config.File_Buffer_Size_ToRead:((size_t)((Partial_End<=MI->Config.File_Size?Partial_End:MI->Config.File_Size)-F.Position_Get())));

            //Testing growing files
            if (!MI->Config.File_IsGrowing && F.Position_Get()>=MI->Config.File_Size)
            {
                if (MediaInfoLib::Config.ParseSpeed_Get()>=1.0) //Only if full parsing
                {
                    int64u FileSize_New=F.Size_Get();
                    if (MI->Config.File_Size!=FileSize_New)
                        MI->Config.File_IsGrowing=true;
                }
            }
            if (MI->Config.File_IsNotGrowingAnymore)
            {
                MI->Config.File_Size=F.Size_Get();;
                MI->Open_Buffer_Init(MI->Config.File_Size, F.Position_Get()-MI->Config.File_Buffer_Size);
                MI->Config.File_IsGrowing=false;
                MI->Config.File_IsNotGrowingAnymore=false;
            }
            if (MI->Config.File_IsGrowing && F.Position_Get()>=MI->Config.File_Size)
            {
                for (size_t CountOfSeconds=0; CountOfSeconds<10; CountOfSeconds++)
                {
                    int64u FileSize_New=F.Size_Get();
                    if (MI->Config.File_Size!=FileSize_New)
                    {
                        MI->Config.File_Size=FileSize_New;
                        MI->Open_Buffer_Init(MI->Config.File_Size, F.Position_Get()-MI->Config.File_Buffer_Size);
                        break;
                    }
                    #ifdef WINDOWS
                        Sleep(1000);
                    #endif //WINDOWS
                }
            }

            #ifdef MEDIAINFO_DEBUG
                Reader_File_BytesRead_Total+=MI->Config.File_Buffer_Size;
                Reader_File_BytesRead+=MI->Config.File_Buffer_Size;
            #endif //MEDIAINFO_DEBUG

            //Parser
            Status=MI->Open_Buffer_Continue(MI->Config.File_Buffer, MI->Config.File_Buffer_Size);
            if (MI->Config.File_Buffer_Size==0)
                break;

            #if MEDIAINFO_DEMUX
                if (MI->Config.Demux_EventWasSent)
                    return 2; //Must return immediately
            #endif //MEDIAINFO_DEMUX

            //Threading
            if (MI->IsTerminating())
                break; //Termination is requested
        }
    }

    #ifdef MEDIAINFO_DEBUG
        std::cout<<std::hex<<Reader_File_Offset<<" - "<<Reader_File_Offset+Reader_File_BytesRead<<" : "<<std::dec<<Reader_File_BytesRead<<" bytes"<<std::endl;
        std::cout<<"Total: "<<std::dec<<Reader_File_BytesRead_Total<<" bytes in "<<Reader_File_Count<<" blocks"<<std::endl;
    #endif //MEDIAINFO_DEBUG

    if (MI==NULL || !MI->Config.File_KeepInfo_Get())
    {
        //File
        F.Close();
    }

    //Is this file detected?
    if (!Status[File__Analyze::IsAccepted])
        return 0;

    MI->Open_Buffer_Finalize();

    #if MEDIAINFO_DEMUX
        if (MI->Config.Demux_EventWasSent)
            return 2; //Must return immediately
    #endif //MEDIAINFO_DEMUX

    return 1;
}

//---------------------------------------------------------------------------
#if MEDIAINFO_SEEK
size_t Reader_File::Format_Test_PerParser_Seek (MediaInfo_Internal* MI, size_t Method, int64u Value, int64u ID)
{
    size_t ToReturn=MI->Open_Buffer_Seek(Method, Value, ID);

    if (ToReturn==0 || ToReturn==1)
    {
        //Reset
        Status=0;
    }

    return ToReturn;
}
#endif //MEDIAINFO_SEEK

} //NameSpace
<|endoftext|>


<commit_before>#include "stufffinder.h"
#include "sqlite3.h"
#include "Database.h"
#include <string>

#include <vector>
#include <Layout.h>
//included for testing only
#include<iostream>
#include<fstream>

StuffFinder::StuffFinder(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
	Output_item_tree();

	// Create context menus
	containerContextMenu = new QMenu(ui.itemsTreeWidget);
	itemContextMenu = new QMenu(ui.itemsTreeWidget);
	ui.itemsTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);

	// Connect the tree widget to the onCustomContextMenu slot function
	connect(ui.itemsTreeWidget, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(onCustomContextMenu(const QPoint &)));
	// Add actions to the menus and connect them to their slots
	containerContextMenu->addAction("Add Container", this, SLOT(addContainerClicked()));
	containerContextMenu->addAction("Add Item", this, SLOT(addItemClicked()));
	itemContextMenu->addAction("Edit Item", this, SLOT(editItemClicked()));

}

StuffFinder::~StuffFinder()
{

}

void StuffFinder::Output_item_tree()
{
	// Clear and setup tree widget
	ui.itemsTreeWidget->clear();
	ui.itemsTreeWidget->header()->close();
	ui.itemsTreeWidget->setColumnCount(1);

	// Get all the layouts and their items
	layouts = db.Load_Layouts();

	if (layouts.size())
	{
		// Iterate over all rooms in layout.   Currently by default does only first layout.
		for (int i = 0; i < layouts[0]->get_rooms().size(); i++)
		{
			// Create top level item and set text
			QTreeWidgetItem *room = new QTreeWidgetItem(ui.itemsTreeWidget);
			room->setText(0, QString::fromStdString(layouts[0]->get_rooms()[i]->get_name()));
			// Add the container id to the tree widget item
			room->setData(0, Qt::UserRole, layouts[0]->get_rooms()[i]->get_container_id());

			ui.containerComboBox->addItem(QString::fromStdString(layouts[0]->get_rooms()[i]->get_name()),
				layouts[0]->get_rooms()[i]->get_container_id());
			// Get all of its children with recursive function
			setItems(room, layouts[0]->get_rooms()[i], 1);
			ui.itemsTreeWidget->addTopLevelItem(room);
		}
	}

	ui.containerComboBox->setCurrentIndex(-1);

}

void StuffFinder::setItems(QTreeWidgetItem * room, Container * cont, int level)
{
	// Recursively go through all subcontainers
	for (int j = 0; j < cont->get_container().size(); j++)
	{
		QTreeWidgetItem * subcontainer = new QTreeWidgetItem(room);
		subcontainer->setText(0, QString::fromStdString(cont->get_container()[j]->get_name()));
		// Add the container id to the tree widget item
		subcontainer->setData(0, Qt::UserRole, cont->get_container()[j]->get_container_id());

		// Get container name and add "-" for each level its at
		QString container_name = QString::fromStdString(cont->get_container()[j]->get_name());
		for (int k = 0; k < level; k++)
		{
			container_name = "-" + container_name;
		}
		// Add container to combo box
		ui.containerComboBox->addItem(container_name,
			cont->get_container()[j]->get_container_id());
		setItems(subcontainer, cont->get_container()[j], ++level);
	}
	// Add owned items to the tree
	for (int i = 0; i < cont->get_items().size(); i++)
	{
		QTreeWidgetItem *item = new QTreeWidgetItem(room);
		item->setText(0, QString::fromStdString(cont->get_items()[i]->get_name()));
		// Set "container id" to 0 so we know its an item
		item->setData(0, Qt::UserRole, 0);
	}

	return;
}

void StuffFinder::on_search_returnPressed()
{
	//binds return key to on_Search_button_clicked
	//function, essentially
	//
	on_Search_button_clicked();
}

void StuffFinder::on_Search_button_clicked()
{
	//get value from search entry field & convert
	//to string.
	//
	std::string query = ui.search->text().toStdString();

	Item * find_item = layouts[0]->search(query);
	//send value to db search function
	if (find_item == NULL)
	{
		QMessageBox msgBox;
		msgBox.setText("Your search found no items with that name.");
		msgBox.exec();
		return;
	}
	else
	{
		QMessageBox msgBox;
		std::string output = "Found your item!!!!\nName: " + find_item->get_name() + "\nDescription: " + find_item->get_description() + "\nCategory: "
			+ find_item->get_category() + "\nQuantity: " + std::to_string(find_item->get_quantity());
		QString qstr = QString::fromStdString(output);
		msgBox.setText(qstr);
		msgBox.exec();
		return;
	}
}

void StuffFinder::on_Add_save_clicked()
{
	//gets values from entry fields and
	//converts to string so can be saved in database
	//

	std::string name = ui.Item_name->text().toStdString();
	std::string descript = ui.Item_descript->toPlainText().toStdString();
	std::string quant = ui.Item_quant->text().toStdString();
	std::string minquant = ui.Min_quant->text().toStdString();
	std::string cost = ui.Item_cost->text().toStdString();
	int container_id = ui.containerComboBox->itemData(ui.containerComboBox->currentIndex(), Qt::UserRole).toInt();

	//send values to an add/edit item function
	//  which is connected to the database
	// Check if the fields are populated
	if (name.empty() || descript.empty() || quant.empty() || minquant.empty()
		|| cost.empty() || ui.containerComboBox->currentIndex() == -1)
	{
		QMessageBox msgBox;
		msgBox.setText("You didnt fill in all the boxees silly!");
		msgBox.exec();
		return;
	}
	// Add item and update list
	Item * add_me = new Item(name, descript, std::stoi(quant.c_str()), "temp");
	db.Create_Item(add_me, container_id);
	Output_item_tree();

	ui.Item_name->clear();
	ui.Item_descript->clear();
	ui.Item_quant->clear();
	ui.Min_quant->clear();
	ui.Item_cost->clear();
	ui.containerComboBox->setCurrentIndex(-1);
	/*test print
	using namespace std;
	ofstream file;
	file.open("testoutput.txt");
	file << name << endl;
	file << iquant << endl;
	file.close();
	*/
}

void StuffFinder::on_Add_cancel_clicked()
{
	/*clears entry fields when cancel button is
	clicked (in add/edit item tab).
	*/
	ui.Item_name->clear();
	ui.Item_descript->clear();
	ui.Item_quant->clear();
	ui.Min_quant->clear();
	ui.Item_cost->clear();
}

void StuffFinder::on_Create_db_clicked()
{
	sqlite3 *db;
	char *zErrMsg = 0;
	int rc;

	rc = sqlite3_open("test.db", &db);

	if (rc)
	{
		QMessageBox msgBox;
		msgBox.setText("Can't open database: %s.");
		msgBox.exec();
	}
	else
	{
		QMessageBox msgBox;
		msgBox.setText("Opened database successfully.");
		msgBox.exec();
	}
	sqlite3_close(db);
}

void StuffFinder::onCustomContextMenu(const QPoint &point)
{
	// Check if its a container
	if (ui.itemsTreeWidget->itemAt(point)->data(0, Qt::UserRole).toInt())
	{
		containerContextMenu->exec(ui.itemsTreeWidget->mapToGlobal(point));
	}
	// Its an item
	else
	{
		itemContextMenu->exec(ui.itemsTreeWidget->mapToGlobal(point));
	}
}

void StuffFinder::addContainerClicked()
{
	// Temp code
	QMessageBox msgBox;
	msgBox.setText("Eventually I'll do something!");
	msgBox.exec();
}

void StuffFinder::addItemClicked()
{
	// Temp code
	QMessageBox msgBox;
	msgBox.setText("Eventually I'll do something(like adding an item)!");
	msgBox.exec();
}

void StuffFinder::editItemClicked()
{
	// Temp code
	QMessageBox msgBox;
	msgBox.setText("Eventually I'll do something to an item!");
	msgBox.exec();
}<commit_msg>Added combo.clear() b/c it kept adding to drop down every time you add item.<commit_after>#include "stufffinder.h"
#include "sqlite3.h"
#include "Database.h"
#include <string>

#include <vector>
#include <Layout.h>
//included for testing only
#include<iostream>
#include<fstream>

StuffFinder::StuffFinder(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
	Output_item_tree();

	// Create context menus
	containerContextMenu = new QMenu(ui.itemsTreeWidget);
	itemContextMenu = new QMenu(ui.itemsTreeWidget);
	ui.itemsTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);

	// Connect the tree widget to the onCustomContextMenu slot function
	connect(ui.itemsTreeWidget, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(onCustomContextMenu(const QPoint &)));
	// Add actions to the menus and connect them to their slots
	containerContextMenu->addAction("Add Container", this, SLOT(addContainerClicked()));
	containerContextMenu->addAction("Add Item", this, SLOT(addItemClicked()));
	itemContextMenu->addAction("Edit Item", this, SLOT(editItemClicked()));

}

StuffFinder::~StuffFinder()
{

}

void StuffFinder::Output_item_tree()
{
	// Clear and setup tree widget
	ui.itemsTreeWidget->clear();
	ui.itemsTreeWidget->header()->close();
	ui.itemsTreeWidget->setColumnCount(1);

	// Get all the layouts and their items
	layouts = db.Load_Layouts();
	ui.containerComboBox->clear();

	if (layouts.size())
	{
		// Iterate over all rooms in layout.   Currently by default does only first layout.
		for (int i = 0; i < layouts[0]->get_rooms().size(); i++)
		{
			// Create top level item and set text
			QTreeWidgetItem *room = new QTreeWidgetItem(ui.itemsTreeWidget);
			room->setText(0, QString::fromStdString(layouts[0]->get_rooms()[i]->get_name()));
			// Add the container id to the tree widget item
			room->setData(0, Qt::UserRole, layouts[0]->get_rooms()[i]->get_container_id());

			ui.containerComboBox->addItem(QString::fromStdString(layouts[0]->get_rooms()[i]->get_name()),
				layouts[0]->get_rooms()[i]->get_container_id());
			// Get all of its children with recursive function
			setItems(room, layouts[0]->get_rooms()[i], 1);
			ui.itemsTreeWidget->addTopLevelItem(room);
		}
	}

	ui.containerComboBox->setCurrentIndex(-1);

}

void StuffFinder::setItems(QTreeWidgetItem * room, Container * cont, int level)
{
	// Recursively go through all subcontainers
	for (int j = 0; j < cont->get_container().size(); j++)
	{
		QTreeWidgetItem * subcontainer = new QTreeWidgetItem(room);
		subcontainer->setText(0, QString::fromStdString(cont->get_container()[j]->get_name()));
		// Add the container id to the tree widget item
		subcontainer->setData(0, Qt::UserRole, cont->get_container()[j]->get_container_id());

		// Get container name and add "-" for each level its at
		QString container_name = QString::fromStdString(cont->get_container()[j]->get_name());
		for (int k = 0; k < level; k++)
		{
			container_name = "-" + container_name;
		}
		// Add container to combo box
		ui.containerComboBox->addItem(container_name,
			cont->get_container()[j]->get_container_id());
		setItems(subcontainer, cont->get_container()[j], ++level);
	}
	// Add owned items to the tree
	for (int i = 0; i < cont->get_items().size(); i++)
	{
		QTreeWidgetItem *item = new QTreeWidgetItem(room);
		item->setText(0, QString::fromStdString(cont->get_items()[i]->get_name()));
		// Set "container id" to 0 so we know its an item
		item->setData(0, Qt::UserRole, 0);
	}

	return;
}

void StuffFinder::on_search_returnPressed()
{
	//binds return key to on_Search_button_clicked
	//function, essentially
	//
	on_Search_button_clicked();
}

void StuffFinder::on_Search_button_clicked()
{
	//get value from search entry field & convert
	//to string.
	//
	std::string query = ui.search->text().toStdString();

	Item * find_item = layouts[0]->search(query);
	//send value to db search function
	if (find_item == NULL)
	{
		QMessageBox msgBox;
		msgBox.setText("Your search found no items with that name.");
		msgBox.exec();
		return;
	}
	else
	{
		QMessageBox msgBox;
		std::string output = "Found your item!!!!\nName: " + find_item->get_name() + "\nDescription: " + find_item->get_description() + "\nCategory: "
			+ find_item->get_category() + "\nQuantity: " + std::to_string(find_item->get_quantity());
		QString qstr = QString::fromStdString(output);
		msgBox.setText(qstr);
		msgBox.exec();
		return;
	}
}

void StuffFinder::on_Add_save_clicked()
{
	//gets values from entry fields and
	//converts to string so can be saved in database
	//

	std::string name = ui.Item_name->text().toStdString();
	std::string descript = ui.Item_descript->toPlainText().toStdString();
	std::string quant = ui.Item_quant->text().toStdString();
	std::string minquant = ui.Min_quant->text().toStdString();
	std::string cost = ui.Item_cost->text().toStdString();
	int container_id = ui.containerComboBox->itemData(ui.containerComboBox->currentIndex(), Qt::UserRole).toInt();

	//send values to an add/edit item function
	//  which is connected to the database
	// Check if the fields are populated
	if (name.empty() || descript.empty() || quant.empty() || minquant.empty()
		|| cost.empty() || ui.containerComboBox->currentIndex() == -1)
	{
		QMessageBox msgBox;
		msgBox.setText("You didnt fill in all the boxees silly!");
		msgBox.exec();
		return;
	}
	// Add item and update list
	Item * add_me = new Item(name, descript, std::stoi(quant.c_str()), "temp");
	db.Create_Item(add_me, container_id);
	Output_item_tree();

	ui.Item_name->clear();
	ui.Item_descript->clear();
	ui.Item_quant->clear();
	ui.Min_quant->clear();
	ui.Item_cost->clear();
	ui.containerComboBox->setCurrentIndex(-1);
	/*test print
	using namespace std;
	ofstream file;
	file.open("testoutput.txt");
	file << name << endl;
	file << iquant << endl;
	file.close();
	*/
}

void StuffFinder::on_Add_cancel_clicked()
{
	/*clears entry fields when cancel button is
	clicked (in add/edit item tab).
	*/
	ui.Item_name->clear();
	ui.Item_descript->clear();
	ui.Item_quant->clear();
	ui.Min_quant->clear();
	ui.Item_cost->clear();
}

void StuffFinder::on_Create_db_clicked()
{
	sqlite3 *db;
	char *zErrMsg = 0;
	int rc;

	rc = sqlite3_open("test.db", &db);

	if (rc)
	{
		QMessageBox msgBox;
		msgBox.setText("Can't open database: %s.");
		msgBox.exec();
	}
	else
	{
		QMessageBox msgBox;
		msgBox.setText("Opened database successfully.");
		msgBox.exec();
	}
	sqlite3_close(db);
}

void StuffFinder::onCustomContextMenu(const QPoint &point)
{
	// Check if its a container
	if (ui.itemsTreeWidget->itemAt(point)->data(0, Qt::UserRole).toInt())
	{
		containerContextMenu->exec(ui.itemsTreeWidget->mapToGlobal(point));
	}
	// Its an item
	else
	{
		itemContextMenu->exec(ui.itemsTreeWidget->mapToGlobal(point));
	}
}

void StuffFinder::addContainerClicked()
{
	// Temp code
	QMessageBox msgBox;
	msgBox.setText("Eventually I'll do something!");
	msgBox.exec();
}

void StuffFinder::addItemClicked()
{
	// Temp code
	QMessageBox msgBox;
	msgBox.setText("Eventually I'll do something(like adding an item)!");
	msgBox.exec();
}

void StuffFinder::editItemClicked()
{
	// Temp code
	QMessageBox msgBox;
	msgBox.setText("Eventually I'll do something to an item!");
	msgBox.exec();
}<|endoftext|>


<commit_before>#include "SimpleITKTestHarness.h"
#include "sitkCastImageFilter.h"
#include "sitkSimpleElastix.h"

namespace sitk = itk::simple;

class SimpleElastixTest : public ::testing::Test
{
protected:

    virtual void SetUp()
    {
        fixedImage = sitk::Cast( sitk::ReadImage( dataFinder.GetFile( "Input/BrainProtonDensitySliceBorder20.png" ) ), sitk::sitkFloat32 );
        movingImage = sitk::Cast( sitk::ReadImage( dataFinder.GetFile( "Input/BrainProtonDensitySliceShifted13x17y.png" ) ), sitk::sitkFloat32 );
        mask = sitk::Cast( sitk::ReadImage( dataFinder.GetFile( "Input/BrainProtonDensitySliceBorder20Mask.png" ) ), sitk::sitkFloat32 );
        outputFolder = std::string( "." );
    }

    typedef sitk::SimpleElastix                       SimpleElastixType;
    typedef SimpleElastixType::ParameterMapType       ParameterMapType;
    typedef SimpleElastixType::ParameterMapVectorType   ParameterMapVectorType;
    typedef SimpleElastixType::ParameterValueVectorType    ParameterValueVectorType;

    sitk::Image fixedImage;
    sitk::Image movingImage;
    sitk::Image mask;
    std::string outputFolder;

    bool IsEmpty( const sitk::Image image )
    {
      return ( image.GetWidth() == 0 && image.GetHeight() == 0 );
    }
};

TEST_F( SimpleElastixTest, ObjectOrientedInterface )
{
    SimpleElastixType elastix;

    EXPECT_EQ( elastix.GetName(), "SimpleElastix" );
    EXPECT_EQ( elastix.GetParameterMap().size(), 0u );
    EXPECT_EQ( elastix.GetTransformParameterMap().size(), 0u );

    EXPECT_THROW( elastix.Execute(), sitk::GenericException );
    EXPECT_NO_THROW( elastix.SetFixedImage( fixedImage ) );
    EXPECT_THROW( elastix.Execute(), sitk::GenericException );
    EXPECT_NO_THROW( elastix.SetMovingImage( movingImage ) );

    // Minimum viable parameter map
    ParameterMapType parameterMap;
    parameterMap[ "Interpolator"]         = ParameterValueVectorType( 1, "LinearInterpolator");
    parameterMap[ "Optimizer" ]           = ParameterValueVectorType( 1, "AdaptiveStochasticGradientDescent" );
    parameterMap[ "Resampler"]            = ParameterValueVectorType( 1, "DefaultResampler" );
    parameterMap[ "ResampleInterpolator"] = ParameterValueVectorType( 1, "FinalBSplineInterpolator" );
    parameterMap[ "ImageSampler" ]        = ParameterValueVectorType( 1, "RandomCoordinate" );
    parameterMap[ "Registration" ]        = ParameterValueVectorType( 1, "MultiResolutionRegistration" );
    parameterMap[ "Transform" ]           = ParameterValueVectorType( 1, "TranslationTransform" );
    parameterMap[ "Metric" ]              = ParameterValueVectorType( 1, "AdvancedMattesMutualInformation" );

    EXPECT_NO_THROW( elastix.LogToConsoleOn();  );
    EXPECT_NO_THROW( elastix.LogToFileOn();  );
    EXPECT_NO_THROW( elastix.SetParameterMap( parameterMap ) );
    EXPECT_NO_THROW( elastix.Execute() );
    EXPECT_FALSE( this->IsEmpty( elastix.GetResultImage() ) );

    EXPECT_NO_THROW( elastix.SetFixedMask( mask ) );
    EXPECT_NO_THROW( elastix.Execute() );
    EXPECT_FALSE( this->IsEmpty( elastix.GetResultImage() ) );

    EXPECT_NO_THROW( elastix.SetMovingMask( mask ) );
    EXPECT_NO_THROW( elastix.Execute() );
    EXPECT_FALSE( this->IsEmpty( elastix.GetResultImage() ) );

    EXPECT_NO_THROW( elastix.SetFixedMask( sitk::Image() ) ); // set mask to zero
    EXPECT_NO_THROW( elastix.Execute() );
    EXPECT_FALSE( this->IsEmpty( elastix.GetResultImage() ) );
}

TEST_F( SimpleElastixTest, ProceduralInterface )
{
    sitk::Image resultImage;

    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, "translation") );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( Elastix( fixedImage, movingImage, "translation", true ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( Elastix( fixedImage, movingImage, "translation", true, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( Elastix( fixedImage, movingImage, "translation", false, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );

    ParameterMapType parameterMap = sitk::GetDefaultParameterMap( "translation" );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMap) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMap, true ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMap, true, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMap, false, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );

    ParameterMapVectorType parameterMapVector;
    parameterMapVector.push_back( sitk::GetDefaultParameterMap( "translation" ) );
    parameterMapVector.push_back( sitk::GetDefaultParameterMap( "rigid" ) );

    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMapVector) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMapVector, true ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMapVector, true, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMapVector, false, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );

    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, "translation", mask, mask ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, "translation", mask, mask, true ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, "translation", true, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, "translation", false, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );

    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMap, mask, mask ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMap, mask, mask, true ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMap, mask, mask, true, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMap, mask, mask, false, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );

    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMapVector, mask, mask ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMapVector, mask, mask, true ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMapVector, mask, mask, true, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMapVector, mask, mask, false, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );

    parameterMap["WriteResultImage"] = ParameterValueVectorType( 1, "false" );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMap ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );

    parameterMapVector[1]["WriteResultImage"] = ParameterValueVectorType( 1, "false" );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMapVector ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );

    EXPECT_NO_THROW( sitk::PrettyPrint( parameterMapVector ) );
}

TEST_F( SimpleElastixTest, DefaultPairwiseParameterMaps )
{
    sitk::Image resultImage;

    SimpleElastixType elastix;
    elastix.SetFixedImage( fixedImage );
    elastix.SetMovingImage( movingImage );

    EXPECT_NO_THROW( elastix.SetParameterMap( sitk::GetDefaultParameterMap( "translation" ) ) );
    EXPECT_NO_THROW( elastix.Execute() );
    EXPECT_NO_THROW( resultImage = elastix.GetResultImage() );

    EXPECT_NO_THROW( elastix.SetParameterMap( sitk::GetDefaultParameterMap( "rigid" ) ) );
    EXPECT_NO_THROW( elastix.Execute() );
    EXPECT_NO_THROW( resultImage = elastix.GetResultImage() );

    EXPECT_NO_THROW( elastix.SetParameterMap( sitk::GetDefaultParameterMap( "affine" ) ) );
    EXPECT_NO_THROW( elastix.Execute() );
    EXPECT_NO_THROW( resultImage = elastix.GetResultImage() );

    EXPECT_NO_THROW( elastix.SetParameterMap( sitk::GetDefaultParameterMap( "nonrigid" ) ) );
    EXPECT_NO_THROW( elastix.Execute() );
    EXPECT_NO_THROW( resultImage = elastix.GetResultImage() );

    EXPECT_NO_THROW( elastix.PrettyPrint( elastix.GetTransformParameterMap() ) );
}
<commit_msg>ENH: Use new dedicated function for removing fixed mask<commit_after>#include "SimpleITKTestHarness.h"
#include "sitkCastImageFilter.h"
#include "sitkSimpleElastix.h"

namespace sitk = itk::simple;

class SimpleElastixTest : public ::testing::Test
{
protected:

    virtual void SetUp()
    {
        fixedImage = sitk::Cast( sitk::ReadImage( dataFinder.GetFile( "Input/BrainProtonDensitySliceBorder20.png" ) ), sitk::sitkFloat32 );
        movingImage = sitk::Cast( sitk::ReadImage( dataFinder.GetFile( "Input/BrainProtonDensitySliceShifted13x17y.png" ) ), sitk::sitkFloat32 );
        mask = sitk::Cast( sitk::ReadImage( dataFinder.GetFile( "Input/BrainProtonDensitySliceBorder20Mask.png" ) ), sitk::sitkFloat32 );
        outputFolder = std::string( "." );
    }

    typedef sitk::SimpleElastix                       SimpleElastixType;
    typedef SimpleElastixType::ParameterMapType       ParameterMapType;
    typedef SimpleElastixType::ParameterMapVectorType   ParameterMapVectorType;
    typedef SimpleElastixType::ParameterValueVectorType    ParameterValueVectorType;

    sitk::Image fixedImage;
    sitk::Image movingImage;
    sitk::Image mask;
    std::string outputFolder;

    bool IsEmpty( const sitk::Image image )
    {
      return ( image.GetWidth() == 0 && image.GetHeight() == 0 );
    }
};

TEST_F( SimpleElastixTest, ObjectOrientedInterface )
{
    SimpleElastixType elastix;

    EXPECT_EQ( elastix.GetName(), "SimpleElastix" );
    EXPECT_EQ( elastix.GetParameterMap().size(), 0u );
    EXPECT_EQ( elastix.GetTransformParameterMap().size(), 0u );

    EXPECT_THROW( elastix.Execute(), sitk::GenericException );
    EXPECT_NO_THROW( elastix.SetFixedImage( fixedImage ) );
    EXPECT_THROW( elastix.Execute(), sitk::GenericException );
    EXPECT_NO_THROW( elastix.SetMovingImage( movingImage ) );

    // Minimum viable parameter map
    ParameterMapType parameterMap;
    parameterMap[ "Interpolator"]         = ParameterValueVectorType( 1, "LinearInterpolator");
    parameterMap[ "Optimizer" ]           = ParameterValueVectorType( 1, "AdaptiveStochasticGradientDescent" );
    parameterMap[ "Resampler"]            = ParameterValueVectorType( 1, "DefaultResampler" );
    parameterMap[ "ResampleInterpolator"] = ParameterValueVectorType( 1, "FinalBSplineInterpolator" );
    parameterMap[ "ImageSampler" ]        = ParameterValueVectorType( 1, "RandomCoordinate" );
    parameterMap[ "Registration" ]        = ParameterValueVectorType( 1, "MultiResolutionRegistration" );
    parameterMap[ "Transform" ]           = ParameterValueVectorType( 1, "TranslationTransform" );
    parameterMap[ "Metric" ]              = ParameterValueVectorType( 1, "AdvancedMattesMutualInformation" );

    EXPECT_NO_THROW( elastix.LogToConsoleOn();  );
    EXPECT_NO_THROW( elastix.LogToFileOn();  );
    EXPECT_NO_THROW( elastix.SetParameterMap( parameterMap ) );
    EXPECT_NO_THROW( elastix.Execute() );
    EXPECT_FALSE( this->IsEmpty( elastix.GetResultImage() ) );

    EXPECT_NO_THROW( elastix.SetFixedMask( mask ) );
    EXPECT_NO_THROW( elastix.Execute() );
    EXPECT_FALSE( this->IsEmpty( elastix.GetResultImage() ) );

    EXPECT_NO_THROW( elastix.SetMovingMask( mask ) );
    EXPECT_NO_THROW( elastix.Execute() );
    EXPECT_FALSE( this->IsEmpty( elastix.GetResultImage() ) );

    EXPECT_NO_THROW( elastix.RemoveFixedMask() );
    EXPECT_NO_THROW( elastix.Execute() );
    EXPECT_FALSE( this->IsEmpty( elastix.GetResultImage() ) );
}

TEST_F( SimpleElastixTest, ProceduralInterface )
{
    sitk::Image resultImage;

    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, "translation") );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( Elastix( fixedImage, movingImage, "translation", true ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( Elastix( fixedImage, movingImage, "translation", true, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( Elastix( fixedImage, movingImage, "translation", false, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );

    ParameterMapType parameterMap = sitk::GetDefaultParameterMap( "translation" );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMap) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMap, true ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMap, true, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMap, false, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );

    ParameterMapVectorType parameterMapVector;
    parameterMapVector.push_back( sitk::GetDefaultParameterMap( "translation" ) );
    parameterMapVector.push_back( sitk::GetDefaultParameterMap( "rigid" ) );

    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMapVector) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMapVector, true ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMapVector, true, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMapVector, false, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );

    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, "translation", mask, mask ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, "translation", mask, mask, true ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, "translation", true, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, "translation", false, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );

    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMap, mask, mask ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMap, mask, mask, true ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMap, mask, mask, true, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMap, mask, mask, false, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );

    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMapVector, mask, mask ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMapVector, mask, mask, true ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMapVector, mask, mask, true, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMapVector, mask, mask, false, outputFolder ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );

    parameterMap["WriteResultImage"] = ParameterValueVectorType( 1, "false" );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMap ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );

    parameterMapVector[1]["WriteResultImage"] = ParameterValueVectorType( 1, "false" );
    EXPECT_NO_THROW( resultImage = Elastix( fixedImage, movingImage, parameterMapVector ) );
    EXPECT_FALSE( this->IsEmpty( resultImage ) );

    EXPECT_NO_THROW( sitk::PrettyPrint( parameterMapVector ) );
}

TEST_F( SimpleElastixTest, DefaultPairwiseParameterMaps )
{
    sitk::Image resultImage;

    SimpleElastixType elastix;
    elastix.SetFixedImage( fixedImage );
    elastix.SetMovingImage( movingImage );

    EXPECT_NO_THROW( elastix.SetParameterMap( sitk::GetDefaultParameterMap( "translation" ) ) );
    EXPECT_NO_THROW( elastix.Execute() );
    EXPECT_NO_THROW( resultImage = elastix.GetResultImage() );

    EXPECT_NO_THROW( elastix.SetParameterMap( sitk::GetDefaultParameterMap( "rigid" ) ) );
    EXPECT_NO_THROW( elastix.Execute() );
    EXPECT_NO_THROW( resultImage = elastix.GetResultImage() );

    EXPECT_NO_THROW( elastix.SetParameterMap( sitk::GetDefaultParameterMap( "affine" ) ) );
    EXPECT_NO_THROW( elastix.Execute() );
    EXPECT_NO_THROW( resultImage = elastix.GetResultImage() );

    EXPECT_NO_THROW( elastix.SetParameterMap( sitk::GetDefaultParameterMap( "nonrigid" ) ) );
    EXPECT_NO_THROW( elastix.Execute() );
    EXPECT_NO_THROW( resultImage = elastix.GetResultImage() );

    EXPECT_NO_THROW( elastix.PrettyPrint( elastix.GetTransformParameterMap() ) );
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <NormLPQ.h>
#include <ModuleFactories.h>

class TestEdgeFavouringMask : public ::testing::Test {
protected:
    ModulePtr n1_1;
    ModulePtr n1_2;

    ModulePtr n2_1;
    ModulePtr n2_2;

    ModulePtr n05_1;
    ModulePtr n05_05;

    ModulePtr n2_1_05;

    TestEdgeFavouringMask() :
        n1_1(makeEdgeFavouringMask(1)),
        n1_2(makeEdgeFavouringMask(1, 2)),
        n2_1(makeEdgeFavouringMask(2, 1)),
        n2_2(makeEdgeFavouringMask(2, 2)),
        n05_1(makeEdgeFavouringMask(0.5, 1)),
        n05_05(makeEdgeFavouringMask(0.5, 0.5)),
        n2_1_05(makeEdgeFavouringMask(2, 1, 0.5))
    {

    };
    ~TestEdgeFavouringMask() {};
};

TEST_F(TestEdgeFavouringMask, TestEdgeFavouringMask1_1)
{
    EXPECT_EQ(0., n1_1->GetValue(0.5, 0.5, 0.5)) <<
        "Incorrect value at origin";

    EXPECT_EQ(1., n1_1->GetValue(1., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n1_1->GetValue(0., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n1_1->GetValue(1., 0., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n1_1->GetValue(0., 0., 0.)) <<
        "Incorrect value at corner";

    EXPECT_EQ(1., n1_1->GetValue(1., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n1_1->GetValue(0., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n1_1->GetValue(0.5, 1., 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n1_1->GetValue(0.5, 0., 0.)) <<
        "Incorrect value on axis";

    EXPECT_EQ(1., n1_1->GetValue(0.75, 0.75, 0.)) <<
        "Incorrect value";
}

TEST_F(TestEdgeFavouringMask, TestEdgeFavouringMask1_2)
{
    EXPECT_EQ(0., n1_2->GetValue(0.5, 0.5, 0.5)) <<
        "Incorrect value at origin";

    EXPECT_EQ(1., n1_2->GetValue(1., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n1_2->GetValue(0., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n1_2->GetValue(1., 0., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n1_2->GetValue(0., 0., 0.)) <<
        "Incorrect value at corner";

    EXPECT_EQ(1., n1_2->GetValue(1., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n1_2->GetValue(0., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n1_2->GetValue(0.5, 1., 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n1_2->GetValue(0.5, 0., 0.)) <<
        "Incorrect value on axis";

    EXPECT_NEAR(1., n1_2->GetValue(0.75, 0.75, 0.), 0.0001) <<
        "Incorrect value";
}

TEST_F(TestEdgeFavouringMask, TestEdgeFavouringMask2_1)
{
    EXPECT_EQ(0., n2_1->GetValue(0.5, 0.5, 0.5)) <<
        "Incorrect value at origin";

    EXPECT_EQ(1., n2_1->GetValue(1., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n2_1->GetValue(0., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n2_1->GetValue(1., 0., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n2_1->GetValue(0., 0., 0.)) <<
        "Incorrect value at corner";

    EXPECT_EQ(1., n2_1->GetValue(1., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n2_1->GetValue(0., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n2_1->GetValue(0.5, 1., 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n2_1->GetValue(0.5, 0., 0.)) <<
        "Incorrect value on axis";

    EXPECT_NEAR(sqrt(0.5), n2_1->GetValue(0.75, 0.75, 0.), 0.0001) <<
        "Incorrect value";
}

TEST_F(TestEdgeFavouringMask, TestEdgeFavouringMask2_2)
{
    EXPECT_EQ(0., n2_2->GetValue(0.5, 0.5, 0.5)) <<
        "Incorrect value at origin";

    EXPECT_EQ(1., n2_2->GetValue(1., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n2_2->GetValue(0., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n2_2->GetValue(1., 0., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n2_2->GetValue(0., 0., 0.)) <<
        "Incorrect value at corner";

    EXPECT_EQ(1., n2_2->GetValue(1., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n2_2->GetValue(0., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n2_2->GetValue(0.5, 1., 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n2_2->GetValue(0.5, 0., 0.)) <<
        "Incorrect value on axis";

    EXPECT_NEAR(0.5, n2_2->GetValue(0.75, 0.75, 0.), 0.0001) <<
        "Incorrect value";
}

TEST_F(TestEdgeFavouringMask, TestEdgeFavouringMask05_1)
{
    EXPECT_EQ(0., n05_1->GetValue(0.5, 0.5, 0.5)) <<
        "Incorrect value at origin";

    EXPECT_EQ(1., n05_1->GetValue(1., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n05_1->GetValue(0., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n05_1->GetValue(1., 0., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n05_1->GetValue(0., 0., 0.)) <<
        "Incorrect value at corner";

    EXPECT_EQ(1., n05_1->GetValue(1., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n05_1->GetValue(0., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n05_1->GetValue(0.5, 1., 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n05_1->GetValue(0.5, 0., 0.)) <<
        "Incorrect value on axis";

    EXPECT_EQ(1., n05_1->GetValue(0.75, 0.75, 0.)) <<
        "Incorrect value";
}

TEST_F(TestEdgeFavouringMask, TestEdgeFavouringMask05_05)
{
    EXPECT_EQ(0., n05_05->GetValue(0.5, 0.5, 0.5)) <<
        "Incorrect value at origin";

    EXPECT_EQ(1., n05_05->GetValue(1., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n05_05->GetValue(0., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n05_05->GetValue(1., 0., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n05_05->GetValue(0., 0., 0.)) <<
        "Incorrect value at corner";

    EXPECT_EQ(1., n05_05->GetValue(1., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n05_05->GetValue(0., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n05_05->GetValue(0.5, 1., 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n05_05->GetValue(0.5, 0., 0.)) <<
        "Incorrect value on axis";

    EXPECT_EQ(1., n05_05->GetValue(0.75, 0.75, 0.)) <<
        "Incorrect value";
}

TEST_F(TestEdgeFavouringMask, TestEdgeFavouringMask2_1_05)
{
    EXPECT_NEAR(0.5, n2_1_05->GetValue(0.5, 0.5, 0.5), 0.0001) <<
        "Incorrect value at origin";

    EXPECT_EQ(1., n2_1_05->GetValue(1., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n2_1_05->GetValue(0., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n2_1_05->GetValue(1., 0., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n2_1_05->GetValue(0., 0., 0.)) <<
        "Incorrect value at corner";

    EXPECT_EQ(1., n2_1_05->GetValue(1., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n2_1_05->GetValue(0., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n2_1_05->GetValue(0.5, 1., 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n2_1_05->GetValue(0.5, 0., 0.)) <<
        "Incorrect value on axis";

    EXPECT_NEAR(0.5 + sqrt(0.125), n2_1_05->GetValue(0.75, 0.75, 0.), 0.0001) <<
        "Incorrect value";
}<commit_msg>Also update TestEdgeFavouringMask with Reseedables<commit_after>#include <gtest/gtest.h>
#include <NormLPQ.h>
#include <ModuleFactories.h>

class TestEdgeFavouringMask : public ::testing::Test {
protected:
    Reseedable n1_1;
    Reseedable n1_2;

    Reseedable n2_1;
    Reseedable n2_2;

    Reseedable n05_1;
    Reseedable n05_05;

    Reseedable n2_1_05;

    TestEdgeFavouringMask() :
        n1_1(makeEdgeFavouringMask(1)),
        n1_2(makeEdgeFavouringMask(1, 2)),
        n2_1(makeEdgeFavouringMask(2, 1)),
        n2_2(makeEdgeFavouringMask(2, 2)),
        n05_1(makeEdgeFavouringMask(0.5, 1)),
        n05_05(makeEdgeFavouringMask(0.5, 0.5)),
        n2_1_05(makeEdgeFavouringMask(2, 1, 0.5))
    {

    };
    ~TestEdgeFavouringMask() {};
};

TEST_F(TestEdgeFavouringMask, TestEdgeFavouringMask1_1)
{
    EXPECT_EQ(0., n1_1.first->GetValue(0.5, 0.5, 0.5)) <<
        "Incorrect value at origin";

    EXPECT_EQ(1., n1_1.first->GetValue(1., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n1_1.first->GetValue(0., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n1_1.first->GetValue(1., 0., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n1_1.first->GetValue(0., 0., 0.)) <<
        "Incorrect value at corner";

    EXPECT_EQ(1., n1_1.first->GetValue(1., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n1_1.first->GetValue(0., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n1_1.first->GetValue(0.5, 1., 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n1_1.first->GetValue(0.5, 0., 0.)) <<
        "Incorrect value on axis";

    EXPECT_EQ(1., n1_1.first->GetValue(0.75, 0.75, 0.)) <<
        "Incorrect value";
}

TEST_F(TestEdgeFavouringMask, TestEdgeFavouringMask1_2)
{
    EXPECT_EQ(0., n1_2.first->GetValue(0.5, 0.5, 0.5)) <<
        "Incorrect value at origin";

    EXPECT_EQ(1., n1_2.first->GetValue(1., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n1_2.first->GetValue(0., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n1_2.first->GetValue(1., 0., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n1_2.first->GetValue(0., 0., 0.)) <<
        "Incorrect value at corner";

    EXPECT_EQ(1., n1_2.first->GetValue(1., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n1_2.first->GetValue(0., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n1_2.first->GetValue(0.5, 1., 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n1_2.first->GetValue(0.5, 0., 0.)) <<
        "Incorrect value on axis";

    EXPECT_NEAR(1., n1_2.first->GetValue(0.75, 0.75, 0.), 0.0001) <<
        "Incorrect value";
}

TEST_F(TestEdgeFavouringMask, TestEdgeFavouringMask2_1)
{
    EXPECT_EQ(0., n2_1.first->GetValue(0.5, 0.5, 0.5)) <<
        "Incorrect value at origin";

    EXPECT_EQ(1., n2_1.first->GetValue(1., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n2_1.first->GetValue(0., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n2_1.first->GetValue(1., 0., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n2_1.first->GetValue(0., 0., 0.)) <<
        "Incorrect value at corner";

    EXPECT_EQ(1., n2_1.first->GetValue(1., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n2_1.first->GetValue(0., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n2_1.first->GetValue(0.5, 1., 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n2_1.first->GetValue(0.5, 0., 0.)) <<
        "Incorrect value on axis";

    EXPECT_NEAR(sqrt(0.5), n2_1.first->GetValue(0.75, 0.75, 0.), 0.0001) <<
        "Incorrect value";
}

TEST_F(TestEdgeFavouringMask, TestEdgeFavouringMask2_2)
{
    EXPECT_EQ(0., n2_2.first->GetValue(0.5, 0.5, 0.5)) <<
        "Incorrect value at origin";

    EXPECT_EQ(1., n2_2.first->GetValue(1., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n2_2.first->GetValue(0., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n2_2.first->GetValue(1., 0., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n2_2.first->GetValue(0., 0., 0.)) <<
        "Incorrect value at corner";

    EXPECT_EQ(1., n2_2.first->GetValue(1., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n2_2.first->GetValue(0., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n2_2.first->GetValue(0.5, 1., 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n2_2.first->GetValue(0.5, 0., 0.)) <<
        "Incorrect value on axis";

    EXPECT_NEAR(0.5, n2_2.first->GetValue(0.75, 0.75, 0.), 0.0001) <<
        "Incorrect value";
}

TEST_F(TestEdgeFavouringMask, TestEdgeFavouringMask05_1)
{
    EXPECT_EQ(0., n05_1.first->GetValue(0.5, 0.5, 0.5)) <<
        "Incorrect value at origin";

    EXPECT_EQ(1., n05_1.first->GetValue(1., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n05_1.first->GetValue(0., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n05_1.first->GetValue(1., 0., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n05_1.first->GetValue(0., 0., 0.)) <<
        "Incorrect value at corner";

    EXPECT_EQ(1., n05_1.first->GetValue(1., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n05_1.first->GetValue(0., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n05_1.first->GetValue(0.5, 1., 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n05_1.first->GetValue(0.5, 0., 0.)) <<
        "Incorrect value on axis";

    EXPECT_EQ(1., n05_1.first->GetValue(0.75, 0.75, 0.)) <<
        "Incorrect value";
}

TEST_F(TestEdgeFavouringMask, TestEdgeFavouringMask05_05)
{
    EXPECT_EQ(0., n05_05.first->GetValue(0.5, 0.5, 0.5)) <<
        "Incorrect value at origin";

    EXPECT_EQ(1., n05_05.first->GetValue(1., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n05_05.first->GetValue(0., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n05_05.first->GetValue(1., 0., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n05_05.first->GetValue(0., 0., 0.)) <<
        "Incorrect value at corner";

    EXPECT_EQ(1., n05_05.first->GetValue(1., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n05_05.first->GetValue(0., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n05_05.first->GetValue(0.5, 1., 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n05_05.first->GetValue(0.5, 0., 0.)) <<
        "Incorrect value on axis";

    EXPECT_EQ(1., n05_05.first->GetValue(0.75, 0.75, 0.)) <<
        "Incorrect value";
}

TEST_F(TestEdgeFavouringMask, TestEdgeFavouringMask2_1_05)
{
    EXPECT_NEAR(0.5, n2_1_05.first->GetValue(0.5, 0.5, 0.5), 0.0001) <<
        "Incorrect value at origin";

    EXPECT_EQ(1., n2_1_05.first->GetValue(1., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n2_1_05.first->GetValue(0., 1., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n2_1_05.first->GetValue(1., 0., 0.)) <<
        "Incorrect value at corner";
    EXPECT_EQ(1., n2_1_05.first->GetValue(0., 0., 0.)) <<
        "Incorrect value at corner";

    EXPECT_EQ(1., n2_1_05.first->GetValue(1., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n2_1_05.first->GetValue(0., 0.5, 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n2_1_05.first->GetValue(0.5, 1., 0.)) <<
        "Incorrect value on axis";
    EXPECT_EQ(1., n2_1_05.first->GetValue(0.5, 0., 0.)) <<
        "Incorrect value on axis";

    EXPECT_NEAR(0.5 + sqrt(0.125), n2_1_05.first->GetValue(0.75, 0.75, 0.), 0.0001) <<
        "Incorrect value";
}<|endoftext|>


<commit_before>/*
 * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
 * Copyright (C) 2008 Google Inc.
 *
 * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "FrameChromium.h"

#include "Document.h"
#include "FloatRect.h"
#include "RenderView.h"
#include "Settings.h"

using std::min;

namespace WebCore {

void computePageRectsForFrame(Frame* frame, const IntRect& printRect, float headerHeight, float footerHeight, float userScaleFactor, Vector<IntRect>& pages, int& outPageHeight)
{
    ASSERT(frame);

    pages.clear();
    outPageHeight = 0;

    if (!frame->document() || !frame->view() || !frame->document()->renderer())
        return;

    RenderView* root = toRenderView(frame->document()->renderer());

    if (!root) {
        LOG_ERROR("document to be printed has no renderer");
        return;
    }

    if (userScaleFactor <= 0) {
        LOG_ERROR("userScaleFactor has bad value %.2f", userScaleFactor);
        return;
    }

    float ratio = static_cast<float>(printRect.height()) / static_cast<float>(printRect.width());

    float pageWidth  = static_cast<float>(root->overflowWidth());
    float pageHeight = pageWidth * ratio;
    outPageHeight = static_cast<int>(pageHeight);   // this is the height of the page adjusted by margins
    pageHeight -= (headerHeight + footerHeight);

    if (pageHeight <= 0) {
        LOG_ERROR("pageHeight has bad value %.2f", pageHeight);
        return;
    }

    float currPageHeight = pageHeight / userScaleFactor;
    float docHeight      = root->layer()->height();
    float currPageWidth  = pageWidth / userScaleFactor;

    // always return at least one page, since empty files should print a blank page
    float printedPagesHeight = 0.0f;
    do {
        float proposedBottom = min(docHeight, printedPagesHeight + pageHeight);
        frame->view()->adjustPageHeight(&proposedBottom, printedPagesHeight, proposedBottom, printedPagesHeight);
        currPageHeight = max(1.0f, proposedBottom - printedPagesHeight);

        pages.append(IntRect(0, printedPagesHeight, currPageWidth, currPageHeight));
        printedPagesHeight += currPageHeight;
    } while (printedPagesHeight < docHeight);
}

DragImageRef Frame::dragImageForSelection()
{
    if (selection()->isRange())
        return 0;  // FIXME: implement me!

    return 0;
}

} // namespace WebCore
<commit_msg>Fix Chromium bustage.<commit_after>/*
 * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
 * Copyright (C) 2008 Google Inc.
 *
 * 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 APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h"
#include "FrameChromium.h"

#include "Document.h"
#include "FloatRect.h"
#include "RenderView.h"
#include "Settings.h"

using std::min;

namespace WebCore {

void computePageRectsForFrame(Frame* frame, const IntRect& printRect, float headerHeight, float footerHeight, float userScaleFactor, Vector<IntRect>& pages, int& outPageHeight)
{
    ASSERT(frame);

    pages.clear();
    outPageHeight = 0;

    if (!frame->document() || !frame->view() || !frame->document()->renderer())
        return;

    RenderView* root = toRenderView(frame->document()->renderer());

    if (!root) {
        LOG_ERROR("document to be printed has no renderer");
        return;
    }

    if (userScaleFactor <= 0) {
        LOG_ERROR("userScaleFactor has bad value %.2f", userScaleFactor);
        return;
    }

    float ratio = static_cast<float>(printRect.height()) / static_cast<float>(printRect.width());

    float pageWidth  = static_cast<float>(root->rightLayoutOverflow());
    float pageHeight = pageWidth * ratio;
    outPageHeight = static_cast<int>(pageHeight);   // this is the height of the page adjusted by margins
    pageHeight -= (headerHeight + footerHeight);

    if (pageHeight <= 0) {
        LOG_ERROR("pageHeight has bad value %.2f", pageHeight);
        return;
    }

    float currPageHeight = pageHeight / userScaleFactor;
    float docHeight      = root->layer()->height();
    float currPageWidth  = pageWidth / userScaleFactor;

    // always return at least one page, since empty files should print a blank page
    float printedPagesHeight = 0.0f;
    do {
        float proposedBottom = min(docHeight, printedPagesHeight + pageHeight);
        frame->view()->adjustPageHeight(&proposedBottom, printedPagesHeight, proposedBottom, printedPagesHeight);
        currPageHeight = max(1.0f, proposedBottom - printedPagesHeight);

        pages.append(IntRect(0, printedPagesHeight, currPageWidth, currPageHeight));
        printedPagesHeight += currPageHeight;
    } while (printedPagesHeight < docHeight);
}

DragImageRef Frame::dragImageForSelection()
{
    if (selection()->isRange())
        return 0;  // FIXME: implement me!

    return 0;
}

} // namespace WebCore
<|endoftext|>


<commit_before>/**
 * @file Cosa/Event.cpp
 * @version 1.0
 *
 * @section License
 * Copyright (C) Mikael Patel, 2012
 *
 * This library 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 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 * @section Description
 * Event data structure with type, source and value.
 *
 * This file is part of the Arduino Che Cosa project.
 */

#include "Event.h"

Queue Event::queue(Event::QUEUE_MAX, sizeof(Event));

uint8_t
Event::push(Type type, void* source, uint16_t value)
{
  Event event(type, source, value);
  return (queue.enqueue(&event));
}

void
Event::print()
{
#ifndef NDEBUG
  Serial_print("Event(");
  Serial.print(_type);
  Serial_print(", 0x");
  Serial.print((uint16_t) _source, HEX);
  Serial_print(", ");
  Serial.print(_value);
  Serial_print(")");
#endif
}

void
Event::println()
{
#ifndef NDEBUG
  print();
  Serial_print("\n");
#endif
}

<commit_msg>Avoid allocating event queue with malloc.<commit_after>/**
 * @file Cosa/Event.cpp
 * @version 1.0
 *
 * @section License
 * Copyright (C) Mikael Patel, 2012
 *
 * This library 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 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA  02111-1307  USA
 *
 * @section Description
 * Event data structure with type, source and value.
 *
 * This file is part of the Arduino Che Cosa project.
 */

#include "Event.h"

static Event event[Event::QUEUE_MAX];
Queue Event::queue(Event::QUEUE_MAX, sizeof(Event), event);

uint8_t
Event::push(Type type, void* source, uint16_t value)
{
  Event event(type, source, value);
  return (queue.enqueue(&event));
}

void
Event::print()
{
#ifndef NDEBUG
  Serial_print("Event(");
  Serial.print(_type);
  Serial_print(", 0x");
  Serial.print((uint16_t) _source, HEX);
  Serial_print(", ");
  Serial.print(_value);
  Serial_print(")");
#endif
}

void
Event::println()
{
#ifndef NDEBUG
  print();
  Serial_print("\n");
#endif
}

<|endoftext|>


<commit_before>/* Copyright 2019 QReal Research Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

#include "matrixGenerator.h"

#include <generatorBase/generatorCustomizer.h>
#include "iotikGeneratorBase/iotikMasterGeneratorBase.h"

using namespace iotik::simple;
using namespace generatorBase::simple;
using namespace qReal;

const QString arrayName = "matrix_";

MatrixGenerator::MatrixGenerator(int index
		, const qrRepo::RepoApi &repo
		, generatorBase::GeneratorCustomizer &customizer
		, const Id &id
		, QObject *parent)
	: BindingGenerator(repo, customizer, id, "sensors/signalForOnePortFourParameters.t", QList<Binding *>()
			<< Binding::createStatic("@@DRIVER@@", "MATRIX")
			<< Binding::createConverting("@@PORT@@", "Port", customizer.factory()->portNameConverter())

			<< Binding::createStaticConverting("@@JUST_FOR_ARRAY_INIT@@"
							, arrayName + QString::number(index) + " = { 0 }"
							, customizer.factory()->functionBlockConverter(id, "Variable"))
			<< Binding::createStaticConverting("@@ARRAY@@"
								, arrayName + QString::number(index)
								, customizer.factory()->functionBlockConverter(id, "Variable"))

			<< Binding::createStatic("@@PARAM@@"
					, repo.property(id, "Print").toString().compare("false") == 0 ? "'\\0'"
						: "'" + (repo.property(id, "Symbol").toString()[0] == '\'' ||
							repo.property(id, "Symbol").toString()[0] == '"' ? repo.property(id, "Symbol").toString()[1]
							: repo.property(id, "Symbol").toString()[0]) + "'")

			<< Binding::createStaticConverting("@@PARAM_2@@"
					, ColorConverter(repo.property(id, "Color").toString(), repo.property(id, "Intensity").toString(), 'r')
					, customizer.factory()->stringPropertyConverter(id, "Color"))

			<< Binding::createStaticConverting("@@PARAM_3@@"
					, ColorConverter(repo.property(id, "Color").toString(), repo.property(id, "Intensity").toString(), 'g')
					, customizer.factory()->stringPropertyConverter(id, "Color"))

			<< Binding::createStaticConverting("@@PARAM_4@@"
					, ColorConverter(repo.property(id, "Color").toString(), repo.property(id, "Intensity").toString(), 'b')
					, customizer.factory()->stringPropertyConverter(id, "Color"))
			, parent)
{
}

QString MatrixGenerator::ColorConverter(QString color, QString intensity, char rgb)
{
	if (color.compare("off") == 0) {
		return "0";
	}

	int value = 0;

	switch (rgb) {
		case 'r':
			if (color.compare("violet") == 0) {
				value = 127;
			} else if (color.compare("green") == 0 || color.compare("turquoise") == 0 || color.compare("blue") == 0) {
				value = 0;
			} else {
				value = 255;
			}
			break;
		case 'g':
			if (color.compare("orange") == 0) {
				value = 127;
			} else if (color.compare("red") == 0 || color.compare("blue") == 0 || color.compare("violet") == 0) {
				value = 0;
			} else {
				value = 255;
			}
			break;
		case 'b':
				if (color.compare("red") == 0 || color.compare("orange") == 0 || color.compare("yellow") == 0
						|| color.compare("green") == 0) {
					value = 0;
				} else {
					value = 255;
				}
			break;
	}

	bool ok = false;
	int i = intensity.toInt(&ok);

	if (ok) {
		value *= i;
		value /= 100;
		return QString::number(value);
	}

	return QString::number(value) + " * " + intensity + " / 100";
}
<commit_msg>Fix long lines<commit_after>/* Copyright 2019 QReal Research Group
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

#include "matrixGenerator.h"

#include <generatorBase/generatorCustomizer.h>
#include "iotikGeneratorBase/iotikMasterGeneratorBase.h"

using namespace iotik::simple;
using namespace generatorBase::simple;
using namespace qReal;

const QString arrayName = "matrix_";

MatrixGenerator::MatrixGenerator(int index
		, const qrRepo::RepoApi &repo
		, generatorBase::GeneratorCustomizer &customizer
		, const Id &id
		, QObject *parent)
	: BindingGenerator(repo, customizer, id, "sensors/signalForOnePortFourParameters.t", QList<Binding *>()
			<< Binding::createStatic("@@DRIVER@@", "MATRIX")
			<< Binding::createConverting("@@PORT@@", "Port", customizer.factory()->portNameConverter())

			<< Binding::createStaticConverting("@@JUST_FOR_ARRAY_INIT@@"
							, arrayName + QString::number(index) + " = { 0 }"
							, customizer.factory()->functionBlockConverter(id, "Variable"))
			<< Binding::createStaticConverting("@@ARRAY@@"
								, arrayName + QString::number(index)
								, customizer.factory()->functionBlockConverter(id, "Variable"))

			<< Binding::createStatic("@@PARAM@@"
					, repo.property(id, "Print").toString().compare("false") == 0 ? "'\\0'"
						: "'" + (repo.property(id, "Symbol").toString()[0] == '\'' ||
							repo.property(id, "Symbol").toString()[0] == '"' ? repo.property(id, "Symbol").toString()[1]
							: repo.property(id, "Symbol").toString()[0]) + "'")

			<< Binding::createStaticConverting("@@PARAM_2@@"
					, ColorConverter(repo.property(id, "Color").toString()
					, repo.property(id, "Intensity").toString(), 'r')
					, customizer.factory()->stringPropertyConverter(id, "Color"))

			<< Binding::createStaticConverting("@@PARAM_3@@"
					, ColorConverter(repo.property(id, "Color").toString()
					, repo.property(id, "Intensity").toString(), 'g')
					, customizer.factory()->stringPropertyConverter(id, "Color"))

			<< Binding::createStaticConverting("@@PARAM_4@@"
					, ColorConverter(repo.property(id, "Color").toString()
					, repo.property(id, "Intensity").toString(), 'b')
					, customizer.factory()->stringPropertyConverter(id, "Color"))
			, parent)
{
}

QString MatrixGenerator::ColorConverter(QString color, QString intensity, char rgb)
{
	if (color.compare("off") == 0) {
		return "0";
	}

	int value = 0;

	switch (rgb) {
		case 'r':
			if (color.compare("violet") == 0) {
				value = 127;
			} else if (color.compare("green") == 0 || color.compare("turquoise") == 0 || color.compare("blue") == 0) {
				value = 0;
			} else {
				value = 255;
			}
			break;
		case 'g':
			if (color.compare("orange") == 0) {
				value = 127;
			} else if (color.compare("red") == 0 || color.compare("blue") == 0 || color.compare("violet") == 0) {
				value = 0;
			} else {
				value = 255;
			}
			break;
		case 'b':
				if (color.compare("red") == 0 || color.compare("orange") == 0 || color.compare("yellow") == 0
						|| color.compare("green") == 0) {
					value = 0;
				} else {
					value = 255;
				}
			break;
	}

	bool ok = false;
	int i = intensity.toInt(&ok);

	if (ok) {
		value *= i;
		value /= 100;
		return QString::number(value);
	}

	return QString::number(value) + " * " + intensity + " / 100";
}
<|endoftext|>


<commit_before>// Scriptname : TinyDS1307.cpp
// Author     : Evgeniy Kiselyov
// Contact    : jeka911@gmail.com
// Date       : 2014-27-03
// Version    : 0.00001
// License    : The MIT License
//
// Description:
// Library for ATtiny85 on Arduino for DS1307. With RAM support.
// Please check README.md file

#include "TinyDS1307.h"

static unsigned char bcd2bin (unsigned char val) { return val - 6 * (val >> 4); }
static unsigned char bin2bcd (unsigned char val) { return val + 6 * (val / 10); }

bool TINYDS1307::begin(void) {
  return true;
}

bool TINYDS1307::isrunning(void) {
  TinyWireM.beginTransmission(DS1307_ADDRESS);
  TinyWireM.send(0);
  TinyWireM.endTransmission();

  TinyWireM.requestFrom(DS1307_ADDRESS, 1);
  uint8_t ss = TinyWireM.receive();
  return !(ss>>7);
}

bool TINYDS1307::adjust(unsigned short year, unsigned char month, unsigned char day, unsigned char hour, unsigned char min, unsigned char sec)
{
    if (year >= 2000)
        year -= 2000;
    TinyWireM.beginTransmission(DS1307_ADDRESS);
    TinyWireM.send(0);
    TinyWireM.send(bin2bcd(sec));
    TinyWireM.send(bin2bcd(min));
    TinyWireM.send(bin2bcd(hour));
    TinyWireM.send(bin2bcd(0));
    TinyWireM.send(bin2bcd(day));
    TinyWireM.send(bin2bcd(month));
    TinyWireM.send(bin2bcd(year));
    TinyWireM.send(0);

    if (TinyWireM.endTransmission() != 0)
	return false;
    return true;
}

bool TINYDS1307::read()  {
  TinyWireM.beginTransmission(DS1307_ADDRESS);
  TinyWireM.send(0);
  if (TinyWireM.endTransmission() != 0)
	return false;

  TinyWireM.requestFrom(DS1307_ADDRESS, 7);
  ss = bcd2bin(TinyWireM.receive() & 0x7F);
  mm = bcd2bin(TinyWireM.receive());
  hh = bcd2bin(TinyWireM.receive() & 0x3f);
  TinyWireM.receive();
  d = bcd2bin(TinyWireM.receive());
  m = bcd2bin(TinyWireM.receive());
  y = bcd2bin(TinyWireM.receive()) + 2000;

  if (ss & 0x80) return false; // clock is halted
  return true;
}

bool TINYDS1307::read_ram(void) {
  TinyWireM.beginTransmission(DS1307_ADDRESS);
  TinyWireM.send(8);	 // RAM starts there
  if (TinyWireM.endTransmission() != 0)
	return false;
  TinyWireM.requestFrom(DS1307_ADDRESS, DS1307_RAM_SIZE);
  int tries = 0;
  while(!TinyWireM.available())
  {
    delay(50);
    tries++;
    if (tries == 20)   /// wait results for 1 sec max
	return false;
  }
  for(int i=0; i<DS1307_RAM_SIZE; i++)
  {
    ram[i] = TinyWireM.receive();
  }

  return true;
}

bool TINYDS1307::write_ram(void) {
  TinyWireM.beginTransmission(DS1307_ADDRESS);
  TinyWireM.send(8);	 // RAM starts there
  for(int i=0; i<DS1307_RAM_SIZE; i++)
  {
    TinyWireM.send(ram[i]);
  }
  if (TinyWireM.endTransmission() != 0)
	return false;
  return true;
}

class TINYDS1307 tinyrtc;
<commit_msg>start-stop bits<commit_after>// Scriptname : TinyDS1307.cpp
// Author     : Evgeniy Kiselyov
// Contact    : jeka911@gmail.com
// Date       : 2014-27-03
// Version    : 0.00001
// License    : The MIT License
//
// Description:
// Library for ATtiny85 on Arduino for DS1307. With RAM support.
// Please check README.md file

#include "TinyDS1307.h"

static unsigned char bcd2bin (unsigned char val) { return val - 6 * (val >> 4); }
static unsigned char bin2bcd (unsigned char val) { return val + 6 * (val / 10); }

bool TINYDS1307::begin(void) {
  return true;
}

bool TINYDS1307::isrunning(void) {
  TinyWireM.beginTransmission(DS1307_ADDRESS);
  TinyWireM.send(0);
  TinyWireM.endTransmission();

  TinyWireM.requestFrom(DS1307_ADDRESS, 1);
  uint8_t ss = TinyWireM.receive();
  return !(ss>>7);
}

bool TINYDS1307::adjust(unsigned short year, unsigned char month, unsigned char day, unsigned char hour, unsigned char min, unsigned char sec)
{
    if (year >= 2000)
        year -= 2000;
    TinyWireM.beginTransmission(DS1307_ADDRESS);
    TinyWireM.send(0);
    TinyWireM.send(bin2bcd(sec) | 0x80); // stop the clock
    TinyWireM.send(bin2bcd(min));
    TinyWireM.send(bin2bcd(hour));
    TinyWireM.send(bin2bcd(0));
    TinyWireM.send(bin2bcd(day));
    TinyWireM.send(bin2bcd(month));
    TinyWireM.send(bin2bcd(year));
    TinyWireM.send(0);

    if (TinyWireM.endTransmission() != 0)
	return false;

    TinyWireM.beginTransmission(DS1307_ADDRESS);
    TinyWireM.send(0);
    TinyWireM.send(bin2bcd(sec) & 0x7F); // start the clock

    if (TinyWireM.endTransmission() != 0)
	return false;

    return true;
}

bool TINYDS1307::read()  {
  TinyWireM.beginTransmission(DS1307_ADDRESS);
  TinyWireM.send(0);
  if (TinyWireM.endTransmission() != 0)
	return false;

  TinyWireM.requestFrom(DS1307_ADDRESS, 7);
  ss = bcd2bin(TinyWireM.receive() & 0x7F);
  mm = bcd2bin(TinyWireM.receive());
  hh = bcd2bin(TinyWireM.receive() & 0x3f);
  TinyWireM.receive();
  d = bcd2bin(TinyWireM.receive());
  m = bcd2bin(TinyWireM.receive());
  y = bcd2bin(TinyWireM.receive()) + 2000;

  if (ss & 0x80) return false; // clock is halted
  return true;
}

bool TINYDS1307::read_ram(void) {
  TinyWireM.beginTransmission(DS1307_ADDRESS);
  TinyWireM.send(8);	 // RAM starts there
  if (TinyWireM.endTransmission() != 0)
	return false;
  TinyWireM.requestFrom(DS1307_ADDRESS, DS1307_RAM_SIZE);
  int tries = 0;
  while(!TinyWireM.available())
  {
    delay(50);
    tries++;
    if (tries == 20)   /// wait results for 1 sec max
	return false;
  }
  for(int i=0; i<DS1307_RAM_SIZE; i++)
  {
    ram[i] = TinyWireM.receive();
  }

  return true;
}

bool TINYDS1307::write_ram(void) {
  TinyWireM.beginTransmission(DS1307_ADDRESS);
  TinyWireM.send(8);	 // RAM starts there
  for(int i=0; i<DS1307_RAM_SIZE; i++)
  {
    TinyWireM.send(ram[i]);
  }
  if (TinyWireM.endTransmission() != 0)
	return false;
  return true;
}

class TINYDS1307 tinyrtc;
<|endoftext|>