<commit_before>/*************************************************************************
 *
 *  $RCSfile: grfshex.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2001-07-23 10:04:56 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _GRFSH_HXX
#include <grfsh.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _TEXTSH_HXX
#include <textsh.hxx>
#endif
#ifndef _VIEWOPT_HXX
#include <viewopt.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx>
#endif
#ifndef _SHELLS_HRC
#include <shells.hrc>
#endif
#ifndef _CAPTION_HXX
#include <caption.hxx>
#endif
#define _SVSTDARR_STRINGSSORTDTOR
#include <svtools/svstdarr.hxx>
#ifndef _FILTER_HXX
#include <svtools/filter.hxx>
#endif
#ifndef _SVX_IMPGRF_HXX
#include <svx/impgrf.hxx>
#endif
#ifndef _SVX_HTMLMODE_HXX //autogen
#include <svx/htmlmode.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _FRMFMT_HXX
#include <frmfmt.hxx>
#endif
#ifndef _FRMMGR_HXX
#include <frmmgr.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _SWSTYLENAMEMAPPER_HXX
#include <SwStyleNameMapper.hxx>
#endif

#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_
#include <com/sun/star/ui/dialogs/ListboxControlActions.hpp>
#endif
#ifndef _POOLFMT_HRC
#include <poolfmt.hrc>
#endif

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::sfx2;
using namespace ::rtl;

BOOL SwTextShell::InsertGraphicDlg()
{
#ifndef ENABLE_PROP_WITHOUTLINK
#define ENABLE_PROP_WITHOUTLINK 0x08
#endif

    BOOL bReturn = FALSE;
    SwView &rVw = GetView();
    SwDocShell* pDocShell = rVw.GetDocShell();
    USHORT nHtmlMode = ::GetHtmlMode(pDocShell);
    // im HTML-Mode nur verknuepft einfuegen
    FileDialogHelper* pFileDlg = new FileDialogHelper( SFXWB_GRAPHIC );
    pFileDlg->SetTitle(SW_RESSTR(STR_INSERT_GRAPHIC ));
    Reference < XFilePicker > xFP = pFileDlg->GetFilePicker();
    Reference < XFilePickerControlAccess > xCtrlAcc(xFP, UNO_QUERY);
    if(nHtmlMode & HTMLMODE_ON)
    {
        sal_Bool bTrue = sal_True;
        Any aVal(&bTrue, ::getBooleanCppuType());
        xCtrlAcc->setValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0, aVal);
        xCtrlAcc->enableControl( ExtendedFilePickerElementIds::CHECKBOX_LINK, sal_False);
    }

    SvStringsSortDtor aFormats;
    SwDoc* pDoc = pDocShell->GetDoc();
    const USHORT nArrLen = pDoc->GetFrmFmts()->Count();
    USHORT i;
    for( i = 0; i < nArrLen; i++ )
    {
        SwFrmFmt* pFmt = (*pDoc->GetFrmFmts())[ i ];
        if(pFmt->IsDefault() || pFmt->IsAuto())
            continue;
        String *pFormat = new String(pFmt->GetName());
        aFormats.Insert(pFormat);
    }

    // pool formats
    //
    const SvStringsDtor& rFrmPoolArr = SwStyleNameMapper::GetFrmFmtUINameArray();
    for( i = 0; i < rFrmPoolArr.Count(); i++ )
    {
        String *pFormat = new String(*rFrmPoolArr[i]);
        if (!aFormats.Insert(pFormat))
            delete pFormat;
    }

    Sequence<OUString> aListBoxEntries(aFormats.Count());
    OUString* pEntries = aListBoxEntries.getArray();
    sal_Int16 nSelect = 0;
    String sGraphicFormat = SW_RESSTR(STR_POOLFRM_GRAPHIC);
    for(i = 0; i < aFormats.Count(); ++i)
    {
        pEntries[i] = *aFormats[i];
        if(pEntries[i].equals(sGraphicFormat))
            nSelect = i;
    }
    try
    {
        Any aTemplates(&aListBoxEntries, ::getCppuType(&aListBoxEntries));

        xCtrlAcc->setValue( ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE,
            ListboxControlActions::ADD_ITEMS , aTemplates );

        Any aSelectPos(&nSelect, ::getCppuType(&nSelect));
        xCtrlAcc->setValue( ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE,
            ListboxControlActions::SET_SELECT_ITEM, aSelectPos );
    }
    catch(Exception& )
    {
        DBG_ERROR("control acces failed")
    }

    if( ERRCODE_NONE == pFileDlg->Execute() )
    {
        SwWrtShell& rSh = GetShell();
        rSh.StartAction();
        rSh.StartUndo(UNDO_INSERT);
        sal_Bool bAsLink;
        if(nHtmlMode & HTMLMODE_ON)
            bAsLink = sal_True;
        else
        {
            Any aVal = xCtrlAcc->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0);
            DBG_ASSERT(aVal.hasValue(), "Value CBX_INSERT_AS_LINK not found")
            bAsLink = aVal.hasValue() ? *(sal_Bool*) aVal.getValue() : sal_True;
            Any aTemplateValue = xCtrlAcc->getValue(
                ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE,
                ListboxControlActions::GET_SELECTED_ITEM );
            OUString sTmpl;
            aTemplateValue >>= sTmpl;
            sGraphicFormat = sTmpl;
        }
        USHORT nError = InsertGraphic( pFileDlg->GetPath(), pFileDlg->GetCurrentFilter(),
                                bAsLink, ::GetGrfFilter() );

        // Format ist ungleich Current Filter, jetzt mit auto. detection
        if( nError == GRFILTER_FORMATERROR )
            nError = InsertGraphic( pFileDlg->GetPath(), aEmptyStr, bAsLink,
                                    ::GetGrfFilter() );
        if ( rSh.IsFrmSelected() )
        {
            SwFrmFmt* pFmt = pDoc->FindFrmFmtByName( sGraphicFormat );
            if(!pFmt)
                pFmt = pDoc->MakeFrmFmt(sGraphicFormat, 0);
            rSh.SetFrmFmt( pFmt );
        }

        RESOURCE_TYPE nResId = 0;
        switch( nError )
        {
            case GRFILTER_OPENERROR:
                nResId = STR_GRFILTER_OPENERROR;
                break;
            case GRFILTER_IOERROR:
                nResId = STR_GRFILTER_IOERROR;
                break;
            case GRFILTER_FORMATERROR:
                nResId = STR_GRFILTER_FORMATERROR;
                break;
            case GRFILTER_VERSIONERROR:
                nResId = STR_GRFILTER_VERSIONERROR;
                break;
            case GRFILTER_FILTERERROR:
                nResId = STR_GRFILTER_FILTERERROR;
                break;
            case GRFILTER_TOOBIG:
                nResId = STR_GRFILTER_TOOBIG;
                break;
        }

        if( nResId )
        {
            rSh.EndAction();
            InfoBox aInfoBox( rVw.GetWindow(), SW_RESSTR( nResId ));
            aInfoBox.Execute();
        }
        else
        {
            // set the specific graphic attrbutes to the graphic
            rSh.EndAction();
            bReturn = TRUE;
            rVw.AutoCaption( GRAPHIC_CAP );
        }
        rSh.EndUndo(UNDO_INSERT); // wegen moegl. Shellwechsel
    }

    DELETEZ( pFrmMgr );
    delete pFileDlg;

    return bReturn;
}

<commit_msg>#90224# Use SFXWB_SHOWSTYLES to display the style listbox<commit_after>/*************************************************************************
 *
 *  $RCSfile: grfshex.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: dv $ $Date: 2001-07-25 15:50:55 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifdef PRECOMPILED
#include "ui_pch.hxx"
#endif

#pragma hdrstop

#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _GRFSH_HXX
#include <grfsh.hxx>
#endif
#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _VIEW_HXX
#include <view.hxx>
#endif
#ifndef _DOC_HXX
#include <doc.hxx>
#endif
#ifndef _DOCARY_HXX
#include <docary.hxx>
#endif
#ifndef _TEXTSH_HXX
#include <textsh.hxx>
#endif
#ifndef _VIEWOPT_HXX
#include <viewopt.hxx>
#endif
#ifndef _SWUNDO_HXX
#include <swundo.hxx>
#endif
#ifndef _SHELLS_HRC
#include <shells.hrc>
#endif
#ifndef _CAPTION_HXX
#include <caption.hxx>
#endif
#define _SVSTDARR_STRINGSSORTDTOR
#include <svtools/svstdarr.hxx>
#ifndef _FILTER_HXX
#include <svtools/filter.hxx>
#endif
#ifndef _SVX_IMPGRF_HXX
#include <svx/impgrf.hxx>
#endif
#ifndef _SVX_HTMLMODE_HXX //autogen
#include <svx/htmlmode.hxx>
#endif
#ifndef _DOCSH_HXX
#include <docsh.hxx>
#endif
#ifndef _FRMFMT_HXX
#include <frmfmt.hxx>
#endif
#ifndef _FRMMGR_HXX
#include <frmmgr.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _SWSTYLENAMEMAPPER_HXX
#include <SwStyleNameMapper.hxx>
#endif

#ifndef _FILEDLGHELPER_HXX
#include <sfx2/filedlghelper.hxx>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILEPICKERCONTROLACCESS_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_EXTENDEDFILEPICKERELEMENTIDS_HPP_
#include <com/sun/star/ui/dialogs/ExtendedFilePickerElementIds.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_LISTBOXCONTROLACTIONS_HPP_
#include <com/sun/star/ui/dialogs/ListboxControlActions.hpp>
#endif
#ifndef _POOLFMT_HRC
#include <poolfmt.hrc>
#endif

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::sfx2;
using namespace ::rtl;

BOOL SwTextShell::InsertGraphicDlg()
{
#ifndef ENABLE_PROP_WITHOUTLINK
#define ENABLE_PROP_WITHOUTLINK 0x08
#endif

    BOOL bReturn = FALSE;
    SwView &rVw = GetView();
    SwDocShell* pDocShell = rVw.GetDocShell();
    USHORT nHtmlMode = ::GetHtmlMode(pDocShell);
    // im HTML-Mode nur verknuepft einfuegen
    FileDialogHelper* pFileDlg = new FileDialogHelper( SFXWB_GRAPHIC | SFXWB_SHOWSTYLES );
    pFileDlg->SetTitle(SW_RESSTR(STR_INSERT_GRAPHIC ));
    Reference < XFilePicker > xFP = pFileDlg->GetFilePicker();
    Reference < XFilePickerControlAccess > xCtrlAcc(xFP, UNO_QUERY);
    if(nHtmlMode & HTMLMODE_ON)
    {
        sal_Bool bTrue = sal_True;
        Any aVal(&bTrue, ::getBooleanCppuType());
        xCtrlAcc->setValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0, aVal);
        xCtrlAcc->enableControl( ExtendedFilePickerElementIds::CHECKBOX_LINK, sal_False);
    }

    SvStringsSortDtor aFormats;
    SwDoc* pDoc = pDocShell->GetDoc();
    const USHORT nArrLen = pDoc->GetFrmFmts()->Count();
    USHORT i;
    for( i = 0; i < nArrLen; i++ )
    {
        SwFrmFmt* pFmt = (*pDoc->GetFrmFmts())[ i ];
        if(pFmt->IsDefault() || pFmt->IsAuto())
            continue;
        String *pFormat = new String(pFmt->GetName());
        aFormats.Insert(pFormat);
    }

    // pool formats
    //
    const SvStringsDtor& rFrmPoolArr = SwStyleNameMapper::GetFrmFmtUINameArray();
    for( i = 0; i < rFrmPoolArr.Count(); i++ )
    {
        String *pFormat = new String(*rFrmPoolArr[i]);
        if (!aFormats.Insert(pFormat))
            delete pFormat;
    }

    Sequence<OUString> aListBoxEntries(aFormats.Count());
    OUString* pEntries = aListBoxEntries.getArray();
    sal_Int16 nSelect = 0;
    String sGraphicFormat = SW_RESSTR(STR_POOLFRM_GRAPHIC);
    for(i = 0; i < aFormats.Count(); ++i)
    {
        pEntries[i] = *aFormats[i];
        if(pEntries[i].equals(sGraphicFormat))
            nSelect = i;
    }
    try
    {
        Any aTemplates(&aListBoxEntries, ::getCppuType(&aListBoxEntries));

        xCtrlAcc->setValue( ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE,
            ListboxControlActions::ADD_ITEMS , aTemplates );

        Any aSelectPos(&nSelect, ::getCppuType(&nSelect));
        xCtrlAcc->setValue( ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE,
            ListboxControlActions::SET_SELECT_ITEM, aSelectPos );
    }
    catch(Exception& )
    {
        DBG_ERROR("control acces failed")
    }

    if( ERRCODE_NONE == pFileDlg->Execute() )
    {
        SwWrtShell& rSh = GetShell();
        rSh.StartAction();
        rSh.StartUndo(UNDO_INSERT);
        sal_Bool bAsLink;
        if(nHtmlMode & HTMLMODE_ON)
            bAsLink = sal_True;
        else
        {
            Any aVal = xCtrlAcc->getValue( ExtendedFilePickerElementIds::CHECKBOX_LINK, 0);
            DBG_ASSERT(aVal.hasValue(), "Value CBX_INSERT_AS_LINK not found")
            bAsLink = aVal.hasValue() ? *(sal_Bool*) aVal.getValue() : sal_True;
            Any aTemplateValue = xCtrlAcc->getValue(
                ExtendedFilePickerElementIds::LISTBOX_IMAGE_TEMPLATE,
                ListboxControlActions::GET_SELECTED_ITEM );
            OUString sTmpl;
            aTemplateValue >>= sTmpl;
            sGraphicFormat = sTmpl;
        }
        USHORT nError = InsertGraphic( pFileDlg->GetPath(), pFileDlg->GetCurrentFilter(),
                                bAsLink, ::GetGrfFilter() );

        // Format ist ungleich Current Filter, jetzt mit auto. detection
        if( nError == GRFILTER_FORMATERROR )
            nError = InsertGraphic( pFileDlg->GetPath(), aEmptyStr, bAsLink,
                                    ::GetGrfFilter() );
        if ( rSh.IsFrmSelected() )
        {
            SwFrmFmt* pFmt = pDoc->FindFrmFmtByName( sGraphicFormat );
            if(!pFmt)
                pFmt = pDoc->MakeFrmFmt(sGraphicFormat, 0);
            rSh.SetFrmFmt( pFmt );
        }

        RESOURCE_TYPE nResId = 0;
        switch( nError )
        {
            case GRFILTER_OPENERROR:
                nResId = STR_GRFILTER_OPENERROR;
                break;
            case GRFILTER_IOERROR:
                nResId = STR_GRFILTER_IOERROR;
                break;
            case GRFILTER_FORMATERROR:
                nResId = STR_GRFILTER_FORMATERROR;
                break;
            case GRFILTER_VERSIONERROR:
                nResId = STR_GRFILTER_VERSIONERROR;
                break;
            case GRFILTER_FILTERERROR:
                nResId = STR_GRFILTER_FILTERERROR;
                break;
            case GRFILTER_TOOBIG:
                nResId = STR_GRFILTER_TOOBIG;
                break;
        }

        if( nResId )
        {
            rSh.EndAction();
            InfoBox aInfoBox( rVw.GetWindow(), SW_RESSTR( nResId ));
            aInfoBox.Execute();
        }
        else
        {
            // set the specific graphic attrbutes to the graphic
            rSh.EndAction();
            bReturn = TRUE;
            rVw.AutoCaption( GRAPHIC_CAP );
        }
        rSh.EndUndo(UNDO_INSERT); // wegen moegl. Shellwechsel
    }

    DELETEZ( pFrmMgr );
    delete pFileDlg;

    return bReturn;
}

<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <cstdarg>

#include <svtools/svmedit.hxx>
#include <svl/eitem.hxx>
#include <svl/whiter.hxx>
#include <sfx2/event.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/viewfrm.hxx>
#include <vcl/msgbox.hxx>
#include <svl/stritem.hxx>
#include <svl/itemset.hxx>
#include <sfx2/request.hxx>
#include <com/sun/star/sdb/CommandType.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/sdbc/XDataSource.hpp>
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#include <com/sun/star/sdb/XQueriesSupplier.hpp>
#include <com/sun/star/sdb/XDatabaseAccess.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/container/XChild.hpp>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/sdbc/XRowSet.hpp>
#include <sfx2/frame.hxx>
#include <fldmgr.hxx>
#include <fldbas.hxx>
#include "dbmgr.hxx"
#include <comphelper/uno3.hxx>
#include <svx/dataaccessdescriptor.hxx>
#include <memory>

#include <vcl/svapp.hxx>

#include "view.hxx"
#include "wrtsh.hxx"
#include "swtypes.hxx"
#include "cmdid.h"
#include "swevent.hxx"
#include "shells.hrc"
#include "textsh.hxx"
#include "swabstdlg.hxx"
#include "dbui.hrc"

#include <unomid.h>

using namespace ::svx;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::beans;

#define DB_DD_DELIM 0x0b

struct DBTextStruct_Impl
{
    SwDBData aDBData;
    Sequence<Any> aSelection;
    Reference<XResultSet>   xCursor;
    Reference<XConnection>  xConnection;
};

inline void AddSelList( List& rLst, long nRow )
{
    rLst.Insert( (void*)nRow , LIST_APPEND );
}

void SwTextShell::ExecDB(SfxRequest &rReq)
{
    const SfxItemSet *pArgs = rReq.GetArgs();
    SwNewDBMgr* pNewDBMgr = GetShell().GetNewDBMgr();
    USHORT nSlot = rReq.GetSlot();
    ::rtl::OUString sSourceArg, sCommandArg;
    sal_Int32 nCommandTypeArg = 0;

    const SfxPoolItem* pSourceItem = 0;
    const SfxPoolItem* pCursorItem = 0;
    const SfxPoolItem* pConnectionItem = 0;
    const SfxPoolItem* pCommandItem = 0;
    const SfxPoolItem* pCommandTypeItem = 0;
    const SfxPoolItem* pSelectionItem = 0;

    // first get the selection of rows to be inserted
    pArgs->GetItemState(FN_DB_DATA_SELECTION_ANY, FALSE, &pSelectionItem);

    Sequence<Any> aSelection;
    if(pSelectionItem)
        ((SfxUsrAnyItem*)pSelectionItem)->GetValue() >>= aSelection;

    // get the data source name
    pArgs->GetItemState(FN_DB_DATA_SOURCE_ANY, FALSE, &pSourceItem);
    if(pSourceItem)
        ((const SfxUsrAnyItem*)pSourceItem)->GetValue() >>= sSourceArg;

    // get the command
    pArgs->GetItemState(FN_DB_DATA_COMMAND_ANY, FALSE, &pCommandItem);
    if(pCommandItem)
        ((const SfxUsrAnyItem*)pCommandItem)->GetValue() >>= sCommandArg;

    // get the command type
    pArgs->GetItemState(FN_DB_DATA_COMMAND_TYPE_ANY, FALSE, &pCommandTypeItem);
    if(pCommandTypeItem)
        ((const SfxUsrAnyItem*)pCommandTypeItem)->GetValue() >>= nCommandTypeArg;

    Reference<XConnection> xConnection;
    pArgs->GetItemState(FN_DB_CONNECTION_ANY, FALSE, &pConnectionItem);
    if ( pConnectionItem )
        ((const SfxUsrAnyItem*)pConnectionItem)->GetValue() >>= xConnection;
    // may be we even get no connection
    if ( !xConnection.is() )
    {
        Reference<XDataSource> xSource;
        xConnection = pNewDBMgr->GetConnection(sSourceArg, xSource);
    }
    if(!xConnection.is())
        return ;

    // get the cursor, we use to travel, may be NULL
    Reference<XResultSet> xCursor;
    pArgs->GetItemState(FN_DB_DATA_CURSOR_ANY, FALSE, &pCursorItem);
    if ( pCursorItem )
        ((const SfxUsrAnyItem*)pCursorItem)->GetValue() >>= xCursor;

    switch (nSlot)
    {
        case FN_QRY_INSERT:
            {
                if(pSourceItem && pCommandItem && pCommandTypeItem)
                {
                    DBTextStruct_Impl* pNew     = new DBTextStruct_Impl;
                    pNew->aDBData.sDataSource   = sSourceArg;
                    pNew->aDBData.sCommand      = sCommandArg;
                    pNew->aDBData.nCommandType  = nCommandTypeArg;
                    pNew->aSelection            = aSelection;
                    //if the cursor is NULL, it must be created inside InsertDBTextHdl
                    // because it called via a PostUserEvent
                    pNew->xCursor               = xCursor;
                    pNew->xConnection           = xConnection;

                    Application::PostUserEvent( STATIC_LINK( this, SwBaseShell,
                                            InsertDBTextHdl ), pNew );
                    // the pNew will be removed in InsertDBTextHdl !!
                }
            }
            break;

        case FN_QRY_MERGE_FIELD:
            {
                // we don't get any cursor, so we must create our own
                BOOL bDisposeResultSet = FALSE;
                if ( !xCursor.is() )
                {
                    xCursor = SwNewDBMgr::createCursor(sSourceArg,sCommandArg,nCommandTypeArg,xConnection);
                    bDisposeResultSet = xCursor.is();
                }

                ODataAccessDescriptor aDescriptor;
                aDescriptor.setDataSource(sSourceArg);
                aDescriptor[daCommand]      <<= sCommandArg;
                aDescriptor[daCursor]       <<= xCursor;
                aDescriptor[daSelection]    <<= aSelection;
                aDescriptor[daCommandType]  <<= nCommandTypeArg;

                SwMergeDescriptor aMergeDesc( DBMGR_MERGE, *GetShellPtr(), aDescriptor );
                pNewDBMgr->MergeNew(aMergeDesc);

                if ( bDisposeResultSet )
                    ::comphelper::disposeComponent(xCursor);
            }
            break;

        case FN_QRY_INSERT_FIELD:
            {
                const SfxPoolItem* pColumnItem = 0;
                const SfxPoolItem* pColumnNameItem = 0;

                pArgs->GetItemState(FN_DB_COLUMN_ANY, FALSE, &pColumnItem);
                pArgs->GetItemState(FN_DB_DATA_COLUMN_NAME_ANY, FALSE, &pColumnNameItem);

                ::rtl::OUString sColumnName;
                if(pColumnNameItem)
                    ((SfxUsrAnyItem*)pColumnNameItem)->GetValue() >>= sColumnName;
                String sDBName = sSourceArg;
                sDBName += DB_DELIM;
                sDBName += (String)sCommandArg;
                sDBName += DB_DELIM;
                sDBName += String::CreateFromInt32(nCommandTypeArg);
                sDBName += DB_DELIM;
                sDBName += (String)sColumnName;

                SwFldMgr aFldMgr(GetShellPtr());
                SwInsertFld_Data aData(TYP_DBFLD, 0, sDBName, aEmptyStr, 0, FALSE, TRUE);
                if(pConnectionItem)
                    aData.aDBConnection = ((SfxUsrAnyItem*)pConnectionItem)->GetValue();
                if(pColumnItem)
                    aData.aDBColumn = ((SfxUsrAnyItem*)pColumnItem)->GetValue();
                aFldMgr.InsertFld(aData);
                SfxViewFrame* pViewFrame = GetView().GetViewFrame();
                uno::Reference< frame::XDispatchRecorder > xRecorder =
                        pViewFrame->GetBindings().GetRecorder();
                if ( xRecorder.is() )
                {
                    SfxRequest aReq( pViewFrame, FN_INSERT_DBFIELD );
                    aReq.AppendItem( SfxUInt16Item(FN_PARAM_FIELD_TYPE, TYP_DBFLD));
                    aReq.AppendItem( SfxStringItem( FN_INSERT_DBFIELD, sDBName ));
                    aReq.AppendItem( SfxStringItem( FN_PARAM_1, sCommandArg ));
                    aReq.AppendItem( SfxStringItem( FN_PARAM_2, sColumnName ));
                    aReq.AppendItem( SfxInt32Item( FN_PARAM_3, nCommandTypeArg));
                    aReq.Done();
                }
            }
            break;

        default:
            OSL_ENSURE(!this, "wrong dispatcher");
            return;
    }
}

IMPL_STATIC_LINK( SwBaseShell, InsertDBTextHdl, DBTextStruct_Impl*, pDBStruct )
{
    if( pDBStruct )
    {
        sal_Bool bDispose = sal_False;
        Reference< sdbc::XConnection> xConnection = pDBStruct->xConnection;
        Reference<XDataSource> xSource = SwNewDBMgr::getDataSourceAsParent(xConnection,pDBStruct->aDBData.sDataSource);
        // #111987# the connection is disposed an so no parent has been found
        if(xConnection.is() && !xSource.is())
            return 0;

        if ( !xConnection.is()  )
        {
            xConnection = SwNewDBMgr::GetConnection(pDBStruct->aDBData.sDataSource, xSource);
            bDispose = sal_True;
        }

        Reference< XColumnsSupplier> xColSupp;
        if(xConnection.is())
            xColSupp = SwNewDBMgr::GetColumnSupplier(xConnection,
                                    pDBStruct->aDBData.sCommand,
                                    pDBStruct->aDBData.nCommandType == CommandType::QUERY ?
                                        SW_DB_SELECT_QUERY : SW_DB_SELECT_TABLE);

        if( xColSupp.is() )
        {
            SwDBData aDBData = pDBStruct->aDBData;
            SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
            OSL_ENSURE(pFact, "SwAbstractDialogFactory fail!");
            ::std::auto_ptr<AbstractSwInsertDBColAutoPilot>pDlg (pFact->CreateSwInsertDBColAutoPilot( pThis->GetView(),
                                                                                xSource,
                                                                                xColSupp,
                                                                                aDBData,
                                                                                DLG_AP_INSERT_DB_SEL ));
            if( RET_OK == pDlg->Execute() )
            {
                Reference <XResultSet> xResSet = pDBStruct->xCursor;
                pDlg->DataToDoc( pDBStruct->aSelection, xSource, xConnection, xResSet);
            }
        }
        if ( bDispose )
            ::comphelper::disposeComponent(xConnection);
    }

    delete pDBStruct;
    return 0;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Remove unused function.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

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

#include <cstdarg>

#include <svtools/svmedit.hxx>
#include <svl/eitem.hxx>
#include <svl/whiter.hxx>
#include <sfx2/event.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/viewfrm.hxx>
#include <vcl/msgbox.hxx>
#include <svl/stritem.hxx>
#include <svl/itemset.hxx>
#include <sfx2/request.hxx>
#include <com/sun/star/sdb/CommandType.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/sdbc/XDataSource.hpp>
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#include <com/sun/star/sdbcx/XColumnsSupplier.hpp>
#include <com/sun/star/sdb/XQueriesSupplier.hpp>
#include <com/sun/star/sdb/XDatabaseAccess.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/container/XChild.hpp>
#include <comphelper/processfactory.hxx>
#include <com/sun/star/sdbc/XRowSet.hpp>
#include <sfx2/frame.hxx>
#include <fldmgr.hxx>
#include <fldbas.hxx>
#include "dbmgr.hxx"
#include <comphelper/uno3.hxx>
#include <svx/dataaccessdescriptor.hxx>
#include <memory>

#include <vcl/svapp.hxx>

#include "view.hxx"
#include "wrtsh.hxx"
#include "swtypes.hxx"
#include "cmdid.h"
#include "swevent.hxx"
#include "shells.hrc"
#include "textsh.hxx"
#include "swabstdlg.hxx"
#include "dbui.hrc"

#include <unomid.h>

using namespace ::svx;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::sdb;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::beans;

#define DB_DD_DELIM 0x0b

struct DBTextStruct_Impl
{
    SwDBData aDBData;
    Sequence<Any> aSelection;
    Reference<XResultSet>   xCursor;
    Reference<XConnection>  xConnection;
};

void SwTextShell::ExecDB(SfxRequest &rReq)
{
    const SfxItemSet *pArgs = rReq.GetArgs();
    SwNewDBMgr* pNewDBMgr = GetShell().GetNewDBMgr();
    USHORT nSlot = rReq.GetSlot();
    ::rtl::OUString sSourceArg, sCommandArg;
    sal_Int32 nCommandTypeArg = 0;

    const SfxPoolItem* pSourceItem = 0;
    const SfxPoolItem* pCursorItem = 0;
    const SfxPoolItem* pConnectionItem = 0;
    const SfxPoolItem* pCommandItem = 0;
    const SfxPoolItem* pCommandTypeItem = 0;
    const SfxPoolItem* pSelectionItem = 0;

    // first get the selection of rows to be inserted
    pArgs->GetItemState(FN_DB_DATA_SELECTION_ANY, FALSE, &pSelectionItem);

    Sequence<Any> aSelection;
    if(pSelectionItem)
        ((SfxUsrAnyItem*)pSelectionItem)->GetValue() >>= aSelection;

    // get the data source name
    pArgs->GetItemState(FN_DB_DATA_SOURCE_ANY, FALSE, &pSourceItem);
    if(pSourceItem)
        ((const SfxUsrAnyItem*)pSourceItem)->GetValue() >>= sSourceArg;

    // get the command
    pArgs->GetItemState(FN_DB_DATA_COMMAND_ANY, FALSE, &pCommandItem);
    if(pCommandItem)
        ((const SfxUsrAnyItem*)pCommandItem)->GetValue() >>= sCommandArg;

    // get the command type
    pArgs->GetItemState(FN_DB_DATA_COMMAND_TYPE_ANY, FALSE, &pCommandTypeItem);
    if(pCommandTypeItem)
        ((const SfxUsrAnyItem*)pCommandTypeItem)->GetValue() >>= nCommandTypeArg;

    Reference<XConnection> xConnection;
    pArgs->GetItemState(FN_DB_CONNECTION_ANY, FALSE, &pConnectionItem);
    if ( pConnectionItem )
        ((const SfxUsrAnyItem*)pConnectionItem)->GetValue() >>= xConnection;
    // may be we even get no connection
    if ( !xConnection.is() )
    {
        Reference<XDataSource> xSource;
        xConnection = pNewDBMgr->GetConnection(sSourceArg, xSource);
    }
    if(!xConnection.is())
        return ;

    // get the cursor, we use to travel, may be NULL
    Reference<XResultSet> xCursor;
    pArgs->GetItemState(FN_DB_DATA_CURSOR_ANY, FALSE, &pCursorItem);
    if ( pCursorItem )
        ((const SfxUsrAnyItem*)pCursorItem)->GetValue() >>= xCursor;

    switch (nSlot)
    {
        case FN_QRY_INSERT:
            {
                if(pSourceItem && pCommandItem && pCommandTypeItem)
                {
                    DBTextStruct_Impl* pNew     = new DBTextStruct_Impl;
                    pNew->aDBData.sDataSource   = sSourceArg;
                    pNew->aDBData.sCommand      = sCommandArg;
                    pNew->aDBData.nCommandType  = nCommandTypeArg;
                    pNew->aSelection            = aSelection;
                    //if the cursor is NULL, it must be created inside InsertDBTextHdl
                    // because it called via a PostUserEvent
                    pNew->xCursor               = xCursor;
                    pNew->xConnection           = xConnection;

                    Application::PostUserEvent( STATIC_LINK( this, SwBaseShell,
                                            InsertDBTextHdl ), pNew );
                    // the pNew will be removed in InsertDBTextHdl !!
                }
            }
            break;

        case FN_QRY_MERGE_FIELD:
            {
                // we don't get any cursor, so we must create our own
                BOOL bDisposeResultSet = FALSE;
                if ( !xCursor.is() )
                {
                    xCursor = SwNewDBMgr::createCursor(sSourceArg,sCommandArg,nCommandTypeArg,xConnection);
                    bDisposeResultSet = xCursor.is();
                }

                ODataAccessDescriptor aDescriptor;
                aDescriptor.setDataSource(sSourceArg);
                aDescriptor[daCommand]      <<= sCommandArg;
                aDescriptor[daCursor]       <<= xCursor;
                aDescriptor[daSelection]    <<= aSelection;
                aDescriptor[daCommandType]  <<= nCommandTypeArg;

                SwMergeDescriptor aMergeDesc( DBMGR_MERGE, *GetShellPtr(), aDescriptor );
                pNewDBMgr->MergeNew(aMergeDesc);

                if ( bDisposeResultSet )
                    ::comphelper::disposeComponent(xCursor);
            }
            break;

        case FN_QRY_INSERT_FIELD:
            {
                const SfxPoolItem* pColumnItem = 0;
                const SfxPoolItem* pColumnNameItem = 0;

                pArgs->GetItemState(FN_DB_COLUMN_ANY, FALSE, &pColumnItem);
                pArgs->GetItemState(FN_DB_DATA_COLUMN_NAME_ANY, FALSE, &pColumnNameItem);

                ::rtl::OUString sColumnName;
                if(pColumnNameItem)
                    ((SfxUsrAnyItem*)pColumnNameItem)->GetValue() >>= sColumnName;
                String sDBName = sSourceArg;
                sDBName += DB_DELIM;
                sDBName += (String)sCommandArg;
                sDBName += DB_DELIM;
                sDBName += String::CreateFromInt32(nCommandTypeArg);
                sDBName += DB_DELIM;
                sDBName += (String)sColumnName;

                SwFldMgr aFldMgr(GetShellPtr());
                SwInsertFld_Data aData(TYP_DBFLD, 0, sDBName, aEmptyStr, 0, FALSE, TRUE);
                if(pConnectionItem)
                    aData.aDBConnection = ((SfxUsrAnyItem*)pConnectionItem)->GetValue();
                if(pColumnItem)
                    aData.aDBColumn = ((SfxUsrAnyItem*)pColumnItem)->GetValue();
                aFldMgr.InsertFld(aData);
                SfxViewFrame* pViewFrame = GetView().GetViewFrame();
                uno::Reference< frame::XDispatchRecorder > xRecorder =
                        pViewFrame->GetBindings().GetRecorder();
                if ( xRecorder.is() )
                {
                    SfxRequest aReq( pViewFrame, FN_INSERT_DBFIELD );
                    aReq.AppendItem( SfxUInt16Item(FN_PARAM_FIELD_TYPE, TYP_DBFLD));
                    aReq.AppendItem( SfxStringItem( FN_INSERT_DBFIELD, sDBName ));
                    aReq.AppendItem( SfxStringItem( FN_PARAM_1, sCommandArg ));
                    aReq.AppendItem( SfxStringItem( FN_PARAM_2, sColumnName ));
                    aReq.AppendItem( SfxInt32Item( FN_PARAM_3, nCommandTypeArg));
                    aReq.Done();
                }
            }
            break;

        default:
            OSL_ENSURE(!this, "wrong dispatcher");
            return;
    }
}

IMPL_STATIC_LINK( SwBaseShell, InsertDBTextHdl, DBTextStruct_Impl*, pDBStruct )
{
    if( pDBStruct )
    {
        sal_Bool bDispose = sal_False;
        Reference< sdbc::XConnection> xConnection = pDBStruct->xConnection;
        Reference<XDataSource> xSource = SwNewDBMgr::getDataSourceAsParent(xConnection,pDBStruct->aDBData.sDataSource);
        // #111987# the connection is disposed an so no parent has been found
        if(xConnection.is() && !xSource.is())
            return 0;

        if ( !xConnection.is()  )
        {
            xConnection = SwNewDBMgr::GetConnection(pDBStruct->aDBData.sDataSource, xSource);
            bDispose = sal_True;
        }

        Reference< XColumnsSupplier> xColSupp;
        if(xConnection.is())
            xColSupp = SwNewDBMgr::GetColumnSupplier(xConnection,
                                    pDBStruct->aDBData.sCommand,
                                    pDBStruct->aDBData.nCommandType == CommandType::QUERY ?
                                        SW_DB_SELECT_QUERY : SW_DB_SELECT_TABLE);

        if( xColSupp.is() )
        {
            SwDBData aDBData = pDBStruct->aDBData;
            SwAbstractDialogFactory* pFact = SwAbstractDialogFactory::Create();
            OSL_ENSURE(pFact, "SwAbstractDialogFactory fail!");
            ::std::auto_ptr<AbstractSwInsertDBColAutoPilot>pDlg (pFact->CreateSwInsertDBColAutoPilot( pThis->GetView(),
                                                                                xSource,
                                                                                xColSupp,
                                                                                aDBData,
                                                                                DLG_AP_INSERT_DB_SEL ));
            if( RET_OK == pDlg->Execute() )
            {
                Reference <XResultSet> xResSet = pDBStruct->xCursor;
                pDlg->DataToDoc( pDBStruct->aSelection, xSource, xConnection, xResSet);
            }
        }
        if ( bDispose )
            ::comphelper::disposeComponent(xConnection);
    }

    delete pDBStruct;
    return 0;
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include "monster_hunter_data.h"
#include "query.h"
#include "armor_up.h"
#include "helpers.h"

using namespace monster_avengers;

int main(int argc, char **argv) {
  std::setlocale(LC_ALL, "en_US.UTF-8");
  CHECK(2 <= argc);
  ArmorUp armor_up(argv[1]);
  if (argc < 3) {
    armor_up.ListSkills();
  } else {
    Query query;
    CHECK_SUCCESS(Query::ParseFile(argv[2], &query));
    armor_up.SearchAndOutput(query, 10);
  }
  return 0;
}
<commit_msg>decrease find_armor to only output 3<commit_after>#include "monster_hunter_data.h"
#include "query.h"
#include "armor_up.h"
#include "helpers.h"

using namespace monster_avengers;

int main(int argc, char **argv) {
  std::setlocale(LC_ALL, "en_US.UTF-8");
  CHECK(2 <= argc);
  ArmorUp armor_up(argv[1]);
  if (argc < 3) {
    armor_up.ListSkills();
  } else {
    Query query;
    CHECK_SUCCESS(Query::ParseFile(argv[2], &query));
    armor_up.SearchAndOutput(query, 3);
  }
  return 0;
}
<|endoftext|>


<commit_before>/** \file   log_rotate.cc
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2017 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  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 <iostream>
#include <stdexcept>
#include <cstdlib>
#include <cstring>
#include "FileUtil.h"
#include "MiscUtil.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "util.h"

const unsigned DEFAULT_MAX_ROTATIONS(5);

void Usage() {
    std::cerr << "Usage: " << ::progname
              << " [--max-rotations=max_rotations|--no-of-lines-to-keep=max_line_count] directory file_regex\n"
              << "       where the default for \"max_rotations\" is " << DEFAULT_MAX_ROTATIONS << '\n'
              << "       and \"file_regex\" must be a PCRE.  (There is no default for \"max_line_count\".)\n"
              << "       When using --no-of-lines-to-keep, the result will be either empty, if the original\n"
              << "       was empty, or the file will end in a newline even if it originally didn't.\n\n";
    std::exit(EXIT_FAILURE);
}

void SkipLines(File * const input, unsigned skip_count) {
    while (skip_count-- > 0) {
        std::string line;
        input->getline(&line);
    }
}

void CopyLines(File * const input, File * const output) {
    while (not input->eof()) {
        std::string line;
        if (unlikely(not output->write(line + "\n")))
            Error("in CopyLines: failed to write a line to \"" + output->getPath() + "\"!");
    }
}

// Keeps the last \"max_line_count\" number of lines in \"filename\".
void KeepLines(const std::string &filename, const unsigned &max_line_count) {
    const size_t original_line_count(FileUtil::CountLines(filename));
    if (original_line_count <= max_line_count)
        return;

    std::unique_ptr<File> input(FileUtil::OpenInputFileOrDie(filename));
    SkipLines(input.get(), original_line_count - max_line_count);

    FileUtil::AutoTempFile temp_file;
    std::unique_ptr<File> output(FileUtil::OpenOutputFileOrDie(temp_file.getFilePath()));
    CopyLines(input.get(), output.get());
    input->close(), output->close();
    if (not FileUtil::RenameFile(temp_file.getFilePath(), filename, /* remove_target = */ true))
        Error("in KeepLines: failed to rename \"" + temp_file.getFilePath() + "\" to \"" + filename + "\"!");
}

