<commit_before>/*************************************************************************
 *
 *  $RCSfile: TSkipDeletedSet.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: oj $ $Date: 2001-11-30 14:09:45 $
 *
 *  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_SKIPDELETEDSSET_HXX
#include "TSkipDeletedSet.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

using namespace connectivity;
// -----------------------------------------------------------------------------
OSkipDeletedSet::OSkipDeletedSet(IResultSetHelper* _pHelper)
    : m_pHelper(_pHelper)
{
}
// -----------------------------------------------------------------------------
sal_Bool OSkipDeletedSet::skipDeleted(IResultSetHelper::Movement _eCursorPosition, sal_Int32 _nOffset, sal_Bool _bRetrieveData)
{
    OSL_ENSURE(_eCursorPosition != IResultSetHelper::BOOKMARK,"OSkipDeletedSet::SkipDeleted can't be called for BOOKMARK");

    IResultSetHelper::Movement eDelPosition = _eCursorPosition;
    sal_Int32 nDelOffset = abs(_nOffset);

    switch (_eCursorPosition)
    {
        case IResultSetHelper::ABSOLUTE:
        case IResultSetHelper::FIRST:                   // set the movement when positioning failed
            eDelPosition = IResultSetHelper::NEXT;
            nDelOffset = 1;
            break;
        case IResultSetHelper::LAST:
            eDelPosition = IResultSetHelper::PRIOR; // lsat row is invalid so position before
            nDelOffset = 1;
            break;
        case IResultSetHelper::RELATIVE:
            eDelPosition = (_nOffset >= 0) ? IResultSetHelper::NEXT : IResultSetHelper::PRIOR;
            break;
    }

    sal_Int32 nNewOffset    = _nOffset;
    sal_Bool bDone          = sal_True;
    sal_Bool bDataFound     = sal_False;

    if (_eCursorPosition == IResultSetHelper::ABSOLUTE)
    {
        return moveAbsolute(_nOffset,_bRetrieveData);
    }
    else if (_eCursorPosition == IResultSetHelper::LAST)
    {
        sal_Int32 nBookmark = 0;
        sal_Int32 nCurPos = 1;
        // first position on the last known row
        if(m_aBookmarks.empty())
        {
            bDataFound = m_pHelper->move(IResultSetHelper::FIRST, 0, _bRetrieveData);
            if(bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()))
                m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first);
        }
        else
        {
            // I already have a bookmark so we can positioned on that and look if it is the last one
            nBookmark = (*m_aBookmarksPositions.rbegin())->first;

            bDataFound = m_pHelper->move(IResultSetHelper::BOOKMARK, nBookmark, _bRetrieveData);
            OSL_ENSURE((m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()),"A bookmark should not be deleted!");
            nCurPos    = (*m_aBookmarksPositions.rbegin())->second;
        }

        // and than move forward until we are after the last row
        while(bDataFound)
        {
            bDataFound = m_pHelper->move(IResultSetHelper::NEXT, 1, sal_False); // we don't need the data here
            if(bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()))
            {   // we weren't on the last row we remember it and move on
                ++nCurPos;
                m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first);
            }
            else if(!bDataFound && m_aBookmarks.size())
            {
                // i already know the last bookmark :-)
                // now we only have to repositioning us to the last row
                nBookmark = (*m_aBookmarksPositions.rbegin())->first;
                bDataFound = m_pHelper->move(IResultSetHelper::BOOKMARK, nBookmark, _bRetrieveData);
                break;
            }
        }
        return bDataFound;
    }
    else if (_eCursorPosition != IResultSetHelper::RELATIVE)
    {
        bDataFound = m_pHelper->move(_eCursorPosition, _nOffset, _bRetrieveData);
        bDone = bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted());
    }
    else
    {
        bDataFound = m_pHelper->move(eDelPosition, 1, _bRetrieveData);
        if (bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()))
        {
            m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first);
            bDone = (--nDelOffset) == 0;
        }
        else
            bDone = sal_False;
    }

    while (bDataFound && !bDone)            // solange iterieren bis man auf einem gltigen Satz ist
    {
        bDataFound = m_pHelper->move(eDelPosition, 1, _bRetrieveData);
        if (_eCursorPosition != IResultSetHelper::RELATIVE)
            bDone = bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted());
        else if (bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()))
        {
            m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first);
            bDone = (--nDelOffset) == 0;
        }
        else
            bDone = sal_False;
    }

    if(bDataFound && bDone)
    {
        sal_Int32 nDriverPos = m_pHelper->getDriverPos();
        if(m_aBookmarks.find(nDriverPos) == m_aBookmarks.end())
            m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(nDriverPos,m_aBookmarksPositions.size()+1)).first);
    }

    return bDataFound;
}
// -------------------------------------------------------------------------
sal_Bool OSkipDeletedSet::moveAbsolute(sal_Int32 _nOffset,sal_Bool _bRetrieveData)
{
    sal_Bool bDataFound = sal_False;
    sal_Int32 nNewOffset = _nOffset;
    if(nNewOffset > 0)
    {
        if((sal_Int32)m_aBookmarks.size() < nNewOffset)
        {
            // bookmark isn't known yet
            // start at the last position
            sal_Int32 nCurPos = 0,nLastBookmark = 1;
            IResultSetHelper::Movement eFilePos = IResultSetHelper::FIRST;
            if(!m_aBookmarks.empty())
            {
                nLastBookmark   = (*m_aBookmarksPositions.rbegin())->first;
                nCurPos         = (*m_aBookmarksPositions.rbegin())->second;
                nNewOffset      = nNewOffset - nCurPos;
                bDataFound      = m_pHelper->move(IResultSetHelper::BOOKMARK, nLastBookmark, _bRetrieveData);
            }
            else
            {
                bDataFound = m_pHelper->move(IResultSetHelper::FIRST, 0, _bRetrieveData );
                if(bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()))
                {
                    ++nCurPos;
                    m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first);
                    --nNewOffset;
                }
            }
            // now move to that row we need and don't count deleted rows
            while (bDataFound && nNewOffset)
            {
                bDataFound = m_pHelper->move(IResultSetHelper::NEXT, 1, _bRetrieveData);
                if(bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()))
                {
                    ++nCurPos;
                    m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first);
                    --nNewOffset;
                }
            }
        }
        else
        {
            sal_Int32 nBookmark = m_aBookmarksPositions[nNewOffset-1]->first;
            bDataFound = m_pHelper->move(IResultSetHelper::BOOKMARK,nBookmark, _bRetrieveData);
            OSL_ENSURE((m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()),"moveAbsolute: row can't be deleted!");
        }
    }
    else
    {
        ++nNewOffset;
        bDataFound = skipDeleted(IResultSetHelper::LAST,0,nNewOffset == 0);

        for(sal_Int32 i=nNewOffset+1;bDataFound && i <= 0;++i)
            bDataFound = skipDeleted(IResultSetHelper::PRIOR,1,i == 0);

    }
    return bDataFound;
}
// -----------------------------------------------------------------------------
void OSkipDeletedSet::clear()
{
    ::std::vector<TInt2IntMap::iterator>().swap(m_aBookmarksPositions);
    TInt2IntMap().swap(m_aBookmarks);
}
// -----------------------------------------------------------------------------
sal_Int32 OSkipDeletedSet::getMappedPosition(sal_Int32 _nPos) const
{
    TInt2IntMap::const_iterator aFind = m_aBookmarks.find(_nPos);
    OSL_ENSURE(aFind != m_aBookmarks.end(),"OSkipDeletedSet::getMappedPosition() invalid bookmark!");
    return aFind->second;
}
// -----------------------------------------------------------------------------
void OSkipDeletedSet::insertNewPosition(sal_Int32 _nPos)
{
    m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(_nPos,m_aBookmarksPositions.size()+1)).first);
}
// -----------------------------------------------------------------------------
void OSkipDeletedSet::deletePosition(sal_Int32 _nPos)
{
    TInt2IntMap::iterator aFind = m_aBookmarks.find(_nPos);
    OSL_ENSURE(aFind != m_aBookmarks.end(),"OSkipDeletedSet::deletePosition() bookmark not found!");
    TInt2IntMap::iterator aIter = aFind;
    ++aIter;
    for (; aIter != m_aBookmarks.end() ; ++aIter)
        --(aIter->second);
    m_aBookmarksPositions.erase(m_aBookmarksPositions.begin() + aFind->second-1);
    m_aBookmarks.erase(_nPos);
}
// -----------------------------------------------------------------------------
<commit_msg>#96476# insert assertion<commit_after>/*************************************************************************
 *
 *  $RCSfile: TSkipDeletedSet.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: oj $ $Date: 2002-10-08 13:40:38 $
 *
 *  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_SKIPDELETEDSSET_HXX
#include "TSkipDeletedSet.hxx"
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif

using namespace connectivity;
// -----------------------------------------------------------------------------
OSkipDeletedSet::OSkipDeletedSet(IResultSetHelper* _pHelper)
    : m_pHelper(_pHelper)
{
}
// -----------------------------------------------------------------------------
sal_Bool OSkipDeletedSet::skipDeleted(IResultSetHelper::Movement _eCursorPosition, sal_Int32 _nOffset, sal_Bool _bRetrieveData)
{
    OSL_ENSURE(_eCursorPosition != IResultSetHelper::BOOKMARK,"OSkipDeletedSet::SkipDeleted can't be called for BOOKMARK");

    IResultSetHelper::Movement eDelPosition = _eCursorPosition;
    sal_Int32 nDelOffset = abs(_nOffset);

    switch (_eCursorPosition)
    {
        case IResultSetHelper::ABSOLUTE:
        case IResultSetHelper::FIRST:                   // set the movement when positioning failed
            eDelPosition = IResultSetHelper::NEXT;
            nDelOffset = 1;
            break;
        case IResultSetHelper::LAST:
            eDelPosition = IResultSetHelper::PRIOR; // lsat row is invalid so position before
            nDelOffset = 1;
            break;
        case IResultSetHelper::RELATIVE:
            eDelPosition = (_nOffset >= 0) ? IResultSetHelper::NEXT : IResultSetHelper::PRIOR;
            break;
    }

    sal_Int32 nNewOffset    = _nOffset;
    sal_Bool bDone          = sal_True;
    sal_Bool bDataFound     = sal_False;

    if (_eCursorPosition == IResultSetHelper::ABSOLUTE)
    {
        return moveAbsolute(_nOffset,_bRetrieveData);
    }
    else if (_eCursorPosition == IResultSetHelper::LAST)
    {
        sal_Int32 nBookmark = 0;
        sal_Int32 nCurPos = 1;
        // first position on the last known row
        if(m_aBookmarks.empty())
        {
            bDataFound = m_pHelper->move(IResultSetHelper::FIRST, 0, _bRetrieveData);
            if(bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()))
                m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first);
        }
        else
        {
            // I already have a bookmark so we can positioned on that and look if it is the last one
            nBookmark = (*m_aBookmarksPositions.rbegin())->first;

            bDataFound = m_pHelper->move(IResultSetHelper::BOOKMARK, nBookmark, _bRetrieveData);
            OSL_ENSURE((m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()),"A bookmark should not be deleted!");
            nCurPos    = (*m_aBookmarksPositions.rbegin())->second;
        }

        // and than move forward until we are after the last row
        while(bDataFound)
        {
            bDataFound = m_pHelper->move(IResultSetHelper::NEXT, 1, sal_False); // we don't need the data here
            if(bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()))
            {   // we weren't on the last row we remember it and move on
                ++nCurPos;
                m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first);
            }
            else if(!bDataFound && m_aBookmarks.size())
            {
                // i already know the last bookmark :-)
                // now we only have to repositioning us to the last row
                nBookmark = (*m_aBookmarksPositions.rbegin())->first;
                bDataFound = m_pHelper->move(IResultSetHelper::BOOKMARK, nBookmark, _bRetrieveData);
                break;
            }
        }
        return bDataFound;
    }
    else if (_eCursorPosition != IResultSetHelper::RELATIVE)
    {
        bDataFound = m_pHelper->move(_eCursorPosition, _nOffset, _bRetrieveData);
        bDone = bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted());
    }
    else
    {
        bDataFound = m_pHelper->move(eDelPosition, 1, _bRetrieveData);
        if (bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()))
        {
            m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first);
            bDone = (--nDelOffset) == 0;
        }
        else
            bDone = sal_False;
    }

    while (bDataFound && !bDone)            // solange iterieren bis man auf einem gltigen Satz ist
    {
        bDataFound = m_pHelper->move(eDelPosition, 1, _bRetrieveData);
        if (_eCursorPosition != IResultSetHelper::RELATIVE)
            bDone = bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted());
        else if (bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()))
        {
            m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first);
            bDone = (--nDelOffset) == 0;
        }
        else
            bDone = sal_False;
    }

    if(bDataFound && bDone)
    {
        sal_Int32 nDriverPos = m_pHelper->getDriverPos();
        if(m_aBookmarks.find(nDriverPos) == m_aBookmarks.end())
            m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(nDriverPos,m_aBookmarksPositions.size()+1)).first);
    }

    return bDataFound;
}
// -------------------------------------------------------------------------
sal_Bool OSkipDeletedSet::moveAbsolute(sal_Int32 _nOffset,sal_Bool _bRetrieveData)
{
    sal_Bool bDataFound = sal_False;
    sal_Int32 nNewOffset = _nOffset;
    if(nNewOffset > 0)
    {
        if((sal_Int32)m_aBookmarks.size() < nNewOffset)
        {
            // bookmark isn't known yet
            // start at the last position
            sal_Int32 nCurPos = 0,nLastBookmark = 1;
            IResultSetHelper::Movement eFilePos = IResultSetHelper::FIRST;
            if(!m_aBookmarks.empty())
            {
                nLastBookmark   = (*m_aBookmarksPositions.rbegin())->first;
                nCurPos         = (*m_aBookmarksPositions.rbegin())->second;
                nNewOffset      = nNewOffset - nCurPos;
                bDataFound      = m_pHelper->move(IResultSetHelper::BOOKMARK, nLastBookmark, _bRetrieveData);
            }
            else
            {
                bDataFound = m_pHelper->move(IResultSetHelper::FIRST, 0, _bRetrieveData );
                if(bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()))
                {
                    ++nCurPos;
                    m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first);
                    --nNewOffset;
                }
            }
            // now move to that row we need and don't count deleted rows
            while (bDataFound && nNewOffset)
            {
                bDataFound = m_pHelper->move(IResultSetHelper::NEXT, 1, _bRetrieveData);
                if(bDataFound && (m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()))
                {
                    ++nCurPos;
                    m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(m_pHelper->getDriverPos(),m_aBookmarksPositions.size()+1)).first);
                    --nNewOffset;
                }
            }
        }
        else
        {
            sal_Int32 nBookmark = m_aBookmarksPositions[nNewOffset-1]->first;
            bDataFound = m_pHelper->move(IResultSetHelper::BOOKMARK,nBookmark, _bRetrieveData);
            OSL_ENSURE((m_pHelper->deletedVisible() || !m_pHelper->isRowDeleted()),"moveAbsolute: row can't be deleted!");
        }
    }
    else
    {
        ++nNewOffset;
        bDataFound = skipDeleted(IResultSetHelper::LAST,0,nNewOffset == 0);

        for(sal_Int32 i=nNewOffset+1;bDataFound && i <= 0;++i)
            bDataFound = skipDeleted(IResultSetHelper::PRIOR,1,i == 0);

    }
    return bDataFound;
}
// -----------------------------------------------------------------------------
void OSkipDeletedSet::clear()
{
    ::std::vector<TInt2IntMap::iterator>().swap(m_aBookmarksPositions);
    TInt2IntMap().swap(m_aBookmarks);
}
// -----------------------------------------------------------------------------
sal_Int32 OSkipDeletedSet::getMappedPosition(sal_Int32 _nPos) const
{
    TInt2IntMap::const_iterator aFind = m_aBookmarks.find(_nPos);
    OSL_ENSURE(aFind != m_aBookmarks.end(),"OSkipDeletedSet::getMappedPosition() invalid bookmark!");
    return aFind->second;
}
// -----------------------------------------------------------------------------
void OSkipDeletedSet::insertNewPosition(sal_Int32 _nPos)
{
    OSL_ENSURE(m_aBookmarks.find(_nPos) == m_aBookmarks.end(),"OSkipDeletedSet::insertNewPosition: Invalid position");
    m_aBookmarksPositions.push_back(m_aBookmarks.insert(TInt2IntMap::value_type(_nPos,m_aBookmarksPositions.size()+1)).first);
}
// -----------------------------------------------------------------------------
void OSkipDeletedSet::deletePosition(sal_Int32 _nPos)
{
    TInt2IntMap::iterator aFind = m_aBookmarks.find(_nPos);
    OSL_ENSURE(aFind != m_aBookmarks.end(),"OSkipDeletedSet::deletePosition() bookmark not found!");
    TInt2IntMap::iterator aIter = aFind;
    ++aIter;
    for (; aIter != m_aBookmarks.end() ; ++aIter)
        --(aIter->second);
    m_aBookmarksPositions.erase(m_aBookmarksPositions.begin() + aFind->second-1);
    m_aBookmarks.erase(_nPos);
}
// -----------------------------------------------------------------------------
<|endoftext|>


<commit_before>/***************************************************************************
                          main.cpp  -  description
                             -------------------
    begin                : Wed Dec 26 03:12:10 CLST 2001
    copyright            : (C) 2001 by Duncan Mac-Vicar Prett
    email                : duncan@kde.org
 ***************************************************************************/

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

