<commit_before>/*************************************************************************
 *
 *  $RCSfile: ENoException.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2003-09-04 08:26:47 $
 *
 *  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 _CONNECTIVITY_FLAT_TABLE_HXX_
#include "flat/ETable.hxx"
#endif
#ifndef _CONNECTIVITY_FLAT_ECONNECTION_HXX_
#include "flat/EConnection.hxx"
#endif

using namespace connectivity;
using namespace connectivity::flat;

//------------------------------------------------------------------
xub_StrLen OFlatString::GetTokenCount( sal_Unicode cTok, sal_Unicode cStrDel ) const
{
    if ( !Len() )
        return 0;

    xub_StrLen nTokCount = 1;
    BOOL bStart = TRUE;     // Stehen wir auf dem ersten Zeichen im Token?
    BOOL bInString = FALSE; // Befinden wir uns INNERHALB eines (cStrDel delimited) String?

    // Suche bis Stringende nach dem ersten nicht uebereinstimmenden Zeichen
    for( xub_StrLen i = 0; i < Len(); i++ )
    {
        if (bStart)
        {
            bStart = FALSE;
            // Erstes Zeichen ein String-Delimiter?
            if ((*this).GetChar(i) == cStrDel)
            {
                bInString = TRUE;   // dann sind wir jetzt INNERHALB des Strings!
                continue;           // dieses Zeichen ueberlesen!
            }
        }

        if (bInString) {
            // Wenn jetzt das String-Delimiter-Zeichen auftritt ...
            if ( (*this).GetChar(i) == cStrDel )
            {
                if ((i+1 < Len()) && ((*this).GetChar(i+1) == cStrDel))
                {
                    // Verdoppeltes String-Delimiter-Zeichen:
                    i++;    // kein String-Ende, naechstes Zeichen ueberlesen.
                }
                else
                {
                    // String-Ende
                    bInString = FALSE;
                }
            }
        } else {
            // Stimmt das Tokenzeichen ueberein, dann erhoehe TokCount
            if ( (*this).GetChar(i) == cTok )
            {
                nTokCount++;
                bStart = TRUE;
            }
        }
    }

    return nTokCount;
}

//------------------------------------------------------------------
void OFlatString::GetTokenSpecial( String& _rStr,xub_StrLen& nStartPos, sal_Unicode cTok, sal_Unicode cStrDel ) const
{
    _rStr.Erase();
    xub_StrLen nLen = Len();
    if ( nLen )
    {
        BOOL bInString = (nStartPos < nLen) && ((*this).GetChar(nStartPos) == cStrDel); // Befinden wir uns INNERHALB eines (cStrDel delimited) String?

        // Erstes Zeichen ein String-Delimiter?
        if (bInString )
            ++nStartPos;            // dieses Zeichen ueberlesen!
        // Suche bis Stringende nach dem ersten nicht uebereinstimmenden Zeichen
        xub_StrLen i = nStartPos;
        for( ; i < nLen; ++i )
        {
            if (bInString)
            {
                // Wenn jetzt das String-Delimiter-Zeichen auftritt ...
                if ( (*this).GetChar(i) == cStrDel )
                {
                    if ((i+1 < nLen) && ((*this).GetChar(i+1) == cStrDel))
                    {
                        // Verdoppeltes String-Delimiter-Zeichen:
                        ++i;    // kein String-Ende, naechstes Zeichen ueberlesen.

                        _rStr += (*this).GetChar(i);    // Zeichen gehoert zum Resultat-String
                    }
                    else
                    {
                        // String-Ende
                        bInString = FALSE;
                    }
                }
                else
                {
                    _rStr += (*this).GetChar(i);    // Zeichen gehoert zum Resultat-String
                }

            }
            else
            {
                // Stimmt das Tokenzeichen ueberein, dann erhoehe nTok
                if ( (*this).GetChar(i) == cTok )
                {
                    // Vorzeitiger Abbruch der Schleife moeglich, denn
                    // wir haben, was wir wollten.
                    nStartPos = i+1;
                    break;
                }
                else
                {
                    _rStr += (*this).GetChar(i);    // Zeichen gehoert zum Resultat-String
                }
            }
        }
        if ( i == nLen && nStartPos < i )
            nStartPos = nLen;
    }
}
// -----------------------------------------------------------------------------
sal_Bool OFlatTable::checkHeaderLine()
{
    if (m_nFilePos == 0 && ((OFlatConnection*)m_pConnection)->isHeaderLine())
    {
        BOOL bRead2;
        do
        {
            bRead2 = m_pFileStream->ReadByteStringLine(m_aCurrentLine,m_pConnection->getTextEncoding());
        }
        while(bRead2 && !m_aCurrentLine.Len());

        m_nFilePos = m_pFileStream->Tell();
        if (m_pFileStream->IsEof())
            return sal_False;
    }
    return sal_True;
}
//------------------------------------------------------------------
sal_Bool OFlatTable::seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32& nCurPos)
{
    if ( !m_pFileStream )
        return sal_False;
    OFlatConnection* pConnection = (OFlatConnection*)m_pConnection;
    // ----------------------------------------------------------
    // Positionierung vorbereiten:

    sal_uInt32 nTempPos = m_nFilePos;
    m_nFilePos = nCurPos;

    switch(eCursorPosition)
    {
        case IResultSetHelper::FIRST:
            m_nFilePos = 0;
            m_nRowPos = 1;
            // run through
        case IResultSetHelper::NEXT:
            if(eCursorPosition != IResultSetHelper::FIRST)
                ++m_nRowPos;
            m_pFileStream->Seek(m_nFilePos);
            if (m_pFileStream->IsEof() || !checkHeaderLine())
            {
                m_nMaxRowCount = m_nRowPos;
                return sal_False;
            }

            m_aRowToFilePos.insert(::std::map<sal_Int32,sal_Int32>::value_type(m_nRowPos,m_nFilePos));

            m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
            if (m_pFileStream->IsEof())
            {
                m_nMaxRowCount = m_nRowPos;
                return sal_False;
            }
            nCurPos = m_pFileStream->Tell();
            break;
        case IResultSetHelper::PRIOR:
            --m_nRowPos;
            if(m_nRowPos > 0)
            {
                m_nFilePos = m_aRowToFilePos.find(m_nRowPos)->second;
                m_pFileStream->Seek(m_nFilePos);
                if (m_pFileStream->IsEof() || !checkHeaderLine())
                    return sal_False;
                m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
                if (m_pFileStream->IsEof())
                    return sal_False;
                nCurPos = m_pFileStream->Tell();
            }
            else
                m_nRowPos = 0;

            break;

            break;
        case IResultSetHelper::LAST:
            if(m_nMaxRowCount)
            {
                m_nFilePos = m_aRowToFilePos.rbegin()->second;
                m_nRowPos  = m_aRowToFilePos.rbegin()->first;
                m_pFileStream->Seek(m_nFilePos);
                if (m_pFileStream->IsEof() || !checkHeaderLine())
                    return sal_False;
                m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
                if (m_pFileStream->IsEof())
                    return sal_False;
                nCurPos = m_pFileStream->Tell();
            }
            else
            {
                while(seekRow(IResultSetHelper::NEXT,1,nCurPos)) ; // run through after last row
                // now I know all
                seekRow(IResultSetHelper::PRIOR,1,nCurPos);
            }
            break;
        case IResultSetHelper::RELATIVE:
            if(nOffset > 0)
            {
                for(sal_Int32 i = 0;i<nOffset;++i)
                    seekRow(IResultSetHelper::NEXT,1,nCurPos);
            }
            else if(nOffset < 0)
            {
                for(sal_Int32 i = nOffset;i;++i)
                    seekRow(IResultSetHelper::PRIOR,1,nCurPos);
            }
            break;
        case IResultSetHelper::ABSOLUTE:
            {
                if(nOffset < 0)
                    nOffset = m_nRowPos + nOffset;
                ::std::map<sal_Int32,sal_Int32>::const_iterator aIter = m_aRowToFilePos.find(nOffset);
                if(aIter != m_aRowToFilePos.end())
                {
                    m_nFilePos = aIter->second;
                    m_pFileStream->Seek(m_nFilePos);
                    if (m_pFileStream->IsEof() || !checkHeaderLine())
                        return sal_False;
                    m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
                    if (m_pFileStream->IsEof())
                        return sal_False;
                    nCurPos = m_pFileStream->Tell();
                }
                else if(m_nMaxRowCount && nOffset > m_nMaxRowCount) // offset is outside the table
                {
                    m_nRowPos = m_nMaxRowCount;
                    return sal_False;
                }
                else
                {
                    aIter = m_aRowToFilePos.upper_bound(nOffset);
                    if(aIter == m_aRowToFilePos.end())
                    {
                        m_nRowPos   = m_aRowToFilePos.rbegin()->first;
                        nCurPos = m_nFilePos = m_aRowToFilePos.rbegin()->second;
                        while(m_nRowPos != nOffset)
                            seekRow(IResultSetHelper::NEXT,1,nCurPos);
                    }
                    else
                    {
                        --aIter;
                        m_nRowPos   = aIter->first;
                        m_nFilePos  = aIter->second;
                        m_pFileStream->Seek(m_nFilePos);
                        if (m_pFileStream->IsEof() || !checkHeaderLine())
                            return sal_False;
                        m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
                        if (m_pFileStream->IsEof())
                            return sal_False;
                        nCurPos = m_pFileStream->Tell();
                    }
                }
            }

            break;
        case IResultSetHelper::BOOKMARK:
            m_pFileStream->Seek(nOffset);
            if (m_pFileStream->IsEof())
                return sal_False;

            m_nFilePos = m_pFileStream->Tell(); // Byte-Position in der Datei merken (am ZeilenANFANG)
            m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
            if (m_pFileStream->IsEof())
                return sal_False;
            nCurPos  = m_pFileStream->Tell();
            break;
    }

    return sal_True;
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS ooo19126 (1.6.198); FILE MERGED 2005/09/05 17:23:54 rt 1.6.198.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: ENoException.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:00:35 $
 *
 *  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 _CONNECTIVITY_FLAT_TABLE_HXX_
#include "flat/ETable.hxx"
#endif
#ifndef _CONNECTIVITY_FLAT_ECONNECTION_HXX_
#include "flat/EConnection.hxx"
#endif

using namespace connectivity;
using namespace connectivity::flat;

//------------------------------------------------------------------
xub_StrLen OFlatString::GetTokenCount( sal_Unicode cTok, sal_Unicode cStrDel ) const
{
    if ( !Len() )
        return 0;

    xub_StrLen nTokCount = 1;
    BOOL bStart = TRUE;     // Stehen wir auf dem ersten Zeichen im Token?
    BOOL bInString = FALSE; // Befinden wir uns INNERHALB eines (cStrDel delimited) String?

    // Suche bis Stringende nach dem ersten nicht uebereinstimmenden Zeichen
    for( xub_StrLen i = 0; i < Len(); i++ )
    {
        if (bStart)
        {
            bStart = FALSE;
            // Erstes Zeichen ein String-Delimiter?
            if ((*this).GetChar(i) == cStrDel)
            {
                bInString = TRUE;   // dann sind wir jetzt INNERHALB des Strings!
                continue;           // dieses Zeichen ueberlesen!
            }
        }

        if (bInString) {
            // Wenn jetzt das String-Delimiter-Zeichen auftritt ...
            if ( (*this).GetChar(i) == cStrDel )
            {
                if ((i+1 < Len()) && ((*this).GetChar(i+1) == cStrDel))
                {
                    // Verdoppeltes String-Delimiter-Zeichen:
                    i++;    // kein String-Ende, naechstes Zeichen ueberlesen.
                }
                else
                {
                    // String-Ende
                    bInString = FALSE;
                }
            }
        } else {
            // Stimmt das Tokenzeichen ueberein, dann erhoehe TokCount
            if ( (*this).GetChar(i) == cTok )
            {
                nTokCount++;
                bStart = TRUE;
            }
        }
    }

    return nTokCount;
}

//------------------------------------------------------------------
void OFlatString::GetTokenSpecial( String& _rStr,xub_StrLen& nStartPos, sal_Unicode cTok, sal_Unicode cStrDel ) const
{
    _rStr.Erase();
    xub_StrLen nLen = Len();
    if ( nLen )
    {
        BOOL bInString = (nStartPos < nLen) && ((*this).GetChar(nStartPos) == cStrDel); // Befinden wir uns INNERHALB eines (cStrDel delimited) String?

        // Erstes Zeichen ein String-Delimiter?
        if (bInString )
            ++nStartPos;            // dieses Zeichen ueberlesen!
        // Suche bis Stringende nach dem ersten nicht uebereinstimmenden Zeichen
        xub_StrLen i = nStartPos;
        for( ; i < nLen; ++i )
        {
            if (bInString)
            {
                // Wenn jetzt das String-Delimiter-Zeichen auftritt ...
                if ( (*this).GetChar(i) == cStrDel )
                {
                    if ((i+1 < nLen) && ((*this).GetChar(i+1) == cStrDel))
                    {
                        // Verdoppeltes String-Delimiter-Zeichen:
                        ++i;    // kein String-Ende, naechstes Zeichen ueberlesen.

                        _rStr += (*this).GetChar(i);    // Zeichen gehoert zum Resultat-String
                    }
                    else
                    {
                        // String-Ende
                        bInString = FALSE;
                    }
                }
                else
                {
                    _rStr += (*this).GetChar(i);    // Zeichen gehoert zum Resultat-String
                }

            }
            else
            {
                // Stimmt das Tokenzeichen ueberein, dann erhoehe nTok
                if ( (*this).GetChar(i) == cTok )
                {
                    // Vorzeitiger Abbruch der Schleife moeglich, denn
                    // wir haben, was wir wollten.
                    nStartPos = i+1;
                    break;
                }
                else
                {
                    _rStr += (*this).GetChar(i);    // Zeichen gehoert zum Resultat-String
                }
            }
        }
        if ( i == nLen && nStartPos < i )
            nStartPos = nLen;
    }
}
// -----------------------------------------------------------------------------
sal_Bool OFlatTable::checkHeaderLine()
{
    if (m_nFilePos == 0 && ((OFlatConnection*)m_pConnection)->isHeaderLine())
    {
        BOOL bRead2;
        do
        {
            bRead2 = m_pFileStream->ReadByteStringLine(m_aCurrentLine,m_pConnection->getTextEncoding());
        }
        while(bRead2 && !m_aCurrentLine.Len());

        m_nFilePos = m_pFileStream->Tell();
        if (m_pFileStream->IsEof())
            return sal_False;
    }
    return sal_True;
}
//------------------------------------------------------------------
sal_Bool OFlatTable::seekRow(IResultSetHelper::Movement eCursorPosition, sal_Int32 nOffset, sal_Int32& nCurPos)
{
    if ( !m_pFileStream )
        return sal_False;
    OFlatConnection* pConnection = (OFlatConnection*)m_pConnection;
    // ----------------------------------------------------------
    // Positionierung vorbereiten:

    sal_uInt32 nTempPos = m_nFilePos;
    m_nFilePos = nCurPos;

    switch(eCursorPosition)
    {
        case IResultSetHelper::FIRST:
            m_nFilePos = 0;
            m_nRowPos = 1;
            // run through
        case IResultSetHelper::NEXT:
            if(eCursorPosition != IResultSetHelper::FIRST)
                ++m_nRowPos;
            m_pFileStream->Seek(m_nFilePos);
            if (m_pFileStream->IsEof() || !checkHeaderLine())
            {
                m_nMaxRowCount = m_nRowPos;
                return sal_False;
            }

            m_aRowToFilePos.insert(::std::map<sal_Int32,sal_Int32>::value_type(m_nRowPos,m_nFilePos));

            m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
            if (m_pFileStream->IsEof())
            {
                m_nMaxRowCount = m_nRowPos;
                return sal_False;
            }
            nCurPos = m_pFileStream->Tell();
            break;
        case IResultSetHelper::PRIOR:
            --m_nRowPos;
            if(m_nRowPos > 0)
            {
                m_nFilePos = m_aRowToFilePos.find(m_nRowPos)->second;
                m_pFileStream->Seek(m_nFilePos);
                if (m_pFileStream->IsEof() || !checkHeaderLine())
                    return sal_False;
                m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
                if (m_pFileStream->IsEof())
                    return sal_False;
                nCurPos = m_pFileStream->Tell();
            }
            else
                m_nRowPos = 0;

            break;

            break;
        case IResultSetHelper::LAST:
            if(m_nMaxRowCount)
            {
                m_nFilePos = m_aRowToFilePos.rbegin()->second;
                m_nRowPos  = m_aRowToFilePos.rbegin()->first;
                m_pFileStream->Seek(m_nFilePos);
                if (m_pFileStream->IsEof() || !checkHeaderLine())
                    return sal_False;
                m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
                if (m_pFileStream->IsEof())
                    return sal_False;
                nCurPos = m_pFileStream->Tell();
            }
            else
            {
                while(seekRow(IResultSetHelper::NEXT,1,nCurPos)) ; // run through after last row
                // now I know all
                seekRow(IResultSetHelper::PRIOR,1,nCurPos);
            }
            break;
        case IResultSetHelper::RELATIVE:
            if(nOffset > 0)
            {
                for(sal_Int32 i = 0;i<nOffset;++i)
                    seekRow(IResultSetHelper::NEXT,1,nCurPos);
            }
            else if(nOffset < 0)
            {
                for(sal_Int32 i = nOffset;i;++i)
                    seekRow(IResultSetHelper::PRIOR,1,nCurPos);
            }
            break;
        case IResultSetHelper::ABSOLUTE:
            {
                if(nOffset < 0)
                    nOffset = m_nRowPos + nOffset;
                ::std::map<sal_Int32,sal_Int32>::const_iterator aIter = m_aRowToFilePos.find(nOffset);
                if(aIter != m_aRowToFilePos.end())
                {
                    m_nFilePos = aIter->second;
                    m_pFileStream->Seek(m_nFilePos);
                    if (m_pFileStream->IsEof() || !checkHeaderLine())
                        return sal_False;
                    m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
                    if (m_pFileStream->IsEof())
                        return sal_False;
                    nCurPos = m_pFileStream->Tell();
                }
                else if(m_nMaxRowCount && nOffset > m_nMaxRowCount) // offset is outside the table
                {
                    m_nRowPos = m_nMaxRowCount;
                    return sal_False;
                }
                else
                {
                    aIter = m_aRowToFilePos.upper_bound(nOffset);
                    if(aIter == m_aRowToFilePos.end())
                    {
                        m_nRowPos   = m_aRowToFilePos.rbegin()->first;
                        nCurPos = m_nFilePos = m_aRowToFilePos.rbegin()->second;
                        while(m_nRowPos != nOffset)
                            seekRow(IResultSetHelper::NEXT,1,nCurPos);
                    }
                    else
                    {
                        --aIter;
                        m_nRowPos   = aIter->first;
                        m_nFilePos  = aIter->second;
                        m_pFileStream->Seek(m_nFilePos);
                        if (m_pFileStream->IsEof() || !checkHeaderLine())
                            return sal_False;
                        m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
                        if (m_pFileStream->IsEof())
                            return sal_False;
                        nCurPos = m_pFileStream->Tell();
                    }
                }
            }

            break;
        case IResultSetHelper::BOOKMARK:
            m_pFileStream->Seek(nOffset);
            if (m_pFileStream->IsEof())
                return sal_False;

            m_nFilePos = m_pFileStream->Tell(); // Byte-Position in der Datei merken (am ZeilenANFANG)
            m_pFileStream->ReadByteStringLine(m_aCurrentLine,pConnection->getTextEncoding());
            if (m_pFileStream->IsEof())
                return sal_False;
            nCurPos  = m_pFileStream->Tell();
            break;
    }

    return sal_True;
}
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: MacabHeader.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: ihi $ $Date: 2007-09-13 17:52:42 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"

#include "MacabHeader.hxx"

#ifndef _CONNECTIVITY_MACAB_RECORD_HXX_
#include "MacabRecord.hxx"
#endif

#ifndef _CONNECTIVITY_MACAB_UTILITIES_HXX_
#include "macabutilities.hxx"
#endif

#include <math.h>

#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif

using namespace connectivity::macab;
using namespace com::sun::star::sdbc;

// -------------------------------------------------------------------------
MacabHeader::MacabHeader(const sal_Int32 _size, macabfield **_fields)
{
    sal_Int32 i;
    size = _size;
    fields = new macabfield *[size];
    for(i = 0; i < size; i++)
    {
        if(_fields[i] == NULL)
        {
            fields[i] = NULL;
        }
        else
        {
            /* The constructor duplicates the macabfields it gets because they
             * are either deleted later or used for other purposes.
             */
            fields[i] = new macabfield;
            fields[i]->type = _fields[i]->type;
            fields[i]->value = _fields[i]->value;
            CFRetain(fields[i]->value);
        }
    }

}

