<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dsselect.cxx,v $
 *
 *  $Revision: 1.19 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-26 08:00:01 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _DBAUI_ODBC_CONFIG_HXX_
#include "odbcconfig.hxx"
#endif

#ifndef _DBAUI_DSSELECT_HXX_
#include "dsselect.hxx"
#endif
#ifndef _DBAUI_DSSELECT_HRC_
#include "dsselect.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DBAUI_LOCALRESACCESS_HXX_
#include "localresaccess.hxx"
#endif
#ifndef _TOOLS_RCID_H
#include <tools/rcid.h>
#endif

#if defined( WIN ) || defined( WNT )
#define HWND    void*
#define HMENU   void*
typedef void*               HDC;
    // was unable to include windows.h, that's why this direct define
#endif
#ifndef _SV_SYSDATA_HXX
#include <vcl/sysdata.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XCREATECATALOG_HPP_
#include <com/sun/star/sdbcx/XCreateCatalog.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XEXECUTABLEDIALOG_HPP_
#include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif

//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::comphelper;
//==================================================================
ODatasourceSelectDialog::ODatasourceSelectDialog(Window* _pParent, const StringBag& _rDatasources, DATASOURCE_TYPE _eType,SfxItemSet* _pOutputSet)
     :ModalDialog(_pParent, ModuleRes(DLG_DATASOURCE_SELECTION))
     ,m_aDescription        (this, ModuleRes(FT_DESCRIPTION))
     ,m_aDatasource         (this, ModuleRes(LB_DATASOURCE))
     ,m_aOk                 (this, ModuleRes(PB_OK))
     ,m_aCancel             (this, ModuleRes(PB_CANCEL))
     ,m_aHelp               (this, ModuleRes(PB_HELP))
     ,m_aManageDatasources  (this, ModuleRes(PB_MANAGE))
     ,m_aCreateAdabasDB     (this, ModuleRes(PB_CREATE))
     ,m_pOutputSet(_pOutputSet)
{
    if (DST_ADABAS == _eType)
    {   // set a new title (indicating that we're browsing local data sources only)
        SetText(ModuleRes(STR_LOCAL_DATASOURCES));
        m_aDescription.SetText(ModuleRes(STR_DESCRIPTION2));

        m_aCreateAdabasDB.Show();
        m_aCreateAdabasDB.SetClickHdl(LINK(this,ODatasourceSelectDialog,CreateDBClickHdl));

        // resize the dialog a little bit, 'cause Adabas data source names are usually somewhat shorter
        // than ODBC ones are

        // shrink the listbox
        Size aOldSize = m_aDatasource.GetSizePixel();
        Size aNewSize(3 * aOldSize.Width() / 4, aOldSize.Height());
        m_aDatasource.SetSizePixel(aNewSize);

        sal_Int32 nLostPixels = aOldSize.Width() - aNewSize.Width();

        // shrink the fixed text
        aOldSize = m_aDescription.GetSizePixel();
        m_aDescription.SetSizePixel(Size(aOldSize.Width() - nLostPixels, aOldSize.Height()));

        // move the buttons
        PushButton* pButtons[] = { &m_aOk, &m_aCancel, &m_aHelp ,&m_aCreateAdabasDB};
        for (size_t i=0; i<sizeof(pButtons)/sizeof(pButtons[0]); ++i)
        {
            Point aOldPos = pButtons[i]->GetPosPixel();
            pButtons[i]->SetPosPixel(Point(aOldPos.X() - nLostPixels, aOldPos.Y()));
        }

        // resize the dialog itself
        aOldSize = GetSizePixel();
        SetSizePixel(Size(aOldSize.Width() - nLostPixels, aOldSize.Height()));
    }

    fillListBox(_rDatasources);
#ifdef HAVE_ODBC_ADMINISTRATION
    // allow ODBC datasource managenment
    if ( DST_ODBC == _eType || DST_MYSQL_ODBC == _eType )
    {
        m_aManageDatasources.Show();
        m_aManageDatasources.Enable();
        m_aManageDatasources.SetClickHdl(LINK(this,ODatasourceSelectDialog,ManageClickHdl));
    }
#endif
    m_aDatasource.SetDoubleClickHdl(LINK(this,ODatasourceSelectDialog,ListDblClickHdl));
    FreeResource();
}

// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, ListDblClickHdl, ListBox *, pListBox )
{
    if (pListBox->GetSelectEntryCount())
        EndDialog(RET_OK);
    return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, CreateDBClickHdl, PushButton*, /*pButton*/ )
{
    try
    {
        OSL_ENSURE(m_pOutputSet,"No itemset given!");
        Reference< ::com::sun::star::lang::XMultiServiceFactory > xORB = ::comphelper::getProcessServiceFactory();
        Reference<XCreateCatalog> xCatalog(xORB->createInstance(SERVICE_EXTENDED_ADABAS_DRIVER),UNO_QUERY);
        if ( xCatalog.is() && m_pOutputSet )
        {
            Sequence< Any > aArgs(2);
            aArgs[0] <<= PropertyValue(::rtl::OUString::createFromAscii("CreateCatalog"), 0,makeAny(xCatalog) , PropertyState_DIRECT_VALUE);
            aArgs[1] <<= PropertyValue(PROPERTY_PARENTWINDOW, 0, makeAny(VCLUnoHelper::GetInterface(this)), PropertyState_DIRECT_VALUE);

            Reference< XExecutableDialog > xDialog(
                xORB->createInstanceWithArguments(SERVICE_SDB_ADABASCREATIONDIALOG, aArgs), UNO_QUERY);
            if (!xDialog.is())
            {
                //  ShowServiceNotAvailableError(this, String(SERVICE_SDB_ADABASCREATIONDIALOG), sal_True);
                return 0L;
            }

            if ( xDialog->execute() == RET_OK )
            {
                Reference<XPropertySet> xProp(xDialog,UNO_QUERY);
                if(xProp.is())
                {
                    Reference<XPropertySetInfo> xPropInfo(xProp->getPropertySetInfo());
                    if(xPropInfo->hasPropertyByName(PROPERTY_DATABASENAME))
                    {
                        String sDatabaseName;
                        sDatabaseName = String(::comphelper::getString(xProp->getPropertyValue(PROPERTY_DATABASENAME)));
                        m_aDatasource.SelectEntryPos(m_aDatasource.InsertEntry( sDatabaseName ));

                    }
                    if ( xPropInfo->hasPropertyByName(PROPERTY_CONTROLUSER) )
                        m_pOutputSet->Put(SfxStringItem(DSID_CONN_CTRLUSER, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_CONTROLUSER))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_CONTROLPASSWORD) )
                        m_pOutputSet->Put(SfxStringItem(DSID_CONN_CTRLPWD, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_CONTROLPASSWORD))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_USER) )
                        m_pOutputSet->Put(SfxStringItem(DSID_USER, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_USER))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_PASSWORD) )
                    {
                        m_pOutputSet->Put(SfxStringItem(DSID_PASSWORD, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_PASSWORD))));
                        m_pOutputSet->Put(SfxBoolItem(DSID_PASSWORDREQUIRED, TRUE));
                    }
                    if ( xPropInfo->hasPropertyByName(PROPERTY_CACHESIZE) )
                        m_pOutputSet->Put(SfxInt32Item(DSID_CONN_CACHESIZE, ::comphelper::getINT32(xProp->getPropertyValue(PROPERTY_CACHESIZE))));
                }
            }
        }
    }
    catch(Exception&)
    {
    }
    return 0L;
}
// -----------------------------------------------------------------------
#ifdef HAVE_ODBC_ADMINISTRATION
IMPL_LINK( ODatasourceSelectDialog, ManageClickHdl, PushButton*, EMPTYARG )
{
    OOdbcManagement aOdbcConfig;
    if (!aOdbcConfig.isLoaded())
    {
        // show an error message
        LocalResourceAccess aLocRes(DLG_DATASOURCE_SELECTION, RSC_MODALDIALOG);
        String sError(ModuleRes(STR_COULDNOTLOAD_CONFIGLIB));
        sError.SearchAndReplaceAscii("#lib#", aOdbcConfig.getLibraryName());
        ErrorBox aDialog(this, WB_OK, sError);
        aDialog.Execute();
        m_aDatasource.GrabFocus();
        m_aManageDatasources.Disable();
        return 1L;
    }

    aOdbcConfig.manageDataSources(GetSystemData()->hWnd);
    // now we have to look if there are any new datasources added
    StringBag aOdbcDatasources;
    OOdbcEnumeration aEnumeration;
    aEnumeration.getDatasourceNames(aOdbcDatasources);
    fillListBox(aOdbcDatasources);

    return 0L;
}
#endif
// -----------------------------------------------------------------------------
void ODatasourceSelectDialog::fillListBox(const StringBag& _rDatasources)
{
    ::rtl::OUString sSelected;
    if (m_aDatasource.GetEntryCount())
         sSelected = m_aDatasource.GetSelectEntry();
    m_aDatasource.Clear();
    // fill the list
    for (   ConstStringBagIterator aDS = _rDatasources.begin();
            aDS != _rDatasources.end();
            ++aDS
        )
    {
        m_aDatasource.InsertEntry( *aDS );
    }

    if (m_aDatasource.GetEntryCount())
    {
        if (sSelected.getLength())
            m_aDatasource.SelectEntry(sSelected);
        else        // select the first entry
            m_aDatasource.SelectEntryPos(0);
    }
}

//.........................................................................
}   // namespace dbaui
//.........................................................................

<commit_msg>INTEGRATION: CWS oj14 (1.14.8); FILE MERGED 2007/06/04 18:25:23 oj 1.14.8.6: RESYNC: (1.18-1.19); FILE MERGED 2006/11/07 09:23:12 oj 1.14.8.5: RESYNC: (1.16-1.18); FILE MERGED 2006/07/04 07:58:38 oj 1.14.8.4: RESYNC: (1.14-1.16); FILE MERGED 2006/04/25 13:02:59 oj 1.14.8.3: new include 2006/03/20 07:48:31 oj 1.14.8.2: use of module client helper 2006/01/03 07:49:09 oj 1.14.8.1: changed module client<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dsselect.cxx,v $
 *
 *  $Revision: 1.20 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-06 08:16:45 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _DBAUI_ODBC_CONFIG_HXX_
#include "odbcconfig.hxx"
#endif

#ifndef _DBAUI_DSSELECT_HXX_
#include "dsselect.hxx"
#endif
#ifndef _DBAUI_DSSELECT_HRC_
#include "dsselect.hrc"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DBAUI_LOCALRESACCESS_HXX_
#include "localresaccess.hxx"
#endif
#ifndef _TOOLS_RCID_H
#include <tools/rcid.h>
#endif