#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>
#include "kopete.h"

static const char *description =
	I18N_NOOP("Kopete, the KDE Instant Messenger");

#define KOPETE_VERSION "0.4.1"

static KCmdLineOptions options[] =
{
  { 0, 0, 0 }
};

int main(int argc, char *argv[])
{
	KAboutData aboutData( "kopete", I18N_NOOP("Kopete"),
		KOPETE_VERSION, description, KAboutData::License_GPL,
		"(c) 2001,2002, Duncan Mac-Vicar Prett\n(c) 2002, The Kopete Development Team", "kopete-devel@kde.org", "http://kopete.kde.org");

	aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, core developer"), "duncan@kde.org", "http://www.mac-vicar.com" );
	aboutData.addAuthor ( "Nick Betcher", I18N_NOOP("Core developer, fastest plugin developer on earth."), "nbetcher@usinternet.com", "http://www.kdedevelopers.net" );
	aboutData.addAuthor ( "Ryan Cumming", I18N_NOOP("Core developer"), "bodnar42@phalynx.dhs.org" );
	aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Patches, bugfixes"), "klingens@kde.org" );
	aboutData.addAuthor ( "Richard Stellingwerff", I18N_NOOP("features and bugfixes"), "remenic@linuxfromscratch.org");
	aboutData.addAuthor ( "Daniel Stone", I18N_NOOP("Core developer, Jabber plugin"), "dstone@kde.org", "http://raging.dropbear.id.au/daniel/");
	aboutData.addAuthor ( "Andres Krapf", I18N_NOOP("random hacks and bugfixes"), "dae@chez.com" );

	aboutData.addCredit ( "Herwin Jan Steehouwer", I18N_NOOP("KxEngine ICQ code") );
	aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") );
	aboutData.addCredit ( "Neil Stevens", I18N_NOOP("TAim engine AIM code") );
	aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Psi Jabber code") );

	KCmdLineArgs::init( argc, argv, &aboutData );
	KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
	KUniqueApplication::addCmdLineOptions();

	Kopete kopete;
	kopete.exec();
}
<commit_msg><commit_after>/***************************************************************************
                          main.cpp  -  description
                             -------------------
    begin                : Wed Dec 26 03:12:10 CLST 2001
    copyright            : (C) 2001 by Duncan Mac-Vicar Prett
    email                : duncan@kde.org
 ***************************************************************************/

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

#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>
#include "kopete.h"

static const char *description =
	I18N_NOOP("Kopete, the KDE Instant Messenger");

#define KOPETE_VERSION "0.4.1"

static KCmdLineOptions options[] =
{
  { 0, 0, 0 }
};