inline bool HasNumericExtension(const std::string &filename) {
    static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactory("\\.[0-9]+$"));
    return matcher->matched(filename);
}

int main(int argc, char *argv[]) {
    ::progname = argv[0];

    if (argc != 3 and argc != 4)
        Usage();

    unsigned max_rotations(DEFAULT_MAX_ROTATIONS), max_line_count(0);
    std::string directory_path, file_regex;
    if (argc == 3) {
        directory_path = argv[1];
        file_regex     = argv[2];
    } else { // argc == 4.
        if (StringUtil::StartsWith(argv[1], "--max-rotations=")) {
            if (not StringUtil::ToUnsigned(argv[1] + std::strlen("--max-rotations="), &max_rotations)
                or max_rotations == 0)
                Error("\"" + std::string(argv[1] + std::strlen("--max-rotations="))
                      + "\" is not a valid maximum rotation count!");
            else if (not StringUtil::StartsWith(argv[1], "--no-of-lines-to-keep=")) {
                if (not StringUtil::ToUnsigned(argv[1] + std::strlen("--no-of-lines-to-keep="), &max_line_count)
                    or max_line_count == 0)
                    Error("\"" + std::string(argv[1] + std::strlen("--no-of-lines-to-keep="))
                          + "\" is not a valid line count!");
            } else
                Usage();
            directory_path = argv[2];
            file_regex     = argv[3];
        }
    }

    try {
        FileUtil::Directory directory(directory_path, file_regex);
        for (const auto &entry : directory) {
            if (not HasNumericExtension(entry.getName())) {
                if (max_line_count > 0)
                    KeepLines(entry.getName(), max_line_count);
                else
                    MiscUtil::LogRotate(entry.getName(), max_rotations);
            }
        }
    } catch (const std::exception &x) {
        Error("caught exception: " + std::string(x.what()));
    }
}
<commit_msg>Fixed argument processing.<commit_after>/** \file   log_rotate.cc
 *  \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)
 *
 *  \copyright 2017 Universitätsbibliothek Tübingen.  All rights reserved.
 *
 *  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 <iostream>
#include <stdexcept>
#include <cstdlib>
#include <cstring>
#include "FileUtil.h"
#include "MiscUtil.h"
#include "RegexMatcher.h"
#include "StringUtil.h"
#include "util.h"

const unsigned DEFAULT_MAX_ROTATIONS(5);

void Usage() {
    std::cerr << "Usage: " << ::progname
              << " [--max-rotations=max_rotations|--no-of-lines-to-keep=max_line_count] directory file_regex\n"
              << "       where the default for \"max_rotations\" is " << DEFAULT_MAX_ROTATIONS << '\n'
              << "       and \"file_regex\" must be a PCRE.  (There is no default for \"max_line_count\".)\n"
              << "       When using --no-of-lines-to-keep, the result will be either empty, if the original\n"
              << "       was empty, or the file will end in a newline even if it originally didn't.\n\n";
    std::exit(EXIT_FAILURE);
}

void SkipLines(File * const input, unsigned skip_count) {
    while (skip_count-- > 0) {
        std::string line;
        input->getline(&line);
    }
}

void CopyLines(File * const input, File * const output) {
    while (not input->eof()) {
        std::string line;
        if (unlikely(not output->write(line + "\n")))
            Error("in CopyLines: failed to write a line to \"" + output->getPath() + "\"!");
    }
}

// Keeps the last \"max_line_count\" number of lines in \"filename\".
void KeepLines(const std::string &filename, const unsigned &max_line_count) {
    const size_t original_line_count(FileUtil::CountLines(filename));
    if (original_line_count <= max_line_count)
        return;

    std::unique_ptr<File> input(FileUtil::OpenInputFileOrDie(filename));
    SkipLines(input.get(), original_line_count - max_line_count);

    FileUtil::AutoTempFile temp_file;
    std::unique_ptr<File> output(FileUtil::OpenOutputFileOrDie(temp_file.getFilePath()));
    CopyLines(input.get(), output.get());
    input->close(), output->close();
    if (not FileUtil::RenameFile(temp_file.getFilePath(), filename, /* remove_target = */ true))
        Error("in KeepLines: failed to rename \"" + temp_file.getFilePath() + "\" to \"" + filename + "\"!");
}

