<commit_before>/*
  Q Light Controller Plus
  audiorenderer_coreaudio.cpp

  Copyright (c) Massimo Callegari

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
  Version 2 as published by the Free Software Foundation.

  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. The license is
  in the file "COPYING".

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

#include <QString>
#include <QDebug>

#include "audiodecoder.h"
#include "audiorenderer_coreaudio.h"

AudioRendererCoreAudio::AudioRendererCoreAudio(QObject * parent)
    : AudioRenderer(parent)
{
    m_buffersFilled = 0;
    m_bufferIndex = 0;
}

AudioRendererCoreAudio::~AudioRendererCoreAudio()
{
}

void AudioRendererCoreAudio::inCallback(void *inUserData, AudioQueueRef, AudioQueueBufferRef)
{
    AudioRendererCoreAudio *CAobj = (AudioRendererCoreAudio *)inUserData;
    qDebug() << "inCallback called !!";
    CAobj->m_buffersFilled--;
}

bool AudioRendererCoreAudio::initialize(quint32 freq, int chan, AudioFormat format)
{
    OSStatus status;
    AudioStreamBasicDescription fmt;

    fmt.mFormatID = kAudioFormatLinearPCM;
    fmt.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
    fmt.mSampleRate = freq;
    fmt.mFramesPerPacket = 1;
    fmt.mChannelsPerFrame = chan;
    switch (format)
    {
    case PCM_S8:
        fmt.mBitsPerChannel = 8;
        break;
    case PCM_S16LE:
        fmt.mBitsPerChannel = 16;
        break;
    case PCM_S24LE:
        fmt.mBitsPerChannel = 24;
        break;
    case PCM_S32LE:
        fmt.mBitsPerChannel = 32;
        break;
    default:
        qWarning("AudioRendererCoreAudio: unsupported format detected");
        return false;
    }
    fmt.mBytesPerFrame = fmt.mChannelsPerFrame * fmt.mBitsPerChannel/8;
    fmt.mBytesPerPacket = fmt.mBytesPerFrame * fmt.mFramesPerPacket;

    status = AudioQueueNewOutput(&fmt, AudioRendererCoreAudio::inCallback, this, CFRunLoopGetCurrent(),
                    kCFRunLoopCommonModes, 0, &m_queue);

    if (status == kAudioFormatUnsupportedDataFormatError)
    {
        qDebug() << Q_FUNC_INFO << "Fatal: Unsupported data format";
        return false;
    }
    else
        qDebug() << Q_FUNC_INFO << "initialize status: " << status;

    for (int i = 0; i < AUDIO_BUFFERS_NUM; i++)
    {
        status = AudioQueueAllocateBuffer (m_queue, AUDIO_BUFFER_SIZE, &m_buffer[i]);
        qDebug() << Q_FUNC_INFO << "Buffer #" << i << " allocate status: " << status;
    }

    status = AudioQueueStart(m_queue, NULL);
    if (status)
    {
        qDebug() << Q_FUNC_INFO << "Cannot start Audio Queue !";
        return false;
    }

    return true;
}

qint64 AudioRendererCoreAudio::latency()
{
    return 0;
}

qint64 AudioRendererCoreAudio::writeAudio(unsigned char *data, qint64 maxSize)
{
    if(m_buffersFilled == AUDIO_BUFFERS_NUM)
        return 0;

    qint64 size = maxSize;
    if (maxSize > AUDIO_BUFFER_SIZE)
        size = AUDIO_BUFFER_SIZE;

    m_buffer[m_bufferIndex]->mAudioDataByteSize = size;
    memcpy(m_buffer[m_bufferIndex]->mAudioData, data, size);

    AudioQueueEnqueueBuffer(m_queue, m_buffer[m_bufferIndex], 0, 0);
    m_bufferIndex++;
    if (m_bufferIndex == AUDIO_BUFFERS_NUM)
        m_bufferIndex = 0;
    m_buffersFilled++;

    return size;
}

void AudioRendererCoreAudio::drain()
{
}

void AudioRendererCoreAudio::reset()
{
    OSStatus status;

    AudioQueueStop(m_queue, true);
    m_bufferIndex = 0;
    m_buffersFilled = 0;
    for (int i = 0; i < AUDIO_BUFFERS_NUM; i++)
    {
        status = AudioQueueFreeBuffer(m_queue, m_buffer[i]);
        if (status)
            qDebug() << Q_FUNC_INFO << "Failed to free buffer #" << i;
    }
}

void AudioRendererCoreAudio::suspend()
{
    OSStatus status;

    status = AudioQueuePause(m_queue);
    if (status)
        qDebug() << Q_FUNC_INFO << "Failed to pause Audio Queue !!";
}

void AudioRendererCoreAudio::resume()
{
    OSStatus status;

    status = AudioQueueStart(m_queue, NULL);
    if (status)
        qDebug() << Q_FUNC_INFO << "Failed to resume Audio Queue !!";
}
<commit_msg>Fixed AudioCore renderer to invoke data callback on the proper thread<commit_after>/*
  Q Light Controller Plus
  audiorenderer_coreaudio.cpp

  Copyright (c) Massimo Callegari

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
  Version 2 as published by the Free Software Foundation.

  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. The license is
  in the file "COPYING".

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

#include <QString>
#include <QDebug>

#include "audiodecoder.h"
#include "audiorenderer_coreaudio.h"

AudioRendererCoreAudio::AudioRendererCoreAudio(QObject * parent)
    : AudioRenderer(parent)
{
    m_buffersFilled = 0;
    m_bufferIndex = 0;
}

AudioRendererCoreAudio::~AudioRendererCoreAudio()
{
}

void AudioRendererCoreAudio::inCallback(void *inUserData, AudioQueueRef, AudioQueueBufferRef)
{
    AudioRendererCoreAudio *CAobj = (AudioRendererCoreAudio *)inUserData;
    qDebug() << "inCallback called !!";
    CAobj->m_buffersFilled--;
}

bool AudioRendererCoreAudio::initialize(quint32 freq, int chan, AudioFormat format)
{
    OSStatus status;
    AudioStreamBasicDescription fmt;

    fmt.mFormatID = kAudioFormatLinearPCM;
    fmt.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
    fmt.mSampleRate = freq;
    fmt.mFramesPerPacket = 1;
    fmt.mChannelsPerFrame = chan;
    switch (format)
    {
    case PCM_S8:
        fmt.mBitsPerChannel = 8;
        break;
    case PCM_S16LE:
        fmt.mBitsPerChannel = 16;
        break;
    case PCM_S24LE:
        fmt.mBitsPerChannel = 24;
        break;
    case PCM_S32LE:
        fmt.mBitsPerChannel = 32;
        break;
    default:
        qWarning("AudioRendererCoreAudio: unsupported format detected");
        return false;
    }
    fmt.mBytesPerFrame = fmt.mChannelsPerFrame * fmt.mBitsPerChannel/8;
    fmt.mBytesPerPacket = fmt.mBytesPerFrame * fmt.mFramesPerPacket;

    status = AudioQueueNewOutput(&fmt, AudioRendererCoreAudio::inCallback, this, CFRunLoopGetMain(),
                    kCFRunLoopCommonModes, 0, &m_queue);

    if (status == kAudioFormatUnsupportedDataFormatError)
    {
        qDebug() << Q_FUNC_INFO << "Fatal: Unsupported data format";
        return false;
    }
    else
        qDebug() << Q_FUNC_INFO << "initialize status: " << status;

    for (int i = 0; i < AUDIO_BUFFERS_NUM; i++)
    {
        status = AudioQueueAllocateBuffer (m_queue, AUDIO_BUFFER_SIZE, &m_buffer[i]);
        qDebug() << Q_FUNC_INFO << "Buffer #" << i << " allocate status: " << status;
    }

    status = AudioQueueStart(m_queue, NULL);
    if (status)
    {
        qDebug() << Q_FUNC_INFO << "Cannot start Audio Queue !";
        return false;
    }

    return true;
}

qint64 AudioRendererCoreAudio::latency()
{
    return 0;
}

qint64 AudioRendererCoreAudio::writeAudio(unsigned char *data, qint64 maxSize)
{
    if(m_buffersFilled == AUDIO_BUFFERS_NUM)
        return 0;

    qint64 size = maxSize;
    if (maxSize > AUDIO_BUFFER_SIZE)
        size = AUDIO_BUFFER_SIZE;

    m_buffer[m_bufferIndex]->mAudioDataByteSize = size;
    memcpy(m_buffer[m_bufferIndex]->mAudioData, data, size);

    AudioQueueEnqueueBuffer(m_queue, m_buffer[m_bufferIndex], 0, 0);
    m_bufferIndex++;
    if (m_bufferIndex == AUDIO_BUFFERS_NUM)
        m_bufferIndex = 0;
    m_buffersFilled++;

    return size;
}

void AudioRendererCoreAudio::drain()
{
}

void AudioRendererCoreAudio::reset()
{
    OSStatus status;

    AudioQueueStop(m_queue, true);
    m_bufferIndex = 0;
    m_buffersFilled = 0;
    for (int i = 0; i < AUDIO_BUFFERS_NUM; i++)
    {
        status = AudioQueueFreeBuffer(m_queue, m_buffer[i]);
        if (status)
            qDebug() << Q_FUNC_INFO << "Failed to free buffer #" << i;
    }
}

void AudioRendererCoreAudio::suspend()
{
    OSStatus status;

    status = AudioQueuePause(m_queue);
    if (status)
        qDebug() << Q_FUNC_INFO << "Failed to pause Audio Queue !!";
}

void AudioRendererCoreAudio::resume()
{
    OSStatus status;

    status = AudioQueueStart(m_queue, NULL);
    if (status)
        qDebug() << Q_FUNC_INFO << "Failed to resume Audio Queue !!";
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: bibconfig.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: os $ $Date: 2002-08-14 15:20:41 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _BIBCONFIG_HXX
#define _BIBCONFIG_HXX

#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
class MappingArray;

//-----------------------------------------------------------------------------
#define COLUMN_COUNT                31
#define IDENTIFIER_POS              0
#define AUTHORITYTYPE_POS           1
#define AUTHOR_POS                  2
#define TITLE_POS                   3
#define YEAR_POS                    4
#define ISBN_POS                    5
#define BOOKTITLE_POS               6
#define CHAPTER_POS                 7
#define EDITION_POS                 8
#define EDITOR_POS                  9
#define HOWPUBLISHED_POS            10
#define INSTITUTION_POS             11
#define JOURNAL_POS                 12
#define MONTH_POS                   13
#define NOTE_POS                    14
#define ANNOTE_POS                  15
#define NUMBER_POS                  16
#define ORGANIZATIONS_POS           17
#define PAGES_POS                   18
#define PUBLISHER_POS               19
#define ADDRESS_POS                 20
#define SCHOOL_POS                  21
#define SERIES_POS                  22
#define REPORTTYPE_POS              23
#define VOLUME_POS                  24
#define URL_POS                     25
#define CUSTOM1_POS                 26
#define CUSTOM2_POS                 27
#define CUSTOM3_POS                 28
#define CUSTOM4_POS                 29
#define CUSTOM5_POS                 30
//-----------------------------------------------------------------------------
struct StringPair
{
    rtl::OUString   sRealColumnName;
    rtl::OUString   sLogicalColumnName;
};
//-----------------------------------------------------------------------------
struct Mapping
{
    rtl::OUString       sTableName;
    rtl::OUString       sURL;
    sal_Int16           nCommandType;
    StringPair          aColumnPairs[COLUMN_COUNT];

    Mapping() :
        nCommandType(0){}
};
//-----------------------------------------------------------------------------
struct BibDBDescriptor
{
    rtl::OUString   sDataSource;
    rtl::OUString   sTableOrQuery;
    sal_Int32       nCommandType;
};
//-----------------------------------------------------------------------------

class BibConfig : public utl::ConfigItem
{
    rtl::OUString   sDataSource;
    rtl::OUString   sTableOrQuery;
    sal_Int32       nTblOrQuery;

    rtl::OUString   sQueryField;
    rtl::OUString   sQueryText;
    long            nBeamerSize;
    long            nViewSize;
    sal_Bool        bShowColumnAssignmentWarning;

    MappingArray*               pMappingsArr;
    rtl::OUString               aColumnDefaults[COLUMN_COUNT];

    com::sun::star::uno::Sequence<rtl::OUString>& GetPropertyNames();
public:
    BibConfig();
    ~BibConfig();

    virtual void    Commit();

    BibDBDescriptor         GetBibliographyURL();
    void                    SetBibliographyURL(const BibDBDescriptor& rDesc);

    const Mapping*          GetMapping(const BibDBDescriptor& rDesc) const;
    void                    SetMapping(const BibDBDescriptor& rDesc, const Mapping* pMapping);

    const rtl::OUString&    GetDefColumnName(sal_uInt16 nIndex) const
                                            {return aColumnDefaults[nIndex];}

    void                    setBeamerSize(long nSize) {SetModified(); nBeamerSize = nSize;}
    long                    getBeamerSize()const {return nBeamerSize;}
    void                    setViewSize(long nSize) {SetModified(); nViewSize = nSize;}
    long                    getViewSize() {return nViewSize;}

    const rtl::OUString&    getQueryField() const {return sQueryField;}
    void                    setQueryField(const rtl::OUString& rSet) {SetModified(); sQueryField = rSet;}

    const rtl::OUString&    getQueryText() const {return sQueryText;}
    void                    setQueryText(const rtl::OUString& rSet) {SetModified(); sQueryText = rSet;}

    sal_Bool                IsShowColumnAssignmentWarning() const
                                { return bShowColumnAssignmentWarning;}
    void                    SetShowColumnAssignmentWarning(sal_Bool bSet)
                                { bShowColumnAssignmentWarning = bSet;}
};
/* -----------------------------20.11.00 11:47--------------------------------

 ---------------------------------------------------------------------------*/