int main(int argc, char *argv[])
{
	KAboutData aboutData( "kopete", I18N_NOOP("Kopete"),
		KOPETE_VERSION, description, KAboutData::License_GPL,
		"(c) 2001,2002, Duncan Mac-Vicar Prett\n(c) 2002, The Kopete Development Team", "kopete-devel@kde.org", "http://kopete.kde.org");

	aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Original author, core developer"), "duncan@kde.org", "http://www.mac-vicar.com" );
	aboutData.addAuthor ( "Nick Betcher", I18N_NOOP("Core developer, fastest plugin developer on earth."), "nbetcher@usinternet.com", "http://www.kdedevelopers.net" );
	aboutData.addAuthor ( "Ryan Cumming", I18N_NOOP("Core developer"), "bodnar42@phalynx.dhs.org" );
	aboutData.addAuthor ( "Martijn Klingens", I18N_NOOP("Core developer"), "klingens@kde.org" );
	aboutData.addAuthor ( "Richard Stellingwerff", I18N_NOOP("Developer"), "remenic@linuxfromscratch.org");
	aboutData.addAuthor ( "Daniel Stone", I18N_NOOP("Core developer, Jabber plugin"), "dstone@kde.org", "http://raging.dropbear.id.au/daniel/");
    aboutData.addAuthor ( "Hendrik vom Lehn", I18N_NOOP("Developer"), "hennevl@hennevl.de", "http://www.hennevl.de");
	aboutData.addAuthor ( "Andres Krapf", I18N_NOOP("Random hacks and bugfixes"), "dae@chez.com" );

	aboutData.addCredit ( "Herwin Jan Steehouwer", I18N_NOOP("KxEngine ICQ code") );
	aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") );
	aboutData.addCredit ( "Neil Stevens", I18N_NOOP("TAim engine AIM code") );
	aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Psi Jabber code") );

	KCmdLineArgs::init( argc, argv, &aboutData );
	KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
	KUniqueApplication::addCmdLineOptions();

	Kopete kopete;
	kopete.exec();
}
<|endoftext|>


<commit_before>// Copyright (C) 2019 Egor Pugin <egor.pugin@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <boost/algorithm/string.hpp>
#include <primitives/command.h>
#include <primitives/sw/main.h>
#include <primitives/sw/cl.h>
#include <primitives/sw/settings_program_name.h>

static cl::opt<path> git(cl::Positional, cl::Required);
static cl::opt<path> wdir(cl::Positional, cl::Required);
static cl::opt<path> outfn(cl::Positional, cl::Required);

int main(int argc, char *argv[]) {
    cl::ParseCommandLineOptions(argc, argv);
    String rev, status, time;

    {
        primitives::Command c;
        c.working_directory = wdir;
        c.arguments.push_back(git.u8string());
        c.arguments.push_back("rev-parse");
        c.arguments.push_back("HEAD");
        try {
            error_code ec;
            c.execute(ec);
            if (ec) {
                rev = "unknown";
            } else {
                rev = boost::trim_copy(c.out.text);
            }
        } catch (std::exception &) {
            rev = "unknown";
        }
    }

    {
        primitives::Command c;
        c.working_directory = wdir;
        c.arguments.push_back(git.u8string());
        c.arguments.push_back("status");
        c.arguments.push_back("--porcelain");
        c.arguments.push_back("-uno");
        error_code ec;
        c.execute(ec);
        if (ec)
        {
            status = "0";
        }
        else
        {
            status = boost::trim_copy(c.out.text);
            if (status.empty())
                status = "0";
            else
                status = std::to_string(split_lines(status).size());
        }
    }

    {
        time = std::to_string(std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()));
    }

    String t;
    t += "#define SW_GIT_REV \"" + rev + "\"\n";
    t += "#define SW_GIT_CHANGED_FILES " + status + "\n";
    t += "#define SW_BUILD_TIME_T " + time + "LL\n";

    write_file(outfn, t);

    return 0;
}
<commit_msg>Debug.<commit_after>// Copyright (C) 2019 Egor Pugin <egor.pugin@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <boost/algorithm/string.hpp>
#include <primitives/command.h>
#include <primitives/sw/main.h>
#include <primitives/sw/cl.h>
#include <primitives/sw/settings_program_name.h>

#include <iostream>

static cl::opt<path> git(cl::Positional, cl::Required);
static cl::opt<path> wdir(cl::Positional, cl::Required);
static cl::opt<path> outfn(cl::Positional, cl::Required);

int main(int argc, char *argv[]) {
    cl::ParseCommandLineOptions(argc, argv);
    String rev, status, time;

    {
        std::cerr << "1" << std::endl;
        primitives::Command c;
        c.working_directory = wdir;
        c.arguments.push_back(git.u8string());
        c.arguments.push_back("rev-parse");
        c.arguments.push_back("HEAD");
        std::cerr << "2" << std::endl;
        try {
        std::cerr << "3" << std::endl;
            error_code ec;
            c.execute(ec);
        std::cerr << "4" << std::endl;
            if (ec) {
        std::cerr << "5" << std::endl;
                rev = "unknown";
            } else {
        std::cerr << "6" << std::endl;
                rev = boost::trim_copy(c.out.text);
            }
        std::cerr << "7" << std::endl;
        } catch (...) {
        std::cerr << "8" << std::endl;
            rev = "unknown";
        }
        std::cerr << "9" << std::endl;
    }

    {
        primitives::Command c;
        c.working_directory = wdir;
        c.arguments.push_back(git.u8string());
        c.arguments.push_back("status");
        c.arguments.push_back("--porcelain");
        c.arguments.push_back("-uno");
        error_code ec;
        c.execute(ec);
        if (ec)
        {
            status = "0";
        }
        else
        {
            status = boost::trim_copy(c.out.text);
            if (status.empty())
                status = "0";
            else
                status = std::to_string(split_lines(status).size());
        }
    }

    {
        time = std::to_string(std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()));
    }

    String t;
    t += "#define SW_GIT_REV \"" + rev + "\"\n";
    t += "#define SW_GIT_CHANGED_FILES " + status + "\n";
    t += "#define SW_BUILD_TIME_T " + time + "LL\n";

    write_file(outfn, t);

    return 0;
}
<|endoftext|>


<commit_before>
// Qt include.
#include <QCoreApplication>
#include <QFileInfo>
#include <QFile>
#include <QTextStream>

// QtArg include.
#include <QtArg/Arg>
#include <QtArg/Help>
#include <QtArg/CmdLine>
#include <QtArg/Exceptions>

// QtConfFile include.
#include <QtConfFile/Utils>

// Generator include.
#include "generator.hpp"

//
// ForGeneration
//

//! Data uses to generate.
class ForGeneration {
public:
	ForGeneration()
	{
	}

	ForGeneration( const QString & inputFile, const QString & outputFile )
		:	m_inputFileName( inputFile )
		,	m_outputFileName( outputFile )
	{
	}

	~ForGeneration()
	{
	}

	ForGeneration( const ForGeneration & other )
		:	m_inputFileName( other.inputFile() )
		,	m_outputFileName( other.outputFile() )
	{
	}

	ForGeneration & operator = ( const ForGeneration & other )
	{
		if( this != &other )
		{
			m_inputFileName = other.inputFile();
			m_outputFileName = other.outputFile();
		}

		return *this;
	}

	//! \return Input file name.
	const QString & inputFile() const
	{
		return m_inputFileName;
	}

	//! \return Output file name.
	const QString & outputFile() const
	{
		return m_outputFileName;
	}

private:
	//! Input file name.
	QString m_inputFileName;
	//! Output file name.
	QString m_outputFileName;
}; // class ForGeneration

//
// parseCommandLineArguments
//

static inline ForGeneration parseCommandLineArguments( int argc, char ** argv )
{
	QtArg input( QLatin1Char( 'i' ), QLatin1String( "input" ),
		QLatin1String( "Input file name" ), true, true );
	QtArg output( QLatin1Char( 'o' ), QLatin1String( "output" ),
		QLatin1String( "Output file name" ), true, true );

	QtArgCmdLine cmd( argc, argv );

	QtArgHelp help( &cmd );
	help.printer()->setProgramDescription(
		QLatin1String( "C++ header generator for QtConfFile." ) );
	help.printer()->setExecutableName( QLatin1String( argv[ 0 ] ) );

	cmd.addArg( &input );
	cmd.addArg( &output );
	cmd.addArg( &help );

	cmd.parse();

	ForGeneration data( input.value().toString(),
		output.value().toString() );

	QTextStream stream( stdout );

	if( data.inputFile().isEmpty() )
	{
		stream << QLatin1String( "Please specify input file." );

		exit( 1 );
	}

	if( !QFileInfo( data.inputFile() ).exists() )
	{
		stream << QLatin1String( "Specified input file doesn't exist." );

		exit( 1 );
	}

	if( data.outputFile().isEmpty() )
	{
		stream << QLatin1String( "Please specify output file." );

		exit( 1 );
	}

	return data;
}