inline bool HasNumericExtension(const std::string &filename) {
    static RegexMatcher * const matcher(RegexMatcher::RegexMatcherFactory("\\.[0-9]+$"));
    return matcher->matched(filename);
}

int main(int argc, char *argv[]) {
    ::progname = argv[0];

    if (argc != 3 and argc != 4)
        Usage();

    unsigned max_rotations(DEFAULT_MAX_ROTATIONS), max_line_count(0);
    std::string directory_path, file_regex;
    if (argc == 3) {
        directory_path = argv[1];
        file_regex     = argv[2];
    } else { // argc == 4.
        if (StringUtil::StartsWith(argv[1], "--max-rotations=")) {
            if (StringUtil::ToUnsigned(argv[1] + std::strlen("--max-rotations="), &max_rotations)
                or max_rotations == 0)
                Error("\"" + std::string(argv[1] + std::strlen("--max-rotations="))
                      + "\" is not a valid maximum rotation count!");
            else if (StringUtil::StartsWith(argv[1], "--no-of-lines-to-keep=")) {
                if (not StringUtil::ToUnsigned(argv[1] + std::strlen("--no-of-lines-to-keep="), &max_line_count)
                    or max_line_count == 0)
                    Error("\"" + std::string(argv[1] + std::strlen("--no-of-lines-to-keep="))
                          + "\" is not a valid line count!");
            } else
                Usage();
            directory_path = argv[2];
            file_regex     = argv[3];
        }
    }

    try {
        FileUtil::Directory directory(directory_path, file_regex);
        for (const auto &entry : directory) {
            if (not HasNumericExtension(entry.getName())) {
                if (max_line_count > 0)
                    KeepLines(entry.getName(), max_line_count);
                else
                    MiscUtil::LogRotate(entry.getName(), max_rotations);
            }
        }
    } catch (const std::exception &x) {
        Error("caught exception: " + std::string(x.what()));
    }
}
<|endoftext|>


