<commit_before>/*************************************************************************
 *
 *  $RCSfile: b2dvector.cxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: rt $ $Date: 2005-05-10 16:05:14 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _BGFX_VECTOR_B2DVECTOR_HXX
#include <basegfx/vector/b2dvector.hxx>
#endif

#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif

#ifndef _BGFX_NUMERIC_FTOOLS_HXX
#include <basegfx/numeric/ftools.hxx>
#endif

namespace basegfx
{
    B2DVector& B2DVector::normalize()
    {
        double fLen(scalar(*this));

        if(::basegfx::fTools::equalZero(fLen))
        {
            mfX = 0.0;
            mfY = 0.0;
        }
        else
        {
            const double fOne(1.0);

            if(!::basegfx::fTools::equal(fOne, fLen))
            {
                fLen = sqrt(fLen);

                if(!::basegfx::fTools::equalZero(fLen))
                {
                    mfX /= fLen;
                    mfY /= fLen;
                }
            }
        }

        return *this;
    }

    B2DVector& B2DVector::operator=( const ::basegfx::B2DTuple& rVec )
    {
        mfX = rVec.getX();
        mfY = rVec.getY();
        return *this;
    }

    double B2DVector::getLength() const
    {
        return hypot( mfX, mfY );
    }

    double B2DVector::scalar( const B2DVector& rVec ) const
    {
        return((mfX * rVec.mfX) + (mfY * rVec.mfY));
    }

    double B2DVector::cross( const B2DVector& rVec ) const
    {
        return(mfX * rVec.getY() - mfY * rVec.getX());
    }

    double B2DVector::angle( const B2DVector& rVec ) const
    {
        return atan2(mfX * rVec.getY() - mfY * rVec.getX(),
            mfX * rVec.getX() + mfY * rVec.getY());
    }

    const B2DVector& B2DVector::getEmptyVector()
    {
        return (const B2DVector&) ::basegfx::B2DTuple::getEmptyTuple();
    }

    B2DVector& B2DVector::operator*=( const B2DHomMatrix& rMat )
    {
        const double fTempX( rMat.get(0,0)*mfX +
                            rMat.get(0,1)*mfY );
        const double fTempY( rMat.get(1,0)*mfX +
                            rMat.get(1,1)*mfY );
        mfX = fTempX;
        mfY = fTempY;

        return *this;
    }

    B2DVector& B2DVector::setLength(double fLen)
    {
        double fLenNow(scalar(*this));

        if(!::basegfx::fTools::equalZero(fLenNow))
        {
            const double fOne(10.0);

            if(!::basegfx::fTools::equal(fOne, fLenNow))
            {
                fLen /= sqrt(fLenNow);
            }

            mfX *= fLen;
            mfY *= fLen;
        }

        return *this;
    }

    bool B2DVector::isNormalized() const
    {
        const double fOne(1.0);
        const double fScalar(scalar(*this));

        return (::basegfx::fTools::equal(fOne, fScalar));
    }

    bool areParallel( const B2DVector& rVecA, const B2DVector& rVecB )
    {
        double fVal(rVecA.getX() * rVecB.getY() - rVecA.getY() * rVecB.getX());
        return ::basegfx::fTools::equalZero(fVal);
    }

    B2VectorOrientation getOrientation( const B2DVector& rVecA, const B2DVector& rVecB )
    {
        double fVal(rVecA.getX() * rVecB.getY() - rVecA.getY() * rVecB.getX());

        if(::basegfx::fTools::equalZero(fVal))
        {
            return ORIENTATION_NEUTRAL;
        }

        if(fVal > 0.0)
        {
            return ORIENTATION_POSITIVE;
        }
        else
        {
            return ORIENTATION_NEGATIVE;
        }
    }

    B2DVector getPerpendicular( const B2DVector& rNormalizedVec )
    {
        B2DVector aPerpendicular(-rNormalizedVec.getY(), rNormalizedVec.getX());
        return aPerpendicular;
    }

    B2DVector getNormalizedPerpendicular( const B2DVector& rVec )
    {
        B2DVector aPerpendicular(rVec);
        aPerpendicular.normalize();
        const double aTemp(-aPerpendicular.getY());
        aPerpendicular.setY(aPerpendicular.getX());
        aPerpendicular.setX(aTemp);
        return aPerpendicular;
    }

    B2DVector operator*( const ::basegfx::B2DHomMatrix& rMat, const B2DVector& rVec )
    {
        B2DVector aRes( rVec );
        return aRes*=rMat;
    }

    B2VectorContinuity getContinuity(const B2DVector& rBackVector, const B2DVector& rForwardVector )
    {
        B2VectorContinuity eRetval(::basegfx::CONTINUITY_NONE);

        if(!rBackVector.equalZero() && !rForwardVector.equalZero())
        {
            const B2DVector aInverseForwardVector(-rForwardVector.getX(), -rForwardVector.getY());

            if(rBackVector.equal(aInverseForwardVector))
            {
                // same direction and same length -> C2
                eRetval = ::basegfx::CONTINUITY_C2;
            }
            else if(areParallel(rBackVector, aInverseForwardVector))
            {
                // same direction -> C1
                eRetval = ::basegfx::CONTINUITY_C1;
            }
        }

        return eRetval;
    }
} // end of namespace basegfx

// eof
<commit_msg>INTEGRATION: CWS ooo19126 (1.12.8); FILE MERGED 2005/09/05 17:38:47 rt 1.12.8.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: b2dvector.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 20:54:06 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *
 ************************************************************************/

#ifndef _BGFX_VECTOR_B2DVECTOR_HXX
#include <basegfx/vector/b2dvector.hxx>
#endif

#ifndef _BGFX_MATRIX_B2DHOMMATRIX_HXX
#include <basegfx/matrix/b2dhommatrix.hxx>
#endif

#ifndef _BGFX_NUMERIC_FTOOLS_HXX
#include <basegfx/numeric/ftools.hxx>
#endif

namespace basegfx
{
    B2DVector& B2DVector::normalize()
    {
        double fLen(scalar(*this));

        if(::basegfx::fTools::equalZero(fLen))
        {
            mfX = 0.0;
            mfY = 0.0;
        }
        else
        {
            const double fOne(1.0);

            if(!::basegfx::fTools::equal(fOne, fLen))
            {
                fLen = sqrt(fLen);

                if(!::basegfx::fTools::equalZero(fLen))
                {
                    mfX /= fLen;
                    mfY /= fLen;
                }
            }
        }

        return *this;
    }

    B2DVector& B2DVector::operator=( const ::basegfx::B2DTuple& rVec )
    {
        mfX = rVec.getX();
        mfY = rVec.getY();
        return *this;
    }

    double B2DVector::getLength() const
    {
        return hypot( mfX, mfY );
    }

    double B2DVector::scalar( const B2DVector& rVec ) const
    {
        return((mfX * rVec.mfX) + (mfY * rVec.mfY));
    }

    double B2DVector::cross( const B2DVector& rVec ) const
    {
        return(mfX * rVec.getY() - mfY * rVec.getX());
    }

    double B2DVector::angle( const B2DVector& rVec ) const
    {
        return atan2(mfX * rVec.getY() - mfY * rVec.getX(),
            mfX * rVec.getX() + mfY * rVec.getY());
    }

    const B2DVector& B2DVector::getEmptyVector()
    {
        return (const B2DVector&) ::basegfx::B2DTuple::getEmptyTuple();
    }

    B2DVector& B2DVector::operator*=( const B2DHomMatrix& rMat )
    {
        const double fTempX( rMat.get(0,0)*mfX +
                            rMat.get(0,1)*mfY );
        const double fTempY( rMat.get(1,0)*mfX +
                            rMat.get(1,1)*mfY );
        mfX = fTempX;
        mfY = fTempY;

        return *this;
    }

    B2DVector& B2DVector::setLength(double fLen)
    {
        double fLenNow(scalar(*this));

        if(!::basegfx::fTools::equalZero(fLenNow))
        {
            const double fOne(10.0);

            if(!::basegfx::fTools::equal(fOne, fLenNow))
            {
                fLen /= sqrt(fLenNow);
            }

            mfX *= fLen;
            mfY *= fLen;
        }

        return *this;
    }

    bool B2DVector::isNormalized() const
    {
        const double fOne(1.0);
        const double fScalar(scalar(*this));

        return (::basegfx::fTools::equal(fOne, fScalar));
    }

    bool areParallel( const B2DVector& rVecA, const B2DVector& rVecB )
    {
        double fVal(rVecA.getX() * rVecB.getY() - rVecA.getY() * rVecB.getX());
        return ::basegfx::fTools::equalZero(fVal);
    }

    B2VectorOrientation getOrientation( const B2DVector& rVecA, const B2DVector& rVecB )
    {
        double fVal(rVecA.getX() * rVecB.getY() - rVecA.getY() * rVecB.getX());

        if(::basegfx::fTools::equalZero(fVal))
        {
            return ORIENTATION_NEUTRAL;
        }

        if(fVal > 0.0)
        {
            return ORIENTATION_POSITIVE;
        }
        else
        {
            return ORIENTATION_NEGATIVE;
        }
    }

    B2DVector getPerpendicular( const B2DVector& rNormalizedVec )
    {
        B2DVector aPerpendicular(-rNormalizedVec.getY(), rNormalizedVec.getX());
        return aPerpendicular;
    }

    B2DVector getNormalizedPerpendicular( const B2DVector& rVec )
    {
        B2DVector aPerpendicular(rVec);
        aPerpendicular.normalize();
        const double aTemp(-aPerpendicular.getY());
        aPerpendicular.setY(aPerpendicular.getX());
        aPerpendicular.setX(aTemp);
        return aPerpendicular;
    }

    B2DVector operator*( const ::basegfx::B2DHomMatrix& rMat, const B2DVector& rVec )
    {
        B2DVector aRes( rVec );
        return aRes*=rMat;
    }

    B2VectorContinuity getContinuity(const B2DVector& rBackVector, const B2DVector& rForwardVector )
    {
        B2VectorContinuity eRetval(::basegfx::CONTINUITY_NONE);

        if(!rBackVector.equalZero() && !rForwardVector.equalZero())
        {
            const B2DVector aInverseForwardVector(-rForwardVector.getX(), -rForwardVector.getY());

            if(rBackVector.equal(aInverseForwardVector))
            {
                // same direction and same length -> C2
                eRetval = ::basegfx::CONTINUITY_C2;
            }
            else if(areParallel(rBackVector, aInverseForwardVector))
            {
                // same direction -> C1
                eRetval = ::basegfx::CONTINUITY_C1;
            }
        }

        return eRetval;
    }
} // end of namespace basegfx

// eof
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2006 Funambol
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "base/util/BasicTime.h"

BasicTime::BasicTime() {
    year = 1970;
    month = 1;
    day = 1;
    weekday = 0;
    hour = 0;
    min = 0;
    sec = 0;
    tzHour = 0;
    tzMin = 0;
}

int BasicTime::set(int yy, int mon, int dd, int wd,
                   int hh, int mm, int ss, int tzh, int tzm)
{
    //  TODO
    return 0;
}