int main( int argc, char ** argv )
{
	ForGeneration data;

	try {
		data = parseCommandLineArguments( argc, argv );
	}
	catch( const QtArgHelpHasPrintedEx & x )
	{
		return 0;
	}
	catch( const QtArgBaseException & x )
	{
		QTextStream stream( stdout );

		stream << x.whatAsQString();

		return 1;
	}

	QtConfFile::Generator::Cfg::Model model;

	try {
		QtConfFile::Generator::Cfg::TagModel tag;

		QtConfFile::readQtConfFile( tag, data.inputFile(),
			QTextCodec::codecForName( "UTF-8" ) );

		model = tag.cfg();

		model.prepare();

		model.check();
	}
	catch( const QtConfFile::Exception & x )
	{
		QTextStream stream( stdout );

		stream << x.whatAsQString();

		return 1;
	}

	QFile output( data.outputFile() );

	if( output.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
	{
		QTextStream stream( &output );

		QtConfFile::Generator::CppGenerator gen( model );

		gen.generate( stream );

		output.close();

		return 0;
	}
	else
	{
		QTextStream stream( stdout );

		stream << QLatin1String( "Couldn't open output file for writting." );

		return 1;
	}
}
<commit_msg>Added line endings in generator console output.<commit_after>
// Qt include.
#include <QCoreApplication>
#include <QFileInfo>
#include <QFile>
#include <QTextStream>

// QtArg include.
#include <QtArg/Arg>
#include <QtArg/Help>
#include <QtArg/CmdLine>
#include <QtArg/Exceptions>

// QtConfFile include.
#include <QtConfFile/Utils>

// Generator include.
#include "generator.hpp"

//
// ForGeneration
//

//! Data uses to generate.
class ForGeneration {
public:
	ForGeneration()
	{
	}

	ForGeneration( const QString & inputFile, const QString & outputFile )
		:	m_inputFileName( inputFile )
		,	m_outputFileName( outputFile )
	{
	}

	~ForGeneration()
	{
	}

	ForGeneration( const ForGeneration & other )
		:	m_inputFileName( other.inputFile() )
		,	m_outputFileName( other.outputFile() )
	{
	}

	ForGeneration & operator = ( const ForGeneration & other )
	{
		if( this != &other )
		{
			m_inputFileName = other.inputFile();
			m_outputFileName = other.outputFile();
		}

		return *this;
	}

	//! \return Input file name.
	const QString & inputFile() const
	{
		return m_inputFileName;
	}

	//! \return Output file name.
	const QString & outputFile() const
	{
		return m_outputFileName;
	}

private:
	//! Input file name.
	QString m_inputFileName;
	//! Output file name.
	QString m_outputFileName;
}; // class ForGeneration

//
// parseCommandLineArguments
//

static inline ForGeneration parseCommandLineArguments( int argc, char ** argv )
{
	QtArg input( QLatin1Char( 'i' ), QLatin1String( "input" ),
		QLatin1String( "Input file name" ), true, true );
	QtArg output( QLatin1Char( 'o' ), QLatin1String( "output" ),
		QLatin1String( "Output file name" ), true, true );

	QtArgCmdLine cmd( argc, argv );

	QtArgHelp help( &cmd );
	help.printer()->setProgramDescription(
		QLatin1String( "C++ header generator for QtConfFile." ) );
	help.printer()->setExecutableName( QLatin1String( argv[ 0 ] ) );

	cmd.addArg( &input );
	cmd.addArg( &output );
	cmd.addArg( &help );

	cmd.parse();

	ForGeneration data( input.value().toString(),
		output.value().toString() );

	QTextStream stream( stdout );

	if( data.inputFile().isEmpty() )
	{
		stream << QLatin1String( "Please specify input file." ) << endl;

		exit( 1 );
	}

	if( !QFileInfo( data.inputFile() ).exists() )
	{
		stream << QLatin1String( "Specified input file doesn't exist." ) << endl;

		exit( 1 );
	}

	if( data.outputFile().isEmpty() )
	{
		stream << QLatin1String( "Please specify output file." ) << endl;

		exit( 1 );
	}

	return data;
}

int main( int argc, char ** argv )
{
	ForGeneration data;

	try {
		data = parseCommandLineArguments( argc, argv );
	}
	catch( const QtArgHelpHasPrintedEx & x )
	{
		return 0;
	}
	catch( const QtArgBaseException & x )
	{
		QTextStream stream( stdout );

		stream << x.whatAsQString() << endl;

		return 1;
	}

	QtConfFile::Generator::Cfg::Model model;

	try {
		QtConfFile::Generator::Cfg::TagModel tag;

		QtConfFile::readQtConfFile( tag, data.inputFile(),
			QTextCodec::codecForName( "UTF-8" ) );

		model = tag.cfg();

		model.prepare();

		model.check();
	}
	catch( const QtConfFile::Exception & x )
	{
		QTextStream stream( stdout );

		stream << x.whatAsQString() << endl;

		return 1;
	}

	QFile output( data.outputFile() );

	if( output.open( QIODevice::WriteOnly | QIODevice::Truncate ) )
	{
		QTextStream stream( &output );

		QtConfFile::Generator::CppGenerator gen( model );

		gen.generate( stream );

		output.close();

		return 0;
	}
	else
	{
		QTextStream stream( stdout );

		stream << QLatin1String( "Couldn't open output file for writting." )
			<< endl;

		return 1;
	}
}
<|endoftext|>


<commit_before>/*
    Kopete , The KDE Instant Messenger
    Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org>

    Viva Chile Mierda!
    Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile

    Kopete    (c) 2002-2005 by the Kopete developers  <kopete-devel@kde.org>

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

#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include "kopeteapplication.h"
#include <klocale.h>
#include "kopeteversion.h"

static const char description[] =
	I18N_NOOP( "Kopete, the KDE Instant Messenger" );

static KCmdLineOptions options[] =
{
	{ "noplugins",              I18N_NOOP( "Do not load plugins. This option overrides all other options." ), 0 },
	{ "noconnect",              I18N_NOOP( "Disable auto-connection" ), 0 },
	{ "autoconnect <accounts>", I18N_NOOP( "Auto-connect the specified accounts. Use a comma-separated list\n"
		"to auto-connect multiple accounts." ), 0 },
	{ "disable <plugins>",      I18N_NOOP( "Do not load the specified plugin. Use a comma-separated list\n"
		"to disable multiple plugins." ), 0 },
	{ "load-plugins <plugins>", I18N_NOOP( "Load only the specified plugins. Use a comma-separated list\n"
		"to load multiple plugins. This option has no effect when\n"
		"--noplugins is set and overrides all other plugin related\n"
		"command line options." ), 0 },
//	{ "url <url>",              I18N_NOOP( "Load the given Kopete URL" ), 0 },
//	{ "!+[plugin]",            I18N_NOOP( "Load specified plugins" ), 0 },
	{ "!+[URL]",                 I18N_NOOP("URLs to pass to kopete / emoticon themes to install"), 0},
	KCmdLineLastOption
};

int main( int argc, char *argv[] )
{
	KAboutData aboutData( "kopete", I18N_NOOP("Kopete"),
		KOPETE_VERSION_STRING, description, KAboutData::License_GPL,
		I18N_NOOP("(c) 2001-2004, Duncan Mac-Vicar Prett\n(c) 2002-2005, Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org");

	aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Developer and Project founder"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" );
	aboutData.addAuthor ( "Andre Duffeck", I18N_NOOP("Developer, Yahoo plugin maintainer"), "andre@duffeck.de" );
	aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@telenet.be" );
	aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Developer, Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk");
	aboutData.addAuthor ( "Cláudio da Silveira Pinheiro", I18N_NOOP("Developer, Video device support"), "taupter@gmail.com", "http://taupter.homelinux.org" );
	aboutData.addAuthor ( "Gregg Edghill", I18N_NOOP("Developer, MSN"), "gregg.edghill@gmail.com");
	aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Developer, Gadu plugin maintainer"), "gj@pointblue.com.pl" );
	aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Developer"), "jason@keirstead.org", "http://www.keirstead.org");
	aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Lead Developer, AIM and ICQ plugin maintainer"), "mattr@kde.org" );
	aboutData.addAuthor ( "Michel Hermier", I18N_NOOP("IRC plugin maintainer"), "michel.hermier@wanadoo.fr" );
	aboutData.addAuthor ( "Michaël Larouche", I18N_NOOP("Lead Developer"), "larouche@kde.org", "http://www.tehbisnatch.org/" );
	aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Lead Developer, MSN plugin maintainer"), "ogoffart @ kde.org");
	aboutData.addAuthor ( "Ollivier Lapeyre Johann", I18N_NOOP("Artist / Developer, Artwork maintainer"), "johann.ollivierlapeyre@gmail.com" );
	aboutData.addAuthor ( "Richard Smith", I18N_NOOP("Developer, UI maintainer"), "kde@metafoo.co.uk" );
	aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Developer, Jabber plugin maintainer"), "till@tantalo.net");
	aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Lead Developer, GroupWise maintainer"), "lists@stevello.free-online.co.uk" );
	aboutData.addAuthor ( "Rafael Fernández López", I18N_NOOP("Developer"), "ereslibre@gmail.com" );

	aboutData.addCredit ( "Vally8", I18N_NOOP("Konki style author"), "vally8@gmail.com", "http://vally8.free.fr/" );
	aboutData.addCredit ( "Tm_T", I18N_NOOP("Hacker style author"), "jussi.kekkonen@gmail.com");
	aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Kopete's icon author") );
	aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") );
	aboutData.addCredit ( "Jessica Hall", I18N_NOOP("Kopete Docugoddess, Bug and Patch Testing.") );
	aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Iris Jabber Backend Library") );
	aboutData.addCredit ( "Tom Linsky", I18N_NOOP("OscarSocket author"), "twl6@po.cwru.edu" );
	aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") );
    aboutData.addCredit ( "Chetan Reddy", I18N_NOOP("Former developer"), "chetan13@gmail.com" );
	aboutData.addCredit ( "Nick Betcher", I18N_NOOP("Former developer, project co-founder"), "nbetcher@kde.org");
	aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "ryan@kde.org" );
	aboutData.addCredit ( "Stefan Gehn", I18N_NOOP("Former developer"), "metz@gehn.net", "http://metz.gehn.net" );
	aboutData.addCredit ( "Martijn Klingens", I18N_NOOP("Former developer"), "klingens@kde.org" );
	aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former developer"), "dae@chez.com" );
	aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc bugfixes and enhancements"), "pfeiffer@kde.org" );
	aboutData.addCredit ( "Zack Rusin", I18N_NOOP("Former developer, original Gadu plugin author"), "zack@kde.org" );
	aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former developer"), "remenic@linuxfromscratch.org");
	aboutData.addCredit ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin author"), "daniel@fooishbar.org", "http://fooishbar.org");
	aboutData.addCredit ( "Chris TenHarmsel", I18N_NOOP("Former developer, Oscar plugin"), "tenharmsel@users.sourceforge.net");
	aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former developer"), "hennevl@hennevl.de", "http://www.hennevl.de");
	aboutData.addCredit ( "Gav Wood", I18N_NOOP("Former developer and WinPopup maintainer"), "gav@indigoarchive.net" );

	aboutData.setTranslator( ki18nc("NAME OF TRANSLATORS","Your names"),
		ki18nc("EMAIL OF TRANSLATORS","Your emails") );

	KCmdLineArgs::init( argc, argv, &aboutData );
	KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
	KUniqueApplication::addCmdLineOptions();

	KopeteApplication kopete;
//	new KIMIfaceImpl();
//	kapp->dcopClient()->registerAs( "kopete", false );
//	kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec

	return kopete.exec();
}
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>Update my status in Kopete<commit_after>/*
    Kopete , The KDE Instant Messenger
    Copyright (c) 2001-2002 by Duncan Mac-Vicar Prett <duncan@kde.org>

    Viva Chile Mierda!
    Started at Wed Dec 26 03:12:10 CLST 2001, Santiago de Chile

    Kopete    (c) 2002-2005 by the Kopete developers  <kopete-devel@kde.org>

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

#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include "kopeteapplication.h"
#include <klocale.h>
#include "kopeteversion.h"

static const char description[] =
	I18N_NOOP( "Kopete, the KDE Instant Messenger" );

static KCmdLineOptions options[] =
{
	{ "noplugins",              I18N_NOOP( "Do not load plugins. This option overrides all other options." ), 0 },
	{ "noconnect",              I18N_NOOP( "Disable auto-connection" ), 0 },
	{ "autoconnect <accounts>", I18N_NOOP( "Auto-connect the specified accounts. Use a comma-separated list\n"
		"to auto-connect multiple accounts." ), 0 },
	{ "disable <plugins>",      I18N_NOOP( "Do not load the specified plugin. Use a comma-separated list\n"
		"to disable multiple plugins." ), 0 },
	{ "load-plugins <plugins>", I18N_NOOP( "Load only the specified plugins. Use a comma-separated list\n"
		"to load multiple plugins. This option has no effect when\n"
		"--noplugins is set and overrides all other plugin related\n"
		"command line options." ), 0 },
//	{ "url <url>",              I18N_NOOP( "Load the given Kopete URL" ), 0 },
//	{ "!+[plugin]",            I18N_NOOP( "Load specified plugins" ), 0 },
	{ "!+[URL]",                 I18N_NOOP("URLs to pass to kopete / emoticon themes to install"), 0},
	KCmdLineLastOption
};

int main( int argc, char *argv[] )
{
	KAboutData aboutData( "kopete", I18N_NOOP("Kopete"),
		KOPETE_VERSION_STRING, description, KAboutData::License_GPL,
		I18N_NOOP("(c) 2001-2004, Duncan Mac-Vicar Prett\n(c) 2002-2005, Kopete Development Team"), "kopete-devel@kde.org", "http://kopete.kde.org");

	aboutData.addAuthor ( "Duncan Mac-Vicar Prett", I18N_NOOP("Developer and Project founder"), "duncan@kde.org", "http://www.mac-vicar.org/~duncan" );
	aboutData.addAuthor ( "Andre Duffeck", I18N_NOOP("Developer, Yahoo plugin maintainer"), "andre@duffeck.de" );
	aboutData.addAuthor ( "Andy Goossens", I18N_NOOP("Developer"), "andygoossens@telenet.be" );
	aboutData.addAuthor ( "Chris Howells", I18N_NOOP("Developer, Connection status plugin author"), "howells@kde.org", "http://chrishowells.co.uk");
	aboutData.addAuthor ( "Cláudio da Silveira Pinheiro", I18N_NOOP("Developer, Video device support"), "taupter@gmail.com", "http://taupter.homelinux.org" );
	aboutData.addAuthor ( "Gregg Edghill", I18N_NOOP("Developer, MSN"), "gregg.edghill@gmail.com");
	aboutData.addAuthor ( "Grzegorz Jaskiewicz", I18N_NOOP("Developer, Gadu plugin maintainer"), "gj@pointblue.com.pl" );
	aboutData.addAuthor ( "Jason Keirstead", I18N_NOOP("Developer"), "jason@keirstead.org", "http://www.keirstead.org");
	aboutData.addAuthor ( "Matt Rogers", I18N_NOOP("Lead Developer, AIM and ICQ plugin maintainer"), "mattr@kde.org" );
	aboutData.addAuthor ( "Michel Hermier", I18N_NOOP("IRC plugin maintainer"), "michel.hermier@wanadoo.fr" );
	aboutData.addAuthor ( "Michaël Larouche", I18N_NOOP("Lead Developer, Telepathy and Messenger plugin maintainer"), "larouche@kde.org", "http://www.tehbisnatch.org/" );
	aboutData.addAuthor ( "Olivier Goffart", I18N_NOOP("Lead Developer, MSN plugin maintainer"), "ogoffart @ kde.org");
	aboutData.addAuthor ( "Ollivier Lapeyre Johann", I18N_NOOP("Artist / Developer, Artwork maintainer"), "johann.ollivierlapeyre@gmail.com" );
	aboutData.addAuthor ( "Richard Smith", I18N_NOOP("Developer, UI maintainer"), "kde@metafoo.co.uk" );
	aboutData.addAuthor ( "Till Gerken", I18N_NOOP("Developer, Jabber plugin maintainer"), "till@tantalo.net");
	aboutData.addAuthor ( "Will Stephenson", I18N_NOOP("Lead Developer, GroupWise maintainer"), "lists@stevello.free-online.co.uk" );
	aboutData.addAuthor ( "Rafael Fernández López", I18N_NOOP("Developer"), "ereslibre@gmail.com" );

	aboutData.addCredit ( "Vally8", I18N_NOOP("Konki style author"), "vally8@gmail.com", "http://vally8.free.fr/" );
	aboutData.addCredit ( "Tm_T", I18N_NOOP("Hacker style author"), "jussi.kekkonen@gmail.com");
	aboutData.addCredit ( "Luciash d' Being", I18N_NOOP("Kopete's icon author") );
	aboutData.addCredit ( "Steve Cable", I18N_NOOP("Sounds") );
	aboutData.addCredit ( "Jessica Hall", I18N_NOOP("Kopete Docugoddess, Bug and Patch Testing.") );
	aboutData.addCredit ( "Justin Karneges", I18N_NOOP("Iris Jabber Backend Library") );
	aboutData.addCredit ( "Tom Linsky", I18N_NOOP("OscarSocket author"), "twl6@po.cwru.edu" );
	aboutData.addCredit ( "Olaf Lueg", I18N_NOOP("Kmerlin MSN code") );
    aboutData.addCredit ( "Chetan Reddy", I18N_NOOP("Former developer"), "chetan13@gmail.com" );
	aboutData.addCredit ( "Nick Betcher", I18N_NOOP("Former developer, project co-founder"), "nbetcher@kde.org");
	aboutData.addCredit ( "Ryan Cumming", I18N_NOOP("Former developer"), "ryan@kde.org" );
	aboutData.addCredit ( "Stefan Gehn", I18N_NOOP("Former developer"), "metz@gehn.net", "http://metz.gehn.net" );
	aboutData.addCredit ( "Martijn Klingens", I18N_NOOP("Former developer"), "klingens@kde.org" );
	aboutData.addCredit ( "Andres Krapf", I18N_NOOP("Former developer"), "dae@chez.com" );
	aboutData.addCredit ( "Carsten Pfeiffer", I18N_NOOP("Misc bugfixes and enhancements"), "pfeiffer@kde.org" );
	aboutData.addCredit ( "Zack Rusin", I18N_NOOP("Former developer, original Gadu plugin author"), "zack@kde.org" );
	aboutData.addCredit ( "Richard Stellingwerff", I18N_NOOP("Former developer"), "remenic@linuxfromscratch.org");
	aboutData.addCredit ( "Daniel Stone", I18N_NOOP("Former developer, Jabber plugin author"), "daniel@fooishbar.org", "http://fooishbar.org");
	aboutData.addCredit ( "Chris TenHarmsel", I18N_NOOP("Former developer, Oscar plugin"), "tenharmsel@users.sourceforge.net");
	aboutData.addCredit ( "Hendrik vom Lehn", I18N_NOOP("Former developer"), "hennevl@hennevl.de", "http://www.hennevl.de");
	aboutData.addCredit ( "Gav Wood", I18N_NOOP("Former developer and WinPopup maintainer"), "gav@indigoarchive.net" );

	aboutData.setTranslator( ki18nc("NAME OF TRANSLATORS","Your names"),
		ki18nc("EMAIL OF TRANSLATORS","Your emails") );

	KCmdLineArgs::init( argc, argv, &aboutData );
	KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
	KUniqueApplication::addCmdLineOptions();

	KopeteApplication kopete;
//	new KIMIfaceImpl();
//	kapp->dcopClient()->registerAs( "kopete", false );
//	kapp->dcopClient()->setDefaultObject( (new KopeteIface())->objId() ); // Has to be called before exec

	return kopete.exec();
}
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|>


<commit_before>#include "ignnetwork.h"

ignnetwork::ignnetwork(QObject *parent):
    QObject(parent)
{
}

QString ignnetwork::myIP(){
    QString host;
    Q_FOREACH(QHostAddress address, QNetworkInterface::allAddresses()) {
      if (!address.isLoopback() && (address.protocol() == QAbstractSocket::IPv4Protocol)) {
         host = address.toString();
         break;
       }
    }

    if(host.isEmpty()){
        return "IP not found";
    }
    else{
        return host;
    }
}

void ignnetwork::setProxy(const QVariant &config){
    /* json parsing */
    QJsonParseError *err = new QJsonParseError();
    QJsonDocument json = QJsonDocument::fromVariant(config);

    if (err->error != 0) {
      qDebug() << err->errorString();
      exit (1);
    }

    QJsonObject jObject = json.object();
    QVariantMap set_proxy = jObject.toVariantMap();

    if(set_proxy["type"].toString() != ""){
        QNetworkProxy proxy;
        QString proxy_type = set_proxy["type"].toString();
        if(proxy_type == "http"){
            proxy.setType(QNetworkProxy::HttpProxy);
        }
        else if(proxy_type == "socks5"){
            proxy.setType(QNetworkProxy::Socks5Proxy);
        }
        else if(proxy_type == "ftp"){
            proxy.setType(QNetworkProxy::FtpCachingProxy);
        }
        else if(proxy_type == "httpCaching"){
            proxy.setType(QNetworkProxy::HttpCachingProxy);
        }
        else{
            qDebug()<<"Please input your type proxy (http,socks5,ftp,httpCaching)!";
        }

        if(set_proxy["url"].toString() != ""){
            QString url = set_proxy["url"].toString();
            QStringList url_proxy = url.split(":");
            proxy.setHostName(url_proxy.at(0));
            proxy.setPort(url_proxy.at(1).toInt());
        }
        else{
            qDebug()<<"Please input your hostname:port Ex: 127.0.0.1:8080!";
        }

        if(set_proxy["username"].toString() != ""){
            proxy.setUser(set_proxy["username"].toString());
        }

        if(set_proxy["password"].toString() != ""){
            proxy.setPassword(set_proxy["password"].toString());
        }

        QNetworkProxy::setApplicationProxy(proxy);
    }
}
<commit_msg>ignnetwork.cpp: Fix typography<commit_after>#include "ignnetwork.h"