<commit_before>// Alexis Giraudet

#include "map.hpp"

int main(int argc, char *argv[])
{
    map<int,int> test_map;
    return 0;
}
<commit_msg>add implementation<commit_after>// Alexis Giraudet
// Théo Cesbron

#include "map.hpp"

int main(int argc, char *argv[])
{
    map<int,int> test_map;

    //On vérifie que la map est vide
    std::cout << test_map.is_empty() << std::endl;

    //On ajoute un élement de clé 1 et de valeur 1
    test_map.put(1,1);

    //On affiche la valeur correspondant a la clé 1
    std::cout << test_map.get(1) << std::endl;

    //On ajoute une deuxieme valeur
    test_map.put(2,2);

    //On vérifie si la clé 2 existe
    std::cout << test_map.contains_key(2) << std::endl;

    //On verifie si la valeur 2 existe
    std::cout << test_map.contains_value(2) << std::endl;

    //On affiche la taille de la chaine
    std::cout << test_map.size() << std::endl;

    //On supprime toute la map
    test_map.remove(2);

    //On affiche la map
    std::cout << test_map;

    //On supprime toute la map
    test_map.clear();

    //On vérifie que la map est vide
    std::cout << test_map.is_empty() << std::endl;

    return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include "chatagent.h"
#include <TelepathyQt4/Channel>
#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4/TextChannel>
#include <TelepathyQt4/ChannelRequest>
#include <TelepathyQt4/PendingChannelRequest>
#include <TelepathyQt4/PendingChannel>
#include <TelepathyQt4/PendingContacts>
#include <TelepathyQt4/Contact>
#include <TelepathyQt4/ContactManager>
#include <TelepathyQt4/ReceivedMessage>
#include <QDebug>

ChatAgent::ChatAgent(const Tp::AccountPtr &account, const Tp::ContactPtr &contact, QObject *parent)
    : QObject(parent),
      mAccount(account),
      mContact(contact),
      mHandleOwners(Tp::HandleOwnerMap()),
      mExistsChat(false),
      mModel(0),
      mPendingChannelRequest(0)
{
    qDebug() << "ChatAgent::ChatAgent: created for contact " << mContact->id();

    connect(mAccount.data(), SIGNAL(connectionChanged(const Tp::ConnectionPtr&)),
            SLOT(onAccountConnectionChanged(const Tp::ConnectionPtr&)));

    onAccountConnectionChanged(mAccount->connection());
    // todo check contact readyness
}

ChatAgent::ChatAgent(const Tp::AccountPtr &account, const QString &roomName, QObject *parent)
    : QObject(parent),
      mAccount(account),
      mHandleOwners(Tp::HandleOwnerMap()),
      mTextChannel(0),
      mExistsChat(false),
      mModel(0),
      mPendingChannelRequest(0)
{
    qDebug() << "ChatAgent::ChatAgent: created for account " << mAccount->uniqueIdentifier()
             << "for a group chat named " << roomName;

    mPendingChannelRequest = mAccount->ensureTextChatroom(roomName, QDateTime::currentDateTime(), QLatin1String("org.freedesktop.Telepathy.Client.MeeGoIM"));
    if (!mPendingChannelRequest) {
        emit error(tr("Unable to create text channel room %1")
                   .arg(roomName));
        endChat();
        return;
    }

    connect(mPendingChannelRequest,
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onPendingChanelRequestFinished(Tp::PendingOperation*)));
    connect(mPendingChannelRequest,
            SIGNAL(channelRequestCreated(Tp::ChannelRequestPtr)),
            SLOT(onPendingChanelRequestCreated(Tp::ChannelRequestPtr)));
    connect(mAccount.data(), SIGNAL(connectionChanged(const Tp::ConnectionPtr&)),
            SLOT(onAccountConnectionChanged(Tp::ConnectionPtr)));
    onAccountConnectionChanged(mAccount->connection());
}