/**
 * Parse the date in RF 822 format
 *
 * Some examples:
 * Date: Fri, 01 Aug 2003 14:04:55 +0800
 * Date: Wed, 30 Jul 2003 13:24:21 -0700
 * Date: 20 Jun 2003 15:42:12 -0500
 *
 * RFC822 date time
 *
 *   date-time   =  [ day "," ] date time        ; dd mm yy
 *                                              ;  hh:mm:ss zzz
 *
 *   day         =  "Mon"  / "Tue" /  "Wed"  / "Thu"
 *               /  "Fri"  / "Sat" /  "Sun"
 *
 *   date        =  1*2DIGIT month 2DIGIT        ; day month year
 *                                               ;  e.g. 20 Jun 82
 *
 *   month       =  "Jan"  /  "Feb" /  "Mar"  /  "Apr"
 *               /  "May"  /  "Jun" /  "Jul"  /  "Aug"
 *               /  "Sep"  /  "Oct" /  "Nov"  /  "Dec"
 *
 *   time        =  hour zone                    ; ANSI and Military
 *
 *   hour        =  2DIGIT ":" 2DIGIT [":" 2DIGIT]
 *                                               ; 00:00:00 - 23:59:59
 *
 *   zone        =  "UT"  / "GMT"                ; Universal Time
 *                                               ; North American : UT
 *               /  "EST" / "EDT"                ;  Eastern:  - 5/ - 4
 *               /  "CST" / "CDT"                ;  Central:  - 6/ - 5
 *               /  "MST" / "MDT"                ;  Mountain: - 7/ - 6
 *               /  "PST" / "PDT"                ;  Pacific:  - 8/ - 7
 *               /  1ALPHA                       ; Military: Z = UT;
 *                                               ;  A:-1; (J not used)
 *                                               ;  M:-12; N:+1; Y:+12
 *               / ( ("+" / "-") 4DIGIT )        ; Local differential
 *                                               ;  hours+min. (HHMM)
**/
int BasicTime::parseRfc822(const char *date)
{
	const char *days[] = {
        T("Sun"), T("Mon"), T("Tue"), T("Wed"),
        T("Thu"), T("Fri"), T("Sat")
    };
	const char *months[] = {
        T("Jan"), T("Feb"), T("Mar"), T("Apr"),
        T("May"), T("Jun"), T("Jul"), T("Aug"),
        T("Sep"), T("Oct"), T("Nov"), T("Dec")
    };
	char dayOfWeek[6] = T("---,");
	char mon[4] = T("---");
	char time[10] = T("00:00:00");
	char timeZone[20] = T("GMT");

    int ret;

    // Wed Feb 01 14:40:45 Europe/Amsterdam 2006
	// do we have day of week?
    const char *pdate = strstr( date, T(",") );
	if ( pdate == 0 ) {
		ret=sscanf(date, T("%d %s %d %s %s"),
            &day, mon, &year, time, timeZone);
    }
	else {
		ret=sscanf(date, T("%s %d %s %d %s %s"),
            dayOfWeek, &day, mon, &year, time, timeZone);
    }
    // Trap parsing error
    if(ret == EOF || ret == 0){
        return -1;
    }
    if (year > 3000 || day < 0 || day > 31){
        *this = BasicTime();
        return -1;
    }

    // Get month
    int i;
	for (i = 0; i < 12; i++) {
		if ( strcmp(months[i], mon) == 0 ) {
            month = i+1;
			break;
        }
	}
    // Trap parsing error
    if (i==13)
        return -1;

	// Year ---------------------------------
	if (year < 100) year += 1900;

	// hh:mm:ss -------------------------
	// do we have sec?
	if (strlen(time) > 6 && time[5] == ':')
		sscanf(time, T("%d:%d:%d"), &hour, &min, &sec);
	else
		sscanf(time, T("%d:%d"), &hour, &min);

	// Timezone ---------------------------------
    if ( strcmp(timeZone, T("GMT")) ) {
		// is this explicit time?
		if ( timeZone[0] == '+' || timeZone[0]== '-' ) {
			char wcH[4] = T("+00");
			char wcM[4] = T("00");

			// get hour
			if ( strlen(timeZone) > 3) {
				wcH[0] = timeZone[0];
				wcH[1] = timeZone[1];
				wcH[2] = timeZone[2];
				wcH[3] = '\0';
			}
			// get min
			if ( strlen(timeZone) >= 5)	{
				wcM[0] = timeZone[3];
				wcM[1] = timeZone[4];
				wcM[2] = '\0';
			}
			tzHour = atoi(wcH);
			tzMin = atoi(wcM);
		}
		// otherwise it could be one string with the time
		else if ( strcmp(timeZone, T("EDT")) )
			tzHour = -4;
		else if ( strcmp(timeZone, T("EST"))
                  ||  strcmp(timeZone, T("CDT")) )
			tzHour = -5;
		else if ( strcmp(timeZone, T("CST"))
                  ||  strcmp(timeZone, T("MDT")) )
			tzHour = -6;
		else if ( strcmp(timeZone, T("MST"))
                  ||  strcmp(timeZone, T("PDT")) )
			tzHour = -7;
		else if ( strcmp(timeZone, T("PST")) )
			tzHour = -8;
	}

	// clean up
	return 0;
}

// Date: Fri, 01 Aug 2003 14:04:55 +0800
char *BasicTime::formatRfc822() const {
	const char *days[] = {
        T("Sun"), T("Mon"), T("Tue"), T("Wed"),
        T("Thu"), T("Fri"), T("Sat"), T("Sun")
    };
	const char *months[] = {
        T("Jan"), T("Feb"), T("Mar"), T("Apr"),
        T("May"), T("Jun"), T("Jul"), T("Aug"),
        T("Sep"), T("Oct"), T("Nov"), T("Dec")
    };
    char *ret = new char[30];

    sprintf(ret, T("%s, %d %s %d %02d:%02d:%02d %+03d%02d"),
                  days[weekday], day, months[month-1], year, hour, min, sec,
                  tzHour, tzMin);

    return ret;
}

ArrayElement *BasicTime::clone() {
    return new BasicTime(*this);
};

BasicTime& BasicTime::operator=(const BasicTime& o) {
    year = o.year;
    month = o.month;
    day = o.day;
    weekday = o.weekday;
    hour = o.hour;
    min = o.min;
    sec = o.sec;
    tzHour = o.tzHour;
    tzMin = o.tzMin;

    return *this;
}

bool BasicTime::operator==(const BasicTime& o) const {
    return (
        year == o.year &&
        month == o.month &&
        day == o.day &&
        weekday == o.weekday &&
        hour == o.hour &&
        min == o.min &&
        sec == o.sec &&
        tzHour == o.tzHour &&
        tzMin == o.tzMin
    );
}

<commit_msg>added unit testing and fixed one problem found by it (memory corruption)<commit_after>/*
 * Copyright (C) 2006 Funambol
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <base/test.h>

#include "base/util/BasicTime.h"

BasicTime::BasicTime() {
    year = 1970;
    month = 1;
    day = 1;
    weekday = 0;
    hour = 0;
    min = 0;
    sec = 0;
    tzHour = 0;
    tzMin = 0;
}

int BasicTime::set(int yy, int mon, int dd, int wd,
                   int hh, int mm, int ss, int tzh, int tzm)
{
    //  TODO
    return 0;
}

/**
 * Parse the date in RF 822 format
 *
 * Some examples:
 * Date: Fri, 01 Aug 2003 14:04:55 +0800
 * Date: Wed, 30 Jul 2003 13:24:21 -0700
 * Date: 20 Jun 2003 15:42:12 -0500
 *
 * RFC822 date time
 *
 *   date-time   =  [ day "," ] date time        ; dd mm yy
 *                                              ;  hh:mm:ss zzz
 *
 *   day         =  "Mon"  / "Tue" /  "Wed"  / "Thu"
 *               /  "Fri"  / "Sat" /  "Sun"
 *
 *   date        =  1*2DIGIT month 2DIGIT        ; day month year
 *                                               ;  e.g. 20 Jun 82
 *
 *   month       =  "Jan"  /  "Feb" /  "Mar"  /  "Apr"
 *               /  "May"  /  "Jun" /  "Jul"  /  "Aug"
 *               /  "Sep"  /  "Oct" /  "Nov"  /  "Dec"
 *
 *   time        =  hour zone                    ; ANSI and Military
 *
 *   hour        =  2DIGIT ":" 2DIGIT [":" 2DIGIT]
 *                                               ; 00:00:00 - 23:59:59
 *
 *   zone        =  "UT"  / "GMT"                ; Universal Time
 *                                               ; North American : UT
 *               /  "EST" / "EDT"                ;  Eastern:  - 5/ - 4
 *               /  "CST" / "CDT"                ;  Central:  - 6/ - 5
 *               /  "MST" / "MDT"                ;  Mountain: - 7/ - 6
 *               /  "PST" / "PDT"                ;  Pacific:  - 8/ - 7
 *               /  1ALPHA                       ; Military: Z = UT;
 *                                               ;  A:-1; (J not used)
 *                                               ;  M:-12; N:+1; Y:+12
 *               / ( ("+" / "-") 4DIGIT )        ; Local differential
 *                                               ;  hours+min. (HHMM)
**/
int BasicTime::parseRfc822(const char *date)
{
	const char *days[] = {
        T("Sun"), T("Mon"), T("Tue"), T("Wed"),
        T("Thu"), T("Fri"), T("Sat")
    };
	const char *months[] = {
        T("Jan"), T("Feb"), T("Mar"), T("Apr"),
        T("May"), T("Jun"), T("Jul"), T("Aug"),
        T("Sep"), T("Oct"), T("Nov"), T("Dec")
    };
	char dayOfWeek[6] = T("---,");
	char mon[4] = T("---");
	char time[10] = T("00:00:00");
	char timeZone[20] = T("GMT");

    int ret;

    // Wed Feb 01 14:40:45 Europe/Amsterdam 2006
	// do we have day of week?
    const char *pdate = strstr( date, T(",") );
	if ( pdate == 0 ) {
		ret=sscanf(date, T("%d %s %d %s %s"),
            &day, mon, &year, time, timeZone);
    }
	else {
		ret=sscanf(date, T("%s %d %s %d %s %s"),
            dayOfWeek, &day, mon, &year, time, timeZone);
    }
    // Trap parsing error
    if(ret == EOF || ret == 0){
        return -1;
    }
    if (year > 3000 || day < 0 || day > 31){
        *this = BasicTime();
        return -1;
    }

    // Get month
    int i;
	for (i = 0; i < 12; i++) {
		if ( strcmp(months[i], mon) == 0 ) {
            month = i+1;
			break;
        }
	}
    // Trap parsing error
    if (i==13)
        return -1;

	// Year ---------------------------------
	if (year < 100) year += 1900;

	// hh:mm:ss -------------------------
	// do we have sec?
	if (strlen(time) > 6 && time[5] == ':')
		sscanf(time, T("%d:%d:%d"), &hour, &min, &sec);
	else
		sscanf(time, T("%d:%d"), &hour, &min);

	// Timezone ---------------------------------
    if ( strcmp(timeZone, T("GMT")) ) {
		// is this explicit time?
		if ( timeZone[0] == '+' || timeZone[0]== '-' ) {
			char wcH[4] = T("+00");
			char wcM[4] = T("00");

			// get hour
			if ( strlen(timeZone) > 3) {
				wcH[0] = timeZone[0];
				wcH[1] = timeZone[1];
				wcH[2] = timeZone[2];
				wcH[3] = '\0';
			}
			// get min
			if ( strlen(timeZone) >= 5)	{
				wcM[0] = timeZone[3];
				wcM[1] = timeZone[4];
				wcM[2] = '\0';
			}
			tzHour = atoi(wcH);
			tzMin = atoi(wcM);
		}
		// otherwise it could be one string with the time
		else if ( strcmp(timeZone, T("EDT")) )
			tzHour = -4;
		else if ( strcmp(timeZone, T("EST"))
                  ||  strcmp(timeZone, T("CDT")) )
			tzHour = -5;
		else if ( strcmp(timeZone, T("CST"))
                  ||  strcmp(timeZone, T("MDT")) )
			tzHour = -6;
		else if ( strcmp(timeZone, T("MST"))
                  ||  strcmp(timeZone, T("PDT")) )
			tzHour = -7;
		else if ( strcmp(timeZone, T("PST")) )
			tzHour = -8;
	}

	// clean up
	return 0;
}

// Date: Fri, 01 Aug 2003 14:04:55 +0800
char *BasicTime::formatRfc822() const {
	const char *days[] = {
        T("Sun"), T("Mon"), T("Tue"), T("Wed"),
        T("Thu"), T("Fri"), T("Sat"), T("Sun")
    };
	const char *months[] = {
        T("Jan"), T("Feb"), T("Mar"), T("Apr"),
        T("May"), T("Jun"), T("Jul"), T("Aug"),
        T("Sep"), T("Oct"), T("Nov"), T("Dec")
    };
    char *ret = new char[60]; // FIXME: avoid sprintf and static size

    sprintf(ret, T("%s, %d %s %d %02d:%02d:%02d %+03d%02d"),
                  days[weekday], day, months[month-1], year, hour, min, sec,
                  tzHour, tzMin);

    return ret;
}

ArrayElement *BasicTime::clone() {
    return new BasicTime(*this);
};