// -------------------------------------------------------------------------
MacabHeader::MacabHeader()
{
    size = 0;
    fields = NULL;
}

// -------------------------------------------------------------------------
MacabHeader::~MacabHeader()
{
}

// -------------------------------------------------------------------------
void MacabHeader::operator+= (const MacabHeader *r)
{
    /* Add one MacabHeader to another. Anything not already in the header is
     * added to the end of it.
     */
    sal_Int32 rSize = r->getSize();
    if(rSize != 0) // If the new header does actually have fields
    {
        /* If our header is currently empty, just copy all of the fields from
         * the new header to this one.
         */
        if(size == 0)
        {
            sal_Int32 i;
            size = rSize;
            fields = new macabfield *[size];
            for(i = 0; i < size; i++)
            {
                fields[i] = r->copy(i);
            }
        }

        /* Otherwise, only add the duplicates. We do this with a two-pass
         * approach. First, find out how many fields to add, then reallocate
         * the size of the fields array and add the old ones at the end.
         * (More precisely, we create a _new_ fields array with the new length
         * allocated to it, then get all of the fields from the current
         * fields array to it, then copy the non-duplicates from the new
         * header to the end.)
         */
        else
        {
            sal_Int32 i;
            sal_Int32 numToAdd = 0, numAdded = 0;
            macabfield **newFields;
            for( i = 0; i < rSize; i++)
            {
                if(!contains(r->get(i)))
                {
                    numToAdd++;
                }
            }

            newFields = new macabfield *[size+numToAdd];
            for(i = 0; i < size; i++)
            {
                newFields[i] = copy(i);
            }

            for( i = 0; i < rSize; i++)
            {
                if(!contains(r->get(i)))
                {
                    newFields[size+numAdded] = r->copy(i);
                    numAdded++;
                    if(numAdded == numToAdd)
                        break;
                }
            }

            releaseFields();
            delete [] fields;
            size += numAdded;
            fields = newFields;
        }
    }
}