ignnetwork::ignnetwork(QObject *parent):
    QObject(parent)
{
}

QString ignnetwork::myIP(){
    QString host;
    Q_FOREACH(QHostAddress address, QNetworkInterface::allAddresses()) {
      if (!address.isLoopback() && (address.protocol() == QAbstractSocket::IPv4Protocol)) {
         host = address.toString();
         break;
       }
    }

    if(host.isEmpty()){
        return "IP not found";
    }
    else{
        return host;
    }
}

void ignnetwork::setProxy(const QVariant &config){
    /* json parsing */
    QJsonParseError *err = new QJsonParseError();
    QJsonDocument json = QJsonDocument::fromVariant(config);

    if (err->error != 0) {
      qDebug() << err->errorString();
      exit (1);
    }

    QJsonObject jObject = json.object();
    QVariantMap set_proxy = jObject.toVariantMap();

    if(set_proxy["type"].toString() != ""){
        QNetworkProxy proxy;
        QString proxy_type = set_proxy["type"].toString();
        if(proxy_type == "http"){
            proxy.setType(QNetworkProxy::HttpProxy);
        }
        else if(proxy_type == "socks5"){
            proxy.setType(QNetworkProxy::Socks5Proxy);
        }
        else if(proxy_type == "ftp"){
            proxy.setType(QNetworkProxy::FtpCachingProxy);
        }
        else if(proxy_type == "httpCaching"){
            proxy.setType(QNetworkProxy::HttpCachingProxy);
        }
        else{
            qDebug()<<"Proxy type is not specified. Available options: http, socks5, ftp, httpCaching.";
        }

        if(set_proxy["url"].toString() != ""){
            QString url = set_proxy["url"].toString();
            QStringList url_proxy = url.split(":");
            proxy.setHostName(url_proxy.at(0));
            proxy.setPort(url_proxy.at(1).toInt());
        }
        else{
            qDebug()<<"Proxy address is not specified.";
        }

        if(set_proxy["username"].toString() != ""){
            proxy.setUser(set_proxy["username"].toString());
        }

        if(set_proxy["password"].toString() != ""){
            proxy.setPassword(set_proxy["password"].toString());
        }

        QNetworkProxy::setApplicationProxy(proxy);
    }
}
<|endoftext|>


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