BasicTime& BasicTime::operator=(const BasicTime& o) {
    year = o.year;
    month = o.month;
    day = o.day;
    weekday = o.weekday;
    hour = o.hour;
    min = o.min;
    sec = o.sec;
    tzHour = o.tzHour;
    tzMin = o.tzMin;

    return *this;
}

bool BasicTime::operator==(const BasicTime& o) const {
    return (
        year == o.year &&
        month == o.month &&
        day == o.day &&
        weekday == o.weekday &&
        hour == o.hour &&
        min == o.min &&
        sec == o.sec &&
        tzHour == o.tzHour &&
        tzMin == o.tzMin
    );
}

#ifdef ENABLE_UNIT_TESTS

class BasicTimeTest : public CppUnit::TestFixture {
    CPPUNIT_TEST_SUITE(BasicTimeTest);
    CPPUNIT_TEST(testEqual);
    CPPUNIT_TEST(testConversion);
    CPPUNIT_TEST_SUITE_END();

public:
    void setUp() {
        // millenium.set(2000, 01, 01, 6,
        //              00, 00, 00,
        //              00, 00);
        millenium.setYear(2000);
        buffer = NULL;
    }
    void tearDown() {
        if (buffer) {
            delete [] buffer;
        }
    }

protected:
    void testEqual() {
        BasicTime empty;
        CPPUNIT_ASSERT(empty != millenium);

        BasicTime copy(millenium);
        CPPUNIT_ASSERT(millenium == copy);
        copy = millenium;
        CPPUNIT_ASSERT(millenium == copy);
    }

    void testConversion() {
        buffer = millenium.formatRfc822();

        BasicTime copy;
        CPPUNIT_ASSERT_EQUAL(0, copy.parseRfc822(buffer));
        CPPUNIT_ASSERT(millenium == copy);
        delete [] buffer; buffer = NULL;

        CPPUNIT_ASSERT_EQUAL(-1, copy.parseRfc822("this is garbage"));

        static const char convertStr[] = "Mon, 6 Nov 2006 20:30:15 +0100";
        BasicTime convert;
        CPPUNIT_ASSERT_EQUAL(0, convert.parseRfc822(convertStr));
        buffer = convert.formatRfc822();
        CPPUNIT_ASSERT(!strcmp(buffer, convertStr));
        delete [] buffer; buffer = NULL;
    }

private:
    BasicTime millenium;
    char *buffer;
};

FUNAMBOL_TEST_SUITE_REGISTRATION(BasicTimeTest);

#endif
<|endoftext|>


<commit_before>#include "mainwindow.h"

#include <state/state_gfe.h>
#include "affordance/OpenGL_Affordance.h"
#include <vector>
using namespace std;
using namespace KDL;
using namespace Eigen;
using namespace opengl;
using namespace state;
using namespace collision;
using namespace action_authoring;
using namespace affordance;
using namespace boost;

//using namespace collision_detection;

/*
 * Filler method to populate affordance and constraint lists until we get proper
 * data sources set up.
 */
void MainWindow::demoPopulateConstraints()
{
    AffPtr rhand = AffPtr(new AffordanceState("Right Hand"));
    AffPtr lhand = AffPtr(new AffordanceState("Left Hand"));
    AffPtr rfoot = AffPtr(new AffordanceState("Right Foot"));
    AffPtr lfoot = AffPtr(new AffordanceState("Left Foot"));
    AffPtr wheel = AffPtr(new AffordanceState("Steering Wheel"));
    AffPtr gas   = AffPtr(new AffordanceState("Gas Pedal"));
    AffPtr brake = AffPtr(new AffordanceState("Brake Pedal"));

    AffPtr sphere 	= AffPtr(new AffordanceState("Pink Sphere"));
    AffPtr box 		= AffPtr(new AffordanceState("Yellow Box"));
    AffPtr cylinder = AffPtr(new AffordanceState("Blue Cylinder"));

    _all_affordances.push_back(wheel);
    _all_affordances.push_back(gas);
    _all_affordances.push_back(brake);

    _all_affordances.push_back(sphere);
    _all_affordances.push_back(box);
    _all_affordances.push_back(cylinder);

    /*    TODO : read from server */
    Qt4ConstraintPtr rfoot_gas   = Qt4ConstraintPtr(new Qt4Constraint(
							AtomicConstraintPtr(new AtomicConstraint("Gas Pedal Constraint", rfoot, gas, AtomicConstraint::NORMAL))));
    Qt4ConstraintPtr lfoot_brake = Qt4ConstraintPtr(new Qt4Constraint(
							AtomicConstraintPtr(new AtomicConstraint("Brake Pedal Constraint", lfoot, brake, AtomicConstraint::TANGENT))));
    Qt4ConstraintPtr rhand_wheel = Qt4ConstraintPtr(new Qt4Constraint(
							AtomicConstraintPtr(new AtomicConstraint("Right Hand Wheel Constraint", rhand, wheel, AtomicConstraint::TANGENT))));
    Qt4ConstraintPtr lhand_wheel = Qt4ConstraintPtr(new Qt4Constraint(
							AtomicConstraintPtr(new AtomicConstraint("Left Hand Wheel Constraint", lhand, wheel, AtomicConstraint::TANGENT))));
    _authoringState._all_gui_constraints.push_back(rfoot_gas);
    _authoringState._all_gui_constraints.push_back(lfoot_brake);
    _authoringState._all_gui_constraints.push_back(rhand_wheel);
    _authoringState._all_gui_constraints.push_back(lhand_wheel);

}

MainWindow::MainWindow(const shared_ptr<lcm::LCM> &theLcm, QWidget* parent)
	: _widget_opengl(),
	  _worldState(theLcm)
{
    // setup the OpenGL 6scene
	_worldState.state_gfe.from_urdf();
	_worldState.colorRobot.set(_worldState.state_gfe);

    // build collision objects
	/*todo  construct collision objects from the affordances
	_collision_object_box = new Collision_Object_Box("box1", Vector3f(0.25, 0.25, 0.25), Vector3f(1.0, 0.0, 0.0), Vector4f(1.0, 0.0, 0.0, 0.0));
    _collision_object_cylinder = new Collision_Object_Cylinder("cylinder1", 0.25, 0.25, Vector3f(0.0, 1.0, 0.0), Vector4f(1.0, 0.0, 0.0, 0.0));
    _collision_object_sphere = new Collision_Object_Sphere("sphere1", 0.125, Vector3f(-0.5, -0.5, 0.0), Vector4f(1.0, 0.0, 0.0, 0.0));
    //_collision_object_gfe("robot1");
*/
    // read the joints from the robot state
    std::vector<std::string> joint_names;
    std::map< std::string, State_GFE_Joint > joints = _worldState.state_gfe.joints();
    for (std::map< std::string, State_GFE_Joint >::const_iterator it = joints.begin(); it != joints.end(); it++)
    {
    	const State_GFE_Joint& state_gfe_joint = it->second;
    	joint_names.push_back(state_gfe_joint.id());
    }

    vector<AffPtr> affordances;
    _worldState.affordances.getAllAffordances(affordances);

    while(affordances.size() == 0)
    {
    	_worldState.affordances.getAllAffordances(affordances);
    	cout << "\n waiting for affordances to be non-zero" << endl;
    	boost::this_thread::sleep(posix_time::seconds(1));
    }

    cout << "\n\n got " << affordances.size() << " affordances " << endl;

    for(uint i = 0; i < affordances.size(); i++)
    {
    	AffPtr next = affordances[i];
    	if (next->_otdf_id == AffordanceState::CYLINDER ||
    		next->_otdf_id == AffordanceState::BOX ||
    		next->_otdf_id == AffordanceState::SPHERE)
    	{
    		OpenGL_Affordance *asGlAff = new OpenGL_Affordance(*next); //todo : get rid of this memory leak
    		_widget_opengl.opengl_scene().add_object(*asGlAff);
    	}
    }

    /*todo
    _widget_opengl.opengl_scene().add_object(_opengl_object_box);
    _widget_opengl.opengl_scene().add_object(_opengl_object_cylinder);
    _widget_opengl.opengl_scene().add_object(_opengl_object_sphere);
*/
    _widget_opengl.opengl_scene().add_object(_worldState.colorRobot);

    /*todo
    _widget_opengl.add_object_with_collision(_collision_object_box);
    _widget_opengl.add_object_with_collision(_collision_object_cylinder);
    _widget_opengl.add_object_with_collision(_collision_object_sphere);
    	*/
    //_widget_opengl.add_object_with_collision(_collision_object_gfe);

    _signalMapper = new QSignalMapper(this);

    QVBoxLayout* layout = new QVBoxLayout();
    layout->setMargin(0);

    QSplitter* splitter = new QSplitter();
    QGroupBox* leftside = new QGroupBox();
    QVBoxLayout* vbox = new QVBoxLayout();

    QWidget* topmenugroup = new QWidget();
    QHBoxLayout* topmenu = new QHBoxLayout();
    topmenu->addWidget(new QLabel("Action: "));
    topmenu->addWidget(new QLineEdit("Ingress"));
    QPushButton* savebutton = new QPushButton("Save");
    topmenu->addWidget(savebutton);
    topmenu->addSpacerItem(new QSpacerItem(100, 0));
    QPushButton* loaddiff = new QPushButton("load a different action");
    topmenu->addWidget(loaddiff);
    topmenugroup->setLayout(topmenu);
    vbox->addWidget(topmenugroup);

    //joint_names = getJointNames("/home/drc/drc/software/models/mit_gazebo_models/mit_robot/model.urdf");

    demoPopulateConstraints();
    for(std::vector<int>::size_type i = 0; i != _authoringState._all_gui_constraints.size(); i++) {
	TogglePanel* tp; // = new TogglePanel(this, "hi");
	_authoringState._all_gui_constraints[i]->setJointNames(joint_names);
	_authoringState._all_gui_constraints[i]->setAffordances(_all_affordances);
	//tp->setTitle("hi there");
	tp = _authoringState._all_gui_constraints[i]->getPanel();
	vbox->addWidget(tp);
    }

    QGroupBox* mediaControls = new QGroupBox();
    QHBoxLayout* mediaControlsLayout = new QHBoxLayout();
    QPushButton* fbwd = new QPushButton();
    QPushButton* bwd = new QPushButton();
    QPushButton* play = new QPushButton();
    QPushButton* fwd = new QPushButton();
    QPushButton* ffwd = new QPushButton();

    // see http://www.qtcentre.org/wiki/index.php?title=Embedded_resources
    QPixmap pixmap1(":/trolltech/styles/commonstyle/images/media-skip-backward-32.png");
    fbwd->setIcon(QIcon(pixmap1));
    fbwd->setIconSize(pixmap1.rect().size());

    QPixmap pixmap2(":/trolltech/styles/commonstyle/images/media-seek-backward-32.png");
    bwd->setIcon(QIcon(pixmap2));
    bwd->setIconSize(pixmap2.rect().size());

    QPixmap pixmap3(":/trolltech/styles/commonstyle/images/media-pause-32.png");
    play->setIcon(QIcon(pixmap3));
    play->setIconSize(pixmap3.rect().size());

    QPixmap pixmap4(":/trolltech/styles/commonstyle/images/media-seek-forward-32.png");
    fwd->setIcon(QIcon(pixmap4));
    fwd->setIconSize(pixmap4.rect().size());

    QPixmap pixmap5(":/trolltech/styles/commonstyle/images/media-skip-forward-32.png");
    ffwd->setIcon(QIcon(pixmap5));
    ffwd->setIconSize(pixmap5.rect().size());

    mediaControlsLayout->addSpacerItem(new QSpacerItem(100, 0));
    mediaControlsLayout->addWidget(fbwd);
    mediaControlsLayout->addWidget(bwd);
    mediaControlsLayout->addWidget(play);
    mediaControlsLayout->addWidget(fwd);
    mediaControlsLayout->addWidget(ffwd);
    mediaControlsLayout->addSpacerItem(new QSpacerItem(100, 0));
    mediaControls->setLayout(mediaControlsLayout);
    play->resize(play->width() * 2, play->height());

    QGroupBox* widgetWrapper = new QGroupBox();
    widgetWrapper->setStyleSheet("QGroupBox { border: 1px solid gray; border-radius: 0px; padding: 0px; margin: 0px; background-color: black; }");
    QVBoxLayout* widgetWrapperLayout = new QVBoxLayout();
    widgetWrapperLayout->setSpacing(0);
    widgetWrapperLayout->setMargin(0);
    widgetWrapperLayout->addWidget(&_widget_opengl);
    widgetWrapperLayout->addWidget(mediaControls);
    widgetWrapper->setLayout(widgetWrapperLayout);

    QVBoxLayout* rightsidelayout = new QVBoxLayout();
    QGroupBox* rightside = new QGroupBox();
    _jointSlider = new QSlider( Qt::Horizontal, this );
    _jointNameLabel = new QLabel();
    DefaultValueSlider* scrubber = new DefaultValueSlider( Qt::Horizontal, this );
    rightsidelayout->addWidget(_jointNameLabel);
    rightsidelayout->addWidget(_jointSlider);
    rightsidelayout->addWidget(widgetWrapper);
    rightsidelayout->addWidget(scrubber );
//    rightside->setStyleSheet("QGroupBox { border: 1px solid black; border-radius: 3px; padding: 0px; background-color: black; } ");
    rightside->setLayout(rightsidelayout);

    splitter->addWidget( leftside);
    splitter->addWidget(rightside);

    layout->addWidget(splitter);
    QGroupBox* toolbarButtons = new QGroupBox(""); //controls
    QHBoxLayout* toolbarButtonsLayout = new QHBoxLayout();
    toolbarButtonsLayout->addWidget(new QPushButton("delete"));
    toolbarButtonsLayout->addSpacing(200);
    toolbarButtonsLayout->addWidget(new QPushButton("move up"));
    toolbarButtonsLayout->addWidget(new QPushButton("move down"));
    toolbarButtons->setLayout(toolbarButtonsLayout);
    vbox->addWidget(toolbarButtons);
    vbox->addStretch(1);
    leftside->setLayout(vbox);

    // fix the borders on the group boxes
    this->setStyleSheet("QGroupBox { border: 1px solid gray; border-radius: 3px; padding: 5px; } "
			"QGroupBox::title { background-color: transparent; "
			"subcontrol-position: top left; /* position at the top left*/ "
			"padding:2 5px; } ");

    this->setLayout(layout);

    // wire up the buttons
    connect(savebutton, SIGNAL(released()), this, SLOT(handleSaveAction()));
    connect(loaddiff, SIGNAL(released()), this, SLOT(handleLoadAction()));
    connect(_jointSlider, SIGNAL(valueChanged(int)), this, SLOT(updateJoint(int)));
}