ChatAgent::ChatAgent(const Tp::AccountPtr &account, const Tp::TextChannelPtr &channel, QObject *parent)
    : QObject(parent),
      mAccount(account),
      mHandleOwners(Tp::HandleOwnerMap()),
      mTextChannel(channel),
      mExistsChat(true),
      mModel(0),
      mPendingChannelRequest(0)
{
    qDebug() << "ChatAgent::ChatAgent: created for account " << mAccount->uniqueIdentifier()
             << "with an existing channel " << channel->objectPath();

    handleReadyChannel();
    emit isConferenceChanged();

    connect(mAccount.data(), SIGNAL(connectionChanged(const Tp::ConnectionPtr&)),
            SIGNAL(onAccountConnectionChanged(const Tp::ConnectionPtr&)));

    onAccountConnectionChanged(mAccount->connection());
}

ChatAgent::~ChatAgent()
{
    qDebug() << "ChatAgent::~ChatAgent: destroyed for contact " << mContact->id();

    // todo deallocate whatever is needed
    endChat();
}

void ChatAgent::startChat()
{
    qDebug() << "ChatAgent::startChat: contact=" << mContact->id();

    QVariantMap request;
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"),
                   QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT));
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"),
                   (uint) Tp::HandleTypeContact);
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle"),
                   mContact->handle()[0]);
    mPendingChannelRequest = mAccount->ensureChannel(
                request,
                QDateTime::currentDateTime(),
                QLatin1String("org.freedesktop.Telepathy.Client.MeeGoIM"));
    if (!mPendingChannelRequest) {
        emit error(tr("Unable to create text channel for contact %1")
                       .arg(mContact->id()));
        endChat();
        return;
    }

    connect(mPendingChannelRequest,
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onPendingChanelRequestFinished(Tp::PendingOperation*)));
    connect(mPendingChannelRequest,
            SIGNAL(channelRequestCreated(Tp::ChannelRequestPtr)),
            SLOT(onPendingChanelRequestCreated(Tp::ChannelRequestPtr)));
}

void ChatAgent::onPendingChanelRequestFinished(Tp::PendingOperation *op)
{
    Q_ASSERT(op);

    qDebug() << "ChatAgent::onPendingChanelRequestFinished:";

    if (op->isError()) {
        emit error(tr("Unable to create channel: %1 - %2")
                      .arg(op->errorName())
                      .arg(op->errorMessage()));
        endChat();
        return;
    }

    mPendingChannelRequest = 0;
}

void ChatAgent::onPendingChanelRequestCreated(const Tp::ChannelRequestPtr &channelRequest)
{
    qDebug() << "ChatAgent::onPendingChanelRequestCreated:";

    if (channelRequest.isNull()) {
        emit error(tr("Unable to create channel"));
        endChat();
        return;
    }

    mPendingChannelRequest = 0;
}

void ChatAgent::onTextChannelAvailable(Tp::TextChannelPtr channel)
{
    qDebug() << "ChatAgent::onTextChannelAvailable: handling channel";

    if (channel.isNull()) {
        emit error(tr("Channel not available"));
        endChat();
        return;
    }

    mTextChannel = channel;
    emit isConferenceChanged();

    Tp::Features features;
    features << Tp::TextChannel::FeatureCore
             << Tp::TextChannel::FeatureChatState
             << Tp::TextChannel::FeatureMessageCapabilities
             << Tp::TextChannel::FeatureMessageQueue
             << Tp::TextChannel::FeatureMessageSentSignal;
    connect(channel->becomeReady(features),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onTextChannelReady(Tp::PendingOperation*)));
}

void ChatAgent::onTextChannelReady(Tp::PendingOperation *op)
{
    qDebug() << "ChatAgent::onTextChannelReady";

    Tp::PendingReady *pr = qobject_cast<Tp::PendingReady*>(op);
    if (!pr || pr->isError()) {
        emit error(tr("Unable to create text channel for contact %1 - %2 - %3")
                      .arg(!mContact.isNull() ? mContact->id() : "")
                      .arg(op ? op->errorName() : "")
                      .arg(op ? op->errorMessage() : ""));
        endChat();
        return;
    }

    //Q_ASSERT(mTextChannel == qobject_cast<Tp::TextChannel*>(pr->object()));

    handleReadyChannel();
}

void ChatAgent::handleReadyChannel()
{
    qDebug() << "ChatAgent::handleReadyChannel():";

    if (mTextChannel.isNull()) {
        emit error(tr("Unable to create text channel"));
        endChat();
        return;
    }
    //Q_ASSERT(mTextChannel->targetHandle() == mContact->handle()[0]);

    connect(mTextChannel.data(),
            SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
            SLOT(onChannelInvalidated(Tp::DBusProxy*,QString,QString)));

    mExistsChat = true;

    createModelForChat();
    emit chatCreated();
    emit existsChatChanged();
    emit pendingConversationsChanged();

    if(mTextChannel->isRequested()) {
        if(mTextChannel->isConference()) {
            emit requestedGroupChatCreated();
        } else {
            emit requestedChatCreated();
        }
    }

    // maintain a map of handles and contacts for group contacts
    if(mTextChannel->isConference()) {
        mHandleOwners = mTextChannel->groupHandleOwners();
        connect(mTextChannel.data(),
                SIGNAL(groupHandleOwnersChanged(Tp::HandleOwnerMap,Tp::UIntList,Tp::UIntList)),
                SLOT(onGroupHandleOwnersChanged(Tp::HandleOwnerMap,Tp::UIntList,Tp::UIntList)));

        foreach(uint handle, mHandleOwners) {
            onNewHandleOwner(handle);
        }
    }

}

void ChatAgent::onGroupHandleOwnersChanged(const Tp::HandleOwnerMap &owners, const Tp::UIntList &added, const Tp::UIntList &removed)
{
    Q_UNUSED(removed);
    mHandleOwners = owners;
    foreach(uint handle, added) {
        onNewHandleOwner(handle);
    }
}

void ChatAgent::onChannelInvalidated(Tp::DBusProxy *, const QString &errorName, const QString &errorMessage)
{
    qDebug() << "ChatAgent::onChannelInvalidated: channel became invalid:" <<
        errorName << "-" << errorMessage;

    if(isConference()) {
        emit error(tr("Invalidated text channel  %1 - %2 - %3")
                   .arg(mTextChannel->objectPath())
                   .arg(errorName)
                   .arg(errorMessage));
    } else {
        emit error(tr("Invalidated text channel for contact %1 - %2 - %3")
                   .arg(mContact->id())
                   .arg(errorName)
                   .arg(errorMessage));
    }

    endChat();
}