// -------------------------------------------------------------------------
::rtl::OUString MacabHeader::getString(const sal_Int32 i) const
{
    ::rtl::OUString nRet;

    if(i < size)
    {
        if(fields[i] == NULL)
            return ::rtl::OUString();
        try
        {
            nRet = CFStringToOUString( (CFStringRef) fields[i]->value);
        }
        catch(...){ }

    }

    return nRet;
}

// -------------------------------------------------------------------------
void MacabHeader::sortRecord()
{
    sortRecord(0,size);
}

// -------------------------------------------------------------------------
macabfield **MacabHeader::sortRecord(const sal_Int32 _start, const sal_Int32 _length)
{
    /* Sort using mergesort. Because it uses mergesort, it is recursive and
     * not in place (so it creates a new array at every step of the
     * recursion), so if you prefer to use a different sort, please feel
     * free to implement it.
     */
    macabfield** sorted = new macabfield *[_length];
    if(_length <= 2)
    {
        if(_length == 2)
        {
            if(compareFields(fields[_start], fields[_start+1]) > 0)
            {
                sorted[0] = get(_start+1);
                sorted[1] = get(_start);
            }
            else
            {
                sorted[0] = get(_start);
                sorted[1] = get(_start+1);
            }
        }
        else if(_length == 1)
        {
            sorted[0] = get(_start);
        }
    }
    else
    {
        sal_Int32 halfLength = floor(_length/2);
        sal_Int32 fp = 0, lp = 0;
        sal_Int32 i;
        macabfield **firstHalf = new macabfield *[halfLength];
        macabfield **lastHalf = new macabfield *[_length - halfLength];

        firstHalf = sortRecord(_start, halfLength);
        lastHalf = sortRecord(_start+halfLength, _length-halfLength);
        for(i = 0; i < _length; i++)
        {
            if(compareFields(firstHalf[fp],lastHalf[lp]) < 0)
            {
                sorted[i] = firstHalf[fp++];
                if(fp == halfLength)
                {
                    for( i++; i < _length; i++)
                    {
                        sorted[i] = lastHalf[lp++];
                    }
                    break;
                }
            }
            else
            {
                sorted[i] = lastHalf[lp++];
                if(lp == _length - halfLength)
                {
                    for( i++; i < _length; i++)
                    {
                        sorted[i] = firstHalf[fp++];
                    }
                    break;
                }
            }
        }
        if(_length == size)
        {
            fields = sorted;
        }
    }
    return sorted;
}

sal_Int32 MacabHeader::compareFields(const macabfield *_field1, const macabfield *_field2)
{
    /* Comparing two fields in a MacabHeader is different than comparing two
     * fields in a MacabRecord. It starts in the same way (if one of the two
     * fields is NULL, it belongs after the other, so it is considered
     * "greater"). But, then, all headers are CFStrings, no matter what
     * type they claim to be (since they actually hold the expected type for
     * the records with that header). That being said, all we have to do is
     * the built-in CFStringCompare.
     */
    if(_field1 == _field2)
        return 0;
    if(_field1 == NULL)
        return 1;
    if(_field2 == NULL)
        return -1;

    CFComparisonResult result = CFStringCompare(
        (CFStringRef) _field1->value,
        (CFStringRef) _field2->value,
        0); // 0 = no options (like ignore case)

    return (sal_Int32) result;
}

// -------------------------------------------------------------------------
sal_Int32 MacabHeader::getColumnNumber(const ::rtl::OUString s) const
{
    sal_Int32 i;
    for(i = 0; i < size; i++)
    {
        if(getString(i) == s)
            break;
    }

    if(i == size)
        i = -1;

    return i;
}

// -------------------------------------------------------------------------
MacabHeader *MacabHeader::begin()
{
    return this;
}

// -------------------------------------------------------------------------
MacabHeader::iterator::iterator ()
{
}

// -------------------------------------------------------------------------
MacabHeader::iterator::~iterator ()
{
}

void MacabHeader::iterator::operator= (MacabHeader *_record)
{
    id = 0;
    record = _record;
}

// -------------------------------------------------------------------------
void MacabHeader::iterator::operator++ ()
{
    id++;
}

// -------------------------------------------------------------------------
sal_Bool MacabHeader::iterator::operator!= (const sal_Int32 i) const
{
    return(id != i);
}

// -------------------------------------------------------------------------
sal_Bool MacabHeader::iterator::operator== (const sal_Int32 i) const
{
    return(id == i);
}

// -------------------------------------------------------------------------
macabfield *MacabHeader::iterator::operator* () const
{
    return record->get(id);
}

// -------------------------------------------------------------------------
sal_Int32 MacabHeader::end() const
{
    return size;
}

<commit_msg>INTEGRATION: CWS aquavcl05_DEV300 (1.2.74); FILE MERGED 2008/01/29 09:17:56 ericb 1.2.74.2: #i83707# cosmetic 2008/01/29 09:09:40 ericb 1.2.74.1: #i83707# fix potential crash. Fixes proposed by P. Luby<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: MacabHeader.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2008-03-05 16:38:31 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"

#include "MacabHeader.hxx"

#ifndef _CONNECTIVITY_MACAB_RECORD_HXX_
#include "MacabRecord.hxx"
#endif

#ifndef _CONNECTIVITY_MACAB_UTILITIES_HXX_
#include "macabutilities.hxx"
#endif

#include <math.h>

#ifndef _COM_SUN_STAR_SDBC_DATATYPE_HPP_
#include <com/sun/star/sdbc/DataType.hpp>
#endif

#ifndef _DBHELPER_DBCONVERSION_HXX_
#include <connectivity/dbconversion.hxx>
#endif

using namespace connectivity::macab;
using namespace com::sun::star::sdbc;
using namespace com::sun::star::util;
using namespace ::dbtools;

// -------------------------------------------------------------------------
MacabHeader::MacabHeader(const sal_Int32 _size, macabfield **_fields)
{
    sal_Int32 i;
    size = _size;
    fields = new macabfield *[size];
    for(i = 0; i < size; i++)
    {
        if(_fields[i] == NULL)
        {
            fields[i] = NULL;
        }
        else
        {
            /* The constructor duplicates the macabfields it gets because they
             * are either deleted later or used for other purposes.
             */
            fields[i] = new macabfield;
            fields[i]->type = _fields[i]->type;
            fields[i]->value = _fields[i]->value;
            if (fields[i]->value)
                CFRetain(fields[i]->value);
        }
    }

}

// -------------------------------------------------------------------------
MacabHeader::MacabHeader()
{
    size = 0;
    fields = NULL;
}

// -------------------------------------------------------------------------
MacabHeader::~MacabHeader()
{
}