MainWindow::~MainWindow()
{

}

void
MainWindow::
handleLoadAction() {
 QString fileName = QFileDialog::getOpenFileName(this,
     tr("Open Action"), "", tr("Action XML Files (*.xml)"));
}

void
MainWindow::
handleSaveAction() {
 QString fileName = QFileDialog::getSaveFileName(this,
     tr("Save Action"), "", tr("Action XML Files (*.xml)"));
}

void
MainWindow::
handleDeleteWaypoint() {

}

void
MainWindow::
handleMoveUp() {

}

void
MainWindow::
handleMoveDown() {

}

void
MainWindow::
handleToggleExpandContract() {

}

void
MainWindow::
updateJoint(int value) {
    if (_selectedJointName != "") {
	std::cout << "joint " << _selectedJointName << " set to " <<  _jointSlider->value() / 100.0 << std::endl;
	_worldState.state_gfe.joint(_selectedJointName).set_position( _jointSlider->value() / 100.0 );
	_worldState.colorRobot.set(_worldState.state_gfe);
	_widget_opengl.update(); //_opengl_widget.update();
	//update();
    }
}

/*
 * change the functionality of the slider to actuate currently selected link
 */
void
MainWindow::
handleRobotLinkChange(QString waypointName) {
    // start by getting the name of the link currently selected
/*
    QComboBox* selected_combo = _all_robot_link_combos.find(waypointName.toStdString())->second;
    // find the selected text
    _selectedJointName = selected_combo->currentText().toStdString();  //itemData(selected_combo->currentIndex());
    _worldState.colorRobot.setSelectedJoint(_selectedJointName);
    _widget_opengl.update(); //_opengl_widget.update();
    _jointNameLabel->setText(QString::fromStdString(_selectedJointName));
*/
}

void
MainWindow::
setSelectedAction(QString waypointName){
/*
    TogglePanel* selected_panel = _all_panels.find(waypointName.toStdString())->second;
    std::map<std::string, TogglePanel*>::iterator iter;
    for (iter = _all_panels.begin(); iter != _all_panels.end(); iter++) {
        TogglePanel* other_panel = iter->second;
	other_panel->setSelected(false);
    }
    selected_panel->setSelected(true);
*/
}
<commit_msg>quick fix<commit_after>#include "mainwindow.h"

#include <state/state_gfe.h>
#include "affordance/OpenGL_Affordance.h"
#include <vector>
using namespace std;
using namespace KDL;
using namespace Eigen;
using namespace opengl;
using namespace state;
using namespace collision;
using namespace action_authoring;
using namespace affordance;
using namespace boost;

//using namespace collision_detection;

/*
 * Filler method to populate affordance and constraint lists until we get proper
 * data sources set up.
 */
void MainWindow::demoPopulateConstraints()
{
    AffPtr rhand = AffPtr(new AffordanceState("Right Hand"));
    AffPtr lhand = AffPtr(new AffordanceState("Left Hand"));
    AffPtr rfoot = AffPtr(new AffordanceState("Right Foot"));
    AffPtr lfoot = AffPtr(new AffordanceState("Left Foot"));
    AffPtr wheel = AffPtr(new AffordanceState("Steering Wheel"));
    AffPtr gas   = AffPtr(new AffordanceState("Gas Pedal"));
    AffPtr brake = AffPtr(new AffordanceState("Brake Pedal"));

    AffPtr sphere 	= AffPtr(new AffordanceState("Pink Sphere"));
    AffPtr box 		= AffPtr(new AffordanceState("Yellow Box"));
    AffPtr cylinder = AffPtr(new AffordanceState("Blue Cylinder"));

    _all_affordances.push_back(wheel);
    _all_affordances.push_back(gas);
    _all_affordances.push_back(brake);

    _all_affordances.push_back(sphere);
    _all_affordances.push_back(box);
    _all_affordances.push_back(cylinder);

    /*    TODO : read from server */
    Qt4ConstraintPtr rfoot_gas   = Qt4ConstraintPtr(new Qt4Constraint(
							AtomicConstraintPtr(new AtomicConstraint("Gas Pedal Constraint", rfoot, gas, AtomicConstraint::NORMAL))));
    Qt4ConstraintPtr lfoot_brake = Qt4ConstraintPtr(new Qt4Constraint(
							AtomicConstraintPtr(new AtomicConstraint("Brake Pedal Constraint", lfoot, brake, AtomicConstraint::TANGENT))));
    Qt4ConstraintPtr rhand_wheel = Qt4ConstraintPtr(new Qt4Constraint(
							AtomicConstraintPtr(new AtomicConstraint("Right Hand Wheel Constraint", rhand, wheel, AtomicConstraint::TANGENT))));
    Qt4ConstraintPtr lhand_wheel = Qt4ConstraintPtr(new Qt4Constraint(
							AtomicConstraintPtr(new AtomicConstraint("Left Hand Wheel Constraint", lhand, wheel, AtomicConstraint::TANGENT))));
    _authoringState._all_gui_constraints.push_back(rfoot_gas);
    _authoringState._all_gui_constraints.push_back(lfoot_brake);
    _authoringState._all_gui_constraints.push_back(rhand_wheel);
    _authoringState._all_gui_constraints.push_back(lhand_wheel);

}

MainWindow::MainWindow(const shared_ptr<lcm::LCM> &theLcm, QWidget* parent)
	: _widget_opengl(),
	  _worldState(theLcm)
{
    // setup the OpenGL 6scene
	_worldState.state_gfe.from_urdf();
	_worldState.colorRobot.set(_worldState.state_gfe);

    // build collision objects
	/*todo  construct collision objects from the affordances
	_collision_object_box = new Collision_Object_Box("box1", Vector3f(0.25, 0.25, 0.25), Vector3f(1.0, 0.0, 0.0), Vector4f(1.0, 0.0, 0.0, 0.0));
    _collision_object_cylinder = new Collision_Object_Cylinder("cylinder1", 0.25, 0.25, Vector3f(0.0, 1.0, 0.0), Vector4f(1.0, 0.0, 0.0, 0.0));
    _collision_object_sphere = new Collision_Object_Sphere("sphere1", 0.125, Vector3f(-0.5, -0.5, 0.0), Vector4f(1.0, 0.0, 0.0, 0.0));
    //_collision_object_gfe("robot1");
*/
    // read the joints from the robot state
    std::vector<std::string> joint_names;
    std::map< std::string, State_GFE_Joint > joints = _worldState.state_gfe.joints();
    for (std::map< std::string, State_GFE_Joint >::const_iterator it = joints.begin(); it != joints.end(); it++)
    {
    	const State_GFE_Joint& state_gfe_joint = it->second;
    	joint_names.push_back(state_gfe_joint.id());
    }

    vector<AffPtr> affordances;
    _worldState.affordances.getAllAffordances(affordances);

    while(affordances.size() == 0)
    {
    	_worldState.affordances.getAllAffordances(affordances);
    	cout << "\n waiting for affordances to be non-zero" << endl;
    	boost::this_thread::sleep(posix_time::seconds(1));
    }

    cout << "\n\n got " << affordances.size() << " affordances " << endl;

    for(uint i = 0; i < affordances.size(); i++)
    {
    	AffPtr next = affordances[i];
    	if (next->_otdf_id == AffordanceState::CYLINDER ||
    		next->_otdf_id == AffordanceState::BOX ||
    		next->_otdf_id == AffordanceState::SPHERE)
    	{
    		OpenGL_Affordance *asGlAff = new OpenGL_Affordance(*next); //todo : get rid of this memory leak
    		_widget_opengl.opengl_scene().add_object(*asGlAff);
    	}
    }

    /*todo
    _widget_opengl.opengl_scene().add_object(_opengl_object_box);
    _widget_opengl.opengl_scene().add_object(_opengl_object_cylinder);
    _widget_opengl.opengl_scene().add_object(_opengl_object_sphere);
*/
    _widget_opengl.opengl_scene().add_object(_worldState.colorRobot);

    /*todo
    _widget_opengl.add_object_with_collision(_collision_object_box);
    _widget_opengl.add_object_with_collision(_collision_object_cylinder);
    _widget_opengl.add_object_with_collision(_collision_object_sphere);
    	*/
    //_widget_opengl.add_object_with_collision(_collision_object_gfe);

    _signalMapper = new QSignalMapper(this);

    QVBoxLayout* layout = new QVBoxLayout();
    layout->setMargin(0);

    QSplitter* splitter = new QSplitter();
    QGroupBox* leftside = new QGroupBox();
    QVBoxLayout* vbox = new QVBoxLayout();

    QWidget* topmenugroup = new QWidget();
    QHBoxLayout* topmenu = new QHBoxLayout();
    topmenu->addWidget(new QLabel("Action: "));
    topmenu->addWidget(new QLineEdit("Ingress"));
    QPushButton* savebutton = new QPushButton("Save");
    topmenu->addWidget(savebutton);
    topmenu->addSpacerItem(new QSpacerItem(100, 0));
    QPushButton* loaddiff = new QPushButton("load a different action");
    topmenu->addWidget(loaddiff);
    topmenugroup->setLayout(topmenu);
    vbox->addWidget(topmenugroup);

    //joint_names = getJointNames("/home/drc/drc/software/models/mit_gazebo_models/mit_robot/model.urdf");

    demoPopulateConstraints();
    for(std::vector<int>::size_type i = 0; i != _authoringState._all_gui_constraints.size(); i++) {
	_authoringState._all_gui_constraints[i]->setJointNames(joint_names);
	_authoringState._all_gui_constraints[i]->setAffordances(_all_affordances);
	TogglePanel* tp = _authoringState._all_gui_constraints[i]->getPanel();
	std::cout << "panel gen'd" << tp << std::endl;
//	vbox->addWidget(tp);
    }

    QGroupBox* mediaControls = new QGroupBox();
    QHBoxLayout* mediaControlsLayout = new QHBoxLayout();
    QPushButton* fbwd = new QPushButton();
    QPushButton* bwd = new QPushButton();
    QPushButton* play = new QPushButton();
    QPushButton* fwd = new QPushButton();
    QPushButton* ffwd = new QPushButton();

    // see http://www.qtcentre.org/wiki/index.php?title=Embedded_resources
    QPixmap pixmap1(":/trolltech/styles/commonstyle/images/media-skip-backward-32.png");
    fbwd->setIcon(QIcon(pixmap1));
    fbwd->setIconSize(pixmap1.rect().size());

    QPixmap pixmap2(":/trolltech/styles/commonstyle/images/media-seek-backward-32.png");
    bwd->setIcon(QIcon(pixmap2));
    bwd->setIconSize(pixmap2.rect().size());

    QPixmap pixmap3(":/trolltech/styles/commonstyle/images/media-pause-32.png");
    play->setIcon(QIcon(pixmap3));
    play->setIconSize(pixmap3.rect().size());

    QPixmap pixmap4(":/trolltech/styles/commonstyle/images/media-seek-forward-32.png");
    fwd->setIcon(QIcon(pixmap4));
    fwd->setIconSize(pixmap4.rect().size());

    QPixmap pixmap5(":/trolltech/styles/commonstyle/images/media-skip-forward-32.png");
    ffwd->setIcon(QIcon(pixmap5));
    ffwd->setIconSize(pixmap5.rect().size());

    mediaControlsLayout->addSpacerItem(new QSpacerItem(100, 0));
    mediaControlsLayout->addWidget(fbwd);
    mediaControlsLayout->addWidget(bwd);
    mediaControlsLayout->addWidget(play);
    mediaControlsLayout->addWidget(fwd);
    mediaControlsLayout->addWidget(ffwd);
    mediaControlsLayout->addSpacerItem(new QSpacerItem(100, 0));
    mediaControls->setLayout(mediaControlsLayout);
    play->resize(play->width() * 2, play->height());

    QGroupBox* widgetWrapper = new QGroupBox();
    widgetWrapper->setStyleSheet("QGroupBox { border: 1px solid gray; border-radius: 0px; padding: 0px; margin: 0px; background-color: black; }");
    QVBoxLayout* widgetWrapperLayout = new QVBoxLayout();
    widgetWrapperLayout->setSpacing(0);
    widgetWrapperLayout->setMargin(0);
    widgetWrapperLayout->addWidget(&_widget_opengl);
    widgetWrapperLayout->addWidget(mediaControls);
    widgetWrapper->setLayout(widgetWrapperLayout);

    QVBoxLayout* rightsidelayout = new QVBoxLayout();
    QGroupBox* rightside = new QGroupBox();
    _jointSlider = new QSlider( Qt::Horizontal, this );
    _jointNameLabel = new QLabel();
    DefaultValueSlider* scrubber = new DefaultValueSlider( Qt::Horizontal, this );
    rightsidelayout->addWidget(_jointNameLabel);
    rightsidelayout->addWidget(_jointSlider);
    rightsidelayout->addWidget(widgetWrapper);
    rightsidelayout->addWidget(scrubber );
//    rightside->setStyleSheet("QGroupBox { border: 1px solid black; border-radius: 3px; padding: 0px; background-color: black; } ");
    rightside->setLayout(rightsidelayout);

    splitter->addWidget( leftside);
    splitter->addWidget(rightside);

    layout->addWidget(splitter);
    QGroupBox* toolbarButtons = new QGroupBox(""); //controls
    QHBoxLayout* toolbarButtonsLayout = new QHBoxLayout();
    toolbarButtonsLayout->addWidget(new QPushButton("delete"));
    toolbarButtonsLayout->addSpacing(200);
    toolbarButtonsLayout->addWidget(new QPushButton("move up"));
    toolbarButtonsLayout->addWidget(new QPushButton("move down"));
    toolbarButtons->setLayout(toolbarButtonsLayout);
    vbox->addWidget(toolbarButtons);
    vbox->addStretch(1);
    leftside->setLayout(vbox);

    // fix the borders on the group boxes
    this->setStyleSheet("QGroupBox { border: 1px solid gray; border-radius: 3px; padding: 5px; } "
			"QGroupBox::title { background-color: transparent; "
			"subcontrol-position: top left; /* position at the top left*/ "
			"padding:2 5px; } ");

    this->setLayout(layout);

    // wire up the buttons
    connect(savebutton, SIGNAL(released()), this, SLOT(handleSaveAction()));
    connect(loaddiff, SIGNAL(released()), this, SLOT(handleLoadAction()));
    connect(_jointSlider, SIGNAL(valueChanged(int)), this, SLOT(updateJoint(int)));
}