class DBChangeDialogConfig_Impl
{
    com::sun::star::uno::Sequence<rtl::OUString> aSourceNames;
public:
    DBChangeDialogConfig_Impl();
    ~DBChangeDialogConfig_Impl();

    const com::sun::star::uno::Sequence<rtl::OUString>& GetDataSourceNames();

};
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.564); FILE MERGED 2005/09/05 12:58:39 rt 1.7.564.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: bibconfig.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 19:12:54 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _BIBCONFIG_HXX
#define _BIBCONFIG_HXX

#ifndef _UTL_CONFIGITEM_HXX_
#include <unotools/configitem.hxx>
#endif
class MappingArray;

//-----------------------------------------------------------------------------
#define COLUMN_COUNT                31
#define IDENTIFIER_POS              0
#define AUTHORITYTYPE_POS           1
#define AUTHOR_POS                  2
#define TITLE_POS                   3
#define YEAR_POS                    4
#define ISBN_POS                    5
#define BOOKTITLE_POS               6
#define CHAPTER_POS                 7
#define EDITION_POS                 8
#define EDITOR_POS                  9
#define HOWPUBLISHED_POS            10
#define INSTITUTION_POS             11
#define JOURNAL_POS                 12
#define MONTH_POS                   13
#define NOTE_POS                    14
#define ANNOTE_POS                  15
#define NUMBER_POS                  16
#define ORGANIZATIONS_POS           17
#define PAGES_POS                   18
#define PUBLISHER_POS               19
#define ADDRESS_POS                 20
#define SCHOOL_POS                  21
#define SERIES_POS                  22
#define REPORTTYPE_POS              23
#define VOLUME_POS                  24
#define URL_POS                     25
#define CUSTOM1_POS                 26
#define CUSTOM2_POS                 27
#define CUSTOM3_POS                 28
#define CUSTOM4_POS                 29
#define CUSTOM5_POS                 30
//-----------------------------------------------------------------------------
struct StringPair
{
    rtl::OUString   sRealColumnName;
    rtl::OUString   sLogicalColumnName;
};
//-----------------------------------------------------------------------------
struct Mapping
{
    rtl::OUString       sTableName;
    rtl::OUString       sURL;
    sal_Int16           nCommandType;
    StringPair          aColumnPairs[COLUMN_COUNT];

    Mapping() :
        nCommandType(0){}
};
//-----------------------------------------------------------------------------
struct BibDBDescriptor
{
    rtl::OUString   sDataSource;
    rtl::OUString   sTableOrQuery;
    sal_Int32       nCommandType;
};
//-----------------------------------------------------------------------------

class BibConfig : public utl::ConfigItem
{
    rtl::OUString   sDataSource;
    rtl::OUString   sTableOrQuery;
    sal_Int32       nTblOrQuery;

    rtl::OUString   sQueryField;
    rtl::OUString   sQueryText;
    long            nBeamerSize;
    long            nViewSize;
    sal_Bool        bShowColumnAssignmentWarning;

    MappingArray*               pMappingsArr;
    rtl::OUString               aColumnDefaults[COLUMN_COUNT];

    com::sun::star::uno::Sequence<rtl::OUString>& GetPropertyNames();
public:
    BibConfig();
    ~BibConfig();

    virtual void    Commit();

    BibDBDescriptor         GetBibliographyURL();
    void                    SetBibliographyURL(const BibDBDescriptor& rDesc);

    const Mapping*          GetMapping(const BibDBDescriptor& rDesc) const;
    void                    SetMapping(const BibDBDescriptor& rDesc, const Mapping* pMapping);

    const rtl::OUString&    GetDefColumnName(sal_uInt16 nIndex) const
                                            {return aColumnDefaults[nIndex];}

    void                    setBeamerSize(long nSize) {SetModified(); nBeamerSize = nSize;}
    long                    getBeamerSize()const {return nBeamerSize;}
    void                    setViewSize(long nSize) {SetModified(); nViewSize = nSize;}
    long                    getViewSize() {return nViewSize;}

    const rtl::OUString&    getQueryField() const {return sQueryField;}
    void                    setQueryField(const rtl::OUString& rSet) {SetModified(); sQueryField = rSet;}

    const rtl::OUString&    getQueryText() const {return sQueryText;}
    void                    setQueryText(const rtl::OUString& rSet) {SetModified(); sQueryText = rSet;}

    sal_Bool                IsShowColumnAssignmentWarning() const
                                { return bShowColumnAssignmentWarning;}
    void                    SetShowColumnAssignmentWarning(sal_Bool bSet)
                                { bShowColumnAssignmentWarning = bSet;}
};
/* -----------------------------20.11.00 11:47--------------------------------

 ---------------------------------------------------------------------------*/
class DBChangeDialogConfig_Impl
{
    com::sun::star::uno::Sequence<rtl::OUString> aSourceNames;
public:
    DBChangeDialogConfig_Impl();
    ~DBChangeDialogConfig_Impl();

    const com::sun::star::uno::Sequence<rtl::OUString>& GetDataSourceNames();

};
#endif
<|endoftext|>


<commit_before>#include "remoteinterface.h"

RemoteInterface::RemoteInterface(QObject *parent) : QXmppInvokable(parent)
{
}

bool RemoteInterface::isAuthorized( const QString &jid ) const
{
    return true;
}

QString RemoteInterface::echoString(const QString& message)
{
    return "Echo: " + message;
}
<commit_msg>silence a compiler warning<commit_after>#include "remoteinterface.h"

RemoteInterface::RemoteInterface(QObject *parent) : QXmppInvokable(parent)
{
}

bool RemoteInterface::isAuthorized( const QString &jid ) const
{
    Q_UNUSED(jid);
    return true;
}

QString RemoteInterface::echoString(const QString& message)
{
    return "Echo: " + message;
}
<|endoftext|>


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

#ifndef _WINFILEOPENIMPL_HXX_
#define _WINFILEOPENIMPL_HXX_

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _COM_SUN_STAR_UI_DIALOGS_XEXTENDEDFILEPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_FILEPICKEREVENT_HPP_
#include <com/sun/star/ui/dialogs/FilePickerEvent.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERGROUPMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterGroupManager.hpp>
#endif

#ifndef _FILTER_CONTAINER_HXX_
#include "FilterContainer.hxx"
#endif

#ifndef _FILEOPENDLG_HXX_
#include "FileOpenDlg.hxx"
#endif

#ifndef _PREVIEWADAPTER_HXX_
#include "previewadapter.hxx"
#endif

#ifndef _HELPPOPUPWINDOW_HXX_
#include "helppopupwindow.hxx"
#endif

#ifndef _CUSTOMCONTROL_HXX_
#include "customcontrol.hxx"
#endif

#ifndef _CUSTOMCONTROLFACTORY_HXX_
#include "customcontrolfactory.hxx"
#endif

#include <utility>
#include <memory>
#include <vector>

#ifndef _OSL_CONDITN_HXX_
#include <osl/conditn.hxx>
#endif

//------------------------------------------------------------------------
// deklarations
//------------------------------------------------------------------------

// forward declaration
class CFilePicker;
class CFilePickerState;
class CExecuteFilePickerState;
class CNonExecuteFilePickerState;

class CWinFileOpenImpl : public CFileOpenDialog
{
public:
    CWinFileOpenImpl(
        CFilePicker* aFilePicker,
        sal_Bool bFileOpenDialog = sal_True,
        sal_uInt32 dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
        sal_uInt32 dwTemplateId = 0,
        HINSTANCE hInstance = 0 );

    virtual ~CWinFileOpenImpl( );

    //-----------------------------------------------------------------------------------------
    // XExecutableDialog
    //-----------------------------------------------------------------------------------------

    virtual sal_Int16 SAL_CALL execute(  ) throw( ::com::sun::star::uno::RuntimeException );

    //-----------------------------------------------------------------------------------------
    // XFilePicker
    //-----------------------------------------------------------------------------------------

    virtual void SAL_CALL setDefaultName( const ::rtl::OUString& aName )
        throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getFiles(  )
        throw(::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL setDisplayDirectory( const ::rtl::OUString& aDirectory )
        throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );

    virtual ::rtl::OUString SAL_CALL getDisplayDirectory( ) throw ( ::com::sun::star::uno::RuntimeException );

    //-----------------------------------------------------------------------------------------
    // XFilterManager
    //-----------------------------------------------------------------------------------------