// -------------------------------------------------------------------------
void MacabHeader::operator+= (const MacabHeader *r)
{
    /* Add one MacabHeader to another. Anything not already in the header is
     * added to the end of it.
     */
    sal_Int32 rSize = r->getSize();
    if(rSize != 0) // If the new header does actually have fields
    {
        /* If our header is currently empty, just copy all of the fields from
         * the new header to this one.
         */
        if(size == 0)
        {
            sal_Int32 i;
            size = rSize;
            fields = new macabfield *[size];
            for(i = 0; i < size; i++)
            {
                fields[i] = r->copy(i);
            }
        }

        /* Otherwise, only add the duplicates. We do this with a two-pass
         * approach. First, find out how many fields to add, then reallocate
         * the size of the fields array and add the old ones at the end.
         * (More precisely, we create a _new_ fields array with the new length
         * allocated to it, then get all of the fields from the current
         * fields array to it, then copy the non-duplicates from the new
         * header to the end.)
         */
        else
        {
            sal_Int32 i;
            sal_Int32 numToAdd = 0, numAdded = 0;
            macabfield **newFields;
            for( i = 0; i < rSize; i++)
            {
                if(!contains(r->get(i)))
                {
                    numToAdd++;
                }
            }

            newFields = new macabfield *[size+numToAdd];
            for(i = 0; i < size; i++)
            {
                newFields[i] = copy(i);
            }

            for( i = 0; i < rSize; i++)
            {
                if(!contains(r->get(i)))
                {
                    newFields[size+numAdded] = r->copy(i);
                    numAdded++;
                    if(numAdded == numToAdd)
                        break;
                }
            }

            releaseFields();
            delete [] fields;
            size += numAdded;
            fields = newFields;
        }
    }
}

// -------------------------------------------------------------------------
::rtl::OUString MacabHeader::getString(const sal_Int32 i) const
{
    ::rtl::OUString nRet;

    if(i < size)
    {
        if(fields[i] == NULL || fields[i]->value == NULL || CFGetTypeID(fields[i]->value) != CFStringGetTypeID())
            return ::rtl::OUString();
        try
        {
            nRet = CFStringToOUString( (CFStringRef) fields[i]->value);
        }
        catch(...){ }
    }

    return nRet;
}

// -------------------------------------------------------------------------
void MacabHeader::sortRecord()
{
    sortRecord(0,size);
}

// -------------------------------------------------------------------------
macabfield **MacabHeader::sortRecord(const sal_Int32 _start, const sal_Int32 _length)
{
    /* Sort using mergesort. Because it uses mergesort, it is recursive and
     * not in place (so it creates a new array at every step of the
     * recursion), so if you prefer to use a different sort, please feel
     * free to implement it.
     */
    macabfield** sorted = new macabfield *[_length];
    if(_length <= 2)
    {
        if(_length == 2)
        {
            if(compareFields(fields[_start], fields[_start+1]) > 0)
            {
                sorted[0] = get(_start+1);
                sorted[1] = get(_start);
            }
            else
            {
                sorted[0] = get(_start);
                sorted[1] = get(_start+1);
            }
        }
        else if(_length == 1)
        {
            sorted[0] = get(_start);
        }
    }
    else
    {
        sal_Int32 halfLength = floor(_length/2);
        sal_Int32 fp = 0, lp = 0;
        sal_Int32 i;
        macabfield **firstHalf = new macabfield *[halfLength];
        macabfield **lastHalf = new macabfield *[_length - halfLength];

        firstHalf = sortRecord(_start, halfLength);
        lastHalf = sortRecord(_start+halfLength, _length-halfLength);
        for(i = 0; i < _length; i++)
        {
            if(compareFields(firstHalf[fp],lastHalf[lp]) < 0)
            {
                sorted[i] = firstHalf[fp++];
                if(fp == halfLength)
                {
                    for( i++; i < _length; i++)
                    {
                        sorted[i] = lastHalf[lp++];
                    }
                    break;
                }
            }
            else
            {
                sorted[i] = lastHalf[lp++];
                if(lp == _length - halfLength)
                {
                    for( i++; i < _length; i++)
                    {
                        sorted[i] = firstHalf[fp++];
                    }
                    break;
                }
            }
        }
        if(_length == size)
        {
            fields = sorted;
        }
    }
    return sorted;
}

sal_Int32 MacabHeader::compareFields(const macabfield *_field1, const macabfield *_field2)
{
    /* Comparing two fields in a MacabHeader is different than comparing two
     * fields in a MacabRecord. It starts in the same way (if one of the two
     * fields is NULL, it belongs after the other, so it is considered
     * "greater"). But, then, all headers are CFStrings, no matter what
     * type they claim to be (since they actually hold the expected type for
     * the records with that header). That being said, all we have to do is
     * the built-in CFStringCompare.
     */
    if(_field1 == _field2)
        return 0;
    if(_field1 == NULL)
        return 1;
    if(_field2 == NULL)
        return -1;

    CFComparisonResult result = CFStringCompare(
        (CFStringRef) _field1->value,
        (CFStringRef) _field2->value,
        0); // 0 = no options (like ignore case)

    return (sal_Int32) result;
}

// -------------------------------------------------------------------------
sal_Int32 MacabHeader::getColumnNumber(const ::rtl::OUString s) const
{
    sal_Int32 i;
    for(i = 0; i < size; i++)
    {
        if(getString(i) == s)
            break;
    }

    if(i == size)
        i = -1;

    return i;
}

// -------------------------------------------------------------------------
MacabHeader *MacabHeader::begin()
{
    return this;
}

// -------------------------------------------------------------------------
MacabHeader::iterator::iterator ()
{
}

// -------------------------------------------------------------------------
MacabHeader::iterator::~iterator ()
{
}

void MacabHeader::iterator::operator= (MacabHeader *_record)
{
    id = 0;
    record = _record;
}

// -------------------------------------------------------------------------
void MacabHeader::iterator::operator++ ()
{
    id++;
}

// -------------------------------------------------------------------------
sal_Bool MacabHeader::iterator::operator!= (const sal_Int32 i) const
{
    return(id != i);
}

// -------------------------------------------------------------------------
sal_Bool MacabHeader::iterator::operator== (const sal_Int32 i) const
{
    return(id == i);
}

// -------------------------------------------------------------------------
macabfield *MacabHeader::iterator::operator* () const
{
    return record->get(id);
}

// -------------------------------------------------------------------------
sal_Int32 MacabHeader::end() const
{
    return size;
}

<|endoftext|>


<commit_before>/*  This file is part of the KDE project
    Copyright (C) 2008 Matthias Kretz <kretz@kde.org>

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

    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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include <QtCore/QCoreApplication>
#include <QtCore/QtDebug>
#include <QtCore/QMutableListIterator>
#include <QtCore/QList>
#include "../qsettingsgroup_p.h"
#include <kcomponentdata.h>
#include <kconfig.h>
#include <kconfiggroup.h>

using Phonon::QSettingsGroup;

Q_DECLARE_METATYPE(QList<int>)

int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);
    KComponentData cData("phonon device preference update");

    KConfig kconfig("phonondevicesrc", KConfig::NoGlobals);
    KConfigGroup globalGroup(&kconfig, "Globals");
    int newIndexForZero = 0;

    foreach (const QString &group, kconfig.groupList()) {
        KConfigGroup configGroup(&kconfig, group);
        int index = configGroup.readEntry("index", -1);
        if (index == 0) {
            newIndexForZero = globalGroup.readEntry("nextIndex", 0);
            configGroup.writeEntry("index", newIndexForZero);
            globalGroup.writeEntry("nextIndex", newIndexForZero + 1);
            break;
        }
    }

    qDebug() << newIndexForZero;
    qRegisterMetaTypeStreamOperators<QList<int> >("QList<int>");

    QSettings qconfig(QLatin1String("kde.org"), QLatin1String("libphonon"));
    QSettingsGroup outputGroup(&qconfig, QLatin1String("AudioOutputDevice"));
    for (int i = -1; i < 10; ++i) {
        const QString oldKey = QLatin1String("Category") + QString::number(i);
        const QString newKey = QLatin1String("Category_") + QString::number(i);
        qDebug() << oldKey << newKey;
        if (outputGroup.hasKey(oldKey) && !outputGroup.hasKey(newKey)) {
            QList<int> deviceIndexes = outputGroup.value(oldKey, QList<int>());
            QMutableListIterator<int> index(deviceIndexes);
            while (index.hasNext()) {
                index.next();
                if (index.value() < 10000 && index.value() >= 0) {
                    qDebug() << "changing index" << index.value();
                    if (index.value() == 0) {
                        Q_ASSERT(newIndexForZero);
                        index.setValue(-newIndexForZero);
                    } else {
                        index.setValue(-index.value());
                    }
                }
            }
            outputGroup.setValue(newKey, deviceIndexes);
            outputGroup.removeEntry(oldKey);
        }
    }

    return 0;
}
<commit_msg>remove debug output<commit_after>/*  This file is part of the KDE project
    Copyright (C) 2008 Matthias Kretz <kretz@kde.org>

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

    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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

*/

#include <QtCore/QCoreApplication>
#include <QtCore/QMutableListIterator>
#include <QtCore/QList>
#include "../qsettingsgroup_p.h"
#include <kcomponentdata.h>
#include <kconfig.h>
#include <kconfiggroup.h>

using Phonon::QSettingsGroup;

Q_DECLARE_METATYPE(QList<int>)