MainWindow::~MainWindow()
{

}

void
MainWindow::
handleLoadAction() {
 QString fileName = QFileDialog::getOpenFileName(this,
     tr("Open Action"), "", tr("Action XML Files (*.xml)"));
}

void
MainWindow::
handleSaveAction() {
 QString fileName = QFileDialog::getSaveFileName(this,
     tr("Save Action"), "", tr("Action XML Files (*.xml)"));
}

void
MainWindow::
handleDeleteWaypoint() {

}

void
MainWindow::
handleMoveUp() {

}

void
MainWindow::
handleMoveDown() {

}

void
MainWindow::
handleToggleExpandContract() {

}

void
MainWindow::
updateJoint(int value) {
    if (_selectedJointName != "") {
	std::cout << "joint " << _selectedJointName << " set to " <<  _jointSlider->value() / 100.0 << std::endl;
	_worldState.state_gfe.joint(_selectedJointName).set_position( _jointSlider->value() / 100.0 );
	_worldState.colorRobot.set(_worldState.state_gfe);
	_widget_opengl.update(); //_opengl_widget.update();
	//update();
    }
}

/*
 * change the functionality of the slider to actuate currently selected link
 */
void
MainWindow::
handleRobotLinkChange(QString waypointName) {
    // start by getting the name of the link currently selected
/*
    QComboBox* selected_combo = _all_robot_link_combos.find(waypointName.toStdString())->second;
    // find the selected text
    _selectedJointName = selected_combo->currentText().toStdString();  //itemData(selected_combo->currentIndex());
    _worldState.colorRobot.setSelectedJoint(_selectedJointName);
    _widget_opengl.update(); //_opengl_widget.update();
    _jointNameLabel->setText(QString::fromStdString(_selectedJointName));
*/
}

void
MainWindow::
setSelectedAction(QString waypointName){
/*
    TogglePanel* selected_panel = _all_panels.find(waypointName.toStdString())->second;
    std::map<std::string, TogglePanel*>::iterator iter;
    for (iter = _all_panels.begin(); iter != _all_panels.end(); iter++) {
        TogglePanel* other_panel = iter->second;
	other_panel->setSelected(false);
    }
    selected_panel->setSelected(true);
*/
}
<|endoftext|>


<commit_before>// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS.  All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.

#include <windows.h>
#include <windowsx.h>

#include <string>

#include "debugutil.hpp"
#include "consoleutil.hpp"
#include "eventutil.hpp"
#include "gtest/gtest.h"
#include "mfplayerutil.hpp"
#include "player.hpp"
#include "player_tests.hpp"
#include "threadutil.hpp"

// TODO(tomfinegan): destroy player between tests

namespace
{
    // TODO(tomfinegan): get rid of this global window handle... all it will
    //                   take to get rid of it is learning how to pass data to
    //                   tests.
    HWND g_hwnd_player = NULL;
}

CPlayer* get_player(HWND hwnd)
{
    CPlayer* ptr_player = NULL;
    LONG_PTR ptr_userdata = GetWindowLongPtr(hwnd, GWLP_USERDATA);
    if (ptr_userdata)
    {
        ptr_player = reinterpret_cast<CPlayer*>(ptr_userdata);
    }
    return ptr_player;
}

HRESULT destroy_player(HWND hwnd)
{
    if (!hwnd)
        return E_INVALIDARG;

    CPlayer* ptr_player = get_player(hwnd);

    HRESULT hr = E_FAIL;
    if (ptr_player)
    {
        ptr_player->Shutdown();
        ptr_player->Release();
        hr = S_OK;
        SetWindowLongPtr(hwnd, GWLP_USERDATA, NULL);
    }
    return hr;
}

void start_webmmf_test_thread(HWND hwnd_player)
{
    g_hwnd_player = hwnd_player;
    using WebmMfUtil::SimpleThread;
    SimpleThread* ptr_simple_thread = NULL;
    HRESULT hr = SimpleThread::Create(&ptr_simple_thread);

    if (SUCCEEDED(hr))
    {
        LPVOID ptr_player_hwnd = reinterpret_cast<LPVOID>(hwnd_player);
        ptr_simple_thread->Run(test_thread, ptr_player_hwnd);
    }
}

DWORD WINAPI test_thread(LPVOID ptr_thread_data)
{
    ptr_thread_data;
    int argc = 1;
    wchar_t* argv = L"mfplay_test_thread";

    // TODO(tomfinegan): open a console window for test output

    WebmMfUtil::ConsoleWindow console_window;
    HRESULT hr = console_window.Create();

    assert(SUCCEEDED(hr));

    testing::InitGoogleTest(&argc, &argv);
    RUN_ALL_TESTS();
    return 0;
}

PlayerController::PlayerController():
  hwnd_player_(NULL),
  waiting_for_state_(0)
{

}

PlayerController::~PlayerController()
{
}

HRESULT PlayerController::Create(HWND hwnd_player)
{
    if (!hwnd_player)
        return E_INVALIDARG;

    hwnd_player_ = hwnd_player;
    return S_OK;
}

HRESULT PlayerController::Play(std::wstring file_to_play)
{
    CPlayer* player = get_player(hwnd_player_);

    if (!player || file_to_play.length() == 0)
        return E_INVALIDARG;

    using WebmMfUtil::MfPlayerCallback;
    HRESULT hr;
    hr = MfPlayerCallback::CreateInstance(OnPlayerStateChange,
                                          reinterpret_cast<UINT_PTR>(this),
                                          &ptr_player_callback_);
    if (FAILED(hr) || ptr_player_callback_ == NULL)
        return E_OUTOFMEMORY;

    hr = player_state_change_waiter_.Create();
    if (FAILED(hr))
        return E_OUTOFMEMORY;

    player->SetStateCallback(ptr_player_callback_);

    waiting_for_state_ = OpenPending;

    const wchar_t* ptr_file_name = file_to_play.c_str();
    PlayerCommandMessage command_msg =
        {PLAYER_CMD_OPEN, reinterpret_cast<const void*>(ptr_file_name)};

    WPARAM command_msg_wparam =
        reinterpret_cast<WPARAM>(&command_msg);
    BOOL posted_msg = PostMessage(hwnd_player_, WM_APP_PLAYER_COMMAND,
                                  command_msg_wparam, 0);
    if (posted_msg)
    {
        waiting_for_state_ = Started;
        DBGLOG("Waiting for Started");
        hr = player_state_change_waiter_.Wait();
        DBGLOG("Started wait result = " << hr);
    }

    return hr;
}

void PlayerController::OnPlayerStateChange(UINT_PTR ptr_this, int state)
{
    ASSERT_NE(ptr_this, 0UL);
    PlayerController* ptr_pc = reinterpret_cast<PlayerController*>(ptr_this);

    if (state == ptr_pc->waiting_for_state_)
    {
        ptr_pc->player_state_change_waiter_.Set();
    }
}

TEST(WebmMfPlayTest, PlayFile)
{
    PlayerController player_controller;
    player_controller.Create(g_hwnd_player);
    std::wstring file = L"C:\\src\\media\\fg.webm";

    HRESULT hr_play = player_controller.Play(file);
    ASSERT_TRUE(SUCCEEDED(hr_play));
}<commit_msg>mfplay: remove unnecessary assignment<commit_after>// Copyright (c) 2010 The WebM project authors. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS.  All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.

#include <windows.h>
#include <windowsx.h>

#include <string>

#include "debugutil.hpp"
#include "consoleutil.hpp"
#include "eventutil.hpp"
#include "gtest/gtest.h"
#include "mfplayerutil.hpp"
#include "player.hpp"
#include "player_tests.hpp"
#include "threadutil.hpp"

// TODO(tomfinegan): destroy player between tests