#include <gtest/gtest.h>
#include <repo/core/handler/fileservice/repo_file_handler_gridfs.h>
#include <repo/core/model/bson/repo_node.h>
#include <repo/lib/repo_exception.h>
#include <repo/lib/repo_utils.h>
#include "../../../../repo_test_database_info.h"

using namespace repo::core::handler::fileservice;

TEST(GridFSFileHandlerTest, Constructor)
{

	EXPECT_NO_THROW({
		auto fileHandler = GridFSFileHandler(getHandler());
	});
	EXPECT_THROW(GridFSFileHandler(nullptr), repo::lib::RepoException);
}

GridFSFileHandler getGridFSHandler()
{
	auto dbHandler = getHandler();
	return GridFSFileHandler(dbHandler);
}
//
//TEST(GridFSFileHandlerTest, deleteFile)
//{
//	auto handler = createHandler();
//	auto pathToFile = getDataPath("fileShare/deleteTest");
//	ASSERT_TRUE(repo::lib::doesFileExist(pathToFile));
//	EXPECT_TRUE(handler.deleteFile("a", "b", "deleteTest"));
//	EXPECT_FALSE(repo::lib::doesFileExist(pathToFile));
//	EXPECT_FALSE(handler.deleteFile("a", "b", "ThisFileDoesNotExist"));
//
//}
//
TEST(GridFSFileHandlerTest, writeFile)
{
	auto handler = getGridFSHandler();
	std::vector<uint8_t> buffer;
	buffer.resize(1024);
	std::string fName = "gridFSFile";
	auto linker = handler.uploadFile("testFileManager", "testFileUpload", fName, buffer);
	EXPECT_EQ(fName, linker);

}
<commit_msg>ISSUE #320 more gridFS test<commit_after>/**
*  Copyright (C) 2019 3D Repo Ltd
*
*  This program is free software: you can redistribute it and/or modify
*  it under the terms of the GNU Affero General Public License as
*  published by the Free Software Foundation, either version 3 of the
*  License, or (at your option) any later version.
*
*  This program is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU Affero General Public License for more details.
*
*  You should have received a copy of the GNU Affero General Public License
*  along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <gtest/gtest.h>
#include <repo/core/handler/fileservice/repo_file_handler_gridfs.h>
#include <repo/core/model/bson/repo_node.h>
#include <repo/lib/repo_exception.h>
#include <repo/lib/repo_utils.h>
#include "../../../../repo_test_database_info.h"

using namespace repo::core::handler::fileservice;

TEST(GridFSFileHandlerTest, Constructor)
{

	EXPECT_NO_THROW({
		auto fileHandler = GridFSFileHandler(getHandler());
	});
	EXPECT_THROW(GridFSFileHandler(nullptr), repo::lib::RepoException);
}

GridFSFileHandler getGridFSHandler()
{
	auto dbHandler = getHandler();
	return GridFSFileHandler(dbHandler);
}

TEST(GridFSFileHandlerTest, deleteFile)
{
	auto handler = getGridFSHandler();
	auto dbHandler = getHandler();
	std::string db = "testFileManager";
	std::string col = "testFileUpload";
	std::string fName = "gridFSFile";

	ASSERT_TRUE(dbHandler->getRawFile(db, col, fName).size() > 0);
	EXPECT_TRUE(handler.deleteFile(db, col, fName));
	EXPECT_EQ(dbHandler->getRawFile(db, col, fName).size(), 0);

}

TEST(GridFSFileHandlerTest, writeFile)
{
	auto handler = getGridFSHandler();
	std::vector<uint8_t> buffer;
	uint32_t fSize = 1024;
	buffer.resize(fSize);
	std::string db = "testFileManager";
	std::string col = "testFileUpload";
	std::string fName = "testFileWrite";
	auto linker = handler.uploadFile(db, col, fName, buffer);
	EXPECT_EQ(fName, linker);
	auto dbHandler = getHandler();

	EXPECT_EQ(dbHandler->getRawFile(db, col, fName).size(), fSize);
}
<|endoftext|>