void ChatAgent::endChat()
{
    // check status

    if (mTextChannel.isNull()) {
        return;
    }

    disconnect(mTextChannel.data(), SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
               this, SLOT(onChannelInvalidated(Tp::DBusProxy*,QString,QString)));

    // todo set status, clean objects, member vars
    // todo handle close
    mTextChannel->requestClose();
    mExistsChat = false;
    emit chatEnded();
}

bool ChatAgent::existsChat()
{
    return mExistsChat;
}

int ChatAgent::pendingConversations() const
{
    if (mModel) {
        return mModel->numPendingMessages();
    }

    return 0;
}

QString ChatAgent::lastPendingMessage() const
{
    if (!pendingConversations()) {
        return QString::null;
    }

    return mTextChannel->messageQueue().last().text();
}

QDateTime ChatAgent::lastPendingMessageSent() const
{
    if (!pendingConversations()) {
        return QDateTime();
    }

    return mTextChannel->messageQueue().first().sent();
}

IMConversationModel *ChatAgent::model() const
{
    return mModel;
}

Tp::TextChannelPtr ChatAgent::textChannel() const
{
    return mTextChannel;
}

QString ChatAgent::channelPath() const
{
    if(mTextChannel) {
        return mTextChannel->objectPath();
    }
    return QString();
}

bool ChatAgent::isConference() const
{
    if(mTextChannel) {
        return mTextChannel->isConference();
    }
    return false;
}

bool ChatAgent::canAddContacts() const
{
    if(mTextChannel) {
        return mTextChannel->groupCanAddContacts();
    }
    return false;
}

bool ChatAgent::isConnectionGroupChatCapable() const
{
    if(mTextChannel) {
        return (mTextChannel->connection()->capabilities().conferenceTextChats()
                || mTextChannel->connection()->capabilities().conferenceTextChatrooms());
    }
    return false;
}

void ChatAgent::createModelForChat()
{
    qDebug() << "ChatAgent::createModelForChat:";

    if (mTextChannel.isNull()) {
        qDebug() << "ChatAgent::createModelForChat: error text channel is invalid";
        return;
    }

    if (mTextChannel->connection().isNull()) {
        qDebug() << "ChatAgent::createModelForChat: connection is invalid";
        return;
    }

    qDebug() << " ChatAgent::createModelForChat: "
             << " connection=" << mTextChannel->connection().data()
             << " cmName=" << mTextChannel->connection()->cmName()
             << " protocolName=" << mTextChannel->connection()->protocolName()
             << " features=" << mTextChannel->connection()->actualFeatures();

    if (mTextChannel->connection()->selfContact().isNull()) {
        qDebug() << "ChatAgent::createModelForChat: self contact is invalid";
        return;
    }
    mModel = new IMConversationModel(mAccount,
        mTextChannel->connection()->selfContact(),
        mContact,
        mTextChannel,
        this);
    if (mModel) {
        connect(mModel,
                SIGNAL(numPendingMessagesChanged()),
                SIGNAL(pendingConversationsChanged()));
    }
}

Tp::AccountPtr ChatAgent::account() const
{
    return mAccount;
}

Tp::ContactPtr ChatAgent::contact() const
{
    return mContact;
}

SimpleContactsListModel *ChatAgent::contactsModel()
{
    if(mTextChannel) {
        Tp::Contacts contacts = mTextChannel->groupContacts();
        //convert to list and remove self contact
        QList<Tp::ContactPtr> contactsList = contacts.toList();
        foreach(Tp::ContactPtr contact, contactsList) {
            if(contact == mTextChannel->groupSelfContact()) {
                contactsList.removeOne(contact);
            }
        }
        return new SimpleContactsListModel(contactsList, this);
    }
    return 0;
}

void ChatAgent::addContacts(const QList<Tp::ContactPtr> contacts)
{
    if(mTextChannel && mTextChannel->groupCanAddContacts()) {
        mTextChannel->groupAddContacts(contacts);
    }
}

uint ChatAgent::globalHandle(const uint &channelHandle) const
{
    if(mHandleOwners.isEmpty()) {
        return 0;
    }

    return mHandleOwners.value(channelHandle, 0);
}

Tp::ContactPtr ChatAgent::channelContact(const QString &contactId) const
{
    if(!mTextChannel) {
        return Tp::ContactPtr();
    }

    foreach(Tp::ContactPtr contact, mTextChannel->groupContacts().toList()) {
        if(contact->id() == contactId) {
            return contact;
        }
    }
    return Tp::ContactPtr();
}

void ChatAgent::onNewHandleOwner(const uint &handle)
{
    uint globalHandle = mHandleOwners.value(handle, 0);

    if(handle != 0) {
        Tp::ContactManagerPtr contactManager = mTextChannel->connection()->contactManager();
        connect(contactManager->contactsForHandles(Tp::UIntList() << globalHandle),
                SIGNAL(finished(Tp::PendingOperation*)),
                SLOT(onNewHandleContact(Tp::PendingOperation*)));
    }
}

void ChatAgent::onNewHandleContact(Tp::PendingOperation *op)
{
    if (!op || op->isError()) {
        qWarning() << "Contacts cannot be obtained from handles";
        return;
    }

    Tp::PendingContacts *pendingContacts = qobject_cast<Tp::PendingContacts *>(op);
    QList<Tp::ContactPtr> contacts = pendingContacts->contacts();

    foreach(Tp::ContactPtr contact, contacts) {
        foreach(uint handle, contact->handle()) {
            mHandleContactMap.insert(handle, contact);
        }
    }
}

Tp::ContactPtr ChatAgent::contactByChannelHandle(const uint &handle) const
{
    return mHandleContactMap.value(globalHandle(handle), Tp::ContactPtr());
}

void ChatAgent::onAccountConnectionChanged(const Tp::ConnectionPtr &conn)
{
    if (conn == NULL) {
        qDebug() << "NULL connection";
        endChat();
    }
    else {
        connect(conn.data(),
            SIGNAL(statusChanged(Tp::ConnectionStatus)),
            SLOT(onConnectionStatusChanged(Tp::ConnectionStatus)));
        connect(conn.data(),
                SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
                SLOT(onConnectionInvalidated(Tp::DBusProxy*)));
        onConnectionStatusChanged(conn->status());
    }
}

void ChatAgent::onConnectionStatusChanged(Tp::ConnectionStatus status)
{
    if(status == Tp::ConnectionStatusDisconnected) {
        endChat();
    }
}

void ChatAgent::onConnectionInvalidated(Tp::DBusProxy *proxy)
{
    Tp::Connection *conn = qobject_cast<Tp::Connection *>(proxy);
    if (conn) {
        disconnect(conn, 0, this, 0);
    }
}
<commit_msg>Fixed slot connection in ChatAgent<commit_after>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

#include "chatagent.h"
#include <TelepathyQt4/Channel>
#include <TelepathyQt4/PendingReady>
#include <TelepathyQt4/TextChannel>
#include <TelepathyQt4/ChannelRequest>
#include <TelepathyQt4/PendingChannelRequest>
#include <TelepathyQt4/PendingChannel>
#include <TelepathyQt4/PendingContacts>
#include <TelepathyQt4/Contact>
#include <TelepathyQt4/ContactManager>
#include <TelepathyQt4/ReceivedMessage>
#include <QDebug>

ChatAgent::ChatAgent(const Tp::AccountPtr &account, const Tp::ContactPtr &contact, QObject *parent)
    : QObject(parent),
      mAccount(account),
      mContact(contact),
      mHandleOwners(Tp::HandleOwnerMap()),
      mExistsChat(false),
      mModel(0),
      mPendingChannelRequest(0)
{
    qDebug() << "ChatAgent::ChatAgent: created for contact " << mContact->id();

    connect(mAccount.data(), SIGNAL(connectionChanged(const Tp::ConnectionPtr&)),
            SLOT(onAccountConnectionChanged(const Tp::ConnectionPtr&)));

    onAccountConnectionChanged(mAccount->connection());
    // todo check contact readyness
}

ChatAgent::ChatAgent(const Tp::AccountPtr &account, const QString &roomName, QObject *parent)
    : QObject(parent),
      mAccount(account),
      mHandleOwners(Tp::HandleOwnerMap()),
      mTextChannel(0),
      mExistsChat(false),
      mModel(0),
      mPendingChannelRequest(0)
{
    qDebug() << "ChatAgent::ChatAgent: created for account " << mAccount->uniqueIdentifier()
             << "for a group chat named " << roomName;

    mPendingChannelRequest = mAccount->ensureTextChatroom(roomName, QDateTime::currentDateTime(), QLatin1String("org.freedesktop.Telepathy.Client.MeeGoIM"));
    if (!mPendingChannelRequest) {
        emit error(tr("Unable to create text channel room %1")
                   .arg(roomName));
        endChat();
        return;
    }

    connect(mPendingChannelRequest,
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onPendingChanelRequestFinished(Tp::PendingOperation*)));
    connect(mPendingChannelRequest,
            SIGNAL(channelRequestCreated(Tp::ChannelRequestPtr)),
            SLOT(onPendingChanelRequestCreated(Tp::ChannelRequestPtr)));
    connect(mAccount.data(), SIGNAL(connectionChanged(const Tp::ConnectionPtr&)),
            SLOT(onAccountConnectionChanged(Tp::ConnectionPtr)));
    onAccountConnectionChanged(mAccount->connection());
}

ChatAgent::ChatAgent(const Tp::AccountPtr &account, const Tp::TextChannelPtr &channel, QObject *parent)
    : QObject(parent),
      mAccount(account),
      mHandleOwners(Tp::HandleOwnerMap()),
      mTextChannel(channel),
      mExistsChat(true),
      mModel(0),
      mPendingChannelRequest(0)
{
    qDebug() << "ChatAgent::ChatAgent: created for account " << mAccount->uniqueIdentifier()
             << "with an existing channel " << channel->objectPath();

    handleReadyChannel();
    emit isConferenceChanged();

    connect(mAccount.data(), SIGNAL(connectionChanged(const Tp::ConnectionPtr&)),
            SLOT(onAccountConnectionChanged(const Tp::ConnectionPtr&)));

    onAccountConnectionChanged(mAccount->connection());
}

ChatAgent::~ChatAgent()
{
    qDebug() << "ChatAgent::~ChatAgent: destroyed for contact " << mContact->id();

    // todo deallocate whatever is needed
    endChat();
}

void ChatAgent::startChat()
{
    qDebug() << "ChatAgent::startChat: contact=" << mContact->id();

    QVariantMap request;
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType"),
                   QLatin1String(TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT));
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType"),
                   (uint) Tp::HandleTypeContact);
    request.insert(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetHandle"),
                   mContact->handle()[0]);
    mPendingChannelRequest = mAccount->ensureChannel(
                request,
                QDateTime::currentDateTime(),
                QLatin1String("org.freedesktop.Telepathy.Client.MeeGoIM"));
    if (!mPendingChannelRequest) {
        emit error(tr("Unable to create text channel for contact %1")
                       .arg(mContact->id()));
        endChat();
        return;
    }

    connect(mPendingChannelRequest,
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onPendingChanelRequestFinished(Tp::PendingOperation*)));
    connect(mPendingChannelRequest,
            SIGNAL(channelRequestCreated(Tp::ChannelRequestPtr)),
            SLOT(onPendingChanelRequestCreated(Tp::ChannelRequestPtr)));
}