namespace
{
    // TODO(tomfinegan): get rid of this global window handle... all it will
    //                   take to get rid of it is learning how to pass data to
    //                   tests.
    HWND g_hwnd_player = NULL;
}

CPlayer* get_player(HWND hwnd)
{
    CPlayer* ptr_player = NULL;
    LONG_PTR ptr_userdata = GetWindowLongPtr(hwnd, GWLP_USERDATA);
    if (ptr_userdata)
    {
        ptr_player = reinterpret_cast<CPlayer*>(ptr_userdata);
    }
    return ptr_player;
}

HRESULT destroy_player(HWND hwnd)
{
    if (!hwnd)
        return E_INVALIDARG;

    CPlayer* ptr_player = get_player(hwnd);

    HRESULT hr = E_FAIL;
    if (ptr_player)
    {
        ptr_player->Shutdown();
        ptr_player->Release();
        hr = S_OK;
        SetWindowLongPtr(hwnd, GWLP_USERDATA, NULL);
    }
    return hr;
}

void start_webmmf_test_thread(HWND hwnd_player)
{
    g_hwnd_player = hwnd_player;
    using WebmMfUtil::SimpleThread;
    SimpleThread* ptr_simple_thread = NULL;
    HRESULT hr = SimpleThread::Create(&ptr_simple_thread);

    if (SUCCEEDED(hr))
    {
        LPVOID ptr_player_hwnd = reinterpret_cast<LPVOID>(hwnd_player);
        ptr_simple_thread->Run(test_thread, ptr_player_hwnd);
    }
}

DWORD WINAPI test_thread(LPVOID ptr_thread_data)
{
    ptr_thread_data;
    int argc = 1;
    wchar_t* argv = L"mfplay_test_thread";

    // TODO(tomfinegan): open a console window for test output

    WebmMfUtil::ConsoleWindow console_window;
    HRESULT hr = console_window.Create();

    assert(SUCCEEDED(hr));

    testing::InitGoogleTest(&argc, &argv);
    RUN_ALL_TESTS();
    return 0;
}

PlayerController::PlayerController():
  hwnd_player_(NULL),
  waiting_for_state_(0)
{

}

PlayerController::~PlayerController()
{
}

HRESULT PlayerController::Create(HWND hwnd_player)
{
    if (!hwnd_player)
        return E_INVALIDARG;

    hwnd_player_ = hwnd_player;
    return S_OK;
}

HRESULT PlayerController::Play(std::wstring file_to_play)
{
    CPlayer* player = get_player(hwnd_player_);

    if (!player || file_to_play.length() == 0)
        return E_INVALIDARG;

    using WebmMfUtil::MfPlayerCallback;
    HRESULT hr;
    hr = MfPlayerCallback::CreateInstance(OnPlayerStateChange,
                                          reinterpret_cast<UINT_PTR>(this),
                                          &ptr_player_callback_);
    if (FAILED(hr) || ptr_player_callback_ == NULL)
        return E_OUTOFMEMORY;

    hr = player_state_change_waiter_.Create();
    if (FAILED(hr))
        return E_OUTOFMEMORY;

    player->SetStateCallback(ptr_player_callback_);

    const wchar_t* ptr_file_name = file_to_play.c_str();
    PlayerCommandMessage command_msg =
        {PLAYER_CMD_OPEN, reinterpret_cast<const void*>(ptr_file_name)};

    WPARAM command_msg_wparam =
        reinterpret_cast<WPARAM>(&command_msg);
    BOOL posted_msg = PostMessage(hwnd_player_, WM_APP_PLAYER_COMMAND,
                                  command_msg_wparam, 0);
    if (posted_msg)
    {
        waiting_for_state_ = Started;
        DBGLOG("Waiting for Started");
        hr = player_state_change_waiter_.Wait();
        DBGLOG("Started wait result = " << hr);
    }

    return hr;
}

void PlayerController::OnPlayerStateChange(UINT_PTR ptr_this, int state)
{
    ASSERT_NE(ptr_this, 0UL);
    PlayerController* ptr_pc = reinterpret_cast<PlayerController*>(ptr_this);

    if (state == ptr_pc->waiting_for_state_)
    {
        ptr_pc->player_state_change_waiter_.Set();
    }
}

TEST(WebmMfPlayTest, PlayFile)
{
    PlayerController player_controller;
    player_controller.Create(g_hwnd_player);
    std::wstring file = L"D:\\src\\media\\webm\\fg.webm";

    HRESULT hr_play = player_controller.Play(file);
    ASSERT_TRUE(SUCCEEDED(hr_play));
}<|endoftext|>


<commit_before>#pragma once

#include "interface.hpp"

#include <any>

using Object = std::map<InterfaceType, std::any>;
using ObjectInfo = std::tuple<sdbusplus::bus::bus*, std::string, Object>;
using RetryIO = std::tuple<size_t, std::chrono::milliseconds>;
using ObjectStateData = std::pair<std::string, ObjectInfo>;
<commit_msg>types: add missing headers<commit_after>#pragma once

#include "interface.hpp"

#include <any>
#include <chrono>
#include <map>
#include <string>
#include <tuple>
#include <utility>

using Object = std::map<InterfaceType, std::any>;
using ObjectInfo = std::tuple<sdbusplus::bus::bus*, std::string, Object>;
using RetryIO = std::tuple<size_t, std::chrono::milliseconds>;
using ObjectStateData = std::pair<std::string, ObjectInfo>;
<|endoftext|>


<commit_before>/* componentPlotter.C
 *
 * Copyright (C) 2009 Marcel Schumann
 *
 * This file is part of QuEasy -- A Toolbox for Automated QSAR Model
 * Construction and Validation.
 * QuEasy is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or (at
 * your option) any later version.
 *
 * QuEasy is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 */

#include <componentPlotter.h>

#include <qwt_plot_curve.h>
#include <qwt_plot_marker.h>
#include <qwt_plot_zoomer.h>
#include <qwt_scale_widget.h>
#include <qwt_color_map.h>

#include <qwt_legend.h>
#include <qwt_legend_item.h>

#include <QColor>

#include <BALL/QSAR/regressionModel.h>

using namespace BALL::QSAR;

namespace BALL
{
	namespace VIEW
	{

		ComponentPlotter::ComponentPlotter(ModelItem* model_item, bool plot_loadings)
			: Plotter(model_item)
		{
			zoomer_ = NULL;
			model_item_ = model_item;
			plot_loadings_ = plot_loadings;
			component_one_combobox_ = new QComboBox(this);
			component_two_combobox_ = new QComboBox(this);
			component_matrix_ = NULL;
			qwt_plot_->enableAxis(QwtPlot::yLeft);
			if(!plot_loadings_) qwt_plot_->enableAxis(QwtPlot::yRight,1);
			else qwt_plot_->enableAxis(QwtPlot::yRight,0);

			data_symbol.setSize(6,6);
			print_data_symbol.setSize(5,5);

			plot(1);
			zoomer_ = new QwtPlotZoomer(qwt_plot_->canvas(),this);

			buttonsLayout_->addWidget(component_one_combobox_);
			buttonsLayout_->addWidget(component_two_combobox_);
			connect(component_one_combobox_,SIGNAL(currentIndexChanged(int)),this,SLOT(selectedCompChanged()));
			connect(component_two_combobox_,SIGNAL(currentIndexChanged(int)),this,SLOT(selectedCompChanged()));

			if(plot_loadings_) setWindowTitle("Loadings Plotter");
			else setWindowTitle("Latent Variable Plotter");

			calculateComponents();
			if(component_matrix_==NULL || component_matrix_->cols()==0)
			{
				throw BALL::Exception::GeneralException(__FILE__,__LINE__,"ComponentPlotter error","No input data available, thus plot cannot be created!");
			}

			// loading-plot is identical for all response variables ...
			if(!plot_loadings_)
			{
				int no_y = model_item_->inputDataItem()->data()->getNoResponseVariables();
				if(no_y>1)
				{
					for(unsigned int i=0; i<no_y;i++)
					{
						String s = "Activity "+String(i);
						activity_combobox_->addItem(s.c_str(),i);
					}
					activity_combobox_->show();
				}
			}
		}

		void ComponentPlotter::selectedCompChanged()
		{
			delete zoomer_;
			zoomer_ = NULL;
			plot(1);
			zoomer_ = new QwtPlotZoomer(qwt_plot_->canvas(),this); // if not creating a new zoomer, zooming will not work correctly
		}

		void ComponentPlotter::calculateComponents()
		{
			RegressionModel* model = (RegressionModel*)model_item_->model();

			if(!model_item_->getRegistryEntry()->latent_variables)
			{
				std::cout << "Plotting of components can only be done for models that create principle components or partial least squares components!" << std::endl;
				return;
			}
			if(model_item_->inputDataItem()->data()==NULL)
			{
				std::cout << "No input data! Thus creation of PCR/PLS components for plotting is not possible!" << std::endl;
				return;
			}
			if(!plot_loadings_ && model_item_->inputDataItem()->data()->getNoResponseVariables()==0)
			{
				std::cout << "There should be response variable(s) for plotting of PLS/PCR components" << std::endl;
				return;
			}

			unsigned int no_components=0;

			LatentVariableModel* lv_model = dynamic_cast<LatentVariableModel*>(model_item_->model());

			if(!plot_loadings_)
			{
				component_matrix_ = lv_model->getLatentVariables();
				if(component_matrix_->cols()==0||component_matrix_->rows()==0)
				{
					model->setDataSource(model_item_->inputDataItem()->data());
					model->readTrainingData();
					model->train();
					component_matrix_ = lv_model->getLatentVariables();
				}

				no_components=component_matrix_->cols();
				if(no_components<2) return;

				unsigned int size = model_item_->model()->data->getNoSubstances();
				min_response_value_ = 1e10;
				max_response_value_ = -1e10;
				const QSARData* data = model_item_->inputDataItem()->data();
				for(unsigned int j=0; j<size; j++)
				{
					vector<double>* resp = data->getActivity(j);
					double response_value = (*resp)[selected_activity_];
					delete resp;
					if(response_value<min_response_value_) min_response_value_=response_value;
					if(response_value>max_response_value_) max_response_value_=response_value;
				}
			}
			else
			{
				component_matrix_ = lv_model->getLoadings();
				if(component_matrix_->cols()==0||component_matrix_->rows()==0)
				{
					model->setDataSource(model_item_->inputDataItem()->data());
					model->readTrainingData();
					model->train();
					component_matrix_ = lv_model->getLoadings();
				}
			}

			no_components=component_matrix_->cols();
			if(no_components<2) return;

			if(component_one_combobox_->count()==0)
			{
				for(unsigned int i=1;i<=no_components;i++)
				{
					String tmp;
					if(!plot_loadings_) tmp="component ";
					else tmp="loading ";
					tmp+=String(i);
					component_one_combobox_->addItem(tmp.c_str(),i);
					component_two_combobox_->addItem(tmp.c_str(),i);
				}
				component_one_combobox_->setCurrentIndex(0);
				component_two_combobox_->setCurrentIndex(1);
			}
		}

		// SLOT
		void ComponentPlotter::activityChange()
		{
			component_matrix_=NULL;  // make sure to recalculate min and max of the response variable
			Plotter::activityChange();
		}