#if defined( WIN ) || defined( WNT )
#define HWND    void*
#define HMENU   void*
typedef void*               HDC;
    // was unable to include windows.h, that's why this direct define
#endif
#ifndef _SV_SYSDATA_HXX
#include <vcl/sysdata.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XCREATECATALOG_HPP_
#include <com/sun/star/sdbcx/XCreateCatalog.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSETINFO_HPP_
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UI_DIALOGS_XEXECUTABLEDIALOG_HPP_
#include <com/sun/star/ui/dialogs/XExecutableDialog.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC
#include "dbustrings.hrc"
#endif
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif

//.........................................................................
namespace dbaui
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::ui::dialogs;
using namespace ::comphelper;
//==================================================================
ODatasourceSelectDialog::ODatasourceSelectDialog(Window* _pParent, const StringBag& _rDatasources, DATASOURCE_TYPE _eType,SfxItemSet* _pOutputSet)
     :ModalDialog(_pParent, ModuleRes(DLG_DATASOURCE_SELECTION))
     ,m_aDescription        (this, ModuleRes(FT_DESCRIPTION))
     ,m_aDatasource         (this, ModuleRes(LB_DATASOURCE))
     ,m_aOk                 (this, ModuleRes(PB_OK))
     ,m_aCancel             (this, ModuleRes(PB_CANCEL))
     ,m_aHelp               (this, ModuleRes(PB_HELP))
     ,m_aManageDatasources  (this, ModuleRes(PB_MANAGE))
     ,m_aCreateAdabasDB     (this, ModuleRes(PB_CREATE))
     ,m_pOutputSet(_pOutputSet)
{
    if (DST_ADABAS == _eType)
    {   // set a new title (indicating that we're browsing local data sources only)
        SetText(ModuleRes(STR_LOCAL_DATASOURCES));
        m_aDescription.SetText(ModuleRes(STR_DESCRIPTION2));

        m_aCreateAdabasDB.Show();
        m_aCreateAdabasDB.SetClickHdl(LINK(this,ODatasourceSelectDialog,CreateDBClickHdl));

        // resize the dialog a little bit, 'cause Adabas data source names are usually somewhat shorter
        // than ODBC ones are

        // shrink the listbox
        Size aOldSize = m_aDatasource.GetSizePixel();
        Size aNewSize(3 * aOldSize.Width() / 4, aOldSize.Height());
        m_aDatasource.SetSizePixel(aNewSize);

        sal_Int32 nLostPixels = aOldSize.Width() - aNewSize.Width();

        // shrink the fixed text
        aOldSize = m_aDescription.GetSizePixel();
        m_aDescription.SetSizePixel(Size(aOldSize.Width() - nLostPixels, aOldSize.Height()));

        // move the buttons
        PushButton* pButtons[] = { &m_aOk, &m_aCancel, &m_aHelp ,&m_aCreateAdabasDB};
        for (size_t i=0; i<sizeof(pButtons)/sizeof(pButtons[0]); ++i)
        {
            Point aOldPos = pButtons[i]->GetPosPixel();
            pButtons[i]->SetPosPixel(Point(aOldPos.X() - nLostPixels, aOldPos.Y()));
        }

        // resize the dialog itself
        aOldSize = GetSizePixel();
        SetSizePixel(Size(aOldSize.Width() - nLostPixels, aOldSize.Height()));
    }

    fillListBox(_rDatasources);
#ifdef HAVE_ODBC_ADMINISTRATION
    // allow ODBC datasource managenment
    if ( DST_ODBC == _eType || DST_MYSQL_ODBC == _eType )
    {
        m_aManageDatasources.Show();
        m_aManageDatasources.Enable();
        m_aManageDatasources.SetClickHdl(LINK(this,ODatasourceSelectDialog,ManageClickHdl));
    }
#endif
    m_aDatasource.SetDoubleClickHdl(LINK(this,ODatasourceSelectDialog,ListDblClickHdl));
    FreeResource();
}

// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, ListDblClickHdl, ListBox *, pListBox )
{
    if (pListBox->GetSelectEntryCount())
        EndDialog(RET_OK);
    return 0;
}
// -----------------------------------------------------------------------
IMPL_LINK( ODatasourceSelectDialog, CreateDBClickHdl, PushButton*, /*pButton*/ )
{
    try
    {
        OSL_ENSURE(m_pOutputSet,"No itemset given!");
        Reference< ::com::sun::star::lang::XMultiServiceFactory > xORB = ::comphelper::getProcessServiceFactory();
        Reference<XCreateCatalog> xCatalog(xORB->createInstance(SERVICE_EXTENDED_ADABAS_DRIVER),UNO_QUERY);
        if ( xCatalog.is() && m_pOutputSet )
        {
            Sequence< Any > aArgs(2);
            aArgs[0] <<= PropertyValue(::rtl::OUString::createFromAscii("CreateCatalog"), 0,makeAny(xCatalog) , PropertyState_DIRECT_VALUE);
            aArgs[1] <<= PropertyValue(PROPERTY_PARENTWINDOW, 0, makeAny(VCLUnoHelper::GetInterface(this)), PropertyState_DIRECT_VALUE);

            Reference< XExecutableDialog > xDialog(
                xORB->createInstanceWithArguments(SERVICE_SDB_ADABASCREATIONDIALOG, aArgs), UNO_QUERY);
            if (!xDialog.is())
            {
                //  ShowServiceNotAvailableError(this, String(SERVICE_SDB_ADABASCREATIONDIALOG), sal_True);
                return 0L;
            }

            if ( xDialog->execute() == RET_OK )
            {
                Reference<XPropertySet> xProp(xDialog,UNO_QUERY);
                if(xProp.is())
                {
                    Reference<XPropertySetInfo> xPropInfo(xProp->getPropertySetInfo());
                    if(xPropInfo->hasPropertyByName(PROPERTY_DATABASENAME))
                    {
                        String sDatabaseName;
                        sDatabaseName = String(::comphelper::getString(xProp->getPropertyValue(PROPERTY_DATABASENAME)));
                        m_aDatasource.SelectEntryPos(m_aDatasource.InsertEntry( sDatabaseName ));

                    }
                    if ( xPropInfo->hasPropertyByName(PROPERTY_CONTROLUSER) )
                        m_pOutputSet->Put(SfxStringItem(DSID_CONN_CTRLUSER, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_CONTROLUSER))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_CONTROLPASSWORD) )
                        m_pOutputSet->Put(SfxStringItem(DSID_CONN_CTRLPWD, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_CONTROLPASSWORD))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_USER) )
                        m_pOutputSet->Put(SfxStringItem(DSID_USER, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_USER))));
                    if ( xPropInfo->hasPropertyByName(PROPERTY_PASSWORD) )
                    {
                        m_pOutputSet->Put(SfxStringItem(DSID_PASSWORD, ::comphelper::getString(xProp->getPropertyValue(PROPERTY_PASSWORD))));
                        m_pOutputSet->Put(SfxBoolItem(DSID_PASSWORDREQUIRED, TRUE));
                    }
                    if ( xPropInfo->hasPropertyByName(PROPERTY_CACHESIZE) )
                        m_pOutputSet->Put(SfxInt32Item(DSID_CONN_CACHESIZE, ::comphelper::getINT32(xProp->getPropertyValue(PROPERTY_CACHESIZE))));
                }
            }
        }
    }
    catch(Exception&)
    {
    }
    return 0L;
}
// -----------------------------------------------------------------------
#ifdef HAVE_ODBC_ADMINISTRATION
IMPL_LINK( ODatasourceSelectDialog, ManageClickHdl, PushButton*, EMPTYARG )
{
    OOdbcManagement aOdbcConfig;
    if (!aOdbcConfig.isLoaded())
    {
        // show an error message
        LocalResourceAccess aLocRes(DLG_DATASOURCE_SELECTION, RSC_MODALDIALOG);
        String sError(ModuleRes(STR_COULDNOTLOAD_CONFIGLIB));
        sError.SearchAndReplaceAscii("#lib#", aOdbcConfig.getLibraryName());
        ErrorBox aDialog(this, WB_OK, sError);
        aDialog.Execute();
        m_aDatasource.GrabFocus();
        m_aManageDatasources.Disable();
        return 1L;
    }

    aOdbcConfig.manageDataSources(GetSystemData()->hWnd);
    // now we have to look if there are any new datasources added
    StringBag aOdbcDatasources;
    OOdbcEnumeration aEnumeration;
    aEnumeration.getDatasourceNames(aOdbcDatasources);
    fillListBox(aOdbcDatasources);

    return 0L;
}
#endif
// -----------------------------------------------------------------------------
void ODatasourceSelectDialog::fillListBox(const StringBag& _rDatasources)
{
    ::rtl::OUString sSelected;
    if (m_aDatasource.GetEntryCount())
         sSelected = m_aDatasource.GetSelectEntry();
    m_aDatasource.Clear();
    // fill the list
    for (   ConstStringBagIterator aDS = _rDatasources.begin();
            aDS != _rDatasources.end();
            ++aDS
        )
    {
        m_aDatasource.InsertEntry( *aDS );
    }

    if (m_aDatasource.GetEntryCount())
    {
        if (sSelected.getLength())
            m_aDatasource.SelectEntry(sSelected);
        else        // select the first entry
            m_aDatasource.SelectEntryPos(0);
    }
}

//.........................................................................
}   // namespace dbaui
//.........................................................................

<|endoftext|>


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

    Copyright (c) 2004 Till Adam <adam@kde.org>

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

    This program is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

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

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include <interfaces/bodypartformatter.h>
#include <interfaces/bodypart.h>
#include <interfaces/bodyparturlhandler.h>
#include <khtmlparthtmlwriter.h>

#include <kmail/callback.h>
#include <kmail/kmmessage.h>

#include <kglobal.h>
#include <klocale.h>
#include <kstringhandler.h>
#include <kglobalsettings.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kapplication.h>

#include <QUrl>
#include <QFile>
#include <QDir>
#include <QTextDocument>

namespace {

  // TODO: Show filename header to make it possible to save the patch.
  // FIXME: The box should only be as wide as necessary.