void ChatAgent::onPendingChanelRequestFinished(Tp::PendingOperation *op)
{
    Q_ASSERT(op);

    qDebug() << "ChatAgent::onPendingChanelRequestFinished:";

    if (op->isError()) {
        emit error(tr("Unable to create channel: %1 - %2")
                      .arg(op->errorName())
                      .arg(op->errorMessage()));
        endChat();
        return;
    }

    mPendingChannelRequest = 0;
}

void ChatAgent::onPendingChanelRequestCreated(const Tp::ChannelRequestPtr &channelRequest)
{
    qDebug() << "ChatAgent::onPendingChanelRequestCreated:";

    if (channelRequest.isNull()) {
        emit error(tr("Unable to create channel"));
        endChat();
        return;
    }

    mPendingChannelRequest = 0;
}

void ChatAgent::onTextChannelAvailable(Tp::TextChannelPtr channel)
{
    qDebug() << "ChatAgent::onTextChannelAvailable: handling channel";

    if (channel.isNull()) {
        emit error(tr("Channel not available"));
        endChat();
        return;
    }

    mTextChannel = channel;
    emit isConferenceChanged();

    Tp::Features features;
    features << Tp::TextChannel::FeatureCore
             << Tp::TextChannel::FeatureChatState
             << Tp::TextChannel::FeatureMessageCapabilities
             << Tp::TextChannel::FeatureMessageQueue
             << Tp::TextChannel::FeatureMessageSentSignal;
    connect(channel->becomeReady(features),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onTextChannelReady(Tp::PendingOperation*)));
}

void ChatAgent::onTextChannelReady(Tp::PendingOperation *op)
{
    qDebug() << "ChatAgent::onTextChannelReady";

    Tp::PendingReady *pr = qobject_cast<Tp::PendingReady*>(op);
    if (!pr || pr->isError()) {
        emit error(tr("Unable to create text channel for contact %1 - %2 - %3")
                      .arg(!mContact.isNull() ? mContact->id() : "")
                      .arg(op ? op->errorName() : "")
                      .arg(op ? op->errorMessage() : ""));
        endChat();
        return;
    }

    //Q_ASSERT(mTextChannel == qobject_cast<Tp::TextChannel*>(pr->object()));

    handleReadyChannel();
}

void ChatAgent::handleReadyChannel()
{
    qDebug() << "ChatAgent::handleReadyChannel():";

    if (mTextChannel.isNull()) {
        emit error(tr("Unable to create text channel"));
        endChat();
        return;
    }
    //Q_ASSERT(mTextChannel->targetHandle() == mContact->handle()[0]);

    connect(mTextChannel.data(),
            SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
            SLOT(onChannelInvalidated(Tp::DBusProxy*,QString,QString)));

    mExistsChat = true;

    createModelForChat();
    emit chatCreated();
    emit existsChatChanged();
    emit pendingConversationsChanged();

    if(mTextChannel->isRequested()) {
        if(mTextChannel->isConference()) {
            emit requestedGroupChatCreated();
        } else {
            emit requestedChatCreated();
        }
    }

    // maintain a map of handles and contacts for group contacts
    if(mTextChannel->isConference()) {
        mHandleOwners = mTextChannel->groupHandleOwners();
        connect(mTextChannel.data(),
                SIGNAL(groupHandleOwnersChanged(Tp::HandleOwnerMap,Tp::UIntList,Tp::UIntList)),
                SLOT(onGroupHandleOwnersChanged(Tp::HandleOwnerMap,Tp::UIntList,Tp::UIntList)));

        foreach(uint handle, mHandleOwners) {
            onNewHandleOwner(handle);
        }
    }

}

void ChatAgent::onGroupHandleOwnersChanged(const Tp::HandleOwnerMap &owners, const Tp::UIntList &added, const Tp::UIntList &removed)
{
    Q_UNUSED(removed);
    mHandleOwners = owners;
    foreach(uint handle, added) {
        onNewHandleOwner(handle);
    }
}

void ChatAgent::onChannelInvalidated(Tp::DBusProxy *, const QString &errorName, const QString &errorMessage)
{
    qDebug() << "ChatAgent::onChannelInvalidated: channel became invalid:" <<
        errorName << "-" << errorMessage;

    if(isConference()) {
        emit error(tr("Invalidated text channel  %1 - %2 - %3")
                   .arg(mTextChannel->objectPath())
                   .arg(errorName)
                   .arg(errorMessage));
    } else {
        emit error(tr("Invalidated text channel for contact %1 - %2 - %3")
                   .arg(mContact->id())
                   .arg(errorName)
                   .arg(errorMessage));
    }

    endChat();
}

void ChatAgent::endChat()
{
    // check status

    if (mTextChannel.isNull()) {
        return;
    }

    disconnect(mTextChannel.data(), SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
               this, SLOT(onChannelInvalidated(Tp::DBusProxy*,QString,QString)));

    // todo set status, clean objects, member vars
    // todo handle close
    mTextChannel->requestClose();
    mExistsChat = false;
    emit chatEnded();
}

bool ChatAgent::existsChat()
{
    return mExistsChat;
}

int ChatAgent::pendingConversations() const
{
    if (mModel) {
        return mModel->numPendingMessages();
    }

    return 0;
}

QString ChatAgent::lastPendingMessage() const
{
    if (!pendingConversations()) {
        return QString::null;
    }

    return mTextChannel->messageQueue().last().text();
}

QDateTime ChatAgent::lastPendingMessageSent() const
{
    if (!pendingConversations()) {
        return QDateTime();
    }

    return mTextChannel->messageQueue().first().sent();
}

IMConversationModel *ChatAgent::model() const
{
    return mModel;
}

Tp::TextChannelPtr ChatAgent::textChannel() const
{
    return mTextChannel;
}

QString ChatAgent::channelPath() const
{
    if(mTextChannel) {
        return mTextChannel->objectPath();
    }
    return QString();
}

bool ChatAgent::isConference() const
{
    if(mTextChannel) {
        return mTextChannel->isConference();
    }
    return false;
}

bool ChatAgent::canAddContacts() const
{
    if(mTextChannel) {
        return mTextChannel->groupCanAddContacts();
    }
    return false;
}

bool ChatAgent::isConnectionGroupChatCapable() const
{
    if(mTextChannel) {
        return (mTextChannel->connection()->capabilities().conferenceTextChats()
                || mTextChannel->connection()->capabilities().conferenceTextChatrooms());
    }
    return false;
}

void ChatAgent::createModelForChat()
{
    qDebug() << "ChatAgent::createModelForChat:";

    if (mTextChannel.isNull()) {
        qDebug() << "ChatAgent::createModelForChat: error text channel is invalid";
        return;
    }

    if (mTextChannel->connection().isNull()) {
        qDebug() << "ChatAgent::createModelForChat: connection is invalid";
        return;
    }

    qDebug() << " ChatAgent::createModelForChat: "
             << " connection=" << mTextChannel->connection().data()
             << " cmName=" << mTextChannel->connection()->cmName()
             << " protocolName=" << mTextChannel->connection()->protocolName()
             << " features=" << mTextChannel->connection()->actualFeatures();

    if (mTextChannel->connection()->selfContact().isNull()) {
        qDebug() << "ChatAgent::createModelForChat: self contact is invalid";
        return;
    }
    mModel = new IMConversationModel(mAccount,
        mTextChannel->connection()->selfContact(),
        mContact,
        mTextChannel,
        this);
    if (mModel) {
        connect(mModel,
                SIGNAL(numPendingMessagesChanged()),
                SIGNAL(pendingConversationsChanged()));
    }
}

Tp::AccountPtr ChatAgent::account() const
{
    return mAccount;
}

Tp::ContactPtr ChatAgent::contact() const
{
    return mContact;
}

SimpleContactsListModel *ChatAgent::contactsModel()
{
    if(mTextChannel) {
        Tp::Contacts contacts = mTextChannel->groupContacts();
        //convert to list and remove self contact
        QList<Tp::ContactPtr> contactsList = contacts.toList();
        foreach(Tp::ContactPtr contact, contactsList) {
            if(contact == mTextChannel->groupSelfContact()) {
                contactsList.removeOne(contact);
            }
        }
        return new SimpleContactsListModel(contactsList, this);
    }
    return 0;
}

void ChatAgent::addContacts(const QList<Tp::ContactPtr> contacts)
{
    if(mTextChannel && mTextChannel->groupCanAddContacts()) {
        mTextChannel->groupAddContacts(contacts);
    }
}

uint ChatAgent::globalHandle(const uint &channelHandle) const
{
    if(mHandleOwners.isEmpty()) {
        return 0;
    }

    return mHandleOwners.value(channelHandle, 0);
}

Tp::ContactPtr ChatAgent::channelContact(const QString &contactId) const
{
    if(!mTextChannel) {
        return Tp::ContactPtr();
    }

    foreach(Tp::ContactPtr contact, mTextChannel->groupContacts().toList()) {
        if(contact->id() == contactId) {
            return contact;
        }
    }
    return Tp::ContactPtr();
}

void ChatAgent::onNewHandleOwner(const uint &handle)
{
    uint globalHandle = mHandleOwners.value(handle, 0);

    if(handle != 0) {
        Tp::ContactManagerPtr contactManager = mTextChannel->connection()->contactManager();
        connect(contactManager->contactsForHandles(Tp::UIntList() << globalHandle),
                SIGNAL(finished(Tp::PendingOperation*)),
                SLOT(onNewHandleContact(Tp::PendingOperation*)));
    }
}

void ChatAgent::onNewHandleContact(Tp::PendingOperation *op)
{
    if (!op || op->isError()) {
        qWarning() << "Contacts cannot be obtained from handles";
        return;
    }

    Tp::PendingContacts *pendingContacts = qobject_cast<Tp::PendingContacts *>(op);
    QList<Tp::ContactPtr> contacts = pendingContacts->contacts();

    foreach(Tp::ContactPtr contact, contacts) {
        foreach(uint handle, contact->handle()) {
            mHandleContactMap.insert(handle, contact);
        }
    }
}

Tp::ContactPtr ChatAgent::contactByChannelHandle(const uint &handle) const
{
    return mHandleContactMap.value(globalHandle(handle), Tp::ContactPtr());
}

void ChatAgent::onAccountConnectionChanged(const Tp::ConnectionPtr &conn)
{
    if (conn == NULL) {
        qDebug() << "NULL connection";
        endChat();
    }
    else {
        connect(conn.data(),
            SIGNAL(statusChanged(Tp::ConnectionStatus)),
            SLOT(onConnectionStatusChanged(Tp::ConnectionStatus)));
        connect(conn.data(),
                SIGNAL(invalidated(Tp::DBusProxy*,QString,QString)),
                SLOT(onConnectionInvalidated(Tp::DBusProxy*)));
        onConnectionStatusChanged(conn->status());
    }
}

void ChatAgent::onConnectionStatusChanged(Tp::ConnectionStatus status)
{
    if(status == Tp::ConnectionStatusDisconnected) {
        endChat();
    }
}