		void ComponentPlotter::plot(bool zoom)
		{
			qwt_plot_->clear();

			if(component_matrix_==NULL||component_matrix_->cols()==0) calculateComponents();
			if(component_matrix_==NULL||component_matrix_->cols()<2) return; // only 1 component

			double min_y=1e10;
			double max_y=-1e10;
			double min_x=1e10;
			double max_x=-1e10;
			const vector<string>* feature_names;
			if(!plot_loadings_) feature_names = model_item_->model()->getSubstanceNames();
			else feature_names = model_item_->model()->getDescriptorNames();
			const unsigned int size = feature_names->size();

			unsigned int comp_one=component_one_combobox_->itemData(component_one_combobox_->currentIndex()).toInt();
			unsigned int comp_two=component_two_combobox_->itemData(component_two_combobox_->currentIndex()).toInt();

			QwtLinearColorMap color_map;
			color_map.setColorInterval(QColor(255,0,0),QColor(0,255,0));
			QwtDoubleInterval interval(min_response_value_,max_response_value_);

			const QSARData* data = model_item_->inputDataItem()->data();

			for(unsigned int j=1; j<=size; j++)
			{
				QwtPlotMarker* marker= new QwtPlotMarker;
				QwtSymbol symbol = data_symbol;

				if(!plot_loadings_)
				{
					vector<double>* resp = data->getActivity(j-1);
					double response_value = (*resp)[selected_activity_];
					delete resp;
					QBrush b(QColor(color_map.rgb(interval,response_value)),Qt::SolidPattern);
					symbol.setBrush(b);
				}

				double x_j = (*component_matrix_)(j,comp_one);
				double y_j = (*component_matrix_)(j,comp_two);
				if(y_j<min_y) min_y=y_j;
				if(y_j>max_y) max_y=y_j;
				if(x_j<min_x) min_x=x_j;
				if(x_j>max_x) max_x=x_j;
				marker->setSymbol(symbol);
				marker->setValue(x_j,y_j);
				marker->attach(qwt_plot_); // attached object will be automatically deleted by QwtPlot

				if(show_data_labels)
				{
					QString s =(*feature_names)[j-1].c_str();
					QwtText label(s);
					label.setFont(data_label_font);
					marker->setLabel(label);
					marker->setLabelAlignment(data_label_alignment);
				}
			}

			QString s1 = component_one_combobox_->itemText(component_one_combobox_->currentIndex());
			QString s2 = component_two_combobox_->itemText(component_two_combobox_->currentIndex());
			LatentVariableModel* lv_model = dynamic_cast<LatentVariableModel*>(model_item_->model());
			const Eigen::MatrixXd* weights = lv_model->getWeights();

			if(!plot_loadings_)
			{
				s1 += "  c="; s1+=String((*weights)(comp_one,1)).c_str();
				s2 += "  c="; s2+=String((*weights)(comp_two,1)).c_str();
			}

			qwt_plot_->setAxisTitle(QwtPlot::yLeft,s2);
			qwt_plot_->setAxisTitle(QwtPlot::xBottom,s1);

			double x_border=(max_x-min_x)*0.05;
			double y_border=(max_y-min_y)*0.05;
			min_x-=x_border; min_y-=y_border;
			max_x+=x_border; max_y+=y_border;

			QwtPlotCurve* zero_line = new QwtPlotCurve;
			QwtPlotCurve* zero_line2 = new QwtPlotCurve;
			double x[2]; x[0]=min_x; x[1]=max_x;
			double y[2]; y[0]=0; y[1]=0;
			zero_line->setData(x,y,2);
			x[0]=0; x[1]=0;
			y[0]=min_y; y[1]=max_y;
			zero_line2->setData(x,y,2);
			QColor c(135,135,135); // grey
			QPen pen(c);
			zero_line->setPen(pen);
			zero_line->attach(qwt_plot_);
			zero_line2->setPen(pen);
			zero_line2->attach(qwt_plot_);

			if(zoom)
			{
				qwt_plot_->setAxisScale(QwtPlot::yLeft,min_y,max_y);
				qwt_plot_->setAxisScale(QwtPlot::xBottom,min_x,max_x);
			}

			if(!plot_loadings_)
			{
				QwtScaleWidget* rightAxis = qwt_plot_->axisWidget(QwtPlot::yRight);
				rightAxis->setTitle("response value");
				rightAxis->setColorBarEnabled(true);
				rightAxis->setColorMap(interval,color_map);
				qwt_plot_->setAxisScale(QwtPlot::yRight,min_response_value_,max_response_value_);
			}
		}
	}
}<commit_msg>Clarified licence<commit_after>#include <componentPlotter.h>

#include <qwt_plot_curve.h>
#include <qwt_plot_marker.h>
#include <qwt_plot_zoomer.h>
#include <qwt_scale_widget.h>
#include <qwt_color_map.h>

#include <qwt_legend.h>
#include <qwt_legend_item.h>

#include <QColor>

#include <BALL/QSAR/regressionModel.h>

using namespace BALL::QSAR;

namespace BALL
{
	namespace VIEW
	{

		ComponentPlotter::ComponentPlotter(ModelItem* model_item, bool plot_loadings)
			: Plotter(model_item)
		{
			zoomer_ = NULL;
			model_item_ = model_item;
			plot_loadings_ = plot_loadings;
			component_one_combobox_ = new QComboBox(this);
			component_two_combobox_ = new QComboBox(this);
			component_matrix_ = NULL;
			qwt_plot_->enableAxis(QwtPlot::yLeft);
			if(!plot_loadings_) qwt_plot_->enableAxis(QwtPlot::yRight,1);
			else qwt_plot_->enableAxis(QwtPlot::yRight,0);

			data_symbol.setSize(6,6);
			print_data_symbol.setSize(5,5);

			plot(1);
			zoomer_ = new QwtPlotZoomer(qwt_plot_->canvas(),this);

			buttonsLayout_->addWidget(component_one_combobox_);
			buttonsLayout_->addWidget(component_two_combobox_);
			connect(component_one_combobox_,SIGNAL(currentIndexChanged(int)),this,SLOT(selectedCompChanged()));
			connect(component_two_combobox_,SIGNAL(currentIndexChanged(int)),this,SLOT(selectedCompChanged()));

			if(plot_loadings_) setWindowTitle("Loadings Plotter");
			else setWindowTitle("Latent Variable Plotter");

			calculateComponents();
			if(component_matrix_==NULL || component_matrix_->cols()==0)
			{
				throw BALL::Exception::GeneralException(__FILE__,__LINE__,"ComponentPlotter error","No input data available, thus plot cannot be created!");
			}

			// loading-plot is identical for all response variables ...
			if(!plot_loadings_)
			{
				int no_y = model_item_->inputDataItem()->data()->getNoResponseVariables();
				if(no_y>1)
				{
					for(unsigned int i=0; i<no_y;i++)
					{
						String s = "Activity "+String(i);
						activity_combobox_->addItem(s.c_str(),i);
					}
					activity_combobox_->show();
				}
			}
		}

		void ComponentPlotter::selectedCompChanged()
		{
			delete zoomer_;
			zoomer_ = NULL;
			plot(1);
			zoomer_ = new QwtPlotZoomer(qwt_plot_->canvas(),this); // if not creating a new zoomer, zooming will not work correctly
		}

		void ComponentPlotter::calculateComponents()
		{
			RegressionModel* model = (RegressionModel*)model_item_->model();

			if(!model_item_->getRegistryEntry()->latent_variables)
			{
				std::cout << "Plotting of components can only be done for models that create principle components or partial least squares components!" << std::endl;
				return;
			}
			if(model_item_->inputDataItem()->data()==NULL)
			{
				std::cout << "No input data! Thus creation of PCR/PLS components for plotting is not possible!" << std::endl;
				return;
			}
			if(!plot_loadings_ && model_item_->inputDataItem()->data()->getNoResponseVariables()==0)
			{
				std::cout << "There should be response variable(s) for plotting of PLS/PCR components" << std::endl;
				return;
			}

			unsigned int no_components=0;

			LatentVariableModel* lv_model = dynamic_cast<LatentVariableModel*>(model_item_->model());

			if(!plot_loadings_)
			{
				component_matrix_ = lv_model->getLatentVariables();
				if(component_matrix_->cols()==0||component_matrix_->rows()==0)
				{
					model->setDataSource(model_item_->inputDataItem()->data());
					model->readTrainingData();
					model->train();
					component_matrix_ = lv_model->getLatentVariables();
				}

				no_components=component_matrix_->cols();
				if(no_components<2) return;

				unsigned int size = model_item_->model()->data->getNoSubstances();
				min_response_value_ = 1e10;
				max_response_value_ = -1e10;
				const QSARData* data = model_item_->inputDataItem()->data();
				for(unsigned int j=0; j<size; j++)
				{
					vector<double>* resp = data->getActivity(j);
					double response_value = (*resp)[selected_activity_];
					delete resp;
					if(response_value<min_response_value_) min_response_value_=response_value;
					if(response_value>max_response_value_) max_response_value_=response_value;
				}
			}
			else
			{
				component_matrix_ = lv_model->getLoadings();
				if(component_matrix_->cols()==0||component_matrix_->rows()==0)
				{
					model->setDataSource(model_item_->inputDataItem()->data());
					model->readTrainingData();
					model->train();
					component_matrix_ = lv_model->getLoadings();
				}
			}

			no_components=component_matrix_->cols();
			if(no_components<2) return;

			if(component_one_combobox_->count()==0)
			{
				for(unsigned int i=1;i<=no_components;i++)
				{
					String tmp;
					if(!plot_loadings_) tmp="component ";
					else tmp="loading ";
					tmp+=String(i);
					component_one_combobox_->addItem(tmp.c_str(),i);
					component_two_combobox_->addItem(tmp.c_str(),i);
				}
				component_one_combobox_->setCurrentIndex(0);
				component_two_combobox_->setCurrentIndex(1);
			}
		}

		// SLOT
		void ComponentPlotter::activityChange()
		{
			component_matrix_=NULL;  // make sure to recalculate min and max of the response variable
			Plotter::activityChange();
		}

		void ComponentPlotter::plot(bool zoom)
		{
			qwt_plot_->clear();

			if(component_matrix_==NULL||component_matrix_->cols()==0) calculateComponents();
			if(component_matrix_==NULL||component_matrix_->cols()<2) return; // only 1 component

			double min_y=1e10;
			double max_y=-1e10;
			double min_x=1e10;
			double max_x=-1e10;
			const vector<string>* feature_names;
			if(!plot_loadings_) feature_names = model_item_->model()->getSubstanceNames();
			else feature_names = model_item_->model()->getDescriptorNames();
			const unsigned int size = feature_names->size();

			unsigned int comp_one=component_one_combobox_->itemData(component_one_combobox_->currentIndex()).toInt();
			unsigned int comp_two=component_two_combobox_->itemData(component_two_combobox_->currentIndex()).toInt();

			QwtLinearColorMap color_map;
			color_map.setColorInterval(QColor(255,0,0),QColor(0,255,0));
			QwtDoubleInterval interval(min_response_value_,max_response_value_);

			const QSARData* data = model_item_->inputDataItem()->data();

			for(unsigned int j=1; j<=size; j++)
			{
				QwtPlotMarker* marker= new QwtPlotMarker;
				QwtSymbol symbol = data_symbol;

				if(!plot_loadings_)
				{
					vector<double>* resp = data->getActivity(j-1);
					double response_value = (*resp)[selected_activity_];
					delete resp;
					QBrush b(QColor(color_map.rgb(interval,response_value)),Qt::SolidPattern);
					symbol.setBrush(b);
				}

				double x_j = (*component_matrix_)(j,comp_one);
				double y_j = (*component_matrix_)(j,comp_two);
				if(y_j<min_y) min_y=y_j;
				if(y_j>max_y) max_y=y_j;
				if(x_j<min_x) min_x=x_j;
				if(x_j>max_x) max_x=x_j;
				marker->setSymbol(symbol);
				marker->setValue(x_j,y_j);
				marker->attach(qwt_plot_); // attached object will be automatically deleted by QwtPlot

				if(show_data_labels)
				{
					QString s =(*feature_names)[j-1].c_str();
					QwtText label(s);
					label.setFont(data_label_font);
					marker->setLabel(label);
					marker->setLabelAlignment(data_label_alignment);
				}
			}

			QString s1 = component_one_combobox_->itemText(component_one_combobox_->currentIndex());
			QString s2 = component_two_combobox_->itemText(component_two_combobox_->currentIndex());
			LatentVariableModel* lv_model = dynamic_cast<LatentVariableModel*>(model_item_->model());
			const Eigen::MatrixXd* weights = lv_model->getWeights();

			if(!plot_loadings_)
			{
				s1 += "  c="; s1+=String((*weights)(comp_one,1)).c_str();
				s2 += "  c="; s2+=String((*weights)(comp_two,1)).c_str();
			}

			qwt_plot_->setAxisTitle(QwtPlot::yLeft,s2);
			qwt_plot_->setAxisTitle(QwtPlot::xBottom,s1);

			double x_border=(max_x-min_x)*0.05;
			double y_border=(max_y-min_y)*0.05;
			min_x-=x_border; min_y-=y_border;
			max_x+=x_border; max_y+=y_border;

			QwtPlotCurve* zero_line = new QwtPlotCurve;
			QwtPlotCurve* zero_line2 = new QwtPlotCurve;
			double x[2]; x[0]=min_x; x[1]=max_x;
			double y[2]; y[0]=0; y[1]=0;
			zero_line->setData(x,y,2);
			x[0]=0; x[1]=0;
			y[0]=min_y; y[1]=max_y;
			zero_line2->setData(x,y,2);
			QColor c(135,135,135); // grey
			QPen pen(c);
			zero_line->setPen(pen);
			zero_line->attach(qwt_plot_);
			zero_line2->setPen(pen);
			zero_line2->attach(qwt_plot_);

			if(zoom)
			{
				qwt_plot_->setAxisScale(QwtPlot::yLeft,min_y,max_y);
				qwt_plot_->setAxisScale(QwtPlot::xBottom,min_x,max_x);
			}

			if(!plot_loadings_)
			{
				QwtScaleWidget* rightAxis = qwt_plot_->axisWidget(QwtPlot::yRight);
				rightAxis->setTitle("response value");
				rightAxis->setColorBarEnabled(true);
				rightAxis->setColorMap(interval,color_map);
				qwt_plot_->setAxisScale(QwtPlot::yRight,min_response_value_,max_response_value_);
			}
		}
	}
}
<|endoftext|>