  class Formatter : public KMail::Interface::BodyPartFormatter {
  public:
    Result format( KMail::Interface::BodyPart *bodyPart, KMail::HtmlWriter *writer ) const {

      if ( !writer ) return Ok;

      if (  bodyPart->defaultDisplay() == KMail::Interface::BodyPart::AsIcon )
        return AsIcon;

      const QString diff = bodyPart->asText();
      if ( diff.isEmpty() ) return AsIcon;

      QString addedLineStyle = QString::fromLatin1(
        "style=\""
        "color: green;\"");
      QString fileAddStyle( "style=\"font-weight: bold; "
                            "color: green; \"" );

      QString removedLineStyle = QString::fromLatin1(
        "style=\""
        "color: red;\"");
      QString fileRemoveStyle( "style=\"font-weight: bold; "
                               "color: red ;\"" );

      QString tableStyle = QString::fromLatin1(
        "style=\""
        "text-align: -khtml-auto; "
        "border: solid black 1px; "
        "padding: 0.5em; "
        "margin: 0em;\"");

      QString sepStyle( "style=\"color: black; font-weight: bold;\"" );
      QString chunkStyle( "style=\"color: blue;\"" );

      QString html = "

";
      html += "
";

      QStringList lines = diff.split( '\n' );
      for ( QStringList::Iterator it = lines.begin(); it != lines.end(); ++it ) {
        QString line( Qt::escape( *it ) );
        QString style;
        if ( line.length() > 0 ) {
          if ( line.startsWith( "+++" ) ) {
            style = fileAddStyle;
          } else if ( line.startsWith( "---" ) ) {
            style = fileRemoveStyle;
          } else if ( line.startsWith( "+" ) || line.startsWith( ">" ) ) {
            style = addedLineStyle;
          } else if ( line.startsWith( "-" ) || line.startsWith( "<" ) ) {
            style = removedLineStyle;
          } else if ( line.startsWith( "==") ) {
            style = sepStyle;
          } else if ( line.startsWith( "@@" ) ) {
            style = chunkStyle;
          } else {
            style = "";
          }
        }
        html += "" + line + "
";
      }

      html += "

";
      //qDebug( "%s", html.toLatin1() );
      writer->queue( html );

      return Ok;
    }
  };

  class Plugin : public KMail::Interface::BodyPartFormatterPlugin {
  public:
    const KMail::Interface::BodyPartFormatter * bodyPartFormatter( int idx ) const {
      return idx == 0 ? new Formatter() : 0 ;
    }
    const char * type( int idx ) const {
      return idx == 0 ? "text" : 0 ;
    }
    const char * subtype( int idx ) const {
      return idx == 0 ? "x-diff" : 0 ;
    }

    const KMail::Interface::BodyPartURLHandler * urlHandler( int ) const { return 0; }
  };

}

extern "C"
KMail::Interface::BodyPartFormatterPlugin *
libkmail_bodypartformatter_text_xdiff_create_bodypart_formatter_plugin() {
  return new Plugin();
}
<commit_msg>fix export<commit_after>/*
    This file is part of kdepim.

    Copyright (c) 2004 Till Adam <adam@kde.org>

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

    This program is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    General Public License for more details.

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

    In addition, as a special exception, the copyright holders give
    permission to link the code of this program with any edition of
    the Qt library by Trolltech AS, Norway (or with modified versions
    of Qt that use the same license as Qt), and distribute linked
    combinations including the two.  You must obey the GNU General
    Public License in all respects for all of the code used other than
    Qt.  If you modify this file, you may extend this exception to
    your version of the file, but you are not obligated to do so.  If
    you do not wish to do so, delete this exception statement from
    your version.
*/

#include <interfaces/bodypartformatter.h>
#include <interfaces/bodypart.h>
#include <interfaces/bodyparturlhandler.h>
#include <khtmlparthtmlwriter.h>

#include <kmail/callback.h>
#include <kmail/kmmessage.h>

#include <kglobal.h>
#include <klocale.h>
#include <kstringhandler.h>
#include <kglobalsettings.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kapplication.h>
#include <kdepimmacros.h>

#include <QUrl>
#include <QFile>
#include <QDir>
#include <QTextDocument>

namespace {

  // TODO: Show filename header to make it possible to save the patch.
  // FIXME: The box should only be as wide as necessary.

  class Formatter : public KMail::Interface::BodyPartFormatter {
  public:
    Result format( KMail::Interface::BodyPart *bodyPart, KMail::HtmlWriter *writer ) const {

      if ( !writer ) return Ok;

      if (  bodyPart->defaultDisplay() == KMail::Interface::BodyPart::AsIcon )
        return AsIcon;

      const QString diff = bodyPart->asText();
      if ( diff.isEmpty() ) return AsIcon;

      QString addedLineStyle = QString::fromLatin1(
        "style=\""
        "color: green;\"");
      QString fileAddStyle( "style=\"font-weight: bold; "
                            "color: green; \"" );

      QString removedLineStyle = QString::fromLatin1(
        "style=\""
        "color: red;\"");
      QString fileRemoveStyle( "style=\"font-weight: bold; "
                               "color: red ;\"" );

      QString tableStyle = QString::fromLatin1(
        "style=\""
        "text-align: -khtml-auto; "
        "border: solid black 1px; "
        "padding: 0.5em; "
        "margin: 0em;\"");

      QString sepStyle( "style=\"color: black; font-weight: bold;\"" );
      QString chunkStyle( "style=\"color: blue;\"" );

      QString html = "

";
      html += "
";

      QStringList lines = diff.split( '\n' );
      for ( QStringList::Iterator it = lines.begin(); it != lines.end(); ++it ) {
        QString line( Qt::escape( *it ) );
        QString style;
        if ( line.length() > 0 ) {
          if ( line.startsWith( "+++" ) ) {
            style = fileAddStyle;
          } else if ( line.startsWith( "---" ) ) {
            style = fileRemoveStyle;
          } else if ( line.startsWith( "+" ) || line.startsWith( ">" ) ) {
            style = addedLineStyle;
          } else if ( line.startsWith( "-" ) || line.startsWith( "<" ) ) {
            style = removedLineStyle;
          } else if ( line.startsWith( "==") ) {
            style = sepStyle;
          } else if ( line.startsWith( "@@" ) ) {
            style = chunkStyle;
          } else {
            style = "";
          }
        }
        html += "" + line + "
";
      }

      html += "

";
      //qDebug( "%s", html.toLatin1() );
      writer->queue( html );

      return Ok;
    }
  };

  class Plugin : public KMail::Interface::BodyPartFormatterPlugin {
  public:
    const KMail::Interface::BodyPartFormatter * bodyPartFormatter( int idx ) const {
      return idx == 0 ? new Formatter() : 0 ;
    }
    const char * type( int idx ) const {
      return idx == 0 ? "text" : 0 ;
    }
    const char * subtype( int idx ) const {
      return idx == 0 ? "x-diff" : 0 ;
    }

    const KMail::Interface::BodyPartURLHandler * urlHandler( int ) const { return 0; }
  };

}