<commit_before>/*
    This file is part of Magnum.

    Original authors — credit is appreciated but not required:

        2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021
             — Vladimír Vondruš <mosra@centrum.cz>
        2021 — Pablo Escobar <mail@rvrs.in>

    This is free and unencumbered software released into the public domain.

    Anyone is free to copy, modify, publish, use, compile, sell, or distribute
    this software, either in source code form or as a compiled binary, for any
    purpose, commercial or non-commercial, and by any means.

    In jurisdictions that recognize copyright laws, the author or authors of
    this software dedicate any and all copyright interest in the software to
    the public domain. We make this dedication for the benefit of the public
    at large and to the detriment of our heirs and successors. We intend this
    dedication to be an overt act of relinquishment in perpetuity of all
    present and future rights to this software under copyright law.

    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 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 <Corrade/Containers/Array.h>
#include <Corrade/Containers/StringView.h>
#include <Corrade/Utility/Assert.h>
#include <Corrade/PluginManager/Manager.h>
#include <Magnum/Magnum.h>
#include <Magnum/Mesh.h>
#include <Magnum/ImageView.h>
#include <Magnum/PixelFormat.h>
#include <Magnum/VertexFormat.h>
#include <Magnum/Math/Color.h>
#include <Magnum/Math/Range.h>
#include <Magnum/ShaderTools/AbstractConverter.h>
#include <Magnum/Trade/AbstractImageConverter.h>
#include <Magnum/Vk/Assert.h>
#include <Magnum/Vk/BufferCreateInfo.h>
#include <Magnum/Vk/CommandBuffer.h>
#include <Magnum/Vk/CommandPoolCreateInfo.h>
#include <Magnum/Vk/DeviceCreateInfo.h>
#include <Magnum/Vk/DeviceProperties.h>
#include <Magnum/Vk/Fence.h>
#include <Magnum/Vk/FramebufferCreateInfo.h>
#include <Magnum/Vk/ImageCreateInfo.h>
#include <Magnum/Vk/ImageViewCreateInfo.h>
#include <Magnum/Vk/InstanceCreateInfo.h>
#include <Magnum/Vk/Memory.h>
#include <Magnum/Vk/Mesh.h>
#include <Magnum/Vk/Pipeline.h>
#include <Magnum/Vk/PipelineLayoutCreateInfo.h>
#include <Magnum/Vk/Queue.h>
#include <Magnum/Vk/RasterizationPipelineCreateInfo.h>
#include <Magnum/Vk/RenderPassCreateInfo.h>
#include <Magnum/Vk/ShaderCreateInfo.h>
#include <Magnum/Vk/ShaderSet.h>

using namespace Corrade::Containers::Literals;
using namespace Magnum;
using namespace Magnum::Math::Literals;

int main(int argc, char** argv) {
    /* Create an instance */
    Vk::Instance instance{Vk::InstanceCreateInfo{argc, argv}
        .setApplicationInfo("Magnum Vulkan Triangle Example"_s, {})
    };

    /* Create a device with a graphics queue */
    Vk::Queue queue{NoCreate};
    Vk::Device device{instance, Vk::DeviceCreateInfo{Vk::pickDevice(instance)}
        .addQueues(Vk::QueueFlag::Graphics, {0.0f}, {queue})
    };

    /* Allocate a command buffer */
    Vk::CommandPool commandPool{device, Vk::CommandPoolCreateInfo{
        device.properties().pickQueueFamily(Vk::QueueFlag::Graphics)
    }};
    Vk::CommandBuffer cmd = commandPool.allocate();

    /* Render pass. We'll want to transfer the image back to the host though a
       buffer once done, so additionally set up a corresponding final image
       layout and a dependency that performs the layout transition before we
       execute the copy command. */
    Vk::RenderPass renderPass{device, Vk::RenderPassCreateInfo{}
        .setAttachments({
            Vk::AttachmentDescription{PixelFormat::RGBA8Srgb,
                Vk::AttachmentLoadOperation::Clear,
                Vk::AttachmentStoreOperation::Store,
                Vk::ImageLayout::Undefined,
                Vk::ImageLayout::TransferSource
            }
        })
        .addSubpass(Vk::SubpassDescription{}
            .setColorAttachments({
                Vk::AttachmentReference{0, Vk::ImageLayout::ColorAttachment}
            })
        )
        .setDependencies({
            Vk::SubpassDependency{
                /* An operation external to the render pass depends on the
                   first subpass */
                0, Vk::SubpassDependency::External,
                /* where transfer gets executed only after color output is
                   done */
                Vk::PipelineStage::ColorAttachmentOutput,
                Vk::PipelineStage::Transfer,
                /* and color data written are available for the transfer to
                   read */
                Vk::Access::ColorAttachmentWrite,
                Vk::Access::TransferRead
            }
        })
    };

    /* Framebuffer image. It doesn't need to be host-visible, however we'll
       copy it to the host through a buffer so enable corresponding usage. */
    Vk::Image image{device, Vk::ImageCreateInfo2D{
        Vk::ImageUsage::ColorAttachment|Vk::ImageUsage::TransferSource,
        PixelFormat::RGBA8Srgb, {800, 600}, 1
    }, Vk::MemoryFlag::DeviceLocal};

    /* Create the triangle mesh */
    Vk::Mesh mesh{Vk::MeshLayout{MeshPrimitive::Triangles}
        .addBinding(0, 2*4*4)
        .addAttribute(0, 0, VertexFormat::Vector4, 0)
        .addAttribute(1, 0, VertexFormat::Vector4, 4*4)
    };
    {
        Vk::Buffer buffer{device, Vk::BufferCreateInfo{
            Vk::BufferUsage::VertexBuffer,
            3*2*4*4 /* Three vertices, each is four-element pos & color */
        }, Vk::MemoryFlag::HostVisible};

        /** @todo arrayCast for an array rvalue */
        Containers::Array<char, Vk::MemoryMapDeleter> data = buffer.dedicatedMemory().map();
        auto view = Containers::arrayCast<Vector4>(data);
        view[0] = {-0.5f, -0.5f, 0.0f, 1.0f}; /* Left vertex, red color */
        view[1] = 0xff0000ff_srgbaf;
        view[2] = { 0.5f, -0.5f, 0.0f, 1.0f}; /* Right vertex, green color */
        view[3] = 0x00ff00ff_srgbaf;
        view[4] = { 0.0f,  0.5f, 0.0f, 1.0f}; /* Top vertex, blue color */
        view[5] = 0x0000ffff_srgbaf;

        mesh.addVertexBuffer(0, std::move(buffer), 0)
            .setCount(3);
    }

    /* Buffer to which the rendered image gets linearized */
    Vk::Buffer pixels{device, Vk::BufferCreateInfo{
        Vk::BufferUsage::TransferDestination, 800*600*4
    }, Vk::MemoryFlag::HostVisible};

    /* Framebuffer */
    Vk::ImageView color{device, Vk::ImageViewCreateInfo2D{image}};
    Vk::Framebuffer framebuffer{device, Vk::FramebufferCreateInfo{renderPass, {
        color
    }, {800, 600}}};

    /* Create the shader */
    constexpr Containers::StringView assembly = R"(
               OpCapability Shader
               OpMemoryModel Logical GLSL450

; Function %1 is vertex shader and has %12, %13 as input and %15, %16 as output
               OpEntryPoint Vertex %1 "ver" %12 %13 %gl_Position %16
; Function %2 is fragment shader and has %5 as input and %6 as output
               OpEntryPoint Fragment %2 "fra" %5 %6
               OpExecutionMode %2 OriginUpperLeft

; Input/output layouts
               OpDecorate %12 Location 0
               OpDecorate %13 Location 1
               OpDecorate %gl_Position BuiltIn Position
               OpDecorate %16 Location 0
               OpDecorate %5 Location 0
               OpDecorate %6 Location 0

; Types
       %void = OpTypeVoid
          %8 = OpTypeFunction %void
      %float = OpTypeFloat 32
    %v4float = OpTypeVector %float 4
%_ptr_Input_v4float = OpTypePointer Input %v4float
         %12 = OpVariable %_ptr_Input_v4float Input
         %13 = OpVariable %_ptr_Input_v4float Input
%_ptr_Output_v4float = OpTypePointer Output %v4float
%gl_Position = OpVariable %_ptr_Output_v4float Output
         %16 = OpVariable %_ptr_Output_v4float Output
          %5 = OpVariable %_ptr_Input_v4float Input
          %6 = OpVariable %_ptr_Output_v4float Output

; %1 = void ver()
          %1 = OpFunction %void None %8
         %33 = OpLabel
         %30 = OpLoad %v4float %12
         %31 = OpLoad %v4float %13
               OpStore %gl_Position %30
               OpStore %16 %31
               OpReturn
               OpFunctionEnd