<commit_before>#include <iostream>
class Solution {
public:
    string longestPalindrome(string s) {

    }

    string reverseStr(string s){
      string res(s.size());
      for(int i = 0; i < s.size(); i++){
        res
      }
    }
};
<commit_msg>same algorithm, but with c++, accept.....orz<commit_after>#include <iostream>
#include <string>
#include <vector>

using namespace std;

class Solution {
public:
    string longestPalindrome(string s) {
        string r(s);
        reverseStr(s, r);
        int epos = 0;
        int lcs = 0;
        int len = s.size();
        std::vector<int> t(len);

        for(int i = 0; i < len; i++){
          if(s[i] == r[0]) t[i] = 1;
          else t[i] = 0;
        }

        for(int j = 1; j < len; j++){
          //show(t);
          for(int i = len - 1; i > 0; i--){
            if(s[i] == r[j]){
              //cout << s[i] << " " << i << " " << j << endl;
              t[i] = t[i - 1] + 1;
              //start pos = reverse_str's end pos
              if(t[i] > lcs && i + 1 - t[i] == len - j - 1){
                lcs = t[i];
                epos = i;
              }
            }
            else t[i] = 0;
          }
          if(s[0] == r[j]) t[0] = 1;
          else t[0] = 0;
        }
        //show(t);
        /*cout << s << endl;
        cout << r << endl;
        cout << "lcs:" << lcs << endl;
        cout << "epos:" << epos << endl;*/
        return lcs == 0 ? string(s, 0, 1) : string(s, epos - lcs + 1, lcs);
    }

    void show(vector<int>& t){
      for(auto i : t)
        cout << " " << i ;
      cout << " " << endl;
    }

    void reverseStr(const string& s, string& r){
      int len = s.size();
      for(int i = 0; i < len; i++){
        r[len - i - 1] = s[i];
      }
    }
};

int main(){
  Solution a;
  cout << a.longestPalindrome("gphyvqruxjmwhonjjrgumxjhfyupajxbjgthzdvrdqmdouuukeaxhjumkmmhdglqrrohydrmbvtuwstgkobyzjjtdtjroqpyusfsbjlusekghtfbdctvgmqzeybnwzlhdnhwzptgkzmujfldoiejmvxnorvbiubfflygrkedyirienybosqzrkbpcfidvkkafftgzwrcitqizelhfsruwmtrgaocjcyxdkovtdennrkmxwpdsxpxuarhgusizmwakrmhdwcgvfljhzcskclgrvvbrkesojyhofwqiwhiupujmkcvlywjtmbncurxxmpdskupyvvweuhbsnanzfioirecfxvmgcpwrpmbhmkdtckhvbxnsbcifhqwjjczfokovpqyjmbywtpaqcfjowxnmtirdsfeujyogbzjnjcmqyzciwjqxxgrxblvqbutqittroqadqlsdzihngpfpjovbkpeveidjpfjktavvwurqrgqdomiibfgqxwybcyovysydxyyymmiuwovnevzsjisdwgkcbsookbarezbhnwyqthcvzyodbcwjptvigcphawzxouixhbpezzirbhvomqhxkfdbokblqmrhhioyqubpyqhjrnwhjxsrodtblqxkhezubprqftrqcyrzwywqrgockioqdmzuqjkpmsyohtlcnesbgzqhkalwixfcgyeqdzhnnlzawrdgskurcxfbekbspupbduxqxjeczpmdvssikbivjhinaopbabrmvscthvoqqbkgekcgyrelxkwoawpbrcbszelnxlyikbulgmlwyffurimlfxurjsbzgddxbgqpcdsuutfiivjbyqzhprdqhahpgenjkbiukurvdwapuewrbehczrtswubthodv") << endl;

  cout << a.longestPalindrome("banana") << endl;
  return 0;
}
<|endoftext|>


<commit_before>#include "LoadSaveState.h"

#include "GameController.h"
#include "VFileDevice.h"

#include <QKeyEvent>

extern "C" {
#include "gba-serialize.h"
#include "gba-video.h"
}

using namespace QGBA;

LoadSaveState::LoadSaveState(GameController* controller, QWidget* parent)
	: QWidget(parent)
	, m_controller(controller)
	, m_currentFocus(0)
{
	m_ui.setupUi(this);

	QImage currentImage(reinterpret_cast<const uchar*>(controller->drawContext()), VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, 1024, QImage::Format_RGB32);
	m_currentImage.convertFromImage(currentImage.rgbSwapped());

	m_slots[0] = m_ui.state1;
	m_slots[1] = m_ui.state2;
	m_slots[2] = m_ui.state3;
	m_slots[3] = m_ui.state4;
	m_slots[4] = m_ui.state5;
	m_slots[5] = m_ui.state6;
	m_slots[6] = m_ui.state7;
	m_slots[7] = m_ui.state8;
	m_slots[8] = m_ui.state9;

	int i;
	for (i = 0; i < NUM_SLOTS; ++i) {
		loadState(i + 1);
		m_slots[i]->installEventFilter(this);
		connect(m_slots[i], &QAbstractButton::clicked, this, [this, i]() { triggerState(i + 1); });
	}
}

void LoadSaveState::setMode(LoadSave mode) {
	m_mode = mode;
	QString text = mode == LoadSave::LOAD ? tr("Load State") : tr("SaveState");
	setWindowTitle(text);
	m_ui.lsLabel->setText(text);
}

bool LoadSaveState::eventFilter(QObject*, QEvent* event) {
	if (event->type() == QEvent::KeyPress) {
		int column = m_currentFocus % 3;
		int row = m_currentFocus - column;
		switch (static_cast<QKeyEvent*>(event)->key()) {
		case Qt::Key_Up:
			row += 6;
			break;
		case Qt::Key_Down:
			row += 3;
			break;
		case Qt::Key_Left:
			column += 2;
			break;
		case Qt::Key_Right:
			column += 1;
			break;
		case Qt::Key_Escape:
			close();
			break;
		default:
			return false;
		}
		column %= 3;
		row %= 9;
		m_currentFocus = column + row;
		m_slots[m_currentFocus]->setFocus();
		return true;
	}
	return false;
}

void LoadSaveState::loadState(int slot) {
	GBAThread* thread = m_controller->thread();
	VFile* vf = GBAGetState(thread->gba, thread->stateDir, slot, false);
	if (!vf) {
		m_slots[slot - 1]->setText(tr("Empty"));
		return;
	}
	VFileDevice vdev(vf);
	QImage stateImage;
	stateImage.load(&vdev, "PNG");
	if (!stateImage.isNull()) {
		QPixmap statePixmap;
		statePixmap.convertFromImage(stateImage);
		m_slots[slot - 1]->setIcon(statePixmap);
		m_slots[slot - 1]->setText(QString());
	} else {
		m_slots[slot - 1]->setText(tr("Slot %1").arg(slot));
	}
}

void LoadSaveState::triggerState(int slot) {
	if (m_mode == LoadSave::SAVE) {
		m_controller->saveState(slot);
	} else {
		m_controller->loadState(slot);
	}
	close();
}

void LoadSaveState::closeEvent(QCloseEvent* event) {
	emit closed();
	QWidget::closeEvent(event);
}
<commit_msg>Key overrides for selecting states<commit_after>#include "LoadSaveState.h"

#include "GameController.h"
#include "VFileDevice.h"

#include <QKeyEvent>

extern "C" {
#include "gba-serialize.h"
#include "gba-video.h"
}

using namespace QGBA;

LoadSaveState::LoadSaveState(GameController* controller, QWidget* parent)
	: QWidget(parent)
	, m_controller(controller)
	, m_currentFocus(0)
{
	m_ui.setupUi(this);

	QImage currentImage(reinterpret_cast<const uchar*>(controller->drawContext()), VIDEO_HORIZONTAL_PIXELS, VIDEO_VERTICAL_PIXELS, 1024, QImage::Format_RGB32);
	m_currentImage.convertFromImage(currentImage.rgbSwapped());

	m_slots[0] = m_ui.state1;
	m_slots[1] = m_ui.state2;
	m_slots[2] = m_ui.state3;
	m_slots[3] = m_ui.state4;
	m_slots[4] = m_ui.state5;
	m_slots[5] = m_ui.state6;
	m_slots[6] = m_ui.state7;
	m_slots[7] = m_ui.state8;
	m_slots[8] = m_ui.state9;

	int i;
	for (i = 0; i < NUM_SLOTS; ++i) {
		loadState(i + 1);
		m_slots[i]->installEventFilter(this);
		connect(m_slots[i], &QAbstractButton::clicked, this, [this, i]() { triggerState(i + 1); });
	}
}

void LoadSaveState::setMode(LoadSave mode) {
	m_mode = mode;
	QString text = mode == LoadSave::LOAD ? tr("Load State") : tr("SaveState");
	setWindowTitle(text);
	m_ui.lsLabel->setText(text);
}

bool LoadSaveState::eventFilter(QObject*, QEvent* event) {
	if (event->type() == QEvent::KeyPress) {
		int column = m_currentFocus % 3;
		int row = m_currentFocus - column;
		switch (static_cast<QKeyEvent*>(event)->key()) {
		case Qt::Key_Up:
			row += 6;
			break;
		case Qt::Key_Down:
			row += 3;
			break;
		case Qt::Key_Left:
			column += 2;
			break;
		case Qt::Key_Right:
			column += 1;
			break;
		case Qt::Key_1:
		case Qt::Key_2:
		case Qt::Key_3:
		case Qt::Key_4:
		case Qt::Key_5:
		case Qt::Key_6:
		case Qt::Key_7:
		case Qt::Key_8:
		case Qt::Key_9:
			triggerState(static_cast<QKeyEvent*>(event)->key() - Qt::Key_1 + 1);
			break;
		case Qt::Key_Escape:
			close();
			break;
		default:
			return false;
		}
		column %= 3;
		row %= 9;
		m_currentFocus = column + row;
		m_slots[m_currentFocus]->setFocus();
		return true;
	}
	return false;
}

void LoadSaveState::loadState(int slot) {
	GBAThread* thread = m_controller->thread();
	VFile* vf = GBAGetState(thread->gba, thread->stateDir, slot, false);
	if (!vf) {
		m_slots[slot - 1]->setText(tr("Empty"));
		return;
	}
	VFileDevice vdev(vf);
	QImage stateImage;
	stateImage.load(&vdev, "PNG");
	if (!stateImage.isNull()) {
		QPixmap statePixmap;
		statePixmap.convertFromImage(stateImage);
		m_slots[slot - 1]->setIcon(statePixmap);
		m_slots[slot - 1]->setText(QString());
	} else {
		m_slots[slot - 1]->setText(tr("Slot %1").arg(slot));
	}
}

void LoadSaveState::triggerState(int slot) {
	if (m_mode == LoadSave::SAVE) {
		m_controller->saveState(slot);
	} else {
		m_controller->loadState(slot);
	}
	close();
}

void LoadSaveState::closeEvent(QCloseEvent* event) {
	emit closed();
	QWidget::closeEvent(event);
}
<|endoftext|>