extern "C"
KDE_EXPORT KMail::Interface::BodyPartFormatterPlugin *
libkmail_bodypartformatter_text_xdiff_create_bodypart_formatter_plugin() {
  return new Plugin();
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Christoph Uhde
////////////////////////////////////////////////////////////////////////////////

#include "RocksDBOptionFeature.h"
#include "Basics/Exceptions.h"
#include "Basics/FileUtils.h"
#include "Basics/process-utils.h"
#include "Basics/tri-strings.h"
#include "Logger/Logger.h"
#include "ProgramOptions/ProgramOptions.h"
#include "ProgramOptions/Section.h"
#include "RestServer/DatabasePathFeature.h"

#include <rocksdb/options.h>
#include <rocksdb/table.h>

#include <thread>

using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::options;

namespace {
rocksdb::Options rocksDBDefaults;
rocksdb::BlockBasedTableOptions rocksDBTableOptionsDefaults;
}

RocksDBOptionFeature::RocksDBOptionFeature(
    application_features::ApplicationServer* server)
    : application_features::ApplicationFeature(server, "RocksDBOption"),
      _writeBufferSize(rocksDBDefaults.write_buffer_size),
      _maxWriteBufferNumber(rocksDBDefaults.max_write_buffer_number),
      _delayedWriteRate(rocksDBDefaults.delayed_write_rate),
      _minWriteBufferNumberToMerge(
          rocksDBDefaults.min_write_buffer_number_to_merge),
      _numLevels(rocksDBDefaults.num_levels),
      _numUncompressedLevels(2),
      _maxBytesForLevelBase(rocksDBDefaults.max_bytes_for_level_base),
      _maxBytesForLevelMultiplier(
          rocksDBDefaults.max_bytes_for_level_multiplier),
      _baseBackgroundCompactions(rocksDBDefaults.base_background_compactions),
      _maxBackgroundCompactions(rocksDBDefaults.max_background_compactions),
      _maxFlushes(rocksDBDefaults.max_background_flushes),
      _numThreadsHigh(rocksDBDefaults.max_background_flushes),
      _numThreadsLow(rocksDBDefaults.max_background_compactions),
      _blockCacheSize((TRI_PhysicalMemory >= (static_cast<uint64_t>(4) << 30))
        ? static_cast<uint64_t>(((TRI_PhysicalMemory - (static_cast<uint64_t>(2) << 30)) * 0.3))
        : (256 << 20)),
      _blockCacheShardBits(0),
      _tableBlockSize(rocksDBTableOptionsDefaults.block_size),
      _recycleLogFileNum(rocksDBDefaults.recycle_log_file_num),
      _compactionReadaheadSize(rocksDBDefaults.compaction_readahead_size),
      _verifyChecksumsInCompaction(
          rocksDBDefaults.verify_checksums_in_compaction),
      _optimizeFiltersForHits(rocksDBDefaults.optimize_filters_for_hits),
      _useDirectReads(rocksDBDefaults.use_direct_reads),
      _useDirectWrites(rocksDBDefaults.use_direct_writes),
      _useFSync(rocksDBDefaults.use_fsync),
      _skipCorrupted(false) {
  uint64_t testSize = _blockCacheSize >> 19;
  while (testSize > 0) {
    _blockCacheShardBits++;
    testSize >>= 1;
  }

  setOptional(true);
  requiresElevatedPrivileges(false);
  startsAfter("DatabasePath");

  // increase parallelism and re-fetch the number of threads
  rocksDBDefaults.IncreaseParallelism(std::thread::hardware_concurrency());
  _numThreadsHigh = rocksDBDefaults.max_background_flushes;
  _numThreadsLow = rocksDBDefaults.max_background_compactions;
}

void RocksDBOptionFeature::collectOptions(
    std::shared_ptr<ProgramOptions> options) {
  options->addSection("rocksdb", "Configure the RocksDB engine");

  options->addObsoleteOption("--rocksdb.enabled",
                             "obsolete always active - Whether or not the "
                             "RocksDB engine is enabled for the persistent "
                             "index",
                             true);

  options->addOption("--rocksdb.write-buffer-size",
                     "amount of data to build up in memory before converting "
                     "to a sorted on-disk file (0 = disabled)",
                     new UInt64Parameter(&_writeBufferSize));

  options->addOption("--rocksdb.max-write-buffer-number",
                     "maximum number of write buffers that built up in memory",
                     new UInt64Parameter(&_maxWriteBufferNumber));

  options->addHiddenOption(
      "--rocksdb.delayed_write_rate",
      "limited write rate to DB (in bytes per second) if we are writing to the "
      "last "
      "mem table allowed and we allow more than 3 mem tables",
      new UInt64Parameter(&_delayedWriteRate));

  options->addOption("--rocksdb.min-write-buffer-number-to-merge",
                     "minimum number of write buffers that will be merged "
                     "together before writing "
                     "to storage",
                     new UInt64Parameter(&_minWriteBufferNumberToMerge));

  options->addOption("--rocksdb.num-levels",
                     "number of levels for the database",
                     new UInt64Parameter(&_numLevels));

  options->addOption("--rocksdb.num-uncompressed-levels",
                     "number of uncompressed levels for the database",
                     new UInt64Parameter(&_numUncompressedLevels));

  options->addHiddenOption("--rocksdb.max-bytes-for-level-base",
                           "control maximum total data size for level-1",
                           new UInt64Parameter(&_maxBytesForLevelBase));

  options->addOption("--rocksdb.max-bytes-for-level-multiplier",
                     "maximum number of bytes for level L can be calculated as "
                     "max-bytes-for-level-base * "
                     "(max-bytes-for-level-multiplier ^ (L-1))",
                     new DoubleParameter(&_maxBytesForLevelMultiplier));

  options->addHiddenOption(
      "--rocksdb.verify-checksums-in-compaction",
      "if true, compaction will verify checksum on every read that happens "
      "as part of compaction",
      new BooleanParameter(&_verifyChecksumsInCompaction));

  options->addHiddenOption(
      "--rocksdb.optimize-filters-for-hits",
      "this flag specifies that the implementation should optimize the filters "
      "mainly for cases where keys are found rather than also optimize for "
      "keys "
      "missed. This would be used in cases where the application knows that "
      "there are very few misses or the performance in the case of misses is "
      "not "
      "important",
      new BooleanParameter(&_optimizeFiltersForHits));

#ifdef __linux__
  options->addHiddenOption("--rocksdb.use-direct-reads",
                           "use O_DIRECT for reading files",
                           new BooleanParameter(&_useDirectReads));

  options->addHiddenOption("--rocksdb.use-direct-writes",
                           "use O_DIRECT for writing files",
                           new BooleanParameter(&_useDirectWrites));
#endif

  options->addHiddenOption("--rocksdb.use-fsync",
                           "issue an fsync when writing to disk (set to true "
                           "for issuing fdatasync only)",
                           new BooleanParameter(&_useFSync));

  options->addHiddenOption(
      "--rocksdb.base-background-compactions",
      "suggested number of concurrent background compaction jobs",
      new UInt64Parameter(&_baseBackgroundCompactions));

  options->addOption("--rocksdb.max-background-compactions",
                     "maximum number of concurrent background compaction jobs",
                     new UInt64Parameter(&_maxBackgroundCompactions));

  options->addOption("--rocksdb.max-background-flushes",
                     "maximum number of concurrent flush operations",
                     new UInt64Parameter(&_maxFlushes));

  options->addOption(
      "--rocksdb.num-threads-priority-high",
      "number of threads for high priority operations (e.g. flush)",
      new UInt64Parameter(&_numThreadsHigh));

  options->addOption(
      "--rocksdb.num-threads-priority-low",
      "number of threads for low priority operations (e.g. compaction)",
      new UInt64Parameter(&_numThreadsLow));

  options->addOption("--rocksdb.block-cache-size",
                     "size of block cache in bytes",
                     new UInt64Parameter(&_blockCacheSize));

  options->addOption("--rocksdb.block-cache-shard-bits",
                     "number of shard bits to use for block cache",
                     new UInt64Parameter(&_blockCacheShardBits));

  options->addOption("--rocksdb.table-block-size",
                     "approximate size (in bytes) of user data packed per block",
                     new UInt64Parameter(&_tableBlockSize));

  options->addHiddenOption("--rocksdb.recycle-log-file-num",
                           "number of log files to keep around for recycling",
                           new UInt64Parameter(&_recycleLogFileNum));

  options->addHiddenOption(
      "--rocksdb.compaction-read-ahead-size",
      "if non-zero, we perform bigger reads when doing compaction. If you're "
      "running RocksDB on spinning disks, you should set this to at least 2MB. "
      "that way RocksDB's compaction is doing sequential instead of random "
      "reads.",
      new UInt64Parameter(&_compactionReadaheadSize));

  options->addHiddenOption("--rocksdb.wal-recovery-skip-corrupted",
                           "skip corrupted records in WAL recovery",
                           new BooleanParameter(&_skipCorrupted));
}

void RocksDBOptionFeature::validateOptions(
    std::shared_ptr<ProgramOptions> options) {
  if (_writeBufferSize > 0 && _writeBufferSize < 1024 * 1024) {
    LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
        << "invalid value for '--rocksdb.write-buffer-size'";
    FATAL_ERROR_EXIT();
  }
  if (_maxBytesForLevelMultiplier <= 0.0) {
    LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
        << "invalid value for '--rocksdb.max-bytes-for-level-multiplier'";
    FATAL_ERROR_EXIT();
  }
  if (_numLevels < 1 || _numLevels > 20) {
    LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
        << "invalid value for '--rocksdb.num-levels'";
    FATAL_ERROR_EXIT();
  }
  if (_baseBackgroundCompactions < 1 || _baseBackgroundCompactions > 64) {
    LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
        << "invalid value for '--rocksdb.base-background-compactions'";
    FATAL_ERROR_EXIT();
  }
  if (_maxBackgroundCompactions < _baseBackgroundCompactions) {
    _maxBackgroundCompactions = _baseBackgroundCompactions;
  }
  if (_maxFlushes < 1 || _maxFlushes > 64) {
    LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
        << "invalid value for '--rocksdb.max-background-flushes'";
    FATAL_ERROR_EXIT();
  }
  if (_numThreadsHigh < 1 || _numThreadsHigh > 64) {
    LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
        << "invalid value for '--rocksdb.num-threads-priority-high'";
    FATAL_ERROR_EXIT();
  }
  if (_numThreadsLow < 1 || _numThreadsLow > 256) {
    LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
        << "invalid value for '--rocksdb.num-threads-priority-low'";
    FATAL_ERROR_EXIT();
  }
  if (_blockCacheShardBits > 32) {
    LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
        << "invalid value for '--rocksdb.block-cache-shard-bits'";
    FATAL_ERROR_EXIT();
  }
}

void RocksDBOptionFeature::start() {
  LOG_TOPIC(TRACE, Logger::FIXME) << "using RocksDB options:"
                                  << " write_buffer_size: " << _writeBufferSize
                                  << " max_write_buffer_number: " << _maxWriteBufferNumber
                                  << " delayed_write_rate: " << _delayedWriteRate
                                  << " min_write_buffer_number_to_merge: " << _minWriteBufferNumberToMerge
                                  << " num_levels: " << _numLevels
                                  << " max_bytes_for_level_base: " << _maxBytesForLevelBase
                                  << " max_bytes_for_level_multiplier: " << _maxBytesForLevelMultiplier
                                  << " base_background_compactions: " << _baseBackgroundCompactions
                                  << " max_background_compactions: " << _maxBackgroundCompactions
                                  << " max_flushes: " << _maxFlushes
                                  << " num_threads_high: " << _numThreadsHigh
                                  << " num_threads_low: " << _numThreadsLow
                                  << " block_cache_size: " << _blockCacheSize
                                  << " block_cache_shard_bits: " << _blockCacheShardBits
                                  << " compaction_read_ahead_size: " << _compactionReadaheadSize
                                  << " verify_checksums_in_compaction: " << std::boolalpha << _verifyChecksumsInCompaction
                                  << " optimize_filters_for_hits: " << std::boolalpha << _optimizeFiltersForHits
                                  << " use_direct_reads: " << std::boolalpha << _useDirectReads
                                  << " use_direct_writes: " << std::boolalpha << _useDirectWrites
                                  << " use_fsync: " << std::boolalpha << _useFSync;
}
<commit_msg>increase default value for block_size to 16 * 1024<commit_after>////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Christoph Uhde
////////////////////////////////////////////////////////////////////////////////

#include "RocksDBOptionFeature.h"
#include "Basics/Exceptions.h"
#include "Basics/FileUtils.h"
#include "Basics/process-utils.h"
#include "Basics/tri-strings.h"
#include "Logger/Logger.h"
#include "ProgramOptions/ProgramOptions.h"
#include "ProgramOptions/Section.h"
#include "RestServer/DatabasePathFeature.h"

#include <rocksdb/options.h>
#include <rocksdb/table.h>

#include <thread>

using namespace arangodb;
using namespace arangodb::application_features;
using namespace arangodb::options;

namespace {
rocksdb::Options rocksDBDefaults;
rocksdb::BlockBasedTableOptions rocksDBTableOptionsDefaults;
}

RocksDBOptionFeature::RocksDBOptionFeature(
    application_features::ApplicationServer* server)
    : application_features::ApplicationFeature(server, "RocksDBOption"),
      _writeBufferSize(rocksDBDefaults.write_buffer_size),
      _maxWriteBufferNumber(rocksDBDefaults.max_write_buffer_number),
      _delayedWriteRate(rocksDBDefaults.delayed_write_rate),
      _minWriteBufferNumberToMerge(
          rocksDBDefaults.min_write_buffer_number_to_merge),
      _numLevels(rocksDBDefaults.num_levels),
      _numUncompressedLevels(2),
      _maxBytesForLevelBase(rocksDBDefaults.max_bytes_for_level_base),
      _maxBytesForLevelMultiplier(
          rocksDBDefaults.max_bytes_for_level_multiplier),
      _baseBackgroundCompactions(rocksDBDefaults.base_background_compactions),
      _maxBackgroundCompactions(rocksDBDefaults.max_background_compactions),
      _maxFlushes(rocksDBDefaults.max_background_flushes),
      _numThreadsHigh(rocksDBDefaults.max_background_flushes),
      _numThreadsLow(rocksDBDefaults.max_background_compactions),
      _blockCacheSize((TRI_PhysicalMemory >= (static_cast<uint64_t>(4) << 30))
        ? static_cast<uint64_t>(((TRI_PhysicalMemory - (static_cast<uint64_t>(2) << 30)) * 0.3))
        : (256 << 20)),
      _blockCacheShardBits(0),
      _tableBlockSize(std::max(rocksDBTableOptionsDefaults.block_size, static_cast<decltype(rocksDBTableOptionsDefaults.block_size)>(16 * 1024))),
      _recycleLogFileNum(rocksDBDefaults.recycle_log_file_num),
      _compactionReadaheadSize(rocksDBDefaults.compaction_readahead_size),
      _verifyChecksumsInCompaction(
          rocksDBDefaults.verify_checksums_in_compaction),
      _optimizeFiltersForHits(rocksDBDefaults.optimize_filters_for_hits),
      _useDirectReads(rocksDBDefaults.use_direct_reads),
      _useDirectWrites(rocksDBDefaults.use_direct_writes),
      _useFSync(rocksDBDefaults.use_fsync),
      _skipCorrupted(false) {
  uint64_t testSize = _blockCacheSize >> 19;
  while (testSize > 0) {
    _blockCacheShardBits++;
    testSize >>= 1;
  }

  setOptional(true);
  requiresElevatedPrivileges(false);
  startsAfter("DatabasePath");

  // increase parallelism and re-fetch the number of threads
  rocksDBDefaults.IncreaseParallelism(std::thread::hardware_concurrency());
  _numThreadsHigh = rocksDBDefaults.max_background_flushes;
  _numThreadsLow = rocksDBDefaults.max_background_compactions;
}

void RocksDBOptionFeature::collectOptions(
    std::shared_ptr<ProgramOptions> options) {
  options->addSection("rocksdb", "Configure the RocksDB engine");

  options->addObsoleteOption("--rocksdb.enabled",
                             "obsolete always active - Whether or not the "
                             "RocksDB engine is enabled for the persistent "
                             "index",
                             true);

  options->addOption("--rocksdb.write-buffer-size",
                     "amount of data to build up in memory before converting "
                     "to a sorted on-disk file (0 = disabled)",
                     new UInt64Parameter(&_writeBufferSize));

  options->addOption("--rocksdb.max-write-buffer-number",
                     "maximum number of write buffers that built up in memory",
                     new UInt64Parameter(&_maxWriteBufferNumber));

  options->addHiddenOption(
      "--rocksdb.delayed_write_rate",
      "limited write rate to DB (in bytes per second) if we are writing to the "
      "last "
      "mem table allowed and we allow more than 3 mem tables",
      new UInt64Parameter(&_delayedWriteRate));

  options->addOption("--rocksdb.min-write-buffer-number-to-merge",
                     "minimum number of write buffers that will be merged "
                     "together before writing "
                     "to storage",
                     new UInt64Parameter(&_minWriteBufferNumberToMerge));

  options->addOption("--rocksdb.num-levels",
                     "number of levels for the database",
                     new UInt64Parameter(&_numLevels));

  options->addOption("--rocksdb.num-uncompressed-levels",
                     "number of uncompressed levels for the database",
                     new UInt64Parameter(&_numUncompressedLevels));

  options->addHiddenOption("--rocksdb.max-bytes-for-level-base",
                           "control maximum total data size for level-1",
                           new UInt64Parameter(&_maxBytesForLevelBase));

  options->addOption("--rocksdb.max-bytes-for-level-multiplier",
                     "maximum number of bytes for level L can be calculated as "
                     "max-bytes-for-level-base * "
                     "(max-bytes-for-level-multiplier ^ (L-1))",
                     new DoubleParameter(&_maxBytesForLevelMultiplier));

  options->addHiddenOption(
      "--rocksdb.verify-checksums-in-compaction",
      "if true, compaction will verify checksum on every read that happens "
      "as part of compaction",
      new BooleanParameter(&_verifyChecksumsInCompaction));

  options->addHiddenOption(
      "--rocksdb.optimize-filters-for-hits",
      "this flag specifies that the implementation should optimize the filters "
      "mainly for cases where keys are found rather than also optimize for "
      "keys "
      "missed. This would be used in cases where the application knows that "
      "there are very few misses or the performance in the case of misses is "
      "not "
      "important",
      new BooleanParameter(&_optimizeFiltersForHits));

#ifdef __linux__
  options->addHiddenOption("--rocksdb.use-direct-reads",
                           "use O_DIRECT for reading files",
                           new BooleanParameter(&_useDirectReads));

  options->addHiddenOption("--rocksdb.use-direct-writes",
                           "use O_DIRECT for writing files",
                           new BooleanParameter(&_useDirectWrites));
#endif

  options->addHiddenOption("--rocksdb.use-fsync",
                           "issue an fsync when writing to disk (set to true "
                           "for issuing fdatasync only)",
                           new BooleanParameter(&_useFSync));

  options->addHiddenOption(
      "--rocksdb.base-background-compactions",
      "suggested number of concurrent background compaction jobs",
      new UInt64Parameter(&_baseBackgroundCompactions));

  options->addOption("--rocksdb.max-background-compactions",
                     "maximum number of concurrent background compaction jobs",
                     new UInt64Parameter(&_maxBackgroundCompactions));

  options->addOption("--rocksdb.max-background-flushes",
                     "maximum number of concurrent flush operations",
                     new UInt64Parameter(&_maxFlushes));

  options->addOption(
      "--rocksdb.num-threads-priority-high",
      "number of threads for high priority operations (e.g. flush)",
      new UInt64Parameter(&_numThreadsHigh));

  options->addOption(
      "--rocksdb.num-threads-priority-low",
      "number of threads for low priority operations (e.g. compaction)",
      new UInt64Parameter(&_numThreadsLow));

  options->addOption("--rocksdb.block-cache-size",
                     "size of block cache in bytes",
                     new UInt64Parameter(&_blockCacheSize));

  options->addOption("--rocksdb.block-cache-shard-bits",
                     "number of shard bits to use for block cache",
                     new UInt64Parameter(&_blockCacheShardBits));

  options->addOption("--rocksdb.table-block-size",
                     "approximate size (in bytes) of user data packed per block",
                     new UInt64Parameter(&_tableBlockSize));

  options->addHiddenOption("--rocksdb.recycle-log-file-num",
                           "number of log files to keep around for recycling",
                           new UInt64Parameter(&_recycleLogFileNum));

  options->addHiddenOption(
      "--rocksdb.compaction-read-ahead-size",
      "if non-zero, we perform bigger reads when doing compaction. If you're "
      "running RocksDB on spinning disks, you should set this to at least 2MB. "
      "that way RocksDB's compaction is doing sequential instead of random "
      "reads.",
      new UInt64Parameter(&_compactionReadaheadSize));

  options->addHiddenOption("--rocksdb.wal-recovery-skip-corrupted",
                           "skip corrupted records in WAL recovery",
                           new BooleanParameter(&_skipCorrupted));
}

void RocksDBOptionFeature::validateOptions(
    std::shared_ptr<ProgramOptions> options) {
  if (_writeBufferSize > 0 && _writeBufferSize < 1024 * 1024) {
    LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
        << "invalid value for '--rocksdb.write-buffer-size'";
    FATAL_ERROR_EXIT();
  }
  if (_maxBytesForLevelMultiplier <= 0.0) {
    LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
        << "invalid value for '--rocksdb.max-bytes-for-level-multiplier'";
    FATAL_ERROR_EXIT();
  }
  if (_numLevels < 1 || _numLevels > 20) {
    LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
        << "invalid value for '--rocksdb.num-levels'";
    FATAL_ERROR_EXIT();
  }
  if (_baseBackgroundCompactions < 1 || _baseBackgroundCompactions > 64) {
    LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
        << "invalid value for '--rocksdb.base-background-compactions'";
    FATAL_ERROR_EXIT();
  }
  if (_maxBackgroundCompactions < _baseBackgroundCompactions) {
    _maxBackgroundCompactions = _baseBackgroundCompactions;
  }
  if (_maxFlushes < 1 || _maxFlushes > 64) {
    LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
        << "invalid value for '--rocksdb.max-background-flushes'";
    FATAL_ERROR_EXIT();
  }
  if (_numThreadsHigh < 1 || _numThreadsHigh > 64) {
    LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
        << "invalid value for '--rocksdb.num-threads-priority-high'";
    FATAL_ERROR_EXIT();
  }
  if (_numThreadsLow < 1 || _numThreadsLow > 256) {
    LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
        << "invalid value for '--rocksdb.num-threads-priority-low'";
    FATAL_ERROR_EXIT();
  }
  if (_blockCacheShardBits > 32) {
    LOG_TOPIC(FATAL, arangodb::Logger::FIXME)
        << "invalid value for '--rocksdb.block-cache-shard-bits'";
    FATAL_ERROR_EXIT();
  }
}

void RocksDBOptionFeature::start() {
  LOG_TOPIC(TRACE, Logger::FIXME) << "using RocksDB options:"
                                  << " write_buffer_size: " << _writeBufferSize
                                  << " max_write_buffer_number: " << _maxWriteBufferNumber
                                  << " delayed_write_rate: " << _delayedWriteRate
                                  << " min_write_buffer_number_to_merge: " << _minWriteBufferNumberToMerge
                                  << " num_levels: " << _numLevels
                                  << " max_bytes_for_level_base: " << _maxBytesForLevelBase
                                  << " max_bytes_for_level_multiplier: " << _maxBytesForLevelMultiplier
                                  << " base_background_compactions: " << _baseBackgroundCompactions
                                  << " max_background_compactions: " << _maxBackgroundCompactions
                                  << " max_flushes: " << _maxFlushes
                                  << " num_threads_high: " << _numThreadsHigh
                                  << " num_threads_low: " << _numThreadsLow
                                  << " block_cache_size: " << _blockCacheSize
                                  << " block_cache_shard_bits: " << _blockCacheShardBits
                                  << " compaction_read_ahead_size: " << _compactionReadaheadSize
                                  << " verify_checksums_in_compaction: " << std::boolalpha << _verifyChecksumsInCompaction
                                  << " optimize_filters_for_hits: " << std::boolalpha << _optimizeFiltersForHits
                                  << " use_direct_reads: " << std::boolalpha << _useDirectReads
                                  << " use_direct_writes: " << std::boolalpha << _useDirectWrites
                                  << " use_fsync: " << std::boolalpha << _useFSync;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cmath>

using namespace std;

double ex_ji(double x_j, double x_i, double R_ji) {
    return ((-(x_j-x_i))/R_ji);
}

double ey_ji(double y_j, double y_i, double R_ji) {
    return ((-(y_j-y_i))/R_ji);
}

double ez_ji(double z_j, double z_i, double R_ji) {
    return ((-(z_j-z_i))/R_ji);
}

double ex_jk(double x_j, double x_k, double R_jk) {
    return ((-(x_j-x_k))/R_jk);
}

double ey_jk(double y_j, double y_k, double R_jk) {
    return ((-(y_j-y_k))/R_jk);
}

double ez_jk(double z_j, double z_k, double R_jk) {
    return ((-(z_j-z_k))/R_jk);
}

double ex_kl(double x_k, double x_l, double R_kl) {
    return ((-(x_k-x_l))/R_kl);
}

double ey_kl(double y_k, double y_l, double R_kl) {
    return ((-(y_k-y_l))/R_kl);
}

double ez_kl(double z_k, double z_l, double R_kl) {
    return ((-(z_k-z_l))/R_kl);
}

double phi_ijk(double ex_ji, double ey_ji, double ez_ji, double ex_jk, double ey_jk, double ez_jk) {
    return acos((ex_ji)*(ex_jk)+(ey_ji)*(ey_jk)+(ez_ji)*(ez_jk));
}

double phi_jkl(double ex_kj, double ey_kj, double ez_kj, double ex_kl, double ey_kl, double ez_kl) {
    return acos((ex_kj)*(ex_kl)+(ey_kj)*(ey_kl)+(ez_kj)*(ez_kl));
}
<commit_msg>adding using fstream<commit_after>#include <iostream>
#include <cmath>
#include <fstream>

using namespace std;

double ex_ji(double x_j, double x_i, double R_ji) {
    return ((-(x_j-x_i))/R_ji);
}

double ey_ji(double y_j, double y_i, double R_ji) {
    return ((-(y_j-y_i))/R_ji);
}

double ez_ji(double z_j, double z_i, double R_ji) {
    return ((-(z_j-z_i))/R_ji);
}

double ex_jk(double x_j, double x_k, double R_jk) {
    return ((-(x_j-x_k))/R_jk);
}

double ey_jk(double y_j, double y_k, double R_jk) {
    return ((-(y_j-y_k))/R_jk);
}

double ez_jk(double z_j, double z_k, double R_jk) {
    return ((-(z_j-z_k))/R_jk);
}

double ex_kl(double x_k, double x_l, double R_kl) {
    return ((-(x_k-x_l))/R_kl);
}

double ey_kl(double y_k, double y_l, double R_kl) {
    return ((-(y_k-y_l))/R_kl);
}

double ez_kl(double z_k, double z_l, double R_kl) {
    return ((-(z_k-z_l))/R_kl);
}

double phi_ijk(double ex_ji, double ey_ji, double ez_ji, double ex_jk, double ey_jk, double ez_jk) {
    return acos((ex_ji)*(ex_jk)+(ey_ji)*(ey_jk)+(ez_ji)*(ez_jk));
}

double phi_jkl(double ex_kj, double ey_kj, double ez_kj, double ex_kl, double ey_kl, double ez_kl) {
    return acos((ex_kj)*(ex_kl)+(ey_kj)*(ey_kl)+(ez_kj)*(ez_kl));
}
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2007 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

#include "gdal_featureset.hpp"
#include <gdal_priv.h>

// boost
#include <boost/format.hpp>

using mapnik::query;
using mapnik::coord2d;
using mapnik::box2d;
using mapnik::Feature;
using mapnik::feature_ptr;
using mapnik::CoordTransform;
using mapnik::point_impl;
using mapnik::geometry2d;

gdal_featureset::gdal_featureset(GDALDataset & dataset, int band, gdal_query q)
    : dataset_(dataset),
      band_(band),
      gquery_(q),
      first_(true) {}

gdal_featureset::~gdal_featureset()
{
#ifdef MAPNIK_DEBUG
    std::clog << "GDAL Plugin: closing dataset = " << &dataset_ << "\n";
#endif
    GDALClose(&dataset_);
}

feature_ptr gdal_featureset::next()
{
    if (first_)
    {
	first_ = false;
#ifdef MAPNIK_DEBUG
	std::clog << "GDAL Plugin: featureset, dataset = " << &dataset_ << "\n";
#endif

	query *q = boost::get<query>(&gquery_);
	if(q) {
	    return get_feature(*q);
	} else {
	    coord2d *p = boost::get<coord2d>(&gquery_);
	    if(p) {
		return get_feature_at_point(*p);
	    }
	}
	// should never reach here
    }
    return feature_ptr();
}

feature_ptr gdal_featureset::get_feature(mapnik::query const& q)
{
    feature_ptr feature(new Feature(1));

    GDALRasterBand * red = 0;
    GDALRasterBand * green = 0;
    GDALRasterBand * blue = 0;
    GDALRasterBand * alpha = 0;
    GDALRasterBand * grey = 0;

    int nbands = dataset_.GetRasterCount();

    unsigned raster_width = dataset_.GetRasterXSize();
    unsigned raster_height = dataset_.GetRasterYSize();

    // TODO - pull from class attributes...
    double tr[6];
    dataset_.GetGeoTransform(tr);

    double dx = tr[1];
    double dy = tr[5];

    double x0 = tr[0] + (raster_height) * tr[2]; // minx
    double y0 = tr[3] + (raster_height) * tr[5]; // miny

    double x1 = tr[0] + (raster_width) * tr[1]; // maxx
    double y1 = tr[3] + (raster_width) * tr[4]; // maxy

    box2d<double> raster_extent(x0,y0,x1,y1);

    CoordTransform t(raster_width,raster_height,raster_extent,0,0);
    box2d<double> intersect = raster_extent.intersect(q.get_bbox());
    box2d<double> box = t.forward(intersect);

    //size of resized output pixel in source image domain
    double margin_x = 1.0/(fabs(dx)*boost::get<0>(q.resolution()));
    double margin_y = 1.0/(fabs(dy)*boost::get<1>(q.resolution()));
    if (margin_x < 1)
        margin_x = 1.0;
    if (margin_y < 1)
        margin_y = 1.0;
    //select minimum raster containing whole box
    int x_off = rint(box.minx() - margin_x);
    int y_off = rint(box.miny() - margin_y);
    int end_x = rint(box.maxx() + margin_x);
    int end_y = rint(box.maxy() + margin_y);
    //clip to available data
    if (x_off < 0)
        x_off = 0;
    if (y_off < 0)
        y_off = 0;
    if (end_x > (int)raster_width)
        end_x = raster_width;
    if (end_y > (int)raster_height)
        end_y = raster_height;
    int width = end_x - x_off;
    int height = end_y - y_off;
    // don't process almost invisible data
    if (box.width() < 0.5)
        width = 0;
    if (box.height() < 0.5)
        height = 0;
    //calculate actual box2d of returned raster
    box2d<double> feature_raster_extent(x_off, y_off, x_off+width, y_off+height);
    intersect = t.backward(feature_raster_extent);

#ifdef MAPNIK_DEBUG
    std::clog << "GDAL Plugin: Raster extent=" << raster_extent << "\n";
    std::clog << "GDAL Plugin: View extent=" << intersect << "\n";
    std::clog << "GDAL Plugin: Query resolution=" << boost::get<0>(q.resolution()) << "," << boost::get<1>(q.resolution()) << "\n";
    std::clog << boost::format("GDAL Plugin: StartX=%d StartY=%d Width=%d Height=%d \n") % x_off % y_off % width % height;
#endif

    if (width > 0 && height > 0)
    {
	int im_width = int(boost::get<0>(q.resolution()) * intersect.width() + 0.5);
	int im_height = int(boost::get<1>(q.resolution()) * intersect.height() + 0.5);

	// case where we need to avoid upsampling so that the
	// image can be later scaled within raster_symbolizer
	if (im_width >= width || im_height >= height)
	{
	    im_width = width;
	    im_height = height;
	}

	mapnik::image_data_32 image(im_width, im_height);
	image.set(0xffffffff);

#ifdef MAPNIK_DEBUG
	std::clog << "GDAL Plugin: Image Size=(" << im_width << "," << im_height << ")\n";
	std::clog << "GDAL Plugin: Reading band " << band_ << "\n";
#endif

	if (band_>0) // we are querying a single band
	{
	    float *imageData = (float*)image.getBytes();
	    GDALRasterBand * band = dataset_.GetRasterBand(band_);
	    band->RasterIO(GF_Read, x_off, y_off, width, height,
			   imageData, image.width(), image.height(),
			   GDT_Float32, 0, 0);

	    feature->set_raster(mapnik::raster_ptr(new mapnik::raster(intersect,image)));
	}

	else // working with all bands
	{
	    for (int i = 0; i < nbands; ++i)
	    {
		GDALRasterBand * band = dataset_.GetRasterBand(i+1);

#ifdef MAPNIK_DEBUG
		get_overview_meta(band);
#endif

		GDALColorInterp color_interp = band->GetColorInterpretation();
		switch (color_interp)
		{
		case GCI_RedBand:
		    red = band;
#ifdef MAPNIK_DEBUG
		    std::clog << "GDAL Plugin: Found red band" << "\n";
#endif
		    break;
		case GCI_GreenBand:
		    green = band;
#ifdef MAPNIK_DEBUG
		    std::clog << "GDAL Plugin: Found green band" << "\n";
#endif
		    break;
		case GCI_BlueBand:
		    blue = band;
#ifdef MAPNIK_DEBUG
		    std::clog << "GDAL Plugin: Found blue band" << "\n";
#endif
		    break;
		case GCI_AlphaBand:
		    alpha = band;
#ifdef MAPNIK_DEBUG
		    std::clog << "GDAL Plugin: Found alpha band" << "\n";
#endif
		    break;
		case GCI_GrayIndex:
		    grey = band;
#ifdef MAPNIK_DEBUG
		    std::clog << "GDAL Plugin: Found gray band" << "\n";
#endif
		    break;
		case GCI_PaletteIndex:
		{
		    grey = band;
#ifdef MAPNIK_DEBUG
		    std::clog << "GDAL Plugin: Found gray band, and colortable..." << "\n";
#endif
		    GDALColorTable *color_table = band->GetColorTable();

		    if ( color_table)
		    {
			int count = color_table->GetColorEntryCount();
#ifdef MAPNIK_DEBUG
			std::clog << "GDAL Plugin: Color Table count = " << count << "\n";
#endif
			for ( int i = 0; i < count; i++ )
			{
			    const GDALColorEntry *ce = color_table->GetColorEntry ( i );
			    if (!ce ) continue;
#ifdef MAPNIK_DEBUG
			    std::clog << "GDAL Plugin: Color entry RGB (" << ce->c1 << "," <<ce->c2 << "," << ce->c3 << ")\n";
#endif
			}
		    }
		    break;
		}
		case GCI_Undefined:
#ifdef MAPNIK_DEBUG
		    std::clog << "GDAL Plugin: Found undefined band (assumming gray band)" << "\n";
#endif
		    grey = band;
		    break;
		default:
#ifdef MAPNIK_DEBUG
		    std::clog << "GDAL Plugin: band type unknown!" << "\n";
#endif
		    break;
		}
	    }

	    if (red && green && blue)
	    {
#ifdef MAPNIK_DEBUG
		std::clog << "GDAL Plugin: processing rgb bands..." << "\n";
#endif
		red->RasterIO(GF_Read,x_off,y_off,width,height,image.getBytes() + 0,
			      image.width(),image.height(),GDT_Byte,4,4*image.width());
		green->RasterIO(GF_Read,x_off,y_off,width,height,image.getBytes() + 1,
				image.width(),image.height(),GDT_Byte,4,4*image.width());
		blue->RasterIO(GF_Read,x_off,y_off,width,height,image.getBytes() + 2,
			       image.width(),image.height(),GDT_Byte,4,4*image.width());
	    }
	    else if (grey)
	    {
#ifdef MAPNIK_DEBUG
		std::clog << "GDAL Plugin: processing gray band..." << "\n";
#endif
		grey->RasterIO(GF_Read,x_off,y_off,width,height,image.getBytes() + 0,
			       image.width(),image.height(),GDT_Byte, 4, 4 * image.width());
		grey->RasterIO(GF_Read,x_off,y_off,width,height,image.getBytes() + 1,
			       image.width(),image.height(),GDT_Byte, 4, 4 * image.width());
		grey->RasterIO(GF_Read,x_off,y_off,width,height,image.getBytes() + 2,
			       image.width(),image.height(),GDT_Byte, 4, 4 * image.width());
	    }

	    if (alpha)
	    {
#ifdef MAPNIK_DEBUG
		std::clog << "GDAL Plugin: processing alpha band..." << "\n";
#endif
		alpha->RasterIO(GF_Read,x_off,y_off,width,height,image.getBytes() + 3,
				image.width(),image.height(),GDT_Byte,4,4*image.width());
	    }

	    feature->set_raster(mapnik::raster_ptr(new mapnik::raster(intersect,image)));
	}
	return feature;
    }
    return feature_ptr();
}

feature_ptr gdal_featureset::get_feature_at_point(mapnik::coord2d const& pt)
{
    if (band_>0) {

	unsigned raster_xsize = dataset_.GetRasterXSize();
	unsigned raster_ysize = dataset_.GetRasterYSize();

	double gt[6];
	dataset_.GetGeoTransform(gt);

	double det = gt[1]*gt[5] - gt[2]*gt[4];
	// subtract half a pixel width & height because gdal coord reference
	// is the top-left corner of a pixel, not the center.
	double X = pt.x - gt[0] - gt[1]/2;
	double Y = pt.y - gt[3] - gt[5]/2;
	double det1 = gt[1]*Y + gt[4]*X;
	double det2 = gt[2]*Y + gt[5]*X;
	unsigned x = det2/det, y = det1/det;

	if(0<=x && x<raster_xsize && 0<=y && y<raster_ysize) {
#ifdef MAPNIK_DEBUG
	    std::clog << boost::format("GDAL Plugin: pt.x=%f pt.y=%f\n") % pt.x % pt.y;
	    std::clog << boost::format("GDAL Plugin: x=%f y=%f\n") % x % y;
#endif
	    GDALRasterBand * band = dataset_.GetRasterBand(band_);
	    int hasNoData;
	    double nodata = band->GetNoDataValue(&hasNoData);
	    double value;
	    band->RasterIO(GF_Read, x, y, 1, 1, &value, 1, 1, GDT_Float64, 0, 0);
	    if(!hasNoData || value!=nodata) {
		// construct feature
		feature_ptr feature(new Feature(1));
		geometry2d * point = new point_impl;
		point->move_to(pt.x, pt.y);
		feature->add_geometry(point);
		(*feature)["value"] = value;
		return feature;
	    }
	}
    }
    return feature_ptr();
}

void gdal_featureset::get_overview_meta(GDALRasterBand * band)
{
    int band_overviews = band->GetOverviewCount();
    if (band_overviews > 0)
    {
        std::clog << "GDAL Plugin: "<< band_overviews << " overviews found!" << "\n";
        for (int b = 0; b < band_overviews; b++)
        {
            GDALRasterBand * overview = band->GetOverview (b);
            std::clog << boost::format("GDAL Plugin: Overview=%d Width=%d Height=%d \n")
		% b % overview->GetXSize() % overview->GetYSize();
        }
    }
    else
    {
        std::clog << "GDAL Plugin: No overviews found!" << "\n";
    }

    int bsx,bsy;
    double scale;
    band->GetBlockSize(&bsx,&bsy);
    scale = band->GetScale();
    std::clog << boost::format("GDAL Plugin: Block=%dx%d Scale=%f Type=%s Color=%s \n") % bsx % bsy % scale
	% GDALGetDataTypeName(band->GetRasterDataType())
	% GDALGetColorInterpretationName(band->GetColorInterpretation());
}
<commit_msg>avoid potential zero division error (floating point exception)<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2007 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

#include "gdal_featureset.hpp"
#include <gdal_priv.h>

// boost
#include <boost/format.hpp>

using mapnik::query;
using mapnik::coord2d;
using mapnik::box2d;
using mapnik::Feature;
using mapnik::feature_ptr;
using mapnik::CoordTransform;
using mapnik::point_impl;
using mapnik::geometry2d;

gdal_featureset::gdal_featureset(GDALDataset & dataset, int band, gdal_query q)
    : dataset_(dataset),
      band_(band),
      gquery_(q),
      first_(true) {}

gdal_featureset::~gdal_featureset()
{
#ifdef MAPNIK_DEBUG
    std::clog << "GDAL Plugin: closing dataset = " << &dataset_ << "\n";
#endif
    GDALClose(&dataset_);
}

feature_ptr gdal_featureset::next()
{
    if (first_)
    {
	first_ = false;
#ifdef MAPNIK_DEBUG
	std::clog << "GDAL Plugin: featureset, dataset = " << &dataset_ << "\n";
#endif

	query *q = boost::get<query>(&gquery_);
	if(q) {
	    return get_feature(*q);
	} else {
	    coord2d *p = boost::get<coord2d>(&gquery_);
	    if(p) {
		return get_feature_at_point(*p);
	    }
	}
	// should never reach here
    }
    return feature_ptr();
}

feature_ptr gdal_featureset::get_feature(mapnik::query const& q)
{
    feature_ptr feature(new Feature(1));

    GDALRasterBand * red = 0;
    GDALRasterBand * green = 0;
    GDALRasterBand * blue = 0;
    GDALRasterBand * alpha = 0;
    GDALRasterBand * grey = 0;

    int nbands = dataset_.GetRasterCount();

    unsigned raster_width = dataset_.GetRasterXSize();
    unsigned raster_height = dataset_.GetRasterYSize();

    // TODO - pull from class attributes...
    double tr[6];
    dataset_.GetGeoTransform(tr);

    double dx = tr[1];
    double dy = tr[5];

    double x0 = tr[0] + (raster_height) * tr[2]; // minx
    double y0 = tr[3] + (raster_height) * tr[5]; // miny

    double x1 = tr[0] + (raster_width) * tr[1]; // maxx
    double y1 = tr[3] + (raster_width) * tr[4]; // maxy

    box2d<double> raster_extent(x0,y0,x1,y1);

    CoordTransform t(raster_width,raster_height,raster_extent,0,0);
    box2d<double> intersect = raster_extent.intersect(q.get_bbox());
    box2d<double> box = t.forward(intersect);

    //size of resized output pixel in source image domain
    double margin_x = 1.0/(fabs(dx)*boost::get<0>(q.resolution()));
    double margin_y = 1.0/(fabs(dy)*boost::get<1>(q.resolution()));
    if (margin_x < 1)
        margin_x = 1.0;
    if (margin_y < 1)
        margin_y = 1.0;
    //select minimum raster containing whole box
    int x_off = rint(box.minx() - margin_x);
    int y_off = rint(box.miny() - margin_y);
    int end_x = rint(box.maxx() + margin_x);
    int end_y = rint(box.maxy() + margin_y);
    //clip to available data
    if (x_off < 0)
        x_off = 0;
    if (y_off < 0)
        y_off = 0;
    if (end_x > (int)raster_width)
        end_x = raster_width;
    if (end_y > (int)raster_height)
        end_y = raster_height;
    int width = end_x - x_off;
    int height = end_y - y_off;
    // don't process almost invisible data
    if (box.width() < 0.5)
        width = 0;
    if (box.height() < 0.5)
        height = 0;
    //calculate actual box2d of returned raster
    box2d<double> feature_raster_extent(x_off, y_off, x_off+width, y_off+height);
    intersect = t.backward(feature_raster_extent);

#ifdef MAPNIK_DEBUG
    std::clog << "GDAL Plugin: Raster extent=" << raster_extent << "\n";
    std::clog << "GDAL Plugin: View extent=" << intersect << "\n";
    std::clog << "GDAL Plugin: Query resolution=" << boost::get<0>(q.resolution()) << "," << boost::get<1>(q.resolution()) << "\n";
    std::clog << boost::format("GDAL Plugin: StartX=%d StartY=%d Width=%d Height=%d \n") % x_off % y_off % width % height;
#endif

    if (width > 0 && height > 0)
    {
	int im_width = int(boost::get<0>(q.resolution()) * intersect.width() + 0.5);
	int im_height = int(boost::get<1>(q.resolution()) * intersect.height() + 0.5);

	// case where we need to avoid upsampling so that the
	// image can be later scaled within raster_symbolizer
	if (im_width >= width || im_height >= height)
	{
	    im_width = width;
	    im_height = height;
	}

	if (im_width > 0 && im_height > 0)
	{
    	mapnik::image_data_32 image(im_width, im_height);
    	image.set(0xffffffff);

    #ifdef MAPNIK_DEBUG
    	std::clog << "GDAL Plugin: Image Size=(" << im_width << "," << im_height << ")\n";
    	std::clog << "GDAL Plugin: Reading band " << band_ << "\n";
    #endif

    	if (band_>0) // we are querying a single band
    	{
    	    float *imageData = (float*)image.getBytes();
    	    GDALRasterBand * band = dataset_.GetRasterBand(band_);
    	    band->RasterIO(GF_Read, x_off, y_off, width, height,
    			   imageData, image.width(), image.height(),
    			   GDT_Float32, 0, 0);

    	    feature->set_raster(mapnik::raster_ptr(new mapnik::raster(intersect,image)));
    	}

    	else // working with all bands
    	{
    	    for (int i = 0; i < nbands; ++i)
    	    {
    		GDALRasterBand * band = dataset_.GetRasterBand(i+1);

    #ifdef MAPNIK_DEBUG
    		get_overview_meta(band);
    #endif

    		GDALColorInterp color_interp = band->GetColorInterpretation();
    		switch (color_interp)
    		{
    		case GCI_RedBand:
    		    red = band;
    #ifdef MAPNIK_DEBUG
    		    std::clog << "GDAL Plugin: Found red band" << "\n";
    #endif
    		    break;
    		case GCI_GreenBand:
    		    green = band;
    #ifdef MAPNIK_DEBUG
    		    std::clog << "GDAL Plugin: Found green band" << "\n";
    #endif
    		    break;
    		case GCI_BlueBand:
    		    blue = band;
    #ifdef MAPNIK_DEBUG
    		    std::clog << "GDAL Plugin: Found blue band" << "\n";
    #endif
    		    break;
    		case GCI_AlphaBand:
    		    alpha = band;
    #ifdef MAPNIK_DEBUG
    		    std::clog << "GDAL Plugin: Found alpha band" << "\n";
    #endif
    		    break;
    		case GCI_GrayIndex:
    		    grey = band;
    #ifdef MAPNIK_DEBUG
    		    std::clog << "GDAL Plugin: Found gray band" << "\n";
    #endif
    		    break;
    		case GCI_PaletteIndex:
    		{
    		    grey = band;
    #ifdef MAPNIK_DEBUG
    		    std::clog << "GDAL Plugin: Found gray band, and colortable..." << "\n";
    #endif
    		    GDALColorTable *color_table = band->GetColorTable();

    		    if ( color_table)
    		    {
    			int count = color_table->GetColorEntryCount();
    #ifdef MAPNIK_DEBUG
    			std::clog << "GDAL Plugin: Color Table count = " << count << "\n";
    #endif
    			for ( int i = 0; i < count; i++ )
    			{
    			    const GDALColorEntry *ce = color_table->GetColorEntry ( i );
    			    if (!ce ) continue;
    #ifdef MAPNIK_DEBUG
    			    std::clog << "GDAL Plugin: Color entry RGB (" << ce->c1 << "," <<ce->c2 << "," << ce->c3 << ")\n";
    #endif
    			}
    		    }
    		    break;
    		}
    		case GCI_Undefined:
    #ifdef MAPNIK_DEBUG
    		    std::clog << "GDAL Plugin: Found undefined band (assumming gray band)" << "\n";
    #endif
    		    grey = band;
    		    break;
    		default:
    #ifdef MAPNIK_DEBUG
    		    std::clog << "GDAL Plugin: band type unknown!" << "\n";
    #endif
    		    break;
    		}
    	    }

    	    if (red && green && blue)
    	    {
    #ifdef MAPNIK_DEBUG
    		std::clog << "GDAL Plugin: processing rgb bands..." << "\n";
    #endif
    		red->RasterIO(GF_Read,x_off,y_off,width,height,image.getBytes() + 0,
    			      image.width(),image.height(),GDT_Byte,4,4*image.width());
    		green->RasterIO(GF_Read,x_off,y_off,width,height,image.getBytes() + 1,
    				image.width(),image.height(),GDT_Byte,4,4*image.width());
    		blue->RasterIO(GF_Read,x_off,y_off,width,height,image.getBytes() + 2,
    			       image.width(),image.height(),GDT_Byte,4,4*image.width());
    	    }
    	    else if (grey)
    	    {
    #ifdef MAPNIK_DEBUG
    		std::clog << "GDAL Plugin: processing gray band..." << "\n";
    #endif
    		grey->RasterIO(GF_Read,x_off,y_off,width,height,image.getBytes() + 0,
    			       image.width(),image.height(),GDT_Byte, 4, 4 * image.width());
    		grey->RasterIO(GF_Read,x_off,y_off,width,height,image.getBytes() + 1,
    			       image.width(),image.height(),GDT_Byte, 4, 4 * image.width());
    		grey->RasterIO(GF_Read,x_off,y_off,width,height,image.getBytes() + 2,
    			       image.width(),image.height(),GDT_Byte, 4, 4 * image.width());
    	    }

    	    if (alpha)
    	    {
    #ifdef MAPNIK_DEBUG
    		std::clog << "GDAL Plugin: processing alpha band..." << "\n";
    #endif
    		alpha->RasterIO(GF_Read,x_off,y_off,width,height,image.getBytes() + 3,
    				image.width(),image.height(),GDT_Byte,4,4*image.width());
    	    }

    	    feature->set_raster(mapnik::raster_ptr(new mapnik::raster(intersect,image)));
    	}
    	return feature;
	}
}
return feature_ptr();
}

feature_ptr gdal_featureset::get_feature_at_point(mapnik::coord2d const& pt)
{
    if (band_>0) {

	unsigned raster_xsize = dataset_.GetRasterXSize();
	unsigned raster_ysize = dataset_.GetRasterYSize();

	double gt[6];
	dataset_.GetGeoTransform(gt);

	double det = gt[1]*gt[5] - gt[2]*gt[4];
	// subtract half a pixel width & height because gdal coord reference
	// is the top-left corner of a pixel, not the center.
	double X = pt.x - gt[0] - gt[1]/2;
	double Y = pt.y - gt[3] - gt[5]/2;
	double det1 = gt[1]*Y + gt[4]*X;
	double det2 = gt[2]*Y + gt[5]*X;
	unsigned x = det2/det, y = det1/det;

	if(0<=x && x<raster_xsize && 0<=y && y<raster_ysize) {
#ifdef MAPNIK_DEBUG
	    std::clog << boost::format("GDAL Plugin: pt.x=%f pt.y=%f\n") % pt.x % pt.y;
	    std::clog << boost::format("GDAL Plugin: x=%f y=%f\n") % x % y;
#endif
	    GDALRasterBand * band = dataset_.GetRasterBand(band_);
	    int hasNoData;
	    double nodata = band->GetNoDataValue(&hasNoData);
	    double value;
	    band->RasterIO(GF_Read, x, y, 1, 1, &value, 1, 1, GDT_Float64, 0, 0);
	    if(!hasNoData || value!=nodata) {
		// construct feature
		feature_ptr feature(new Feature(1));
		geometry2d * point = new point_impl;
		point->move_to(pt.x, pt.y);
		feature->add_geometry(point);
		(*feature)["value"] = value;
		return feature;
	    }
	}
    }
    return feature_ptr();
}

void gdal_featureset::get_overview_meta(GDALRasterBand * band)
{
    int band_overviews = band->GetOverviewCount();
    if (band_overviews > 0)
    {
        std::clog << "GDAL Plugin: "<< band_overviews << " overviews found!" << "\n";
        for (int b = 0; b < band_overviews; b++)
        {
            GDALRasterBand * overview = band->GetOverview (b);
            std::clog << boost::format("GDAL Plugin: Overview=%d Width=%d Height=%d \n")
		% b % overview->GetXSize() % overview->GetYSize();
        }
    }
    else
    {
        std::clog << "GDAL Plugin: No overviews found!" << "\n";
    }

    int bsx,bsy;
    double scale;
    band->GetBlockSize(&bsx,&bsy);
    scale = band->GetScale();
    std::clog << boost::format("GDAL Plugin: Block=%dx%d Scale=%f Type=%s Color=%s \n") % bsx % bsy % scale
	% GDALGetDataTypeName(band->GetRasterDataType())
	% GDALGetColorInterpretationName(band->GetColorInterpretation());
}
<|endoftext|>


<commit_before>//===- lib/ReaderWriter/ELF/Mips/MipsLinkingContext.cpp -------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "Atoms.h"
#include "MipsLinkingContext.h"
#include "MipsRelocationPass.h"
#include "MipsTargetHandler.h"

using namespace lld;
using namespace lld::elf;

MipsLinkingContext::MipsLinkingContext(llvm::Triple triple)
    : ELFLinkingContext(triple, std::unique_ptr<TargetHandlerBase>(
                                    new MipsTargetHandler(*this))) {}

bool MipsLinkingContext::isLittleEndian() const {
  return Mips32ElELFType::TargetEndianness == llvm::support::little;
}

uint64_t MipsLinkingContext::getBaseAddress() const {
  if (_baseAddress == 0 && getOutputELFType() == llvm::ELF::ET_EXEC)
    return 0x400000;
  return _baseAddress;
}

StringRef MipsLinkingContext::entrySymbolName() const {
  if (_outputELFType == elf::ET_EXEC && _entrySymbolName.empty())
    return "__start";
  return _entrySymbolName;
}

StringRef MipsLinkingContext::getDefaultInterpreter() const {
  return "/lib/ld.so.1";
}

void MipsLinkingContext::addPasses(PassManager &pm) {
  auto pass = createMipsRelocationPass(*this);
  if (pass)
    pm.add(std::move(pass));
  ELFLinkingContext::addPasses(pm);
}

bool MipsLinkingContext::isDynamicRelocation(const DefinedAtom &,
                                             const Reference &r) const {
  if (r.kindNamespace() != Reference::KindNamespace::ELF)
    return false;

  switch (r.kindValue()) {
  case llvm::ELF::R_MIPS_COPY:
    return true;
  default:
    return false;
  }
}

bool MipsLinkingContext::isPLTRelocation(const DefinedAtom &,
                                         const Reference &r) const {
  if (r.kindNamespace() != Reference::KindNamespace::ELF)
    return false;
  assert(r.kindArch() == Reference::KindArch::Mips);
  switch (r.kindValue()) {
  case llvm::ELF::R_MIPS_JUMP_SLOT:
    return true;
  default:
    return false;
  }
}
<commit_msg>[Mips] Simplify the code. Replace redundant 'switch' operator by the single 'if' one.<commit_after>//===- lib/ReaderWriter/ELF/Mips/MipsLinkingContext.cpp -------------------===//
//
//                             The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "Atoms.h"
#include "MipsLinkingContext.h"
#include "MipsRelocationPass.h"
#include "MipsTargetHandler.h"

using namespace lld;
using namespace lld::elf;

MipsLinkingContext::MipsLinkingContext(llvm::Triple triple)
    : ELFLinkingContext(triple, std::unique_ptr<TargetHandlerBase>(
                                    new MipsTargetHandler(*this))) {}

bool MipsLinkingContext::isLittleEndian() const {
  return Mips32ElELFType::TargetEndianness == llvm::support::little;
}

uint64_t MipsLinkingContext::getBaseAddress() const {
  if (_baseAddress == 0 && getOutputELFType() == llvm::ELF::ET_EXEC)
    return 0x400000;
  return _baseAddress;
}

StringRef MipsLinkingContext::entrySymbolName() const {
  if (_outputELFType == elf::ET_EXEC && _entrySymbolName.empty())
    return "__start";
  return _entrySymbolName;
}

StringRef MipsLinkingContext::getDefaultInterpreter() const {
  return "/lib/ld.so.1";
}

void MipsLinkingContext::addPasses(PassManager &pm) {
  auto pass = createMipsRelocationPass(*this);
  if (pass)
    pm.add(std::move(pass));
  ELFLinkingContext::addPasses(pm);
}

bool MipsLinkingContext::isDynamicRelocation(const DefinedAtom &,
                                             const Reference &r) const {
  if (r.kindNamespace() != Reference::KindNamespace::ELF)
    return false;
  return r.kindValue() == llvm::ELF::R_MIPS_COPY;
}

bool MipsLinkingContext::isPLTRelocation(const DefinedAtom &,
                                         const Reference &r) const {
  if (r.kindNamespace() != Reference::KindNamespace::ELF)
    return false;
  assert(r.kindArch() == Reference::KindArch::Mips);
  switch (r.kindValue()) {
  case llvm::ELF::R_MIPS_JUMP_SLOT:
    return true;
  default:
    return false;
  }
}
<|endoftext|>