int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);
    KComponentData cData("phonon device preference update");

    KConfig kconfig("phonondevicesrc", KConfig::NoGlobals);
    KConfigGroup globalGroup(&kconfig, "Globals");
    int newIndexForZero = 0;

    foreach (const QString &group, kconfig.groupList()) {
        KConfigGroup configGroup(&kconfig, group);
        int index = configGroup.readEntry("index", -1);
        if (index == 0) {
            newIndexForZero = globalGroup.readEntry("nextIndex", 0);
            configGroup.writeEntry("index", newIndexForZero);
            globalGroup.writeEntry("nextIndex", newIndexForZero + 1);
            break;
        }
    }

    qRegisterMetaTypeStreamOperators<QList<int> >("QList<int>");

    QSettings qconfig(QLatin1String("kde.org"), QLatin1String("libphonon"));
    QSettingsGroup outputGroup(&qconfig, QLatin1String("AudioOutputDevice"));
    for (int i = -1; i < 10; ++i) {
        const QString oldKey = QLatin1String("Category") + QString::number(i);
        const QString newKey = QLatin1String("Category_") + QString::number(i);
        if (outputGroup.hasKey(oldKey) && !outputGroup.hasKey(newKey)) {
            QList<int> deviceIndexes = outputGroup.value(oldKey, QList<int>());
            QMutableListIterator<int> index(deviceIndexes);
            while (index.hasNext()) {
                index.next();
                if (index.value() < 10000 && index.value() >= 0) {
                    if (index.value() == 0) {
                        Q_ASSERT(newIndexForZero);
                        index.setValue(-newIndexForZero);
                    } else {
                        index.setValue(-index.value());
                    }
                }
            }
            outputGroup.setValue(newKey, deviceIndexes);
            outputGroup.removeEntry(oldKey);
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>/* dbRecordEditor.cc                KPilot
**
** Copyright (C) 2003 by Dan Pilone
** Written 2003 by Reinhold Kainhofer
**
**/

/*
** 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 in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/

#include "options.h"

#include <qlineedit.h>
#include <qcheckbox.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <qbuttongroup.h>
#include <qcheckbox.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qpushbutton.h>
#include <qlayout.h>

#include <kmessagebox.h>

#include "pilotRecord.h"
#include "dbRecordEditor.h"
//#include "dbRecordEditor_base.h"

#ifdef USE_KHEXEDIT
#include <khexedit/byteseditinterface.h>
#include <khexedit/hexcolumninterface.h>
#include <khexedit/textcolumninterface.h>
using namespace KHE;
#endif

DBRecordEditor::DBRecordEditor(PilotRecord*r, int n, QWidget *parent)
	: KDialogBase(parent, "RecordEditor",false,i18n("Edit Record..."),
				Ok|Cancel), rec(r), nr(n)
{
//	fWidget=new DBRecordEditorBase(this);
	fWidget=new QWidget(this);
	setMainWidget(fWidget);

	initWidgets();
	fillWidgets();
}

DBRecordEditor::~DBRecordEditor()
{
}

void DBRecordEditor::slotOk()
{
	FUNCTIONSETUP;
	if (KMessageBox::questionYesNo(this, i18n("Changing the record data and flags might corrupt the whole record, or even make the database unusable. Do not change the values unless you are absolutely sure you know what you are doing.\n\nReally assign these new flags?"), i18n("Changing record"))==KMessageBox::Yes)
	{
		int att=rec->getAttrib();
#define setFlag(ctrl, flag) if (ctrl->isChecked()) att|=flag; else att &= ~flag;
		setFlag(fDirty, dlpRecAttrDirty);
		setFlag(fDeleted, dlpRecAttrDeleted);
		setFlag(fBusy, dlpRecAttrBusy);
		setFlag(fSecret, dlpRecAttrSecret);
		setFlag(fArchived, dlpRecAttrArchived);
		rec->setAttrib(att);
#undef setFlag

#ifdef USE_KHEXEDIT
		if ( fRecordDataIf->isModified() )
		{
#ifdef DEBUG
			DEBUGKPILOT << "record data changed, new Length of record: " <<
				fRecordDataIf->dataSize() << endl;
#endif
			// take over data
			fRecordDataIf->setAutoDelete( false );
			rec->setData( fRecordDataIf->data(), fRecordDataIf->dataSize() );
		}
#endif

		KDialogBase::slotOk();
	}
}

void DBRecordEditor::slotCancel()
{
	KDialogBase::slotCancel();
}

void DBRecordEditor::languageChange()
{
	setCaption( tr2i18n( "Form1" ) );
	fRecordIndexLabel->setText( tr2i18n( "Record index:" ) );
	fRecordIDLabel->setText( tr2i18n( "Record ID:" ) );
	fRecordIndex->setText( tr2i18n( "1" ) );
	fRecordID->setText( tr2i18n( "1" ) );
	fFlagsGroup->setTitle( tr2i18n( "Flags" ) );
	fDirty->setText( tr2i18n( "&Dirty" ) );
	fDeleted->setText( tr2i18n( "De&leted" ) );
	fBusy->setText( tr2i18n( "&Busy" ) );
	fSecret->setText( tr2i18n( "&Secret" ) );
	fArchived->setText( tr2i18n( "&Archived" ) );
}

void DBRecordEditor::initWidgets()
{
	// FUNCTIONSETUP

	DBRecordEditorBaseLayout = new QGridLayout( fWidget, 1, 1, 11, 6, "DBRecordEditorBaseLayout");

	fRecordIndexLabel = new QLabel( fWidget, "fRecordIndexLabel" );
	DBRecordEditorBaseLayout->addWidget( fRecordIndexLabel, 0, 0 );

	fRecordIDLabel = new QLabel( fWidget, "fRecordIDLabel" );
	DBRecordEditorBaseLayout->addWidget( fRecordIDLabel, 0, 2 );

	fRecordIndex = new QLineEdit( fWidget, "fRecordIndex" );
	fRecordIndex->setReadOnly( TRUE );

	DBRecordEditorBaseLayout->addWidget( fRecordIndex, 0, 1 );

	fRecordID = new QLineEdit( fWidget, "fRecordID" );
	fRecordID->setReadOnly( TRUE );

	DBRecordEditorBaseLayout->addWidget( fRecordID, 0, 3 );

	fFlagsGroup = new QButtonGroup( fWidget, "fFlagsGroup" );
	fFlagsGroup->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5,
		(QSizePolicy::SizeType)4, 0, 0, fFlagsGroup->sizePolicy().hasHeightForWidth() ) );
	fFlagsGroup->setColumnLayout(0, Qt::Vertical );
	fFlagsGroup->layout()->setSpacing( 6 );
	fFlagsGroup->layout()->setMargin( 11 );
	fFlagsGroupLayout = new QGridLayout( fFlagsGroup->layout() );
	fFlagsGroupLayout->setAlignment( Qt::AlignTop );

	fDirty = new QCheckBox( fFlagsGroup, "fDirty" );
	fFlagsGroupLayout->addWidget( fDirty, 0, 0 );

	fDeleted = new QCheckBox( fFlagsGroup, "fDeleted" );
	fFlagsGroupLayout->addWidget( fDeleted, 1, 0 );

	fBusy = new QCheckBox( fFlagsGroup, "fBusy" );
	fFlagsGroupLayout->addWidget( fBusy, 0, 1 );

	fSecret = new QCheckBox( fFlagsGroup, "fSecret" );
	fFlagsGroupLayout->addMultiCellWidget( fSecret, 1, 1, 1, 2 );

	fArchived = new QCheckBox( fFlagsGroup, "fArchived" );
	fFlagsGroupLayout->addWidget( fArchived, 0, 2 );

	DBRecordEditorBaseLayout->addMultiCellWidget( fFlagsGroup, 1, 1, 0, 3 );

#ifdef USE_KHEXEDIT
	fRecordData = KHE::createBytesEditWidget( fWidget, "fRecordData" );
	if( fRecordData )
	{
		// fetch the editor interface
		fRecordDataIf = KHE::bytesEditInterface( fRecordData );
		Q_ASSERT( fRecordDataIf ); // This should not fail!

		KHE::HexColumnInterface *HexColumn = hexColumnInterface( fRecordData );
		if( HexColumn )
		{
			HexColumn->setNoOfBytesPerLine( 16 );
			HexColumn->setResizeStyle( KHE::HexColumnInterface::LockGrouping );
//			HexColumn->setCoding( HexColumnInterface::HexadecimalCoding );
//			HexColumn->setByteSpacingWidth( 2 );
			HexColumn->setNoOfGroupedBytes( 4 );
			HexColumn->setGroupSpacingWidth( 8 );
		}

		KHE::TextColumnInterface *TextColumn = textColumnInterface( fRecordData );
		if( TextColumn )
		{
			TextColumn->setShowUnprintable( false );
//			TextColumn->setSubstituteChar( '*' );
		}
	}
	else
	{
		QLabel*tmpW = new QLabel( i18n("To view and edit the record data, please install a hex editor (e.g. kbytesedit from kdeutils)."), fWidget );
		tmpW->setBackgroundMode( Qt::PaletteMid );
		tmpW->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter | Qt::WordBreak);
		tmpW->setFrameShape( QFrame::Panel );
		tmpW->setFrameShadow( QFrame::Sunken );
		fRecordData = tmpW;
		fRecordDataIf = 0;
	}

	DBRecordEditorBaseLayout->addMultiCellWidget( fRecordData, 2, 2, 0, 3 );
#endif

	languageChange();
	resize( QSize(600, 561).expandedTo(minimumSizeHint()) );
}

void DBRecordEditor::fillWidgets()
{
	// FUNCTIONSETUP

	fRecordIndex->setText(QString::number(nr));
	fRecordID->setText(QString::number(rec->getID()));

	int att=rec->getAttrib();
	fDirty->setChecked(att & dlpRecAttrDirty);
	fDeleted->setChecked(att & dlpRecAttrDeleted);
	fBusy->setChecked(att & dlpRecAttrBusy);
	fSecret->setChecked(att & dlpRecAttrSecret);
	fArchived->setChecked(att & dlpRecAttrArchived);

#ifdef USE_KHEXEDIT
	if( fRecordDataIf )
	{
		int len = rec->getLen();
		char* buffer = new char[len];
		memcpy( buffer, rec->getData(), len );
		fRecordDataIf->setData( buffer, len );
		fRecordDataIf->setMaxDataSize( 4096 );
		fRecordDataIf->setReadOnly( false );
		// Here we set auto delete to true. Only if we
		// really take over the data, set it to false.
		fRecordDataIf->setAutoDelete( true );
	}
#endif
}

#include "dbRecordEditor.moc"
<commit_msg>We want to allow to extend the buffer above the current size, do we? ;) One bug less to report for this temporary solution...<commit_after>/* dbRecordEditor.cc                KPilot
**
** Copyright (C) 2003 by Dan Pilone
** Written 2003 by Reinhold Kainhofer
**
**/

/*
** 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 in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/

#include "options.h"

#include <qlineedit.h>
#include <qcheckbox.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <qbuttongroup.h>
#include <qcheckbox.h>
#include <qlabel.h>
#include <qlineedit.h>
#include <qpushbutton.h>
#include <qlayout.h>

#include <kmessagebox.h>

#include "pilotRecord.h"
#include "dbRecordEditor.h"
//#include "dbRecordEditor_base.h"

#ifdef USE_KHEXEDIT
#include <khexedit/byteseditinterface.h>
#include <khexedit/hexcolumninterface.h>
#include <khexedit/textcolumninterface.h>
using namespace KHE;
#endif

DBRecordEditor::DBRecordEditor(PilotRecord*r, int n, QWidget *parent)
	: KDialogBase(parent, "RecordEditor",false,i18n("Edit Record..."),
				Ok|Cancel), rec(r), nr(n)
{
//	fWidget=new DBRecordEditorBase(this);
	fWidget=new QWidget(this);
	setMainWidget(fWidget);

	initWidgets();
	fillWidgets();
}

DBRecordEditor::~DBRecordEditor()
{
}

void DBRecordEditor::slotOk()
{
	FUNCTIONSETUP;
	if (KMessageBox::questionYesNo(this, i18n("Changing the record data and flags might corrupt the whole record, or even make the database unusable. Do not change the values unless you are absolutely sure you know what you are doing.\n\nReally assign these new flags?"), i18n("Changing record"))==KMessageBox::Yes)
	{
		int att=rec->getAttrib();
#define setFlag(ctrl, flag) if (ctrl->isChecked()) att|=flag; else att &= ~flag;
		setFlag(fDirty, dlpRecAttrDirty);
		setFlag(fDeleted, dlpRecAttrDeleted);
		setFlag(fBusy, dlpRecAttrBusy);
		setFlag(fSecret, dlpRecAttrSecret);
		setFlag(fArchived, dlpRecAttrArchived);
		rec->setAttrib(att);
#undef setFlag

#ifdef USE_KHEXEDIT
		if ( fRecordDataIf->isModified() )
		{
#ifdef DEBUG
			DEBUGKPILOT << "record data changed, new Length of record: " <<
				fRecordDataIf->dataSize() << endl;
#endif
			// take over data
			fRecordDataIf->setAutoDelete( false );
			rec->setData( fRecordDataIf->data(), fRecordDataIf->dataSize() );
		}
#endif

		KDialogBase::slotOk();
	}
}

void DBRecordEditor::slotCancel()
{
	KDialogBase::slotCancel();
}

void DBRecordEditor::languageChange()
{
	setCaption( tr2i18n( "Form1" ) );
	fRecordIndexLabel->setText( tr2i18n( "Record index:" ) );
	fRecordIDLabel->setText( tr2i18n( "Record ID:" ) );
	fRecordIndex->setText( tr2i18n( "1" ) );
	fRecordID->setText( tr2i18n( "1" ) );
	fFlagsGroup->setTitle( tr2i18n( "Flags" ) );
	fDirty->setText( tr2i18n( "&Dirty" ) );
	fDeleted->setText( tr2i18n( "De&leted" ) );
	fBusy->setText( tr2i18n( "&Busy" ) );
	fSecret->setText( tr2i18n( "&Secret" ) );
	fArchived->setText( tr2i18n( "&Archived" ) );
}

void DBRecordEditor::initWidgets()
{
	// FUNCTIONSETUP

	DBRecordEditorBaseLayout = new QGridLayout( fWidget, 1, 1, 11, 6, "DBRecordEditorBaseLayout");

	fRecordIndexLabel = new QLabel( fWidget, "fRecordIndexLabel" );
	DBRecordEditorBaseLayout->addWidget( fRecordIndexLabel, 0, 0 );

	fRecordIDLabel = new QLabel( fWidget, "fRecordIDLabel" );
	DBRecordEditorBaseLayout->addWidget( fRecordIDLabel, 0, 2 );

	fRecordIndex = new QLineEdit( fWidget, "fRecordIndex" );
	fRecordIndex->setReadOnly( TRUE );

	DBRecordEditorBaseLayout->addWidget( fRecordIndex, 0, 1 );

	fRecordID = new QLineEdit( fWidget, "fRecordID" );
	fRecordID->setReadOnly( TRUE );

	DBRecordEditorBaseLayout->addWidget( fRecordID, 0, 3 );

	fFlagsGroup = new QButtonGroup( fWidget, "fFlagsGroup" );
	fFlagsGroup->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5,
		(QSizePolicy::SizeType)4, 0, 0, fFlagsGroup->sizePolicy().hasHeightForWidth() ) );
	fFlagsGroup->setColumnLayout(0, Qt::Vertical );
	fFlagsGroup->layout()->setSpacing( 6 );
	fFlagsGroup->layout()->setMargin( 11 );
	fFlagsGroupLayout = new QGridLayout( fFlagsGroup->layout() );
	fFlagsGroupLayout->setAlignment( Qt::AlignTop );

	fDirty = new QCheckBox( fFlagsGroup, "fDirty" );
	fFlagsGroupLayout->addWidget( fDirty, 0, 0 );

	fDeleted = new QCheckBox( fFlagsGroup, "fDeleted" );
	fFlagsGroupLayout->addWidget( fDeleted, 1, 0 );

	fBusy = new QCheckBox( fFlagsGroup, "fBusy" );
	fFlagsGroupLayout->addWidget( fBusy, 0, 1 );

	fSecret = new QCheckBox( fFlagsGroup, "fSecret" );
	fFlagsGroupLayout->addMultiCellWidget( fSecret, 1, 1, 1, 2 );

	fArchived = new QCheckBox( fFlagsGroup, "fArchived" );
	fFlagsGroupLayout->addWidget( fArchived, 0, 2 );

	DBRecordEditorBaseLayout->addMultiCellWidget( fFlagsGroup, 1, 1, 0, 3 );

#ifdef USE_KHEXEDIT
	fRecordData = KHE::createBytesEditWidget( fWidget, "fRecordData" );
	if( fRecordData )
	{
		// fetch the editor interface
		fRecordDataIf = KHE::bytesEditInterface( fRecordData );
		Q_ASSERT( fRecordDataIf ); // This should not fail!

		KHE::HexColumnInterface *HexColumn = hexColumnInterface( fRecordData );
		if( HexColumn )
		{
			HexColumn->setNoOfBytesPerLine( 16 );
			HexColumn->setResizeStyle( KHE::HexColumnInterface::LockGrouping );
//			HexColumn->setCoding( HexColumnInterface::HexadecimalCoding );
//			HexColumn->setByteSpacingWidth( 2 );
			HexColumn->setNoOfGroupedBytes( 4 );
			HexColumn->setGroupSpacingWidth( 8 );
		}

		KHE::TextColumnInterface *TextColumn = textColumnInterface( fRecordData );
		if( TextColumn )
		{
			TextColumn->setShowUnprintable( false );
//			TextColumn->setSubstituteChar( '*' );
		}
	}
	else
	{
		QLabel*tmpW = new QLabel( i18n("To view and edit the record data, please install a hex editor (e.g. kbytesedit from kdeutils)."), fWidget );
		tmpW->setBackgroundMode( Qt::PaletteMid );
		tmpW->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter | Qt::WordBreak);
		tmpW->setFrameShape( QFrame::Panel );
		tmpW->setFrameShadow( QFrame::Sunken );
		fRecordData = tmpW;
		fRecordDataIf = 0;
	}

	DBRecordEditorBaseLayout->addMultiCellWidget( fRecordData, 2, 2, 0, 3 );
#endif

	languageChange();
	resize( QSize(600, 561).expandedTo(minimumSizeHint()) );
}

void DBRecordEditor::fillWidgets()
{
	// FUNCTIONSETUP

	fRecordIndex->setText(QString::number(nr));
	fRecordID->setText(QString::number(rec->getID()));

	int att=rec->getAttrib();
	fDirty->setChecked(att & dlpRecAttrDirty);
	fDeleted->setChecked(att & dlpRecAttrDeleted);
	fBusy->setChecked(att & dlpRecAttrBusy);
	fSecret->setChecked(att & dlpRecAttrSecret);
	fArchived->setChecked(att & dlpRecAttrArchived);

#ifdef USE_KHEXEDIT
	if( fRecordDataIf )
	{
		int len = rec->getLen();
		char* buffer = new char[len];
		memcpy( buffer, rec->getData(), len );
		fRecordDataIf->setData( buffer, len, -1, false );
		fRecordDataIf->setMaxDataSize( 4096 );
		fRecordDataIf->setReadOnly( false );
		// Here we set auto delete to true. Only if we
		// really take over the data, set it to false.
		fRecordDataIf->setAutoDelete( true );
	}
#endif
}

#include "dbRecordEditor.moc"
<|endoftext|>


<commit_before>/**************************************************************************

 The MIT License (MIT)

 Copyright (c) 2015 Dmitry Sovetov

 https://github.com/dmsovetov

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.

 **************************************************************************/

#include <Dreemchest.h>
#include "../Examples.h"

DC_USE_DREEMCHEST

using namespace Platform;
using namespace Renderer;

static String s_vertexShader =
    "cbuffer Projection projection : 0;                         \n"
    "cbuffer Camera     camera     : 1;                         \n"

    "varying vec3 v_texCoord;                                   \n"

    "void main()                                                \n"
    "{                                                          \n"
    "   gl_Position = projection.transform                      \n"
    "               * camera.rotation                           \n"
    "               * gl_Vertex;                                \n"
    "   v_texCoord  = gl_Vertex.xyz;                            \n"
    "}                                                          \n"
    ;

static String s_fragmentShader =
    "uniform samplerCube Texture0;                              \n"

    "varying vec3 v_texCoord;                                   \n"

    "void main()                                                \n"
    "{                                                          \n"
    "   gl_FragColor = textureCube(Texture0, v_texCoord);       \n"
    "}                                                          \n"
    ;

// Application delegate is now subclassed from a Examples::ViewerApplicationDelegate to add camera and arcball functionality.
class Cubemaps : public Examples::ViewerApplicationDelegate
{
    StateBlock8 m_renderStates;

    virtual void handleLaunched(Application* application) NIMBLE_OVERRIDE
    {
        Logger::setStandardLogger();

        if (!initialize(800, 600))
        {
            application->quit(-1);
        }

        // Create a cube vertex buffer and bind it to a render state block
        {
            InputLayout   inputLayout  = m_renderingContext->requestInputLayout(VertexFormat::Position);
            VertexBuffer_ vertexBuffer = m_renderingContext->requestVertexBuffer(Examples::UnitCube, sizeof(Examples::UnitCube));

            m_renderStates.bindVertexBuffer(vertexBuffer);
            m_renderStates.bindInputLayout(inputLayout);
        }

        // Load a cubemap texture and bind it to a sampler #0
        {
            const String envName = "Sierra_Madre_B";
            const String files[] =
            {
                  "Assets/Textures/Environments/" + envName + "/posx.tga"
                , "Assets/Textures/Environments/" + envName + "/negx.tga"
                , "Assets/Textures/Environments/" + envName + "/posy.tga"
                , "Assets/Textures/Environments/" + envName + "/negy.tga"
                , "Assets/Textures/Environments/" + envName + "/posz.tga"
                , "Assets/Textures/Environments/" + envName + "/negz.tga"
            };

            Examples::Surface pixels;
            Examples::Image   faces[6];

            for (s32 i = 0; i < 6; i++)
            {
                faces[i] = Examples::tgaFromFile(files[i]);
                pixels.insert(pixels.end(), faces[i].pixels.begin(), faces[i].pixels.end());
            }

            Texture_ env = m_renderingContext->requestTextureCube(&pixels[0], faces[0].width, 1, faces[0].format);
            m_renderStates.bindTexture(env, 0);
        }

        // Create a program that consists from a vertex and fragment shaders.
        Program program = m_renderingContext->requestProgram(s_vertexShader, s_fragmentShader);
        m_renderStates.bindProgram(program);
    }

    // This method is declared inside the Examples::ViewerApplicationDelegate.
    virtual void handleRenderFrame(const RenderFrame& frame, RenderCommandBuffer& commands) NIMBLE_OVERRIDE
    {
        commands.clear(Rgba(0.3f, 0.3f, 0.3f), ClearAll);
        commands.drawPrimitives(0, PrimTriangles, 0, 36, m_renderStates);
    }
};

dcDeclareApplication(new Cubemaps)
<commit_msg>Fixed: cube maps example compilation issue<commit_after>/**************************************************************************

 The MIT License (MIT)

 Copyright (c) 2015 Dmitry Sovetov

 https://github.com/dmsovetov

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 The above copyright notice and this permission notice shall be included in all
 copies or substantial portions of the Software.
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.

 **************************************************************************/

#include <Dreemchest.h>
#include "../Examples.h"

DC_USE_DREEMCHEST

using namespace Platform;
using namespace Renderer;

static String s_vertexShader =
    "cbuffer Projection projection : 0;                         \n"
    "cbuffer Camera     camera     : 1;                         \n"

    "varying vec3 v_texCoord;                                   \n"

    "void main()                                                \n"
    "{                                                          \n"
    "   gl_Position = projection.transform                      \n"
    "               * camera.rotation                           \n"
    "               * gl_Vertex;                                \n"
    "   v_texCoord  = gl_Vertex.xyz;                            \n"
    "}                                                          \n"
    ;

static String s_fragmentShader =
    "uniform samplerCube Texture0;                              \n"

    "varying vec3 v_texCoord;                                   \n"

    "void main()                                                \n"
    "{                                                          \n"
    "   gl_FragColor = textureCube(Texture0, v_texCoord);       \n"
    "}                                                          \n"
    ;

// Application delegate is now subclassed from a Examples::ViewerApplicationDelegate to add camera and arcball functionality.
class Cubemaps : public Examples::ViewerApplicationDelegate
{
    StateBlock8 m_renderStates;

    virtual void handleLaunched(Application* application) NIMBLE_OVERRIDE
    {
        Logger::setStandardLogger();

        if (!initialize(800, 600))
        {
            application->quit(-1);
        }

        // Create a cube vertex buffer and bind it to a render state block
        {
            InputLayout   inputLayout  = m_renderingContext->requestInputLayout(VertexFormat::Position);
            VertexBuffer_ vertexBuffer = m_renderingContext->requestVertexBuffer(Examples::UnitCube, sizeof(Examples::UnitCube));

            m_renderStates.bindVertexBuffer(vertexBuffer);
            m_renderStates.bindInputLayout(inputLayout);
        }

        // Load a cubemap texture and bind it to a sampler #0
        {
            const String envName = "Sierra_Madre_B";
            const String files[] =
            {
                  "Assets/Textures/Environments/" + envName + "/posx.tga"
                , "Assets/Textures/Environments/" + envName + "/negx.tga"
                , "Assets/Textures/Environments/" + envName + "/posy.tga"
                , "Assets/Textures/Environments/" + envName + "/negy.tga"
                , "Assets/Textures/Environments/" + envName + "/posz.tga"
                , "Assets/Textures/Environments/" + envName + "/negz.tga"
            };

            Examples::Surface pixels;
            Examples::Image   faces[6];

            for (s32 i = 0; i < 6; i++)
            {
                faces[i] = Examples::tgaFromFile(files[i]);
                pixels.insert(pixels.end(), faces[i].pixels.begin(), faces[i].pixels.end());
            }

            Texture_ env = m_renderingContext->requestTextureCube(&pixels[0], faces[0].width, 1, faces[0].format);
            m_renderStates.bindTexture(env, 0);
        }

        // Create a program that consists from a vertex and fragment shaders.
        Program program = m_renderingContext->requestProgram(s_vertexShader, s_fragmentShader);
        m_renderStates.bindProgram(program);
    }

    // This method is declared inside the Examples::ViewerApplicationDelegate.
    virtual void handleRenderFrame(RenderFrame& frame, StateStack& stateStack, RenderCommandBuffer& commands) NIMBLE_OVERRIDE
    {
        commands.clear(Rgba(0.3f, 0.3f, 0.3f), ClearAll);
        commands.drawPrimitives(0, PrimTriangles, 0, 36, m_renderStates);
    }
};

dcDeclareApplication(new Cubemaps)
<|endoftext|>


<commit_before>/*
   This file is part of the Nepomuk KDE project.
   Copyright (C) 2011 Sebastian Trueg <trueg@kde.org>

   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) version 3, or any
   later version accepted by the membership of KDE e.V. (or its
   successor approved by the membership of KDE e.V.), which shall
   act as a proxy defined in Section 6 of version 3 of the license.

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

#include "recommendationmanager.h"
#include "recommendationmanageradaptor.h"
#include "recommendation.h"
#include "recommendationaction.h"
#include "locationmanager.h"
#include "kext.h"

#include <kworkspace/kactivityinfo.h>
#include <kworkspace/kactivityconsumer.h>

#include <KRandom>
#include <KRun>
#include <KDebug>

#include <Nepomuk/Query/Query>
#include <Nepomuk/Query/QueryServiceClient>
#include <Nepomuk/Query/ComparisonTerm>
#include <Nepomuk/Query/LiteralTerm>
#include <Nepomuk/Query/AndTerm>
#include <Nepomuk/Query/QueryServiceClient>
#include <Nepomuk/Query/Result>
#include <Nepomuk/Resource>

#include <Soprano/Vocabulary/NAO>

#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusMetaType>

#include <QtLocation/QLandmark>

using namespace Soprano::Vocabulary;
using namespace Nepomuk::Vocabulary;

QTM_USE_NAMESPACE

//Q_DECLARE_METATYPE(Contour::Recommendation*)

// TODO: act on several changes:
//       * later: triggers from the dms

class Contour::RecommendationManager::Private
{
public:
    KActivityConsumer* m_activityConsumer;
    LocationManager* m_locationManager;

    QList<Recommendation> m_recommendations;
    QHash<QString, RecommendationAction> m_actionHash;
    QHash<QString, Recommendation> m_RecommendationForAction;

    Nepomuk::Query::QueryServiceClient m_queryClient;

    RecommendationManager* q;

    void updateRecommendations();
    void _k_locationChanged(const QList<QLandmark>&);
    void _k_currentActivityChanged(const QString&);
    void _k_newResults(const QList<Nepomuk::Query::Result>&);
    void _k_queryFinished();
};

void Contour::RecommendationManager::Private::updateRecommendations()
{
    // remove old recommendations
    m_recommendations.clear();
    m_actionHash.clear();
    m_RecommendationForAction.clear();

    // get resources that have been touched in the current activity (the dumb way for now)
    const QString query
            = QString::fromLatin1("select distinct ?resource, ?uri, ?cache,"
                    "("
                        "("
                            "?lastScore * bif:exp(-"
                                "bif:datediff('day', ?lastUpdate, \"2011-06-30T13:45:01.996Z\"^^<http://www.w3.org/2001/XMLSchema#dateTime>"
                            ")"
                        ")"
                    "as ?score) where {"
                        "?cache kext:targettedResource ?resource ."
                        "?cache a kext:ResourceScoreCache ."
                        "?cache nao:lastModified ?lastUpdate ."
                        "?cache kext:cachedScore ?lastScore ."
                        "?cache kext:usedActivity %1 ."
                        "OPTIONAL { ?resource nie:url ?uri . } ."
                    "}"
                    "ORDER BY DESC (?score)"
                    "LIMIT 10")
            .arg(Soprano::Node::resourceToN3(Nepomuk::Resource(m_activityConsumer->currentActivity(), KExt::Activity()).resourceUri()) /*Soprano::Node::literalToN3(Soprano::LiteralValue(m_activityConsumer->currentActivity()))*/);

    m_queryClient.sparqlQuery(query);

    // IDEA: for files use usage events
    //       for everything else use changes in data via graph metadata
}