; %2 = void fra()
          %2 = OpFunction %void None %8
         %34 = OpLabel
         %32 = OpLoad %v4float %5
               OpStore %6 %32
               OpReturn
               OpFunctionEnd
)"_s;
    Vk::Shader shader{device, Vk::ShaderCreateInfo{
        CORRADE_INTERNAL_ASSERT_EXPRESSION(CORRADE_INTERNAL_ASSERT_EXPRESSION(
            PluginManager::Manager<ShaderTools::AbstractConverter>{}
                .loadAndInstantiate("SpirvAssemblyToSpirvShaderConverter")
        )->convertDataToData({}, assembly))}};

    /* Create a graphics pipeline */
    Vk::ShaderSet shaderSet;
    shaderSet
        .addShader(Vk::ShaderStage::Vertex, shader, "ver"_s)
        .addShader(Vk::ShaderStage::Fragment, shader, "fra"_s);
    Vk::PipelineLayout pipelineLayout{device, Vk::PipelineLayoutCreateInfo{}};
    Vk::Pipeline pipeline{device, Vk::RasterizationPipelineCreateInfo{shaderSet, mesh.layout(), pipelineLayout, renderPass, 0, 1}
        .setViewport({{}, {800.0f, 600.0f}})
    };

    /* Record the command buffer:
        - render pass being converts the framebuffer attachment from Undefined
          to ColorAttachment and clears it
        - the pipeline barrier is needed in order to make the image data copied
          to the buffer visible in time for the host read happening below */
    cmd.begin()
       .beginRenderPass(Vk::RenderPassBeginInfo{renderPass, framebuffer}
           .clearColor(0, 0x1f1f1f_srgbf)
        )
       .bindPipeline(pipeline)
       .draw(mesh)
       .endRenderPass()
       .copyImageToBuffer({image, Vk::ImageLayout::TransferSource, pixels, {
            Vk::BufferImageCopy2D{0, Vk::ImageAspect::Color, 0, {{}, {800, 600}}}
        }})
       .pipelineBarrier(Vk::PipelineStage::Transfer, Vk::PipelineStage::Host, {
            {Vk::Access::TransferWrite, Vk::Access::HostRead, pixels}
        })
       .end();

    /* Submit the command buffer and wait until done */
    queue.submit({Vk::SubmitInfo{}.setCommandBuffers({cmd})}).wait();

    /* Read the image back from the buffer */
    CORRADE_INTERNAL_ASSERT_EXPRESSION(
        PluginManager::Manager<Trade::AbstractImageConverter>{}
            .loadAndInstantiate("AnyImageConverter")
    )->exportToFile(ImageView2D{
        PixelFormat::RGBA8Unorm, {800, 600},
        pixels.dedicatedMemory().mapRead()
    }, "image.png");
    Debug{} << "Saved an image to image.png";
}
<commit_msg>triangle-vulkan: comment your assembly, kids.<commit_after>/*
    This file is part of Magnum.

    Original authors — credit is appreciated but not required:

        2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021
             — Vladimír Vondruš <mosra@centrum.cz>
        2021 — Pablo Escobar <mail@rvrs.in>

    This is free and unencumbered software released into the public domain.

    Anyone is free to copy, modify, publish, use, compile, sell, or distribute
    this software, either in source code form or as a compiled binary, for any
    purpose, commercial or non-commercial, and by any means.

    In jurisdictions that recognize copyright laws, the author or authors of
    this software dedicate any and all copyright interest in the software to
    the public domain. We make this dedication for the benefit of the public
    at large and to the detriment of our heirs and successors. We intend this
    dedication to be an overt act of relinquishment in perpetuity of all
    present and future rights to this software under copyright law.

    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 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 <Corrade/Containers/Array.h>
#include <Corrade/Containers/StringView.h>
#include <Corrade/Utility/Assert.h>
#include <Corrade/PluginManager/Manager.h>
#include <Magnum/Magnum.h>
#include <Magnum/Mesh.h>
#include <Magnum/ImageView.h>
#include <Magnum/PixelFormat.h>
#include <Magnum/VertexFormat.h>
#include <Magnum/Math/Color.h>
#include <Magnum/Math/Range.h>
#include <Magnum/ShaderTools/AbstractConverter.h>
#include <Magnum/Trade/AbstractImageConverter.h>
#include <Magnum/Vk/Assert.h>
#include <Magnum/Vk/BufferCreateInfo.h>
#include <Magnum/Vk/CommandBuffer.h>
#include <Magnum/Vk/CommandPoolCreateInfo.h>
#include <Magnum/Vk/DeviceCreateInfo.h>
#include <Magnum/Vk/DeviceProperties.h>
#include <Magnum/Vk/Fence.h>
#include <Magnum/Vk/FramebufferCreateInfo.h>
#include <Magnum/Vk/ImageCreateInfo.h>
#include <Magnum/Vk/ImageViewCreateInfo.h>
#include <Magnum/Vk/InstanceCreateInfo.h>
#include <Magnum/Vk/Memory.h>
#include <Magnum/Vk/Mesh.h>
#include <Magnum/Vk/Pipeline.h>
#include <Magnum/Vk/PipelineLayoutCreateInfo.h>
#include <Magnum/Vk/Queue.h>
#include <Magnum/Vk/RasterizationPipelineCreateInfo.h>
#include <Magnum/Vk/RenderPassCreateInfo.h>
#include <Magnum/Vk/ShaderCreateInfo.h>
#include <Magnum/Vk/ShaderSet.h>

using namespace Corrade::Containers::Literals;
using namespace Magnum;
using namespace Magnum::Math::Literals;

int main(int argc, char** argv) {
    /* Create an instance */
    Vk::Instance instance{Vk::InstanceCreateInfo{argc, argv}
        .setApplicationInfo("Magnum Vulkan Triangle Example"_s, {})
    };

    /* Create a device with a graphics queue */
    Vk::Queue queue{NoCreate};
    Vk::Device device{instance, Vk::DeviceCreateInfo{Vk::pickDevice(instance)}
        .addQueues(Vk::QueueFlag::Graphics, {0.0f}, {queue})
    };

    /* Allocate a command buffer */
    Vk::CommandPool commandPool{device, Vk::CommandPoolCreateInfo{
        device.properties().pickQueueFamily(Vk::QueueFlag::Graphics)
    }};
    Vk::CommandBuffer cmd = commandPool.allocate();

    /* Render pass. We'll want to transfer the image back to the host though a
       buffer once done, so additionally set up a corresponding final image
       layout and a dependency that performs the layout transition before we
       execute the copy command. */
    Vk::RenderPass renderPass{device, Vk::RenderPassCreateInfo{}
        .setAttachments({
            Vk::AttachmentDescription{PixelFormat::RGBA8Srgb,
                Vk::AttachmentLoadOperation::Clear,
                Vk::AttachmentStoreOperation::Store,
                Vk::ImageLayout::Undefined,
                Vk::ImageLayout::TransferSource
            }
        })
        .addSubpass(Vk::SubpassDescription{}
            .setColorAttachments({
                Vk::AttachmentReference{0, Vk::ImageLayout::ColorAttachment}
            })
        )
        .setDependencies({
            Vk::SubpassDependency{
                /* An operation external to the render pass depends on the
                   first subpass */
                0, Vk::SubpassDependency::External,
                /* where transfer gets executed only after color output is
                   done */
                Vk::PipelineStage::ColorAttachmentOutput,
                Vk::PipelineStage::Transfer,
                /* and color data written are available for the transfer to
                   read */
                Vk::Access::ColorAttachmentWrite,
                Vk::Access::TransferRead
            }
        })
    };

    /* Framebuffer image. It doesn't need to be host-visible, however we'll
       copy it to the host through a buffer so enable corresponding usage. */
    Vk::Image image{device, Vk::ImageCreateInfo2D{
        Vk::ImageUsage::ColorAttachment|Vk::ImageUsage::TransferSource,
        PixelFormat::RGBA8Srgb, {800, 600}, 1
    }, Vk::MemoryFlag::DeviceLocal};

    /* Create the triangle mesh */
    Vk::Mesh mesh{Vk::MeshLayout{MeshPrimitive::Triangles}
        .addBinding(0, 2*4*4)
        .addAttribute(0, 0, VertexFormat::Vector4, 0)
        .addAttribute(1, 0, VertexFormat::Vector4, 4*4)
    };
    {
        Vk::Buffer buffer{device, Vk::BufferCreateInfo{
            Vk::BufferUsage::VertexBuffer,
            3*2*4*4 /* Three vertices, each is four-element pos & color */
        }, Vk::MemoryFlag::HostVisible};

        /** @todo arrayCast for an array rvalue */
        Containers::Array<char, Vk::MemoryMapDeleter> data = buffer.dedicatedMemory().map();
        auto view = Containers::arrayCast<Vector4>(data);
        view[0] = {-0.5f, -0.5f, 0.0f, 1.0f}; /* Left vertex, red color */
        view[1] = 0xff0000ff_srgbaf;
        view[2] = { 0.5f, -0.5f, 0.0f, 1.0f}; /* Right vertex, green color */
        view[3] = 0x00ff00ff_srgbaf;
        view[4] = { 0.0f,  0.5f, 0.0f, 1.0f}; /* Top vertex, blue color */
        view[5] = 0x0000ffff_srgbaf;

        mesh.addVertexBuffer(0, std::move(buffer), 0)
            .setCount(3);
    }

    /* Buffer to which the rendered image gets linearized */
    Vk::Buffer pixels{device, Vk::BufferCreateInfo{
        Vk::BufferUsage::TransferDestination, 800*600*4
    }, Vk::MemoryFlag::HostVisible};

    /* Framebuffer */
    Vk::ImageView color{device, Vk::ImageViewCreateInfo2D{image}};
    Vk::Framebuffer framebuffer{device, Vk::FramebufferCreateInfo{renderPass, {
        color
    }, {800, 600}}};

    /* Create the shader */
    constexpr Containers::StringView assembly = R"(
               OpCapability Shader
               OpMemoryModel Logical GLSL450

               OpEntryPoint Vertex %ver "ver" %position %color %gl_Position %interpolatedColorOut
               OpEntryPoint Fragment %fra "fra" %interpolatedColorIn %fragmentColor
               OpExecutionMode %fra OriginUpperLeft

               OpDecorate %position Location 0
               OpDecorate %color Location 1
               OpDecorate %gl_Position BuiltIn Position
               OpDecorate %interpolatedColorOut Location 0
               OpDecorate %interpolatedColorIn Location 0
               OpDecorate %fragmentColor Location 0

       %void = OpTypeVoid
    %fn_void = OpTypeFunction %void
      %float = OpTypeFloat 32
       %vec4 = OpTypeVector %float 4
%ptr_in_vec4 = OpTypePointer Input %vec4
   %position = OpVariable %ptr_in_vec4 Input
      %color = OpVariable %ptr_in_vec4 Input
%ptr_out_vec4 = OpTypePointer Output %vec4
%gl_Position = OpVariable %ptr_out_vec4 Output
%interpolatedColorOut = OpVariable %ptr_out_vec4 Output
%interpolatedColorIn = OpVariable %ptr_in_vec4 Input
%fragmentColor = OpVariable %ptr_out_vec4 Output

        %ver = OpFunction %void None %fn_void
       %ver_ = OpLabel
          %1 = OpLoad %vec4 %position
          %2 = OpLoad %vec4 %color
               OpStore %gl_Position %1
               OpStore %interpolatedColorOut %2
               OpReturn
               OpFunctionEnd

        %fra = OpFunction %void None %fn_void
       %fra_ = OpLabel
          %3 = OpLoad %vec4 %interpolatedColorIn
               OpStore %fragmentColor %3
               OpReturn
               OpFunctionEnd
)"_s;
    Vk::Shader shader{device, Vk::ShaderCreateInfo{
        CORRADE_INTERNAL_ASSERT_EXPRESSION(CORRADE_INTERNAL_ASSERT_EXPRESSION(
            PluginManager::Manager<ShaderTools::AbstractConverter>{}
                .loadAndInstantiate("SpirvAssemblyToSpirvShaderConverter")
        )->convertDataToData({}, assembly))}};

    /* Create a graphics pipeline */
    Vk::ShaderSet shaderSet;
    shaderSet
        .addShader(Vk::ShaderStage::Vertex, shader, "ver"_s)
        .addShader(Vk::ShaderStage::Fragment, shader, "fra"_s);
    Vk::PipelineLayout pipelineLayout{device, Vk::PipelineLayoutCreateInfo{}};
    Vk::Pipeline pipeline{device, Vk::RasterizationPipelineCreateInfo{shaderSet, mesh.layout(), pipelineLayout, renderPass, 0, 1}
        .setViewport({{}, {800.0f, 600.0f}})
    };

    /* Record the command buffer:
        - render pass being converts the framebuffer attachment from Undefined
          to ColorAttachment and clears it
        - the pipeline barrier is needed in order to make the image data copied
          to the buffer visible in time for the host read happening below */
    cmd.begin()
       .beginRenderPass(Vk::RenderPassBeginInfo{renderPass, framebuffer}
           .clearColor(0, 0x1f1f1f_srgbf)
        )
       .bindPipeline(pipeline)
       .draw(mesh)
       .endRenderPass()
       .copyImageToBuffer({image, Vk::ImageLayout::TransferSource, pixels, {
            Vk::BufferImageCopy2D{0, Vk::ImageAspect::Color, 0, {{}, {800, 600}}}
        }})
       .pipelineBarrier(Vk::PipelineStage::Transfer, Vk::PipelineStage::Host, {
            {Vk::Access::TransferWrite, Vk::Access::HostRead, pixels}
        })
       .end();

    /* Submit the command buffer and wait until done */
    queue.submit({Vk::SubmitInfo{}.setCommandBuffers({cmd})}).wait();

    /* Read the image back from the buffer */
    CORRADE_INTERNAL_ASSERT_EXPRESSION(
        PluginManager::Manager<Trade::AbstractImageConverter>{}
            .loadAndInstantiate("AnyImageConverter")
    )->exportToFile(ImageView2D{
        PixelFormat::RGBA8Unorm, {800, 600},
        pixels.dedicatedMemory().mapRead()
    }, "image.png");
    Debug{} << "Saved an image to image.png";
}
<|endoftext|>