void ChatAgent::onConnectionInvalidated(Tp::DBusProxy *proxy)
{
    Tp::Connection *conn = qobject_cast<Tp::Connection *>(proxy);
    if (conn) {
        disconnect(conn, 0, this, 0);
    }
}
<|endoftext|>


<commit_before>#include "pdbformat.h"

#include <avogadro/core/elements.h>
#include <avogadro/core/molecule.h>
#include <avogadro/core/residue.h>
#include <avogadro/core/utilities.h>
#include <avogadro/core/vector.h>

#include <istream>
#include <string>

using Avogadro::Core::Atom;
using Avogadro::Core::Bond;
using Avogadro::Core::Elements;
using Avogadro::Core::lexicalCast;
using Avogadro::Core::Molecule;
using Avogadro::Core::Residue;
using Avogadro::Core::startsWith;
using Avogadro::Core::trimmed;

using std::getline;
using std::istringstream;
using std::string;
using std::vector;

namespace Avogadro {
namespace Io {

PdbFormat::PdbFormat() {}

PdbFormat::~PdbFormat() {}

bool PdbFormat::read(std::istream& in, Core::Molecule& mol)
{
  string buffer;
  std::vector<int> terList;
  Residue* r;
  size_t currentResidueId = 0;
  bool ok(false);

  while (getline(in, buffer)) { // Read Each line one by one

    if (startsWith(buffer, "ENDMDL"))
      break;

    else if (startsWith(buffer, "ATOM") || startsWith(buffer, "HETATM")) {
      // First we initialize the residue instance
      size_t residueId = lexicalCast<size_t>(buffer.substr(22, 4), ok);
      if (!ok) {
        appendError("Failed to parse residue sequence number: " +
                    buffer.substr(22, 4));
        return false;
      }

      if (residueId != currentResidueId) {
        currentResidueId = residueId;

        string residueName = lexicalCast<string>(buffer.substr(17, 3), ok);
        if (!ok) {
          appendError("Failed to parse residue name: " + buffer.substr(17, 3));
          return false;
        }

        char chainId = lexicalCast<char>(buffer.substr(21, 1), ok);
        if (!ok) {
          appendError("Failed to parse chain identifier: " +
                      buffer.substr(21, 1));
          return false;
        }

        r = &mol.addResidue(residueName, currentResidueId, chainId);
      }

      string atomName = lexicalCast<string>(buffer.substr(12, 4), ok);
      if (!ok) {
        appendError("Failed to parse atom name: " + buffer.substr(12, 4));
        return false;
      }

      Vector3 pos; // Coordinates
      pos.x() = lexicalCast<Real>(buffer.substr(30, 8), ok);
      if (!ok) {
        appendError("Failed to parse x coordinate: " + buffer.substr(30, 8));
        return false;
      }

      pos.y() = lexicalCast<Real>(buffer.substr(38, 8), ok);
      if (!ok) {
        appendError("Failed to parse y coordinate: " + buffer.substr(38, 8));
        return false;
      }

      pos.z() = lexicalCast<Real>(buffer.substr(46, 8), ok);
      if (!ok) {
        appendError("Failed to parse z coordinate: " + buffer.substr(46, 8));
        return false;
      }

      string element; // Element symbol, right justififed
      element = buffer.substr(76, 2);
      element = trimmed(element);
      if (element == "SE") // For Sulphur
        element = 'S';

      unsigned char atomicNum = Elements::atomicNumberFromSymbol(element);
      if (atomicNum == 255)
        appendError("Invalid element");

      Atom newAtom = mol.addAtom(atomicNum);
      newAtom.setPosition3d(pos);
      if (r) {
        r->addResidueAtom(atomName, newAtom);
      }
    }

    else if (startsWith(buffer, "TER")) { //  This is very important, each TER
                                          //  record also counts in the serial.
      // Need to account for that when comparing with CONECT
      terList.push_back(lexicalCast<int>(buffer.substr(6, 5), ok));

      if (!ok) {
        appendError("Failed to parse TER serial");
        return false;
      }
    }

    else if (startsWith(buffer, "CONECT")) {
      int a = lexicalCast<int>(buffer.substr(6, 5), ok);
      if (!ok) {
        appendError("Failed to parse coordinate a " + buffer.substr(6, 5));
        return false;
      }
      --a;
      size_t terCount;
      for (terCount = 0; terCount < terList.size() && a > terList[terCount];
           ++terCount)
        ; // semicolon is intentional
      a = a - terCount;

      int bCoords[] = { 11, 16, 21, 26 };
      for (int i = 0; i < 4; i++) {
        if (trimmed(buffer.substr(bCoords[i], 5)) == "")
          break;

        else {
          int b = lexicalCast<int>(buffer.substr(bCoords[i], 5), ok) - 1;
          if (!ok) {
            appendError("Failed to parse coordinate b" + std::to_string(i) +
                        " " + buffer.substr(bCoords[i], 5));
            return false;
          }

          for (terCount = 0; terCount < terList.size() && b > terList[terCount];
               ++terCount)
            ; // semicolon is intentional
          b = b - terCount;

          if (a < b) {
            mol.Avogadro::Core::Molecule::addBond(a, b, 1);
          }
        }
      }
    }
  } // End while loop
  mol.perceiveBondsSimple();
  mol.perceiveBondsFromResidueData();
  return true;
} // End read

std::vector<std::string> PdbFormat::fileExtensions() const
{
  std::vector<std::string> ext;
  ext.push_back("pdb");
  return ext;
}

std::vector<std::string> PdbFormat::mimeTypes() const
{
  std::vector<std::string> mime;
  mime.push_back("chemical/x-pdb");
  return mime;
}

} // namespace Io
} // namespace Avogadro
<commit_msg>Trajectory support in PDB reader<commit_after>#include "pdbformat.h"

#include <avogadro/core/elements.h>
#include <avogadro/core/molecule.h>
#include <avogadro/core/residue.h>
#include <avogadro/core/utilities.h>
#include <avogadro/core/vector.h>

#include <istream>
#include <string>

using Avogadro::Core::Array;
using Avogadro::Core::Atom;
using Avogadro::Core::Bond;
using Avogadro::Core::Elements;
using Avogadro::Core::lexicalCast;
using Avogadro::Core::Molecule;
using Avogadro::Core::Residue;
using Avogadro::Core::startsWith;
using Avogadro::Core::trimmed;

using std::getline;
using std::istringstream;
using std::string;
using std::vector;

namespace Avogadro {
namespace Io {

PdbFormat::PdbFormat() {}

PdbFormat::~PdbFormat() {}

bool PdbFormat::read(std::istream& in, Core::Molecule& mol)
{
  string buffer;
  std::vector<int> terList;
  Residue* r;
  size_t currentResidueId = 0;
  bool ok(false);
  int coordSet = 0;
  Array<Vector3> positions;

  while (getline(in, buffer)) { // Read Each line one by one

    if (startsWith(buffer, "ENDMDL")) {
      if (coordSet == 0) {
        mol.setCoordinate3d(mol.atomPositions3d(), coordSet++);
        positions.reserve(mol.atomCount());
      } else {
        mol.setCoordinate3d(positions, coordSet++);
        positions.clear();
      }
    }

    else if (startsWith(buffer, "ATOM") || startsWith(buffer, "HETATM")) {
      // First we initialize the residue instance
      size_t residueId = lexicalCast<size_t>(buffer.substr(22, 4), ok);
      if (!ok) {
        appendError("Failed to parse residue sequence number: " +
                    buffer.substr(22, 4));
        return false;
      }

      if (residueId != currentResidueId) {
        currentResidueId = residueId;

        string residueName = lexicalCast<string>(buffer.substr(17, 3), ok);
        if (!ok) {
          appendError("Failed to parse residue name: " + buffer.substr(17, 3));
          return false;
        }

        char chainId = lexicalCast<char>(buffer.substr(21, 1), ok);
        if (!ok) {
          appendError("Failed to parse chain identifier: " +
                      buffer.substr(21, 1));
          return false;
        }

        r = &mol.addResidue(residueName, currentResidueId, chainId);
      }

      string atomName = lexicalCast<string>(buffer.substr(12, 4), ok);
      if (!ok) {
        appendError("Failed to parse atom name: " + buffer.substr(12, 4));
        return false;
      }

      Vector3 pos; // Coordinates
      pos.x() = lexicalCast<Real>(buffer.substr(30, 8), ok);
      if (!ok) {
        appendError("Failed to parse x coordinate: " + buffer.substr(30, 8));
        return false;
      }

      pos.y() = lexicalCast<Real>(buffer.substr(38, 8), ok);
      if (!ok) {
        appendError("Failed to parse y coordinate: " + buffer.substr(38, 8));
        return false;
      }

      pos.z() = lexicalCast<Real>(buffer.substr(46, 8), ok);
      if (!ok) {
        appendError("Failed to parse z coordinate: " + buffer.substr(46, 8));
        return false;
      }

      string element; // Element symbol, right justififed
      element = buffer.substr(76, 2);
      element = trimmed(element);
      if (element == "SE") // For Sulphur
        element = 'S';

      unsigned char atomicNum = Elements::atomicNumberFromSymbol(element);
      if (atomicNum == 255)
        appendError("Invalid element");

      if (coordSet == 0) {
        Atom newAtom = mol.addAtom(atomicNum);
        newAtom.setPosition3d(pos);
        if (r) {
          r->addResidueAtom(atomName, newAtom);
        }
      } else {
        positions.push_back(pos);
      }
    }

    else if (startsWith(buffer, "TER")) { //  This is very important, each TER
                                          //  record also counts in the serial.
      // Need to account for that when comparing with CONECT
      terList.push_back(lexicalCast<int>(buffer.substr(6, 5), ok));

      if (!ok) {
        appendError("Failed to parse TER serial");
        return false;
      }
    }

    else if (startsWith(buffer, "CONECT")) {
      int a = lexicalCast<int>(buffer.substr(6, 5), ok);
      if (!ok) {
        appendError("Failed to parse coordinate a " + buffer.substr(6, 5));
        return false;
      }
      --a;
      size_t terCount;
      for (terCount = 0; terCount < terList.size() && a > terList[terCount];
           ++terCount)
        ; // semicolon is intentional
      a = a - terCount;

      int bCoords[] = { 11, 16, 21, 26 };
      for (int i = 0; i < 4; i++) {
        if (trimmed(buffer.substr(bCoords[i], 5)) == "")
          break;

        else {
          int b = lexicalCast<int>(buffer.substr(bCoords[i], 5), ok) - 1;
          if (!ok) {
            appendError("Failed to parse coordinate b" + std::to_string(i) +
                        " " + buffer.substr(bCoords[i], 5));
            return false;
          }

          for (terCount = 0; terCount < terList.size() && b > terList[terCount];
               ++terCount)
            ; // semicolon is intentional
          b = b - terCount;

          if (a < b) {
            mol.Avogadro::Core::Molecule::addBond(a, b, 1);
          }
        }
      }
    }
  } // End while loop
  mol.perceiveBondsSimple();
  mol.perceiveBondsFromResidueData();
  return true;
} // End read

std::vector<std::string> PdbFormat::fileExtensions() const
{
  std::vector<std::string> ext;
  ext.push_back("pdb");
  return ext;
}

std::vector<std::string> PdbFormat::mimeTypes() const
{
  std::vector<std::string> mime;
  mime.push_back("chemical/x-pdb");
  return mime;
}

} // namespace Io
} // namespace Avogadro
<|endoftext|>