void Contour::RecommendationManager::Private::_k_locationChanged(const QList<QLandmark>&)
{
    updateRecommendations();
}

void Contour::RecommendationManager::Private::_k_currentActivityChanged(const QString&)
{
    updateRecommendations();
}

void Contour::RecommendationManager::Private::_k_newResults(const QList<Nepomuk::Query::Result>& results)
{
    foreach(const Nepomuk::Query::Result& result, results) {
        Recommendation r;
        r.resourceUri = KUrl(result.resource().resourceUri()).url();

        kWarning() << "Got a new result:" << result.excerpt() << result.score();

        // for now we create the one dummy action: open the resource
        QString id;
        do {
            id = KRandom::randomString(5);
        } while(m_actionHash.contains(id));
        RecommendationAction action;
        action.id = id;
        action.text = i18n("Open '%1'", result.resource().genericLabel());
        m_actionHash[id] = action;
        m_RecommendationForAction[id] = r;

        r.actions << action;

        m_recommendations << r;
    }
}

void Contour::RecommendationManager::Private::_k_queryFinished()
{
    emit q->recommendationsChanged();
}

Contour::RecommendationManager::RecommendationManager(QObject *parent)
    : QObject(parent),
      d(new Private())
{
    d->q = this;

    connect(&d->m_queryClient, SIGNAL(newEntries(QList<Nepomuk::Query::Result>)),
            this, SLOT(_k_newResults(QList<Nepomuk::Query::Result>)));

    d->m_activityConsumer = new KActivityConsumer(this);
    connect(d->m_activityConsumer, SIGNAL(currentActivityChanged(QString)),
            this, SLOT(_k_currentActivityChanged(QString)));
    d->m_locationManager = new LocationManager(this);
    connect(d->m_locationManager, SIGNAL(locationChanged(QList<QLandmark>)),
            this, SLOT(_k_locationChanged(QList<QLandmark>)));
    d->updateRecommendations();

    // export via DBus
    qDBusRegisterMetaType<Contour::Recommendation>();
    qDBusRegisterMetaType<QList<Contour::Recommendation> >();
    qDBusRegisterMetaType<Contour::RecommendationAction>();
    (void)new RecommendationManagerAdaptor(this);
    QDBusConnection::sessionBus().registerObject(QLatin1String("/recommendationmanager"), this);
}