    virtual void SAL_CALL appendFilter( const ::rtl::OUString& aTitle, const ::rtl::OUString& aFilter )
        throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL setCurrentFilter( const ::rtl::OUString& aTitle )
        throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );

    virtual ::rtl::OUString  SAL_CALL getCurrentFilter( )
        throw( ::com::sun::star::uno::RuntimeException );

    //-----------------------------------------------------------------------------------------
    // XFilterGroupManager
    //-----------------------------------------------------------------------------------------

    virtual void SAL_CALL appendFilterGroup( const ::rtl::OUString& sGroupTitle, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::StringPair >& aFilters )
        throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    //-----------------------------------------------------------------------------------------
    // XFilePickerControlAccess
    //-----------------------------------------------------------------------------------------

    virtual void SAL_CALL setValue( sal_Int16 aControlId, sal_Int16 aControlAction, const ::com::sun::star::uno::Any& aValue )
        throw( ::com::sun::star::uno::RuntimeException );

    virtual ::com::sun::star::uno::Any SAL_CALL getValue( sal_Int16 aControlId, sal_Int16 aControlAction )
        throw( ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL enableControl( sal_Int16 aControlId, sal_Bool bEnable )
        throw( ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL setLabel( sal_Int16 aControlId, const ::rtl::OUString& aLabel )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::rtl::OUString SAL_CALL getLabel( sal_Int16 aControlId )
        throw ( ::com::sun::star::uno::RuntimeException);

    //------------------------------------------------
    // XFilePreview
    //------------------------------------------------

    virtual ::com::sun::star::uno::Sequence< sal_Int16 > SAL_CALL getSupportedImageFormats(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Int32 SAL_CALL getTargetColorDepth( )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Int32 SAL_CALL getAvailableWidth( )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Int32 SAL_CALL getAvailableHeight( )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL setImage( sal_Int16 aImageFormat, const ::com::sun::star::uno::Any& aImage )
        throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL setShowState( sal_Bool bShowState )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL getShowState( )
        throw (::com::sun::star::uno::RuntimeException);

    //------------------------------------------------
    // XCancelable
    //------------------------------------------------

    virtual void SAL_CALL cancel( );

    //------------------------------------------------
    // Implementation details
    //------------------------------------------------

protected:
    sal_Int16 SAL_CALL getFocused( );

    virtual bool SAL_CALL preModal( );
    virtual void SAL_CALL postModal( sal_Int16 nDialogResult );

    virtual sal_uInt32 SAL_CALL onFileOk();
    virtual void SAL_CALL onSelChanged( HWND hwndListBox );

    // only called back if OFN_EXPLORER is set
    virtual void SAL_CALL onInitDone();
    virtual void SAL_CALL onFolderChanged();
    virtual void SAL_CALL onTypeChanged( sal_uInt32 nFilterIndex );

    // call base class method first when overloading
    virtual void SAL_CALL onInitDialog( HWND hwndDlg, HWND hwndChild );

    virtual sal_uInt32 SAL_CALL onCtrlCommand( HWND hwndDlg, sal_uInt16 ctrlId, sal_uInt16 notifyCode );

    LRESULT SAL_CALL onWMSize(HWND hwnd, WPARAM type, WORD width, WORD height );
    LRESULT SAL_CALL onWMShow(HWND hwnd, BOOL bShow, int fState);
    LRESULT SAL_CALL onWMWindowPosChanged(HWND hwnd);
    LRESULT SAL_CALL onCustomControlHelpRequest(LPHELPINFO lphi);

private:
    inline void SAL_CALL appendFilterGroupSeparator( );

    inline sal_Bool SAL_CALL IsCustomControlHelpRequested(LPHELPINFO lphi) const;

    void EnlargeStdControlLabels() const;

    // initialize all controls from cache
    void SAL_CALL InitControlLabel( HWND hWnd );
    void SAL_CALL InitCustomControlContainer(HWND hCustomControl);

    // save the control state
    void SAL_CALL CacheControlState(HWND hWnd);

    void SAL_CALL SetDefaultExtension();
    void SAL_CALL InitialSetDefaultName();

    static LRESULT CALLBACK SubClassFunc(HWND hWnd, UINT wMessage, WPARAM wParam, LPARAM lParam);

    static BOOL CALLBACK EnumChildWndProc( HWND hWnd, LPARAM lParam );

private:
    std::auto_ptr<CFilterContainer>         m_filterContainer;
    std::auto_ptr<CPreviewAdapter>          m_Preview;
    std::auto_ptr<CCustomControlFactory>    m_CustomControlFactory;
    std::auto_ptr<CCustomControl>           m_CustomControls;
    CFilePicker*                            m_FilePicker;
    WNDPROC                                 m_pfnOldDlgProc;
    rtl::OUString                           m_defaultName;
    sal_Bool                                m_bInitialSelChanged;
    CHelpPopupWindow                        m_HelpPopupWindow;
    CFilePickerState*                       m_FilePickerState;
    CExecuteFilePickerState*                m_ExecuteFilePickerState;
    CNonExecuteFilePickerState*             m_NonExecuteFilePickerState;
};

#endif
<commit_msg>INTEGRATION: CWS sb59 (1.13.100); FILE MERGED 2006/08/10 12:04:48 sb 1.13.100.1: #i67487# Made code warning-free (wntmsci10).<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: WinFileOpenImpl.hxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: obo $ $Date: 2006-10-12 10:49:31 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _WINFILEOPENIMPL_HXX_
#define _WINFILEOPENIMPL_HXX_

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _COM_SUN_STAR_UI_DIALOGS_XEXTENDEDFILEPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_FILEPICKEREVENT_HPP_
#include <com/sun/star/ui/dialogs/FilePickerEvent.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERGROUPMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterGroupManager.hpp>
#endif

#ifndef _FILTER_CONTAINER_HXX_
#include "FilterContainer.hxx"
#endif

#ifndef _FILEOPENDLG_HXX_
#include "FileOpenDlg.hxx"
#endif

#ifndef _PREVIEWADAPTER_HXX_
#include "previewadapter.hxx"
#endif

#ifndef _HELPPOPUPWINDOW_HXX_
#include "helppopupwindow.hxx"
#endif

#ifndef _CUSTOMCONTROL_HXX_
#include "customcontrol.hxx"
#endif

#ifndef _CUSTOMCONTROLFACTORY_HXX_
#include "customcontrolfactory.hxx"
#endif

#include <utility>
#include <memory>
#include <vector>

#ifndef _OSL_CONDITN_HXX_
#include <osl/conditn.hxx>
#endif

//------------------------------------------------------------------------
// deklarations
//------------------------------------------------------------------------

// forward declaration
class CFilePicker;
class CFilePickerState;
class CExecuteFilePickerState;
class CNonExecuteFilePickerState;

class CWinFileOpenImpl : public CFileOpenDialog
{
public:
    CWinFileOpenImpl(
        CFilePicker* aFilePicker,
        sal_Bool bFileOpenDialog = sal_True,
        sal_uInt32 dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
        sal_uInt32 dwTemplateId = 0,
        HINSTANCE hInstance = 0 );

    virtual ~CWinFileOpenImpl( );

    //-----------------------------------------------------------------------------------------
    // XExecutableDialog
    //-----------------------------------------------------------------------------------------

    virtual sal_Int16 SAL_CALL execute(  ) throw( ::com::sun::star::uno::RuntimeException );

    //-----------------------------------------------------------------------------------------
    // XFilePicker
    //-----------------------------------------------------------------------------------------

    virtual void SAL_CALL setDefaultName( const ::rtl::OUString& aName )
        throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getFiles(  )
        throw(::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL setDisplayDirectory( const ::rtl::OUString& aDirectory )
        throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );

    virtual ::rtl::OUString SAL_CALL getDisplayDirectory( ) throw ( ::com::sun::star::uno::RuntimeException );

    //-----------------------------------------------------------------------------------------
    // XFilterManager
    //-----------------------------------------------------------------------------------------

    virtual void SAL_CALL appendFilter( const ::rtl::OUString& aTitle, const ::rtl::OUString& aFilter )
        throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL setCurrentFilter( const ::rtl::OUString& aTitle )
        throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );

    virtual ::rtl::OUString  SAL_CALL getCurrentFilter( )
        throw( ::com::sun::star::uno::RuntimeException );

    //-----------------------------------------------------------------------------------------
    // XFilterGroupManager
    //-----------------------------------------------------------------------------------------

    virtual void SAL_CALL appendFilterGroup( const ::rtl::OUString& sGroupTitle, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::StringPair >& aFilters )
        throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    //-----------------------------------------------------------------------------------------
    // XFilePickerControlAccess
    //-----------------------------------------------------------------------------------------

    virtual void SAL_CALL setValue( sal_Int16 aControlId, sal_Int16 aControlAction, const ::com::sun::star::uno::Any& aValue )
        throw( ::com::sun::star::uno::RuntimeException );

    virtual ::com::sun::star::uno::Any SAL_CALL getValue( sal_Int16 aControlId, sal_Int16 aControlAction )
        throw( ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL enableControl( sal_Int16 aControlId, sal_Bool bEnable )
        throw( ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL setLabel( sal_Int16 aControlId, const ::rtl::OUString& aLabel )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::rtl::OUString SAL_CALL getLabel( sal_Int16 aControlId )
        throw ( ::com::sun::star::uno::RuntimeException);

    //------------------------------------------------
    // XFilePreview
    //------------------------------------------------

    virtual ::com::sun::star::uno::Sequence< sal_Int16 > SAL_CALL getSupportedImageFormats(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Int32 SAL_CALL getTargetColorDepth( )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Int32 SAL_CALL getAvailableWidth( )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Int32 SAL_CALL getAvailableHeight( )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL setImage( sal_Int16 aImageFormat, const ::com::sun::star::uno::Any& aImage )
        throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL setShowState( sal_Bool bShowState )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL getShowState( )
        throw (::com::sun::star::uno::RuntimeException);

    //------------------------------------------------
    // XCancelable
    //------------------------------------------------

    virtual void SAL_CALL cancel( );

    //------------------------------------------------
    // Implementation details
    //------------------------------------------------

protected:
    sal_Int16 SAL_CALL getFocused( );

    virtual bool SAL_CALL preModal( );
    virtual void SAL_CALL postModal( sal_Int16 nDialogResult );

    virtual sal_uInt32 SAL_CALL onFileOk();
    virtual void SAL_CALL onSelChanged( HWND hwndListBox );

    // only called back if OFN_EXPLORER is set
    virtual void SAL_CALL onInitDone();
    virtual void SAL_CALL onFolderChanged();
    virtual void SAL_CALL onTypeChanged( sal_uInt32 nFilterIndex );

    // call base class method first when overloading
    virtual void SAL_CALL onInitDialog( HWND hwndDlg );

    virtual sal_uInt32 SAL_CALL onCtrlCommand( HWND hwndDlg, sal_uInt16 ctrlId, sal_uInt16 notifyCode );

    void onWMSize();
    void onWMShow(BOOL bShow);
    void onWMWindowPosChanged();
    void onCustomControlHelpRequest(LPHELPINFO lphi);

private:
    inline void SAL_CALL appendFilterGroupSeparator( );

    inline sal_Bool SAL_CALL IsCustomControlHelpRequested(LPHELPINFO lphi) const;

    void EnlargeStdControlLabels() const;

    // initialize all controls from cache
    void SAL_CALL InitControlLabel( HWND hWnd );
    void SAL_CALL InitCustomControlContainer(HWND hCustomControl);

    // save the control state
    void SAL_CALL CacheControlState(HWND hWnd);

    void SAL_CALL SetDefaultExtension();
    void SAL_CALL InitialSetDefaultName();

    static LRESULT CALLBACK SubClassFunc(HWND hWnd, UINT wMessage, WPARAM wParam, LPARAM lParam);

    static BOOL CALLBACK EnumChildWndProc( HWND hWnd, LPARAM lParam );

private:
    std::auto_ptr<CFilterContainer>         m_filterContainer;
    std::auto_ptr<CPreviewAdapter>          m_Preview;
    std::auto_ptr<CCustomControlFactory>    m_CustomControlFactory;
    std::auto_ptr<CCustomControl>           m_CustomControls;
    CFilePicker*                            m_FilePicker;
    WNDPROC                                 m_pfnOldDlgProc;
    rtl::OUString                           m_defaultName;
    sal_Bool                                m_bInitialSelChanged;
    CHelpPopupWindow                        m_HelpPopupWindow;
    CFilePickerState*                       m_FilePickerState;
    CExecuteFilePickerState*                m_ExecuteFilePickerState;
    CNonExecuteFilePickerState*             m_NonExecuteFilePickerState;
};

#endif
<|endoftext|>


<commit_before>#include "databaseupdatestest.h"

#include <Cutelyst/Plugins/Utils/Sql>

#include <QSqlQuery>

#include <QThread>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

DatabaseUpdatesTest::DatabaseUpdatesTest(QObject *parent) : Controller(parent)
{

}

void DatabaseUpdatesTest::updates_postgres(Context *c)
{
    QSqlQuery query = CPreparedSqlQueryThreadForDB(
                QLatin1String("SELECT randomNumber FROM world WHERE id = :id"),
                QStringLiteral("postgres"));
    QSqlQuery updateQuery = CPreparedSqlQueryThreadForDB(
                QLatin1String("UPDATE world SET randomNumber = :randomNumber WHERE id = :id"),
                QStringLiteral("postgres"));
    processQuery(c, query, updateQuery);
}

void DatabaseUpdatesTest::updates_mysql(Context *c)
{
    QSqlQuery query = CPreparedSqlQueryThreadForDB(
                QLatin1String("SELECT randomNumber FROM world WHERE id = :id"),
                QStringLiteral("mysql"));
    QSqlQuery updateQuery = CPreparedSqlQueryThreadForDB(
                QLatin1String("UPDATE world SET randomNumber = :randomNumber WHERE id = :id"),
                QStringLiteral("mysql"));
    processQuery(c, query, updateQuery);
}

void DatabaseUpdatesTest::processQuery(Context *c, QSqlQuery &query, QSqlQuery &updateQuery)
{
    QJsonArray array;

    int queries = c->request()->queryParam(QStringLiteral("queries"), QStringLiteral("1")).toInt();
    if (queries < 1) {
        queries = 1;
    } else if (queries > 500) {
        queries = 500;
    }

    for (int i = 0; i < queries; ++i) {
        int id = (qrand() % 10000) + 1;

        query.bindValue(QStringLiteral(":id"), id);
        if (!query.exec() || !query.next()) {
            c->res()->setStatus(Response::InternalServerError);
            return;
        }

        int randomNumber = (qrand() % 10000) + 1;
        updateQuery.bindValue(QStringLiteral(":id"), id);
        updateQuery.bindValue(QStringLiteral(":randomNumber"), randomNumber);
        if (!updateQuery.exec()) {
            c->res()->setStatus(Response::InternalServerError);
            return;
        }

        QJsonObject obj;
        obj.insert(QStringLiteral("id"), query.value(0).toInt());
        obj.insert(QStringLiteral("randomNumber"), randomNumber);
        array.append(obj);
    }

    c->response()->setJsonBody(QJsonDocument(array));
}
<commit_msg>cutelyst: Change update test to do batched updates (#2680)<commit_after>#include "databaseupdatestest.h"

#include <Cutelyst/Plugins/Utils/Sql>

#include <QSqlQuery>

#include <QThread>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

DatabaseUpdatesTest::DatabaseUpdatesTest(QObject *parent) : Controller(parent)
{

}

void DatabaseUpdatesTest::updates_postgres(Context *c)
{
    QSqlQuery query = CPreparedSqlQueryThreadForDB(
                QLatin1String("SELECT randomNumber FROM world WHERE id = :id"),
                QStringLiteral("postgres"));
    QSqlQuery updateQuery = CPreparedSqlQueryThreadForDB(
                QLatin1String("UPDATE world SET randomNumber = :randomNumber WHERE id = :id"),
                QStringLiteral("postgres"));
    processQuery(c, query, updateQuery);
}

void DatabaseUpdatesTest::updates_mysql(Context *c)
{
    QSqlQuery query = CPreparedSqlQueryThreadForDB(
                QLatin1String("SELECT randomNumber FROM world WHERE id = :id"),
                QStringLiteral("mysql"));
    QSqlQuery updateQuery = CPreparedSqlQueryThreadForDB(
                QLatin1String("UPDATE world SET randomNumber = :randomNumber WHERE id = :id"),
                QStringLiteral("mysql"));
    processQuery(c, query, updateQuery);
}

void DatabaseUpdatesTest::processQuery(Context *c, QSqlQuery &query, QSqlQuery &updateQuery)
{
    QJsonArray array;

    int queries = c->request()->queryParam(QStringLiteral("queries"), QStringLiteral("1")).toInt();
    if (queries < 1) {
        queries = 1;
    } else if (queries > 500) {
        queries = 500;
    }

    QVariantList ids, randomNumbers;
    ids.reserve(queries);
    randomNumbers.reserve(queries);
    for (int i = 0; i < queries; ++i) {
        int id = (qrand() % 10000) + 1;

        query.bindValue(QStringLiteral(":id"), id);
        if (!query.exec() || !query.next()) {
            c->res()->setStatus(Response::InternalServerError);
            return;
        }

        int randomNumber = (qrand() % 10000) + 1;
        ids.append(id);
        randomNumbers.append(randomNumber);

        QJsonObject obj;
        obj.insert(QStringLiteral("id"), id);
        obj.insert(QStringLiteral("randomNumber"), randomNumber);
        array.append(obj);
    }

    updateQuery.bindValue(QStringLiteral(":id"), ids);
    updateQuery.bindValue(QStringLiteral(":randomNumber"), randomNumbers);
    if (!updateQuery.execBatch()) {
        c->res()->setStatus(Response::InternalServerError);
        return;
    }

    c->response()->setJsonBody(QJsonDocument(array));
}
<|endoftext|>


<commit_before>/*
 * irods_environment_properties.cpp
 *
 */

#include "irods_environment_properties.hpp"
#include "irods_get_full_path_for_config_file.hpp"

#include "rods.h"
#include "irods_log.hpp"
#include "irods_lookup_table.hpp"
#include "irods_home_directory.hpp"
#include "readServerConfig.hpp"

#include <string>
#include <algorithm>
#include <fstream>

#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;

#define BUF_LEN 500

namespace irods {

    const std::string environment_properties::LEGACY_ENV_FILE = "/.irods/.irodsEnv";
    const std::string environment_properties::JSON_ENV_FILE   = "/.irods/irods_environment.json";

// Access method for singleton
    environment_properties& environment_properties::getInstance() {
        static environment_properties instance;
        return instance;
    }

    error environment_properties::capture_if_needed() {
        error result = SUCCESS();
        if ( !captured_ ) {
            result = capture();
        }
        return result;
    }

    environment_properties::environment_properties() :
        captured_( false ) {

        legacy_key_map_[ "irodsUserName" ]                = CFG_IRODS_USER_NAME_KW;
        legacy_key_map_[ "irodsHost" ]                    = CFG_IRODS_HOST_KW;
        legacy_key_map_[ "irodsPort" ]                    = CFG_IRODS_PORT_KW;
        legacy_key_map_[ "xmsgHost" ]                     = CFG_IRODS_XMSG_HOST_KW;
        legacy_key_map_[ "xmsgPort" ]                     = CFG_IRODS_XMSG_PORT_KW;
        legacy_key_map_[ "irodsHome" ]                    = CFG_IRODS_HOME_KW;
        legacy_key_map_[ "irodsCwd" ]                     = CFG_IRODS_CWD_KW;
        legacy_key_map_[ "irodsAuthScheme" ]              = CFG_IRODS_AUTHENTICATION_SCHEME_KW;
        legacy_key_map_[ "irodsDefResource" ]             = CFG_IRODS_DEFAULT_RESOURCE_KW;
        legacy_key_map_[ "irodsZone" ]                    = CFG_IRODS_ZONE_KW;
        legacy_key_map_[ "irodsServerDn" ]                = CFG_IRODS_GSI_SERVER_DN_KW;
        legacy_key_map_[ "irodsLogLevel" ]                = CFG_IRODS_LOG_LEVEL_KW;
        legacy_key_map_[ "irodsAuthFileName" ]            = CFG_IRODS_AUTHENTICATION_FILE_KW;
        legacy_key_map_[ "irodsDebug" ]                   = CFG_IRODS_DEBUG_KW;
        legacy_key_map_[ "irodsClientServerPolicy" ]      = CFG_IRODS_CLIENT_SERVER_POLICY_KW;
        legacy_key_map_[ "irodsClientServerNegotiation" ] = CFG_IRODS_CLIENT_SERVER_NEGOTIATION_KW;
        legacy_key_map_[ "irodsEncryptionKeySize" ]       = CFG_IRODS_ENCRYPTION_KEY_SIZE_KW;
        legacy_key_map_[ "irodsEncryptionSaltSize" ]      = CFG_IRODS_ENCRYPTION_SALT_SIZE_KW;
        legacy_key_map_[ "irodsEncryptionNumHashRounds" ] = CFG_IRODS_ENCRYPTION_NUM_HASH_ROUNDS_KW;
        legacy_key_map_[ "irodsEncryptionAlgorithm" ]     = CFG_IRODS_ENCRYPTION_ALGORITHM_KW;
        legacy_key_map_[ "irodsDefaultHashScheme" ]       = CFG_IRODS_DEFAULT_HASH_SCHEME_KW;
        legacy_key_map_[ "irodsMatchHashPolicy" ]         = CFG_IRODS_MATCH_HASH_POLICY_KW;

    } // ctor

    error environment_properties::get_json_environment_file(
        std::string& _env_file,
        std::string& _session_file ) {
        // capture parent process id for use in creation of 'session'
        // file which contains the cwd for a given session.  this cwd
        // is only updated by the icd command which writes a new irods
        // CFG_IRODS_CWD_KW to the session dir which repaves the existing
        // one in the original irodsEnv file.
        std::stringstream ppid_str; ppid_str << getppid();

        // if a json version exists, then attempt to capture
        // that
        std::string json_file( IRODS_HOME_DIRECTORY );
        std::string json_session_file( IRODS_HOME_DIRECTORY );
        std::string env_var = to_env( CFG_IRODS_ENVIRONMENT_FILE_KW );
        char* irods_env = getenv(
                              to_env(
                                  CFG_IRODS_ENVIRONMENT_FILE_KW ).c_str() );
        if ( irods_env && strlen( irods_env ) > 0 ) {
            json_file = irods_env;
            // "cwd" is used in this case instead of the ppid given the
            // assumption that scripts will set the env file var to allow
            // for more complex interactions possibly yielding complex pid
            // hierarchies.  this routes all references to the same session
            // for this given use case
            json_session_file = json_file + ".cwd";

        }
        else {
            char* home_dir = getenv( "HOME" );
            // if home env exists, prefer that for run in place
            // or use of existing irods service accound
            if ( home_dir ) {
                json_file = home_dir;
            }

            json_file += JSON_ENV_FILE;
            json_session_file = json_file + "." + ppid_str.str();

        }

        _env_file     = json_file;
        _session_file = json_session_file;

        return SUCCESS();

    } // get_json_environment_file

    error environment_properties::get_legacy_environment_file(
        std::string& _env_file,
        std::string& _session_file ) {
        printf(
            "get_legacy_environment_file - use of legacy configuration is deprecated\n" );
        // capture parent process id for use in creation of 'session'
        // file which contains the cwd for a given session.  this cwd
        // is only updated by the icd command which writes a new irods
        // CFG_IRODS_CWD_KW to the session dir which repaves the existing
        // one in the original irodsEnv file.
        std::stringstream ppid_str; ppid_str << getppid();

        std::string legacy_file( IRODS_HOME_DIRECTORY );
        std::string legacy_session_file( IRODS_HOME_DIRECTORY );
        char* irods_env = getenv(
                              to_env(
                                  CFG_IRODS_ENVIRONMENT_FILE_KW ).c_str() );
        if ( irods_env && strlen( irods_env ) != 0 ) {
            legacy_file = irods_env;

            // "cwd" is used in this case instead of the ppid given the
            // assumption that scripts will set the env file var to allow
            // for more complex interactions possibly yielding complex pid
            // hierarchies.  this routes all references to the same session
            // for this given use case
            legacy_session_file = legacy_file + ".cwd";

        }
        else {
            char* home_dir = getenv( "HOME" );
            // if home env exists, prefer that for run in place
            // or use of existing irods service accound
            if ( home_dir ) {
                legacy_file = home_dir;
            }

            legacy_file += LEGACY_ENV_FILE;
            legacy_session_file = legacy_file + "." + ppid_str.str();

        }

        _env_file     = legacy_file;
        _session_file = legacy_session_file;

        return SUCCESS();

    } // get_legacy_environment_file

    error environment_properties::capture() {
        std::string json_file, json_session_file;
        error ret = get_json_environment_file(
                        json_file,
                        json_session_file );

        bool do_parse_legacy = false;
        if ( ret.ok() ) {
            if ( fs::exists( json_file ) ) {
                ret = capture_json( json_file );
                if ( !ret.ok() ) {
                    // debug - irods::log( PASS( ret ) );
                    do_parse_legacy = true;
                }
                else {
                    config_props_.set< std::string >(
                        CFG_IRODS_ENVIRONMENT_FILE_KW,
                        json_file );
                    ret = capture_json( json_session_file );
                    if ( !ret.ok() ) {
                        // debug - irods::log( PASS( ret ) );
                    }
                    config_props_.set< std::string >(
                        CFG_IRODS_SESSION_ENVIRONMENT_FILE_KW,
                        json_session_file );
                }
            }
            else {
                do_parse_legacy = true;
            }
        }
        else {
            do_parse_legacy = true;
        }

        if ( do_parse_legacy ) {
            std::string legacy_file, legacy_session_file;
            ret = get_legacy_environment_file(
                      legacy_file,
                      legacy_session_file );
            if ( ret.ok() ) {
                ret = capture_legacy( legacy_file );
                if ( !ret.ok() ) {
                    // debug - irods::log( PASS( ret ) );
                } else {
                    config_props_.set< std::string >(
                        CFG_IRODS_ENVIRONMENT_FILE_KW,
                        legacy_file );
                }

                // session file ( written by icd ) already moved
                // to json
                ret = capture_json( legacy_session_file );
                if ( !ret.ok() ) {
                    // debug - irods::log( PASS( ret ) );
                }

                config_props_.set< std::string >(
                    CFG_IRODS_SESSION_ENVIRONMENT_FILE_KW,
                    legacy_session_file );

            }
            else {
                // debug - irods::log( PASS( ret ) );

            }

        } // do parse legacy

        // set the captured flag so we no its already
        // been captured
        captured_ = true;
        return SUCCESS();

    } // capture

    error environment_properties::capture_json(
        const std::string& _fn ) {
        error ret = config_props_.load( _fn );
        return ret;

    } // capture_json

    error environment_properties::capture_legacy(
        const std::string& _fn ) {

        std::ifstream in_file(
            _fn.c_str(),
            std::ios::in );
        if ( !in_file.is_open() ) {
            std::string msg( "failed to open legacy file [" );
            msg += _fn;
            msg += "]";
            return ERROR( SYS_INVALID_FILE_PATH, msg );
        }

        std::string line;
        while ( getline( in_file, line ) ) {
            // left trim whitespace
            line.erase(
                line.begin(),
                std::find_if(
                    line.begin(),
                    line.end(),
                    std::not1(
                        std::ptr_fun<int, int>(
                            std::isspace ) ) ) );
            // skip comments
            if ( '#' == line[0] ) {
                continue;
            }

            std::vector< std::string > toks;
            try {
                boost::split(
                    toks,
                    line,
                    boost::is_any_of( "\t " ),
                    boost::token_compress_on );
            }
            catch ( boost::exception& ) {
                rodsLog( LOG_ERROR, "boost::split failed on line [%s]", line.c_str() );
                continue;
            }
            if ( toks.size() != 2 ||
                    toks[0].empty()  ||
                    toks[1].empty() ) {
                rodsLog(
                    LOG_NOTICE,
                    "environment_properties :: invalid line [%s]",
                    line.c_str() );
                continue;
            }

            std::string& key = toks[0];
            if ( legacy_key_map_.has_entry( key ) ) {
                key = legacy_key_map_[ key ];

            } //if has entry

            std::string& val = toks[1];

            char front = *( val.begin() );
            if ( '"'  == front ||
                    '\'' == front ) {
                val.erase( 0, 1 );
            }

            char back = *( val.rbegin() );
            if ( '"'  == back ||
                    '\'' == back ) {
                val.erase( val.size() - 1 );
            }

            error ret;
            if ( CFG_IRODS_PORT_KW                        == key ||
                 CFG_IRODS_XMSG_PORT_KW                   == key ||
                 CFG_IRODS_LOG_LEVEL_KW                   == key ||
                 CFG_IRODS_ENCRYPTION_KEY_SIZE_KW         == key ||
                 CFG_IRODS_ENCRYPTION_SALT_SIZE_KW        == key ||
                 CFG_IRODS_ENCRYPTION_NUM_HASH_ROUNDS_KW  == key ) {
                try {
                    int i_val = boost::lexical_cast< int >( val );
                    ret = config_props_.set< int >( key, i_val );
                }
                catch ( ... ) {
                    rodsLog(
                        LOG_ERROR,
                        "environment_properties :: lexical_cast failed for [%s]-[%s]",
                        key.c_str(),
                        val.c_str() );
                }
            }
            else {
                ret = config_props_.set <
                      std::string > (
                          key,
                          val );
            }
            if ( !ret.ok() ) {
                irods::log( PASS( ret ) );
            }

        } // while

        in_file.close();

        return SUCCESS();

    } // environment_properties::capture_legacy

} // namespace irods
<commit_msg>[#2686] add error message for invalid json environment file<commit_after>/*
 * irods_environment_properties.cpp
 *
 */

#include "irods_environment_properties.hpp"
#include "irods_get_full_path_for_config_file.hpp"

#include "rods.h"
#include "irods_log.hpp"
#include "irods_lookup_table.hpp"
#include "irods_home_directory.hpp"
#include "readServerConfig.hpp"

#include <string>
#include <algorithm>
#include <fstream>

#include <boost/algorithm/string.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;

#define BUF_LEN 500

namespace irods {

    const std::string environment_properties::LEGACY_ENV_FILE = "/.irods/.irodsEnv";
    const std::string environment_properties::JSON_ENV_FILE   = "/.irods/irods_environment.json";

// Access method for singleton
    environment_properties& environment_properties::getInstance() {
        static environment_properties instance;
        return instance;
    }

    error environment_properties::capture_if_needed() {
        error result = SUCCESS();
        if ( !captured_ ) {
            result = capture();
        }
        return result;
    }

    environment_properties::environment_properties() :
        captured_( false ) {

        legacy_key_map_[ "irodsUserName" ]                = CFG_IRODS_USER_NAME_KW;
        legacy_key_map_[ "irodsHost" ]                    = CFG_IRODS_HOST_KW;
        legacy_key_map_[ "irodsPort" ]                    = CFG_IRODS_PORT_KW;
        legacy_key_map_[ "xmsgHost" ]                     = CFG_IRODS_XMSG_HOST_KW;
        legacy_key_map_[ "xmsgPort" ]                     = CFG_IRODS_XMSG_PORT_KW;
        legacy_key_map_[ "irodsHome" ]                    = CFG_IRODS_HOME_KW;
        legacy_key_map_[ "irodsCwd" ]                     = CFG_IRODS_CWD_KW;
        legacy_key_map_[ "irodsAuthScheme" ]              = CFG_IRODS_AUTHENTICATION_SCHEME_KW;
        legacy_key_map_[ "irodsDefResource" ]             = CFG_IRODS_DEFAULT_RESOURCE_KW;
        legacy_key_map_[ "irodsZone" ]                    = CFG_IRODS_ZONE_KW;
        legacy_key_map_[ "irodsServerDn" ]                = CFG_IRODS_GSI_SERVER_DN_KW;
        legacy_key_map_[ "irodsLogLevel" ]                = CFG_IRODS_LOG_LEVEL_KW;
        legacy_key_map_[ "irodsAuthFileName" ]            = CFG_IRODS_AUTHENTICATION_FILE_KW;
        legacy_key_map_[ "irodsDebug" ]                   = CFG_IRODS_DEBUG_KW;
        legacy_key_map_[ "irodsClientServerPolicy" ]      = CFG_IRODS_CLIENT_SERVER_POLICY_KW;
        legacy_key_map_[ "irodsClientServerNegotiation" ] = CFG_IRODS_CLIENT_SERVER_NEGOTIATION_KW;
        legacy_key_map_[ "irodsEncryptionKeySize" ]       = CFG_IRODS_ENCRYPTION_KEY_SIZE_KW;
        legacy_key_map_[ "irodsEncryptionSaltSize" ]      = CFG_IRODS_ENCRYPTION_SALT_SIZE_KW;
        legacy_key_map_[ "irodsEncryptionNumHashRounds" ] = CFG_IRODS_ENCRYPTION_NUM_HASH_ROUNDS_KW;
        legacy_key_map_[ "irodsEncryptionAlgorithm" ]     = CFG_IRODS_ENCRYPTION_ALGORITHM_KW;
        legacy_key_map_[ "irodsDefaultHashScheme" ]       = CFG_IRODS_DEFAULT_HASH_SCHEME_KW;
        legacy_key_map_[ "irodsMatchHashPolicy" ]         = CFG_IRODS_MATCH_HASH_POLICY_KW;

    } // ctor

    error environment_properties::get_json_environment_file(
        std::string& _env_file,
        std::string& _session_file ) {
        // capture parent process id for use in creation of 'session'
        // file which contains the cwd for a given session.  this cwd
        // is only updated by the icd command which writes a new irods
        // CFG_IRODS_CWD_KW to the session dir which repaves the existing
        // one in the original irodsEnv file.
        std::stringstream ppid_str; ppid_str << getppid();

        // if a json version exists, then attempt to capture
        // that
        std::string json_file( IRODS_HOME_DIRECTORY );
        std::string json_session_file( IRODS_HOME_DIRECTORY );
        std::string env_var = to_env( CFG_IRODS_ENVIRONMENT_FILE_KW );
        char* irods_env = getenv(
                              to_env(
                                  CFG_IRODS_ENVIRONMENT_FILE_KW ).c_str() );
        if ( irods_env && strlen( irods_env ) > 0 ) {
            json_file = irods_env;
            // "cwd" is used in this case instead of the ppid given the
            // assumption that scripts will set the env file var to allow
            // for more complex interactions possibly yielding complex pid
            // hierarchies.  this routes all references to the same session
            // for this given use case
            json_session_file = json_file + ".cwd";

        }
        else {
            char* home_dir = getenv( "HOME" );
            // if home env exists, prefer that for run in place
            // or use of existing irods service accound
            if ( home_dir ) {
                json_file = home_dir;
            }

            json_file += JSON_ENV_FILE;
            json_session_file = json_file + "." + ppid_str.str();

        }

        _env_file     = json_file;
        _session_file = json_session_file;

        return SUCCESS();

    } // get_json_environment_file

    error environment_properties::get_legacy_environment_file(
        std::string& _env_file,
        std::string& _session_file ) {
        printf(
            "get_legacy_environment_file - use of legacy configuration is deprecated\n" );
        // capture parent process id for use in creation of 'session'
        // file which contains the cwd for a given session.  this cwd
        // is only updated by the icd command which writes a new irods
        // CFG_IRODS_CWD_KW to the session dir which repaves the existing
        // one in the original irodsEnv file.
        std::stringstream ppid_str; ppid_str << getppid();

        std::string legacy_file( IRODS_HOME_DIRECTORY );
        std::string legacy_session_file( IRODS_HOME_DIRECTORY );
        char* irods_env = getenv(
                              to_env(
                                  CFG_IRODS_ENVIRONMENT_FILE_KW ).c_str() );
        if ( irods_env && strlen( irods_env ) != 0 ) {
            legacy_file = irods_env;

            // "cwd" is used in this case instead of the ppid given the
            // assumption that scripts will set the env file var to allow
            // for more complex interactions possibly yielding complex pid
            // hierarchies.  this routes all references to the same session
            // for this given use case
            legacy_session_file = legacy_file + ".cwd";

        }
        else {
            char* home_dir = getenv( "HOME" );
            // if home env exists, prefer that for run in place
            // or use of existing irods service accound
            if ( home_dir ) {
                legacy_file = home_dir;
            }

            legacy_file += LEGACY_ENV_FILE;
            legacy_session_file = legacy_file + "." + ppid_str.str();

        }

        _env_file     = legacy_file;
        _session_file = legacy_session_file;

        return SUCCESS();

    } // get_legacy_environment_file

    error environment_properties::capture() {
        std::string json_file, json_session_file;
        error ret = get_json_environment_file(
                        json_file,
                        json_session_file );

        bool do_parse_legacy = false;
        if ( ret.ok() ) {
            if ( fs::exists( json_file ) ) {
                ret = capture_json( json_file );
                if ( !ret.ok() ) {
                    irods::log( ret );
                    do_parse_legacy = true;
                }
                else {
                    config_props_.set< std::string >(
                        CFG_IRODS_ENVIRONMENT_FILE_KW,
                        json_file );
                    ret = capture_json( json_session_file );
                    if ( !ret.ok() ) {
                        // debug - irods::log( PASS( ret ) );
                    }
                    config_props_.set< std::string >(
                        CFG_IRODS_SESSION_ENVIRONMENT_FILE_KW,
                        json_session_file );
                }
            }
            else {
                do_parse_legacy = true;
            }
        }
        else {
            do_parse_legacy = true;
        }

        if ( do_parse_legacy ) {
            std::string legacy_file, legacy_session_file;
            ret = get_legacy_environment_file(
                      legacy_file,
                      legacy_session_file );
            if ( ret.ok() ) {
                ret = capture_legacy( legacy_file );
                if ( !ret.ok() ) {
                    // debug - irods::log( PASS( ret ) );
                } else {
                    config_props_.set< std::string >(
                        CFG_IRODS_ENVIRONMENT_FILE_KW,
                        legacy_file );
                }

                // session file ( written by icd ) already moved
                // to json
                ret = capture_json( legacy_session_file );
                if ( !ret.ok() ) {
                    // debug - irods::log( PASS( ret ) );
                }

                config_props_.set< std::string >(
                    CFG_IRODS_SESSION_ENVIRONMENT_FILE_KW,
                    legacy_session_file );

            }
            else {
                // debug - irods::log( PASS( ret ) );

            }

        } // do parse legacy

        // set the captured flag so we no its already
        // been captured
        captured_ = true;
        return SUCCESS();

    } // capture

    error environment_properties::capture_json(
        const std::string& _fn ) {
        error ret = config_props_.load( _fn );
        return ret;

    } // capture_json

    error environment_properties::capture_legacy(
        const std::string& _fn ) {

        std::ifstream in_file(
            _fn.c_str(),
            std::ios::in );
        if ( !in_file.is_open() ) {
            std::string msg( "failed to open legacy file [" );
            msg += _fn;
            msg += "]";
            return ERROR( SYS_INVALID_FILE_PATH, msg );
        }

        std::string line;
        while ( getline( in_file, line ) ) {
            // left trim whitespace
            line.erase(
                line.begin(),
                std::find_if(
                    line.begin(),
                    line.end(),
                    std::not1(
                        std::ptr_fun<int, int>(
                            std::isspace ) ) ) );
            // skip comments
            if ( '#' == line[0] ) {
                continue;
            }

            std::vector< std::string > toks;
            try {
                boost::split(
                    toks,
                    line,
                    boost::is_any_of( "\t " ),
                    boost::token_compress_on );
            }
            catch ( boost::exception& ) {
                rodsLog( LOG_ERROR, "boost::split failed on line [%s]", line.c_str() );
                continue;
            }
            if ( toks.size() != 2 ||
                    toks[0].empty()  ||
                    toks[1].empty() ) {
                rodsLog(
                    LOG_NOTICE,
                    "environment_properties :: invalid line [%s]",
                    line.c_str() );
                continue;
            }

            std::string& key = toks[0];
            if ( legacy_key_map_.has_entry( key ) ) {
                key = legacy_key_map_[ key ];

            } //if has entry

            std::string& val = toks[1];

            char front = *( val.begin() );
            if ( '"'  == front ||
                    '\'' == front ) {
                val.erase( 0, 1 );
            }

            char back = *( val.rbegin() );
            if ( '"'  == back ||
                    '\'' == back ) {
                val.erase( val.size() - 1 );
            }

            error ret;
            if ( CFG_IRODS_PORT_KW                        == key ||
                 CFG_IRODS_XMSG_PORT_KW                   == key ||
                 CFG_IRODS_LOG_LEVEL_KW                   == key ||
                 CFG_IRODS_ENCRYPTION_KEY_SIZE_KW         == key ||
                 CFG_IRODS_ENCRYPTION_SALT_SIZE_KW        == key ||
                 CFG_IRODS_ENCRYPTION_NUM_HASH_ROUNDS_KW  == key ) {
                try {
                    int i_val = boost::lexical_cast< int >( val );
                    ret = config_props_.set< int >( key, i_val );
                }
                catch ( ... ) {
                    rodsLog(
                        LOG_ERROR,
                        "environment_properties :: lexical_cast failed for [%s]-[%s]",
                        key.c_str(),
                        val.c_str() );
                }
            }
            else {
                ret = config_props_.set <
                      std::string > (
                          key,
                          val );
            }
            if ( !ret.ok() ) {
                irods::log( PASS( ret ) );
            }

        } // while

        in_file.close();

        return SUCCESS();

    } // environment_properties::capture_legacy

} // namespace irods
<|endoftext|>


<commit_before>#pragma once

/**
 * Implement generic backward assignments.
 *
 * Be aware that unless the assignment is invertible the result is an
 * over-approximation so we need to adapt these operations in case we
 * need under-approximations.
 **/

#include <crab/config.h>
#include <crab/common/debug.hpp>
#include <crab/common/stats.hpp>
#include <crab/common/types.hpp>
#include <crab/domains/abstract_domain_operators.hpp>

namespace crab {
  namespace domains {

    template<class AbsDom>
    class BackwardAssignOps {
    public:
      typedef typename AbsDom::number_t number_t;
      typedef typename AbsDom::varname_t varname_t;
      typedef typename AbsDom::variable_t variable_t;
      typedef typename AbsDom::linear_constraint_t linear_constraint_t;
      typedef typename AbsDom::linear_expression_t linear_expression_t;

      /*
       * Backward x := e
       *
       *  General case:
       *   if x does not appear in e
       *      1) add constraint x = e
       *      2) forget x
       *   else
       *      1) add new variable x'
       *      2) add constraint x = e[x'/x]
       *      3) forget x
       *      4) rename x' as x
       *
       *  Invertible operation (y can be equal to x):
       *    x = y + k <--> y = x - k
       *    x = y - k <--> y = x + k
       *    x = y * k <--> y = x / k  if (k != 0)
       *    x = y / k <--> y = x * k  if (k != 0)
       *
       *  Fallback case:
       *   forget(x)
       **/

      // x := e
      static void assign(AbsDom& dom, variable_t x, linear_expression_t e,
			 AbsDom inv) {
	crab::CrabStats::count(AbsDom::getDomainName() + ".count.backward_assign");
	crab::ScopedCrabStats __st__(AbsDom::getDomainName() + ".backward_assign");

	if(dom.is_bottom()) return;

	if (e.variables() >= x) {
	  auto& vfac = x.name().get_var_factory();
	  variable_t old_x(vfac.get(x.index()), x.get_type());
	  std::map<variable_t,variable_t> renaming_map;
	  renaming_map.insert({x, old_x});
	  linear_expression_t renamed_e = e.rename(renaming_map);
	  dom += linear_constraint_t(renamed_e - x, linear_constraint_t::EQUALITY);
	  dom -= x;
	  dom.rename({old_x}, {x});
	} else {
	  dom += linear_constraint_t(e - x, linear_constraint_t::EQUALITY);
	  dom -= x;
	}
	dom = dom & inv;
      }

      // x := y op k
      static void apply(AbsDom& dom, operation_t op, variable_t x, variable_t y, number_t k,
			AbsDom inv) {
	crab::CrabStats::count(AbsDom::getDomainName() + ".count.backward_apply");
	crab::ScopedCrabStats __st__(AbsDom::getDomainName() + ".backward_apply");

	if(dom.is_bottom()) {
	  return;
	}

	CRAB_LOG("backward",
		 crab::outs() << x << ":=" << y << " " << op << " " << k << "\n"
		              << "BEFORE " << dom << "\n";);

	switch(op) {
	case OP_ADDITION:
	  dom.apply(OP_SUBTRACTION, y, x, k);
	  if (!(x == y)) {
	    dom -= x;
	  }
	  break;
	case OP_SUBTRACTION:
	  dom.apply(OP_ADDITION, y, x, k);
	  if (!(x == y)) {
	    dom -= x;
	  }
	  break;
	case OP_MULTIPLICATION:
	  if(k != 0) {
	    dom.apply(OP_SDIV, y, x, k);
	    if (!(x == y)) {
	      dom -= x;
	    }
	  } else {
	    dom -= x;
	  }
	  break;
	case OP_SDIV:
	  if(k != 0) {
	    dom.apply(OP_MULTIPLICATION, y, x, k);
	    if (!(x == y)) {
	      dom -= x;
	    }
	  } else {
	    dom -= x;
	  }
	  break;
	case OP_UDIV:
	case OP_SREM:
	case OP_UREM:
	default:
	  CRAB_WARN("backwards x:= y ", op, " k is not implemented");
	  dom -= x;
	}

	dom = dom & inv;

	CRAB_LOG("backward", crab::outs()<< "AFTER " << dom << "\n");
	return;
      }

      // x = y op z
      static void apply(AbsDom& dom, operation_t op,
			variable_t x, variable_t y, variable_t z,
			AbsDom inv) {
	crab::CrabStats::count(AbsDom::getDomainName() + ".count.backward_apply");
	crab::ScopedCrabStats __st__(AbsDom::getDomainName() + ".backward_apply");

	if(dom.is_bottom()) {
	  return;
	}

	CRAB_LOG("backward",
		 crab::outs() << x << ":=" << y << " " << op << " " << z << "\n"
		              << "BEFORE " << dom << "\n";);

	switch(op) {
	case OP_ADDITION:
	  assign(dom, x, linear_expression_t(y+z), inv);
	  break;
	case OP_SUBTRACTION:
	  assign(dom, x, linear_expression_t(y-z), inv);
	  break;
	case OP_MULTIPLICATION:
	case OP_SDIV:
	case OP_UDIV:
	case OP_SREM:
	case OP_UREM:
	  CRAB_WARN("backwards x = y ", op, " z not implemented");
	  dom -= x;
	  break;
	}
	dom = dom & inv;
	CRAB_LOG("backward", crab::outs()<< "AFTER " << dom << "\n");
      }
    };

  } //end namespace domains
} // end namespace crab

<commit_msg>Generate fresh id for temporary variable<commit_after>#pragma once

/**
 * Implement generic backward assignments.
 *
 * Be aware that unless the assignment is invertible the result is an
 * over-approximation so we need to adapt these operations in case we
 * need under-approximations.
 **/

#include <crab/config.h>
#include <crab/common/debug.hpp>
#include <crab/common/stats.hpp>
#include <crab/common/types.hpp>
#include <crab/domains/abstract_domain_operators.hpp>

namespace crab {
  namespace domains {

    template<class AbsDom>
    class BackwardAssignOps {
    public:
      typedef typename AbsDom::number_t number_t;
      typedef typename AbsDom::varname_t varname_t;
      typedef typename AbsDom::variable_t variable_t;
      typedef typename AbsDom::linear_constraint_t linear_constraint_t;
      typedef typename AbsDom::linear_expression_t linear_expression_t;

      /*
       * Backward x := e
       *
       *  General case:
       *   if x does not appear in e
       *      1) add constraint x = e
       *      2) forget x
       *   else
       *      1) add new variable x'
       *      2) add constraint x = e[x'/x]
       *      3) forget x
       *      4) rename x' as x
       *
       *  Invertible operation (y can be equal to x):
       *    x = y + k <--> y = x - k
       *    x = y - k <--> y = x + k
       *    x = y * k <--> y = x / k  if (k != 0)
       *    x = y / k <--> y = x * k  if (k != 0)
       *
       *  Fallback case:
       *   forget(x)
       **/

      // x := e
      static void assign(AbsDom& dom, variable_t x, linear_expression_t e,
			 AbsDom inv) {
	crab::CrabStats::count(AbsDom::getDomainName() + ".count.backward_assign");
	crab::ScopedCrabStats __st__(AbsDom::getDomainName() + ".backward_assign");

	if(dom.is_bottom()) return;

	if (e.variables() >= x) {
	  auto& vfac = x.name().get_var_factory();
	  variable_t old_x(vfac.get(), x.get_type());
	  std::map<variable_t,variable_t> renaming_map;
	  renaming_map.insert({x, old_x});
	  linear_expression_t renamed_e = e.rename(renaming_map);
	  dom += linear_constraint_t(renamed_e - x, linear_constraint_t::EQUALITY);
	  dom -= x;
	  dom.rename({old_x}, {x});
	} else {
	  dom += linear_constraint_t(e - x, linear_constraint_t::EQUALITY);
	  dom -= x;
	}
	dom = dom & inv;
      }

      // x := y op k
      static void apply(AbsDom& dom, operation_t op, variable_t x, variable_t y, number_t k,
			AbsDom inv) {
	crab::CrabStats::count(AbsDom::getDomainName() + ".count.backward_apply");
	crab::ScopedCrabStats __st__(AbsDom::getDomainName() + ".backward_apply");

	if(dom.is_bottom()) {
	  return;
	}

	CRAB_LOG("backward",
		 crab::outs() << x << ":=" << y << " " << op << " " << k << "\n"
		              << "BEFORE " << dom << "\n";);

	switch(op) {
	case OP_ADDITION:
	  dom.apply(OP_SUBTRACTION, y, x, k);
	  if (!(x == y)) {
	    dom -= x;
	  }
	  break;
	case OP_SUBTRACTION:
	  dom.apply(OP_ADDITION, y, x, k);
	  if (!(x == y)) {
	    dom -= x;
	  }
	  break;
	case OP_MULTIPLICATION:
	  if(k != 0) {
	    dom.apply(OP_SDIV, y, x, k);
	    if (!(x == y)) {
	      dom -= x;
	    }
	  } else {
	    dom -= x;
	  }
	  break;
	case OP_SDIV:
	  if(k != 0) {
	    dom.apply(OP_MULTIPLICATION, y, x, k);
	    if (!(x == y)) {
	      dom -= x;
	    }
	  } else {
	    dom -= x;
	  }
	  break;
	case OP_UDIV:
	case OP_SREM:
	case OP_UREM:
	default:
	  CRAB_WARN("backwards x:= y ", op, " k is not implemented");
	  dom -= x;
	}

	dom = dom & inv;

	CRAB_LOG("backward", crab::outs()<< "AFTER " << dom << "\n");
	return;
      }

      // x = y op z
      static void apply(AbsDom& dom, operation_t op,
			variable_t x, variable_t y, variable_t z,
			AbsDom inv) {
	crab::CrabStats::count(AbsDom::getDomainName() + ".count.backward_apply");
	crab::ScopedCrabStats __st__(AbsDom::getDomainName() + ".backward_apply");

	if(dom.is_bottom()) {
	  return;
	}

	CRAB_LOG("backward",
		 crab::outs() << x << ":=" << y << " " << op << " " << z << "\n"
		              << "BEFORE " << dom << "\n";);

	switch(op) {
	case OP_ADDITION:
	  assign(dom, x, linear_expression_t(y+z), inv);
	  break;
	case OP_SUBTRACTION:
	  assign(dom, x, linear_expression_t(y-z), inv);
	  break;
	case OP_MULTIPLICATION:
	case OP_SDIV:
	case OP_UDIV:
	case OP_SREM:
	case OP_UREM:
	  CRAB_WARN("backwards x = y ", op, " z not implemented");
	  dom -= x;
	  break;
	}
	dom = dom & inv;
	CRAB_LOG("backward", crab::outs()<< "AFTER " << dom << "\n");
      }
    };

  } //end namespace domains
} // end namespace crab

<|endoftext|>


<commit_before>#pragma once

#include <tudocomp_stat/StatPhase.hpp>

#include <tudocomp/compressors/esp/EspContext.hpp>
#include <tudocomp/compressors/esp/RoundContext.hpp>
#include <tudocomp/compressors/esp/meta_blocks.hpp>

#include <tudocomp/compressors/esp/utils.hpp>

namespace tdc {namespace esp {
    template<typename ipd_t>
    SLP EspContext<ipd_t>::generate_grammar(string_ref input) {
        size_t root_node = 0;
        bool empty = false;

        SLP slp;
        size_t slp_counter = 256;
        size_t prev_slp_counter = 0;

        std::unique_ptr<Round<ipd_t>> round;

        // Initialize initial round
        {
            auto phase = with_env([&](auto& env) {
                return StatPhase("Prepare round 0");
            });

            round = std::make_unique<Round<ipd_t>>(Round<ipd_t> {
                GrammarRules<ipd_t>(256),
                256, // TODO: Calc actual alphabet size
                IntVector<dynamic_t>(),
            });
            round->string.reserve(input.size(), bits_for(256 - 1));
            for (auto c : input) {
                round->string.push_back(c);
            }
        }

        for(size_t n = 0;; n++) {
            auto phase = with_env([&](auto& env) {
                std::stringstream ss;
                ss << "Round " << n;
                return StatPhase(ss.str());
            });

            auto& r = *round;
            in_t in = r.string;

            esp::RoundContext<in_t> ctx {
                r.alphabet,
                in,
                behavior_metablocks_maximimze_repeating,
                behavior_landmarks_tie_to_right,
                debug.round(),
            };

            ctx.debug.init(n, in, r.alphabet);

            if (in.size() == 0) {
                empty = true;
                ctx.debug.last_round(0, true);
                break;
            }
            if (in.size() == 1) {
                root_node = in[0] + prev_slp_counter;
                ctx.debug.last_round(root_node, false);
                break;
            }

            IntVector<dynamic_t> new_layer;
            new_layer.reserve(in.size() / 2 + 1, bits_for(in.size() / 2));

            ctx.split(in);

            const auto& v = ctx.adjusted_blocks();

            ctx.debug.slice_symbol_map_start();
            {
                in_t s = in;
                for (auto e : v) {
                    auto slice = s.slice(0, e.len);
                    s = s.slice(e.len);
                    auto rule_name = r.gr.add(slice) - (r.gr.initial_counter() - 1);

                    ctx.debug.slice_symbol_map(slice, rule_name);

                    new_layer.push_back(rule_name);
                }
            }

            // Delete previous string
            r.string = IntVector<dynamic_t>();

            DCHECK_EQ(r.string.size(), 0);
            DCHECK_EQ(r.string.capacity(), 0);

            new_layer.shrink_to_fit();

            // Append to slp array
            {
                size_t old_slp_size = slp.rules.size();
                size_t additional_slp_size = r.gr.rules_count();
                size_t new_slp_size = old_slp_size + additional_slp_size;

                slp.rules.reserve(new_slp_size);
                slp.rules.resize(new_slp_size);

                auto& rv = slp.rules;

                r.gr.for_all([&](const auto& k, const auto& val_) {
                    const auto& val = val_ - r.gr.initial_counter();
                    const auto& key = k.as_view();

                    size_t store_idx = slp_counter + val - 256;
                    rv[store_idx][0] = key[0] + prev_slp_counter;
                    rv[store_idx][1] = key[1] + prev_slp_counter;
                });

                prev_slp_counter = slp_counter;
                slp_counter += additional_slp_size;
            }

            // Delete previous hashmap
            r.gr.clear();

            // Prepare next round
            auto tmp = Round<ipd_t> {
                GrammarRules<ipd_t>(r.gr.rules_count()),
                r.gr.rules_count(),
                std::move(new_layer),
            };

            round.reset();
            round = std::make_unique<Round<ipd_t>>(std::move(tmp));

            phase.log_stat("slp size", slp.rules.size());
        }

        slp.empty = empty;
        slp.root_rule = root_node;

        return slp;
    }
}}
<commit_msg>Fix bit access and bit size bug<commit_after>#pragma once

#include <tudocomp_stat/StatPhase.hpp>

#include <tudocomp/compressors/esp/EspContext.hpp>
#include <tudocomp/compressors/esp/RoundContext.hpp>
#include <tudocomp/compressors/esp/meta_blocks.hpp>

#include <tudocomp/compressors/esp/utils.hpp>

namespace tdc {namespace esp {
    template<typename ipd_t>
    SLP EspContext<ipd_t>::generate_grammar(string_ref input) {
        size_t root_node = 0;
        bool empty = false;

        SLP slp;
        size_t slp_counter = 256;
        size_t prev_slp_counter = 0;

        std::unique_ptr<Round<ipd_t>> round;

        // Initialize initial round
        {
            auto phase = with_env([&](auto& env) {
                return StatPhase("Prepare round 0");
            });

            round = std::make_unique<Round<ipd_t>>(Round<ipd_t> {
                GrammarRules<ipd_t>(256),
                256, // TODO: Calc actual alphabet size
                IntVector<dynamic_t>(),
            });
            round->string.width(bits_for(256 - 1));
            round->string.reserve(input.size(), bits_for(256 - 1));
            for (auto c : input) {
                round->string.push_back(c);
            }
        }

        for(size_t n = 0;; n++) {
            auto phase = with_env([&](auto& env) {
                std::stringstream ss;
                ss << "Round " << n;
                return StatPhase(ss.str());
            });

            auto& r = *round;
            in_t in = r.string;

            esp::RoundContext<in_t> ctx {
                r.alphabet,
                in,
                behavior_metablocks_maximimze_repeating,
                behavior_landmarks_tie_to_right,
                debug.round(),
            };

            ctx.debug.init(n, in, r.alphabet);

            if (in.size() == 0) {
                empty = true;
                ctx.debug.last_round(0, true);
                break;
            }
            if (in.size() == 1) {
                root_node = in[0] + prev_slp_counter;
                ctx.debug.last_round(root_node, false);
                break;
            }

            IntVector<dynamic_t> new_layer;
            size_t new_layer_width = bits_for(in.size() - 1);
            new_layer.width(new_layer_width);
            new_layer.reserve(in.size() / 2 + 1, new_layer_width);

            ctx.split(in);

            const auto& v = ctx.adjusted_blocks();

            ctx.debug.slice_symbol_map_start();
            {
                in_t s = in;
                for (auto e : v) {
                    auto slice = s.slice(0, e.len);
                    s = s.slice(e.len);
                    auto rule_name = r.gr.add(slice) - (r.gr.initial_counter() - 1);

                    ctx.debug.slice_symbol_map(slice, rule_name);

                    new_layer.push_back(rule_name);
                }
            }

            // Delete previous string
            r.string = IntVector<dynamic_t>();

            DCHECK_EQ(r.string.size(), 0);
            DCHECK_EQ(r.string.capacity(), 0);

            new_layer.shrink_to_fit();

            // Append to slp array
            {
                size_t old_slp_size = slp.rules.size();
                size_t additional_slp_size = r.gr.rules_count();
                size_t new_slp_size = old_slp_size + additional_slp_size;

                slp.rules.reserve(new_slp_size);
                slp.rules.resize(new_slp_size);

                auto& rv = slp.rules;

                r.gr.for_all([&](const auto& k, const auto& val_) {
                    const auto& val = val_ - r.gr.initial_counter();
                    const auto& key = k.as_view();

                    size_t store_idx = slp_counter + val - 256;
                    rv[store_idx][0] = key[0] + prev_slp_counter;
                    rv[store_idx][1] = key[1] + prev_slp_counter;
                });

                prev_slp_counter = slp_counter;
                slp_counter += additional_slp_size;
            }

            // Delete previous hashmap
            r.gr.clear();

            // Prepare next round
            auto tmp = Round<ipd_t> {
                GrammarRules<ipd_t>(r.gr.rules_count()),
                r.gr.rules_count(),
                std::move(new_layer),
            };

            round.reset();
            round = std::make_unique<Round<ipd_t>>(std::move(tmp));

            phase.log_stat("slp size", slp.rules.size());
        }

        slp.empty = empty;
        slp.root_rule = root_node;

        return slp;
    }
}}
<|endoftext|>


<commit_before>/*
 *  Copyright 2010-2011 Fabric Technologies Inc. All rights reserved.
 */

#include <Fabric/EDK/EDK.h>

#include "CImg.h"

using namespace Fabric::EDK;
IMPLEMENT_FABRIC_EDK_ENTRIES

using namespace cimg_library;

FABRIC_EXT_EXPORT void FabricCIMGDecode(
  KL::Data data,
  KL::Size dataSize,
  KL::Size &imageWidth,
  KL::Size &imageHeight,
  KL::VariableArray<KL::RGBA> &imagePixels
  )
{
#if defined(FABRIC_OS_WINDOWS)
  char const *dir = getenv("APPDATA");
  if(dir == NULL)
    dir = getenv("TEMP");
  if(dir == NULL)
    dir = getenv("TMP");
  if(dir == NULL)
    Fabric::EDK::throwException("CIMG extension: environment variable APP_DATA or TMP or TEMP is undefined");
  KL::String fileName( _tempnam( dir, "tmpfab_" ) );
#else
  KL::String fileName(tmpnam(NULL));
#endif

  // save the file to disk
  FILE * file = fopen(fileName.data(),"wb");
  if(!file)
    Fabric::EDK::throwException("CIMG extension: Cannot write to temporary file.");
  fwrite(data,dataSize,1,file);
  fclose(file);
  file = NULL;

  CImg<unsigned char> img(fileName.data());
  unsigned char * imgData = img.data();
  imageWidth = img.width();
  imageHeight = img.height();

  size_t nbPixels = imageWidth * imageHeight;
  size_t offsetG = nbPixels;
  size_t offsetB = nbPixels * 2;
  size_t offsetA = nbPixels * 3;

  imagePixels.resize(nbPixels);
  if(img.spectrum() == 1)
  {
    for(size_t i=0;i<nbPixels;i++)
    {
      imagePixels[i].r = imgData[i];
      imagePixels[i].g = imgData[i];
      imagePixels[i].b = imgData[i];
      imagePixels[i].a = 255;
    }
  }
  else if(img.spectrum() == 3)
  {
    for(size_t i=0;i<nbPixels;i++,offsetG++,offsetB++)
    {
      imagePixels[i].r = imgData[i];
      imagePixels[i].g = imgData[offsetG];
      imagePixels[i].b = imgData[offsetB];
      imagePixels[i].a = 255;
    }
  }
  else if(img.spectrum() == 4)
  {
    for(size_t i=0;i<nbPixels;i++,offsetG++,offsetB++,offsetA++)
    {
      imagePixels[i].r = imgData[i];
      imagePixels[i].g = imgData[offsetG];
      imagePixels[i].b = imgData[offsetB];
      imagePixels[i].a = imgData[offsetA];
    }
  }
}

<commit_msg>* Define 'cimg_display' to : '0' to disable display capabilities. in the CIMG library.<commit_after>/*
 *  Copyright 2010-2011 Fabric Technologies Inc. All rights reserved.
 */

#include <Fabric/EDK/EDK.h>

#define cimg_display 0

#include "CImg.h"

using namespace Fabric::EDK;
IMPLEMENT_FABRIC_EDK_ENTRIES

using namespace cimg_library;

FABRIC_EXT_EXPORT void FabricCIMGDecode(
  KL::Data data,
  KL::Size dataSize,
  KL::Size &imageWidth,
  KL::Size &imageHeight,
  KL::VariableArray<KL::RGBA> &imagePixels
  )
{
#if defined(FABRIC_OS_WINDOWS)
  char const *dir = getenv("APPDATA");
  if(dir == NULL)
    dir = getenv("TEMP");
  if(dir == NULL)
    dir = getenv("TMP");
  if(dir == NULL)
    Fabric::EDK::throwException("CIMG extension: environment variable APP_DATA or TMP or TEMP is undefined");
  KL::String fileName( _tempnam( dir, "tmpfab_" ) );
#else
  KL::String fileName(tmpnam(NULL));
#endif

  // save the file to disk
  FILE * file = fopen(fileName.data(),"wb");
  if(!file)
    Fabric::EDK::throwException("CIMG extension: Cannot write to temporary file.");
  fwrite(data,dataSize,1,file);
  fclose(file);
  file = NULL;

  CImg<unsigned char> img(fileName.data());
  unsigned char * imgData = img.data();
  imageWidth = img.width();
  imageHeight = img.height();

  size_t nbPixels = imageWidth * imageHeight;
  size_t offsetG = nbPixels;
  size_t offsetB = nbPixels * 2;
  size_t offsetA = nbPixels * 3;

  imagePixels.resize(nbPixels);
  if(img.spectrum() == 1)
  {
    for(size_t i=0;i<nbPixels;i++)
    {
      imagePixels[i].r = imgData[i];
      imagePixels[i].g = imgData[i];
      imagePixels[i].b = imgData[i];
      imagePixels[i].a = 255;
    }
  }
  else if(img.spectrum() == 3)
  {
    for(size_t i=0;i<nbPixels;i++,offsetG++,offsetB++)
    {
      imagePixels[i].r = imgData[i];
      imagePixels[i].g = imgData[offsetG];
      imagePixels[i].b = imgData[offsetB];
      imagePixels[i].a = 255;
    }
  }
  else if(img.spectrum() == 4)
  {
    for(size_t i=0;i<nbPixels;i++,offsetG++,offsetB++,offsetA++)
    {
      imagePixels[i].r = imgData[i];
      imagePixels[i].g = imgData[offsetG];
      imagePixels[i].b = imgData[offsetB];
      imagePixels[i].a = imgData[offsetA];
    }
  }
}

<|endoftext|>