Contour::RecommendationManager::~RecommendationManager()
{
    delete d;
}

QList<Contour::Recommendation> Contour::RecommendationManager::recommendations() const
{
    return d->m_recommendations;
}

void Contour::RecommendationManager::executeAction(const QString &actionId)
{
    if(d->m_actionHash.contains(actionId)) {
        RecommendationAction action = d->m_actionHash.value(actionId);

        // FIXME: this is the hacky execution of the action, make it correct
        Recommendation r = d->m_RecommendationForAction.value(actionId);
        (void)new KRun(r.resourceUri, 0);
    }
    else {
        kDebug() << "Invalid action id encountered:" << actionId;
    }
}

#include "recommendationmanager.moc"
<commit_msg>Fixed query<commit_after>/*
   This file is part of the Nepomuk KDE project.
   Copyright (C) 2011 Sebastian Trueg <trueg@kde.org>

   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) version 3, or any
   later version accepted by the membership of KDE e.V. (or its
   successor approved by the membership of KDE e.V.), which shall
   act as a proxy defined in Section 6 of version 3 of the license.

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

#include "recommendationmanager.h"
#include "recommendationmanageradaptor.h"
#include "recommendation.h"
#include "recommendationaction.h"
#include "locationmanager.h"
#include "kext.h"

#include <kworkspace/kactivityinfo.h>
#include <kworkspace/kactivityconsumer.h>

#include <KRandom>
#include <KRun>
#include <KDebug>

#include <Nepomuk/Query/Query>
#include <Nepomuk/Query/QueryServiceClient>
#include <Nepomuk/Query/ComparisonTerm>
#include <Nepomuk/Query/LiteralTerm>
#include <Nepomuk/Query/AndTerm>
#include <Nepomuk/Query/QueryServiceClient>
#include <Nepomuk/Query/Result>
#include <Nepomuk/Resource>

#include <Soprano/Vocabulary/NAO>

#include <QtDBus/QDBusConnection>
#include <QtDBus/QDBusMetaType>

#include <QtLocation/QLandmark>

using namespace Soprano::Vocabulary;
using namespace Nepomuk::Vocabulary;

QTM_USE_NAMESPACE

//Q_DECLARE_METATYPE(Contour::Recommendation*)

// TODO: act on several changes:
//       * later: triggers from the dms

class Contour::RecommendationManager::Private
{
public:
    KActivityConsumer* m_activityConsumer;
    LocationManager* m_locationManager;

    QList<Recommendation> m_recommendations;
    QHash<QString, RecommendationAction> m_actionHash;
    QHash<QString, Recommendation> m_RecommendationForAction;

    Nepomuk::Query::QueryServiceClient m_queryClient;

    RecommendationManager* q;

    void updateRecommendations();
    void _k_locationChanged(const QList<QLandmark>&);
    void _k_currentActivityChanged(const QString&);
    void _k_newResults(const QList<Nepomuk::Query::Result>&);
    void _k_queryFinished();
};

void Contour::RecommendationManager::Private::updateRecommendations()
{
    // remove old recommendations
    m_recommendations.clear();
    m_actionHash.clear();
    m_RecommendationForAction.clear();

    // get resources that have been touched in the current activity (the dumb way for now)
    const QString query
            = QString::fromLatin1(
                "select distinct ?resource, "
                "    ( "
                "        ( "
                "            SUM ( "
                "                ?lastScore * bif:exp( "
                "                    - bif:datediff('day', ?lastUpdate, %1) "
                "                ) "
                "            ) "
                "        ) "
                "        as ?score "
                "    ) where { "
                "        ?cache kext:targettedResource ?resource . "
                "        ?cache a kext:ResourceScoreCache . "
                "        ?cache nao:lastModified ?lastUpdate . "
                "        ?cache kext:cachedScore ?lastScore . "
                "        ?cache kext:usedActivity %2 . "
                "    } "
                "    GROUP BY (?resource) "
                "    ORDER BY DESC (?score) "
                "    LIMIT 10 "
            ).arg(
                Soprano::Node::literalToN3(
                    QDateTime::currentDateTime()
                ),
                Soprano::Node::resourceToN3(
                    Nepomuk::Resource(m_activityConsumer->currentActivity(), KExt::Activity()).resourceUri()
                )
            );

    kDebug() << query;

    m_queryClient.sparqlQuery(query);

    // IDEA: for files use usage events
    //       for everything else use changes in data via graph metadata
}

void Contour::RecommendationManager::Private::_k_locationChanged(const QList<QLandmark>&)
{
    updateRecommendations();
}

void Contour::RecommendationManager::Private::_k_currentActivityChanged(const QString&)
{
    updateRecommendations();
}

void Contour::RecommendationManager::Private::_k_newResults(const QList<Nepomuk::Query::Result>& results)
{
    foreach(const Nepomuk::Query::Result& result, results) {
        Recommendation r;
        r.resourceUri = KUrl(result.resource().resourceUri()).url();

        kWarning() << "Got a new result:" << r.resourceUri << result.excerpt() << result.score();

        // for now we create the one dummy action: open the resource
        QString id;
        do {
            id = KRandom::randomString(5);
        } while(m_actionHash.contains(id));
        RecommendationAction action;
        action.id = id;
        action.text = i18n("Open '%1'", result.resource().genericLabel());
        m_actionHash[id] = action;
        m_RecommendationForAction[id] = r;

        r.actions << action;

        m_recommendations << r;
    }
}

void Contour::RecommendationManager::Private::_k_queryFinished()
{
    emit q->recommendationsChanged();
}

Contour::RecommendationManager::RecommendationManager(QObject *parent)
    : QObject(parent),
      d(new Private())
{
    d->q = this;

    connect(&d->m_queryClient, SIGNAL(newEntries(QList<Nepomuk::Query::Result>)),
            this, SLOT(_k_newResults(QList<Nepomuk::Query::Result>)));

    d->m_activityConsumer = new KActivityConsumer(this);
    connect(d->m_activityConsumer, SIGNAL(currentActivityChanged(QString)),
            this, SLOT(_k_currentActivityChanged(QString)));
    d->m_locationManager = new LocationManager(this);
    connect(d->m_locationManager, SIGNAL(locationChanged(QList<QLandmark>)),
            this, SLOT(_k_locationChanged(QList<QLandmark>)));
    d->updateRecommendations();

    // export via DBus
    qDBusRegisterMetaType<Contour::Recommendation>();
    qDBusRegisterMetaType<QList<Contour::Recommendation> >();
    qDBusRegisterMetaType<Contour::RecommendationAction>();
    (void)new RecommendationManagerAdaptor(this);
    QDBusConnection::sessionBus().registerObject(QLatin1String("/recommendationmanager"), this);
}

Contour::RecommendationManager::~RecommendationManager()
{
    delete d;
}

QList<Contour::Recommendation> Contour::RecommendationManager::recommendations() const
{
    return d->m_recommendations;
}

void Contour::RecommendationManager::executeAction(const QString &actionId)
{
    if(d->m_actionHash.contains(actionId)) {
        RecommendationAction action = d->m_actionHash.value(actionId);

        // FIXME: this is the hacky execution of the action, make it correct
        Recommendation r = d->m_RecommendationForAction.value(actionId);
        (void)new KRun(r.resourceUri, 0);
    }
    else {
        kDebug() << "Invalid action id encountered:" << actionId;
    }
}

#include "recommendationmanager.moc"
<|endoftext|>