<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: appbaslib.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2007-03-15 17:03:52 $
 *
 *  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 APPBASLIB_HXX
#define APPBASLIB_HXX

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif
#ifndef _COM_SUN_STAR_SCRIPT_XSTORAGEBASEDLIBRARYCONTAINER_HPP_
#include <com/sun/star/script/XStorageBasedLibraryContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_
#include <com/sun/star/embed/XStorage.hpp>
#endif

class BasicManager;

/** helper class which holds and manipulates a BasicManager
*/
class SfxBasicManagerHolder
{
private:
    BasicManager*   mpBasicManager;
    ::com::sun::star::uno::Reference< ::com::sun::star::script::XStorageBasedLibraryContainer >
                    mxBasicContainer;
    ::com::sun::star::uno::Reference< ::com::sun::star::script::XStorageBasedLibraryContainer >
                    mxDialogContainer;

public:
    SfxBasicManagerHolder();

    enum ContainerType
    {
        SCRIPTS, DIALOGS
    };

    /** returns <TRUE/> if and only if the instance is currently bound to a non-<NULL/>
        BasicManager.
    */
    bool    isValid() const { return mpBasicManager != NULL; }

    /** returns the BasicManager which this instance is currently bound to
    */
    BasicManager*
            get() const { return mpBasicManager; }

    /** binds the instance to the given BasicManager
    */
    void    reset( BasicManager* _pBasicManager );

    ::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >
            getLibraryContainer( ContainerType _eType );

    /** determines whether any of our library containers is modified, i.e. returns <TRUE/>
        in its isContainerModified call.
    */
    bool    isAnyContainerModified() const;

    /** calls the storeLibraries at both our script and basic library container
    */
    void    storeAllLibraries();

    /** calls the setStorage at all our XStorageBasedLibraryContainer.
    */
    void    setStorage(
                const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& _rxStorage
            );

    /** calls the storeLibrariesToStorage at all our XStorageBasedLibraryContainer.
    */
    void    storeLibrariesToStorage(
                const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& _rxStorage
            );

    /** checks if any modules in the SfxLibraryContainer exceed the binary
        limits.
    */
    sal_Bool LegacyPsswdBinaryLimitExceeded( ::com::sun::star::uno::Sequence< rtl::OUString >& sModules );

private:
    void    impl_releaseContainers();

    bool    impl_getContainer(
                ContainerType _eType,
                ::com::sun::star::uno::Reference< ::com::sun::star::script::XStorageBasedLibraryContainer >& _out_rxContainer );
};

class SfxApplicationScriptLibraryContainer
{
public:
    // Service
    static ::com::sun::star::uno::Sequence< ::rtl::OUString > impl_getStaticSupportedServiceNames();
    static ::rtl::OUString impl_getStaticImplementationName();
    static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL impl_createInstance
        ( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager )
            throw( ::com::sun::star::uno::Exception );
    static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > impl_createFactory
        ( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );

};

class SfxApplicationDialogLibraryContainer
{
public:
    // Service
    static ::com::sun::star::uno::Sequence< ::rtl::OUString > impl_getStaticSupportedServiceNames();
    static ::rtl::OUString impl_getStaticImplementationName();
    static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL impl_createInstance
        ( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager )
            throw( ::com::sun::star::uno::Exception );
    static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > impl_createFactory
        ( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );

};

#endif // APPBASLIB_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.4.288); FILE MERGED 2008/04/01 15:39:24 thb 1.4.288.3: #i85898# Stripping all external header guards 2008/04/01 12:40:50 thb 1.4.288.2: #i85898# Stripping all external header guards 2008/03/31 13:38:34 rt 1.4.288.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: appbaslib.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef APPBASLIB_HXX
#define APPBASLIB_HXX

#include <com/sun/star/uno/Sequence.hxx>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <com/sun/star/script/XStorageBasedLibraryContainer.hpp>
#include <com/sun/star/embed/XStorage.hpp>

class BasicManager;

/** helper class which holds and manipulates a BasicManager
*/
class SfxBasicManagerHolder
{
private:
    BasicManager*   mpBasicManager;
    ::com::sun::star::uno::Reference< ::com::sun::star::script::XStorageBasedLibraryContainer >
                    mxBasicContainer;
    ::com::sun::star::uno::Reference< ::com::sun::star::script::XStorageBasedLibraryContainer >
                    mxDialogContainer;

public:
    SfxBasicManagerHolder();

    enum ContainerType
    {
        SCRIPTS, DIALOGS
    };

    /** returns <TRUE/> if and only if the instance is currently bound to a non-<NULL/>
        BasicManager.
    */
    bool    isValid() const { return mpBasicManager != NULL; }

    /** returns the BasicManager which this instance is currently bound to
    */
    BasicManager*
            get() const { return mpBasicManager; }

    /** binds the instance to the given BasicManager
    */
    void    reset( BasicManager* _pBasicManager );

    ::com::sun::star::uno::Reference< ::com::sun::star::script::XLibraryContainer >
            getLibraryContainer( ContainerType _eType );

    /** determines whether any of our library containers is modified, i.e. returns <TRUE/>
        in its isContainerModified call.
    */
    bool    isAnyContainerModified() const;

    /** calls the storeLibraries at both our script and basic library container
    */
    void    storeAllLibraries();

    /** calls the setStorage at all our XStorageBasedLibraryContainer.
    */
    void    setStorage(
                const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& _rxStorage
            );

    /** calls the storeLibrariesToStorage at all our XStorageBasedLibraryContainer.
    */
    void    storeLibrariesToStorage(
                const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& _rxStorage
            );

    /** checks if any modules in the SfxLibraryContainer exceed the binary
        limits.
    */
    sal_Bool LegacyPsswdBinaryLimitExceeded( ::com::sun::star::uno::Sequence< rtl::OUString >& sModules );

private:
    void    impl_releaseContainers();

    bool    impl_getContainer(
                ContainerType _eType,
                ::com::sun::star::uno::Reference< ::com::sun::star::script::XStorageBasedLibraryContainer >& _out_rxContainer );
};

class SfxApplicationScriptLibraryContainer
{
public:
    // Service
    static ::com::sun::star::uno::Sequence< ::rtl::OUString > impl_getStaticSupportedServiceNames();
    static ::rtl::OUString impl_getStaticImplementationName();
    static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL impl_createInstance
        ( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager )
            throw( ::com::sun::star::uno::Exception );
    static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > impl_createFactory
        ( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );

};

class SfxApplicationDialogLibraryContainer
{
public:
    // Service
    static ::com::sun::star::uno::Sequence< ::rtl::OUString > impl_getStaticSupportedServiceNames();
    static ::rtl::OUString impl_getStaticImplementationName();
    static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL impl_createInstance
        ( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager )
            throw( ::com::sun::star::uno::Exception );
    static ::com::sun::star::uno::Reference< ::com::sun::star::lang::XSingleServiceFactory > impl_createFactory
        ( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager );

};

#endif // APPBASLIB_HXX

<|endoftext|>


<commit_before>#include <cstdio>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>

#ifdef WIN32
#include "awdw32.h"
#else
#include <unistd.h>
#endif

#include "awd.h"
#include "util.h"
#include "awdlzma.h"
#include "awdzlib.h"

#include "Types.h"
#include "LzmaEnc.h"

AWD::AWD(AWD_compression compression, awd_uint16 flags)
{
    this->major_version = AWD_MAJOR_VERSION;
    this->minor_version = AWD_MINOR_VERSION;
    this->compression = compression;
    this->flags = flags;
    this->texture_blocks = new AWDBlockList();
    this->material_blocks = new AWDBlockList();
    this->mesh_data_blocks = new AWDBlockList();
    this->skeleton_blocks = new AWDBlockList();
    this->skelanim_blocks = new AWDBlockList();
    this->skelpose_blocks = new AWDBlockList();
    this->uvanim_blocks = new AWDBlockList();
    this->scene_blocks = new AWDBlockList();

    this->last_used_nsid = 0;
    this->last_used_baddr = 0;
    this->header_written = AWD_FALSE;
}

AWD::~AWD()
{
    delete this->texture_blocks;
    delete this->material_blocks;
    delete this->mesh_data_blocks;
    delete this->skeleton_blocks;
    delete this->skelanim_blocks;
    delete this->skelpose_blocks;
    delete this->uvanim_blocks;
    delete this->scene_blocks;
}

void
AWD::add_material(AWDSimpleMaterial *block)
{
    this->material_blocks->append(block);
}

void
AWD::add_namespace(AWDNamespace *block)
{
    if (this->namespace_blocks->append(block)) {
        this->last_used_nsid++;
        block->set_handle(this->last_used_nsid);
    }
}

void
AWD::add_texture(AWDTexture *block)
{
    this->texture_blocks->append(block);
}

void
AWD::add_mesh_data(AWDMeshData *block)
{
    this->mesh_data_blocks->append(block);
}

void
AWD::add_scene_block(AWDSceneBlock *block)
{
    this->scene_blocks->append(block);
}

void
AWD::add_skeleton(AWDSkeleton *block)
{
    this->skeleton_blocks->append(block);
}

void
AWD::add_skeleton_pose(AWDSkeletonPose *block)
{
    this->skelpose_blocks->append(block);
}

void
AWD::add_skeleton_anim(AWDSkeletonAnimation *block)
{
    this->skelanim_blocks->append(block);
}

void
AWD::add_uv_anim(AWDUVAnimation *block)
{
    this->uvanim_blocks->append(block);
}

void
AWD::write_header(int fd, awd_uint32 body_length)
{
    awd_uint16 flags_be;

    // Convert to big-endian if necessary
    flags_be = UI16(this->flags);
    body_length = UI32(body_length);

    write(fd, "AWD", 3);
    write(fd, &this->major_version, sizeof(awd_uint8));
    write(fd, &this->minor_version, sizeof(awd_uint8));
    write(fd, &flags_be, sizeof(awd_uint16));
    write(fd, (awd_uint8*)&this->compression, sizeof(awd_uint8));
    write(fd, &body_length, sizeof(awd_uint32));
}

size_t
AWD::write_blocks(AWDBlockList *blocks, int fd)
{
    size_t len;
    AWDBlock *block;
    AWDBlockIterator it(blocks);

    len = 0;
    while ((block = it.next()) != NULL) {
        //block->add_dependencies(this);
        //TODO: Check flags for wide boolean (hard-coded as false now)
        len += block->write_block(fd, AWD_FALSE, AWD_FALSE, ++this->last_used_baddr);
    }

    return len;
}

void
AWD::flatten_scene(AWDSceneBlock *cur, AWDBlockList *flat_list)
{
    AWDBlock *child;
    AWDBlockIterator *children;

    flat_list->append(cur);

    children = cur->child_iter();
    while ((child = children->next()) != NULL) {
        this->flatten_scene((AWDSceneBlock*)child, flat_list);
    }
}

size_t
AWD::write_scene(AWDBlockList *blocks, int fd)
{
    AWDBlock *block;
    AWDBlockList *ordered;
    AWDBlockIterator it(blocks);

    ordered = new AWDBlockList();

    while ((block = it.next()) != NULL) {
        this->flatten_scene((AWDSceneBlock*)block, ordered);
    }

    return this->write_blocks(ordered, fd);
}

awd_uint32
AWD::flush(int out_fd)
{
    int tmp_fd;
    char *tmp_path;

    off_t tmp_len;
    awd_uint8 *tmp_buf;

    awd_uint8 *body_buf;
    awd_uint32 body_len;

    tmp_len = 0;
    tmp_fd = awdutil_mktmp(&tmp_path);
    if (tmp_fd < 0) {
        extern int errno;
        printf("Could not open temporary file necessary for writing, errno=%d\n", errno);
        return AWD_FALSE;
    }

    tmp_len += this->write_blocks(this->skeleton_blocks, tmp_fd);
    tmp_len += this->write_blocks(this->skelpose_blocks, tmp_fd);
    tmp_len += this->write_blocks(this->skelanim_blocks, tmp_fd);
    tmp_len += this->write_blocks(this->texture_blocks, tmp_fd);
    tmp_len += this->write_blocks(this->material_blocks, tmp_fd);
    tmp_len += this->write_blocks(this->mesh_data_blocks, tmp_fd);
    tmp_len += this->write_blocks(this->uvanim_blocks, tmp_fd);
    tmp_len += this->write_scene(this->scene_blocks, tmp_fd);

    tmp_buf = (awd_uint8 *) malloc(tmp_len);
	lseek(tmp_fd, 0, SEEK_SET);
    read(tmp_fd, tmp_buf, tmp_len);

    // Temp file no longer needed
    close(tmp_fd);
    unlink((const char *)tmp_path);

    if (this->compression == UNCOMPRESSED) {
        // Uncompressed, so output should be the exact
        // same data that was in the temporary file
        body_len = tmp_len;
        body_buf = tmp_buf;
    }
    else if (this->compression == DEFLATE) {
        int stat;
        z_streamp zstrm;
        int zlib_len;
        awd_uint8 *zlib_buf;
        bool done;

        zlib_len = tmp_len;
        zlib_buf = (awd_uint8*)malloc(zlib_len);

        zstrm = (z_streamp)malloc(sizeof(z_stream_s));
        zstrm->zalloc = awd_zalloc;
        zstrm->zfree = awd_zfree;
        zstrm->opaque = NULL;
        zstrm->next_in = tmp_buf;
        zstrm->avail_in = tmp_len;
        zstrm->next_out = zlib_buf;
        zstrm->avail_out = zlib_len;

        stat = deflateInit(zstrm, 9);

        done = false;
        while (!done) {
            stat = deflate(zstrm, Z_NO_FLUSH);

            switch (stat) {
                case Z_STREAM_END:
                case Z_BUF_ERROR:
                    done = true;
                    break;
            }
        }

        deflate(zstrm, Z_FINISH);
        deflateEnd(zstrm);

        body_len = zstrm->total_out;
        body_buf = (awd_uint8*)malloc(sizeof(body_len));
        memcpy(body_buf, zlib_buf, body_len);

        free(zlib_buf);
    }
    else if (this->compression == LZMA) {
        Byte *lzma_buf;
        SizeT lzma_len, props_len;
        CLzmaEncProps props;
        ISzAlloc alloc;
        Byte *props_buf;
        long tmp_len_bo;

        // Create allocation structure. LZMA library uses
        // these functions for memory management. They are
        // defined in awdlzma.c as simple wrappers for
        // malloc() and free().
        alloc.Alloc = &awd_SzAlloc;
        alloc.Free = &awd_SzFree;

        lzma_len = tmp_len;
        lzma_buf = (Byte *)malloc(tmp_len);
        props_len = sizeof(CLzmaEncProps);
        props_buf = (Byte *)malloc(props_len);

        LzmaEncProps_Init(&props);
        props.algo = 1;
        props.level = 9;

        LzmaEncode(lzma_buf, &lzma_len, tmp_buf, tmp_len,
            &props, props_buf, &props_len, 0, NULL, &alloc, &alloc);

        // Body length is the length of the actual
        // compressed body + size of props and an integer
        // definining the uncompressed length (see below)
        body_len = (awd_uint32)lzma_len + (awd_uint32)props_len + sizeof(awd_uint32);

        // Create new buffer containing LZMA props, length
        // of uncompressed body and the actual body data
        // concatenated together.
        tmp_len_bo = UI32(tmp_len);
        body_buf = (awd_uint8*)malloc(body_len);
        memcpy(body_buf, props_buf, props_len);
        memcpy(body_buf+props_len, &tmp_len_bo, sizeof(awd_uint32));
        memcpy(body_buf+props_len+sizeof(awd_uint32), lzma_buf, lzma_len);
    }

    // Write header and then body from possibly
    // compressed buffer
    if (this->header_written == AWD_FALSE) {
        this->header_written = AWD_TRUE;
        this->write_header(out_fd, body_len);
    }

    write(out_fd, body_buf, body_len);

    return AWD_TRUE;
}

<commit_msg>Fixed libawd DEFLATE memory bug (incorrect size in malloc()).<commit_after>#include <cstdio>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>

#ifdef WIN32
#include "awdw32.h"
#else
#include <unistd.h>
#endif

#include "awd.h"
#include "util.h"
#include "awdlzma.h"
#include "awdzlib.h"

#include "Types.h"
#include "LzmaEnc.h"

AWD::AWD(AWD_compression compression, awd_uint16 flags)
{
    this->major_version = AWD_MAJOR_VERSION;
    this->minor_version = AWD_MINOR_VERSION;
    this->compression = compression;
    this->flags = flags;
    this->texture_blocks = new AWDBlockList();
    this->material_blocks = new AWDBlockList();
    this->mesh_data_blocks = new AWDBlockList();
    this->skeleton_blocks = new AWDBlockList();
    this->skelanim_blocks = new AWDBlockList();
    this->skelpose_blocks = new AWDBlockList();
    this->uvanim_blocks = new AWDBlockList();
    this->scene_blocks = new AWDBlockList();

    this->last_used_nsid = 0;
    this->last_used_baddr = 0;
    this->header_written = AWD_FALSE;
}

AWD::~AWD()
{
    delete this->texture_blocks;
    delete this->material_blocks;
    delete this->mesh_data_blocks;
    delete this->skeleton_blocks;
    delete this->skelanim_blocks;
    delete this->skelpose_blocks;
    delete this->uvanim_blocks;
    delete this->scene_blocks;
}

void
AWD::add_material(AWDSimpleMaterial *block)
{
    this->material_blocks->append(block);
}

void
AWD::add_namespace(AWDNamespace *block)
{
    if (this->namespace_blocks->append(block)) {
        this->last_used_nsid++;
        block->set_handle(this->last_used_nsid);
    }
}

void
AWD::add_texture(AWDTexture *block)
{
    this->texture_blocks->append(block);
}

void
AWD::add_mesh_data(AWDMeshData *block)
{
    this->mesh_data_blocks->append(block);
}

void
AWD::add_scene_block(AWDSceneBlock *block)
{
    this->scene_blocks->append(block);
}

void
AWD::add_skeleton(AWDSkeleton *block)
{
    this->skeleton_blocks->append(block);
}

void
AWD::add_skeleton_pose(AWDSkeletonPose *block)
{
    this->skelpose_blocks->append(block);
}

void
AWD::add_skeleton_anim(AWDSkeletonAnimation *block)
{
    this->skelanim_blocks->append(block);
}

void
AWD::add_uv_anim(AWDUVAnimation *block)
{
    this->uvanim_blocks->append(block);
}

void
AWD::write_header(int fd, awd_uint32 body_length)
{
    awd_uint16 flags_be;

    // Convert to big-endian if necessary
    flags_be = UI16(this->flags);
    body_length = UI32(body_length);

    write(fd, "AWD", 3);
    write(fd, &this->major_version, sizeof(awd_uint8));
    write(fd, &this->minor_version, sizeof(awd_uint8));
    write(fd, &flags_be, sizeof(awd_uint16));
    write(fd, (awd_uint8*)&this->compression, sizeof(awd_uint8));
    write(fd, &body_length, sizeof(awd_uint32));
}

size_t
AWD::write_blocks(AWDBlockList *blocks, int fd)
{
    size_t len;
    AWDBlock *block;
    AWDBlockIterator it(blocks);

    len = 0;
    while ((block = it.next()) != NULL) {
        //block->add_dependencies(this);
        //TODO: Check flags for wide boolean (hard-coded as false now)
        len += block->write_block(fd, AWD_FALSE, AWD_FALSE, ++this->last_used_baddr);
    }

    return len;
}

void
AWD::flatten_scene(AWDSceneBlock *cur, AWDBlockList *flat_list)
{
    AWDBlock *child;
    AWDBlockIterator *children;

    flat_list->append(cur);

    children = cur->child_iter();
    while ((child = children->next()) != NULL) {
        this->flatten_scene((AWDSceneBlock*)child, flat_list);
    }
}

size_t
AWD::write_scene(AWDBlockList *blocks, int fd)
{
    AWDBlock *block;
    AWDBlockList *ordered;
    AWDBlockIterator it(blocks);

    ordered = new AWDBlockList();

    while ((block = it.next()) != NULL) {
        this->flatten_scene((AWDSceneBlock*)block, ordered);
    }

    return this->write_blocks(ordered, fd);
}

awd_uint32
AWD::flush(int out_fd)
{
    int tmp_fd;
    char *tmp_path;

    off_t tmp_len;
    awd_uint8 *tmp_buf;

    awd_uint8 *body_buf;
    awd_uint32 body_len;

    tmp_len = 0;
    tmp_fd = awdutil_mktmp(&tmp_path);
    if (tmp_fd < 0) {
        extern int errno;
        printf("Could not open temporary file necessary for writing, errno=%d\n", errno);
        return AWD_FALSE;
    }

    tmp_len += this->write_blocks(this->skeleton_blocks, tmp_fd);
    tmp_len += this->write_blocks(this->skelpose_blocks, tmp_fd);
    tmp_len += this->write_blocks(this->skelanim_blocks, tmp_fd);
    tmp_len += this->write_blocks(this->texture_blocks, tmp_fd);
    tmp_len += this->write_blocks(this->material_blocks, tmp_fd);
    tmp_len += this->write_blocks(this->mesh_data_blocks, tmp_fd);
    tmp_len += this->write_blocks(this->uvanim_blocks, tmp_fd);
    tmp_len += this->write_scene(this->scene_blocks, tmp_fd);

    tmp_buf = (awd_uint8 *) malloc(tmp_len);
	lseek(tmp_fd, 0, SEEK_SET);
    read(tmp_fd, tmp_buf, tmp_len);

    // Temp file no longer needed
    close(tmp_fd);
    unlink((const char *)tmp_path);

    if (this->compression == UNCOMPRESSED) {
        // Uncompressed, so output should be the exact
        // same data that was in the temporary file
        body_len = tmp_len;
        body_buf = tmp_buf;
    }
    else if (this->compression == DEFLATE) {
        int stat;
        z_streamp zstrm;
        int zlib_len;
        awd_uint8 *zlib_buf;
        bool done;

        zlib_len = tmp_len;
        zlib_buf = (awd_uint8*)malloc(zlib_len);

        zstrm = (z_streamp)malloc(sizeof(z_stream_s));
        zstrm->zalloc = awd_zalloc;
        zstrm->zfree = awd_zfree;
        zstrm->opaque = NULL;
        zstrm->next_in = tmp_buf;
        zstrm->avail_in = tmp_len;
        zstrm->next_out = zlib_buf;
        zstrm->avail_out = zlib_len;

        stat = deflateInit(zstrm, 9);

        done = false;
        while (!done) {
            stat = deflate(zstrm, Z_NO_FLUSH);

            switch (stat) {
                case Z_STREAM_END:
                case Z_BUF_ERROR:
                    done = true;
                    break;
            }
        }

        deflate(zstrm, Z_FINISH);
        deflateEnd(zstrm);

        body_len = zstrm->total_out;
        body_buf = (awd_uint8*)malloc(body_len);
        memcpy(body_buf, zlib_buf, body_len);

        free(zlib_buf);
        free(zstrm);
    }
    else if (this->compression == LZMA) {
        Byte *lzma_buf;
        SizeT lzma_len, props_len;
        CLzmaEncProps props;
        ISzAlloc alloc;
        Byte *props_buf;
        long tmp_len_bo;

        // Create allocation structure. LZMA library uses
        // these functions for memory management. They are
        // defined in awdlzma.c as simple wrappers for
        // malloc() and free().
        alloc.Alloc = &awd_SzAlloc;
        alloc.Free = &awd_SzFree;

        lzma_len = tmp_len;
        lzma_buf = (Byte *)malloc(tmp_len);
        props_len = sizeof(CLzmaEncProps);
        props_buf = (Byte *)malloc(props_len);

        LzmaEncProps_Init(&props);
        props.algo = 1;
        props.level = 9;

        LzmaEncode(lzma_buf, &lzma_len, tmp_buf, tmp_len,
            &props, props_buf, &props_len, 0, NULL, &alloc, &alloc);

        // Body length is the length of the actual
        // compressed body + size of props and an integer
        // definining the uncompressed length (see below)
        body_len = (awd_uint32)lzma_len + (awd_uint32)props_len + sizeof(awd_uint32);

        // Create new buffer containing LZMA props, length
        // of uncompressed body and the actual body data
        // concatenated together.
        tmp_len_bo = UI32(tmp_len);
        body_buf = (awd_uint8*)malloc(body_len);
        memcpy(body_buf, props_buf, props_len);
        memcpy(body_buf+props_len, &tmp_len_bo, sizeof(awd_uint32));
        memcpy(body_buf+props_len+sizeof(awd_uint32), lzma_buf, lzma_len);
    }

    // Write header and then body from possibly
    // compressed buffer
    if (this->header_written == AWD_FALSE) {
        this->header_written = AWD_TRUE;
        this->write_header(out_fd, body_len);
    }

    write(out_fd, body_buf, body_len);

    return AWD_TRUE;
}

<|endoftext|>


<commit_before>#include "ProgramProfile.h"

uint8_t ProgramProfile::programShouldAdvance() {
  return !programIsDone &&
         (PHASE_SOAK == programStepPhase &&
          (millis() - stepStartTs) / 60000 > program[currentStep].minutesAtTarget);
}

void ProgramProfile::stepInit(uint16_t currTemp) {
  stepStartTemperature = currTemp;
  programStepPhase = PHASE_RAMP;
  stepStartTs = millis();
}

uint8_t ProgramProfile::isMoreStepsLeft() {
  return currentStep + 1 < programStepsTotal;
}

uint8_t ProgramProfile::isTimeToRamp() {
  return PHASE_RAMP == programStepPhase &&
         millis() - lastProgramInvocationTs > PROGRAM_IMVOCATION_INTERVAL;
}

uint16_t ProgramProfile::computeSetpoint() {
  return stepStartTemperature + (millis() - stepStartTs) / 60000 * program[currentStep].rampDegreesPerMinute;
}

uint8_t ProgramProfile::isTargetSetpointReached(uint16_t currTemp) {
  return currTemp >= program[currentStep].targetTemp;
}

void ProgramProfile::start(uint16_t currTemp) {
  currentStep = 0;
  stepInit(currTemp);
}

void ProgramProfile::compute(uint16_t currTemp) {
  if(programShouldAdvance()) {
    if(isMoreStepsLeft()) {
      currentStep = currentStep + 1;
      stepInit(currTemp);
    } else {
      programIsDone = 1;
      programDoneCallback();
    }
  } else if(isTimeToRamp()){
    if(isTargetSetpointReached(currTemp)) {
      programStepPhase = PHASE_SOAK;
      stepStartTs = millis();
    } else {
      uint16_t newSetpoint = computeSetpoint();
      setpointCallback(newSetpoint);
    }
  }
  lastProgramInvocationTs = millis();
}

/**
5°/h iki 120
prie 120 30min
išjungti
**/
<commit_msg>Fix perefix<commit_after>#include "ProgramProfile.h"

uint8_t ProgramProfile::programShouldAdvance() {
  return !programIsDone &&
         (PHASE_SOAK == programStepPhase &&
          (millis() - stepStartTs) / 60000 > program[currentStep].minutesAtTarget);
}

void ProgramProfile::stepInit(uint16_t currTemp) {
  stepStartTemperature = currTemp;
  programStepPhase = PHASE_RAMP;
  stepStartTs = millis();
  lastProgramInvocationTs = millis();
}

uint8_t ProgramProfile::isMoreStepsLeft() {
  return currentStep + 1 < programStepsTotal;
}

uint8_t ProgramProfile::isTimeToRamp() {
  return PHASE_RAMP == programStepPhase &&
         millis() - lastProgramInvocationTs > PROGRAM_IMVOCATION_INTERVAL;
}

uint16_t ProgramProfile::computeSetpoint() {
  return stepStartTemperature + (millis() - stepStartTs) / 60000 * program[currentStep].rampDegreesPerMinute;
}

uint8_t ProgramProfile::isTargetSetpointReached(uint16_t currTemp) {
  return currTemp >= program[currentStep].targetTemp;
}

void ProgramProfile::start(uint16_t currTemp) {
  currentStep = 0;
  programIsDone = 0;
  stepInit(currTemp);
}

void ProgramProfile::compute(uint16_t currTemp) {
  if(programShouldAdvance()) {
    if(isMoreStepsLeft()) {
      currentStep = currentStep + 1;
      stepInit(currTemp);
    } else {
      programIsDone = 1;
      programDoneCallback();
    }
  } else if(isTimeToRamp()){
    if(isTargetSetpointReached(currTemp)) {
      programStepPhase = PHASE_SOAK;
      stepStartTs = millis();
    } else {
      uint16_t newSetpoint = computeSetpoint();
      setpointCallback(newSetpoint);
      lastProgramInvocationTs = millis();
    }
  }
}

/**
5°/h iki 120
prie 120 30min
išjungti
**/
<|endoftext|>


<commit_before>#pragma once

#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
#include <optional>

#include "acmacs-base/string.hh"
#include "acmacs-base/fmt.hh"

// ----------------------------------------------------------------------

namespace acmacs
{
    namespace argv
    {
        inline namespace v2
        {
            class argv;
            using str = std::string_view;
            using str_array = std::vector<std::string_view>;

            struct desc : public std::string_view { using std::string_view::string_view; };
            struct arg_name : public std::string_view { using std::string_view::string_view; };
            enum mandatory { mandatory };
            template <typename T> struct dflt { dflt(T&& val) : value{std::move(val)} {} T value; explicit operator T() const { return value; } };
            dflt(const char*) -> dflt<str>;

            namespace detail
            {
                using cmd_line_iter = std::vector<const char*>::const_iterator;

                constexpr bool false_ = false;

                class option_base
                {
                  public:
                    option_base(argv& parent);
                    virtual ~option_base() = default;

                    virtual void add(cmd_line_iter& arg, cmd_line_iter last) = 0;
                    virtual void add(std::string_view arg) = 0;
                    std::string names() const noexcept;
                    constexpr bool has_name() const noexcept { return short_name_ || !long_name_.empty(); }
                    constexpr std::string_view description() const noexcept { return description_; }
                    virtual std::string get_default() const noexcept = 0;
                    virtual bool has_arg() const noexcept { return true; }
                    virtual bool has_value() const noexcept = 0;
                    virtual bool multiple_values() const noexcept = 0;
                    virtual bool is_bool() const noexcept = 0;
                    constexpr bool mandatory() const noexcept { return mandatory_; }

                    constexpr char short_name() const noexcept { return short_name_; }
                    constexpr std::string_view long_name() const noexcept { return long_name_; }
                    constexpr std::string_view arg_name() const noexcept { return arg_name_; }

                  protected:
                    constexpr void use_arg(char short_name) noexcept { short_name_ = short_name; }
                    constexpr void use_arg(const char* long_name) noexcept { long_name_ = long_name; }
                    constexpr void use_arg(desc&& description) noexcept { description_ = std::move(description); }
                    constexpr void use_arg(struct arg_name&& an) noexcept { arg_name_ = std::move(an); }
                    constexpr void use_arg(enum mandatory&&) noexcept { mandatory_ = true; }

                  private:
                    char short_name_ = 0;
                    std::string_view long_name_;
                    std::string_view description_;
                    std::string_view arg_name_{"ARG"};
                    bool mandatory_ = false;

                }; // class option_base

                template <typename T> T to_value(std::string_view source) { return source; }
                  // template <> inline const char* to_value<const char*>(std::string_view source) { return source; }
                // template <> inline string to_value<string>(std::string_view source) { return source; }
                template <> inline int to_value<int>(std::string_view source) { return std::stoi(std::string(source)); }
                template <> inline long to_value<long>(std::string_view source) { return std::stol(std::string(source)); }
                template <> inline unsigned long to_value<unsigned long>(std::string_view source) { return std::stoul(std::string(source)); }
                template <> inline double to_value<double>(std::string_view source) { return std::stod(std::string(source)); }
                template <> inline bool to_value<bool>(std::string_view source) { return std::stoi(std::string(source)); }

                template <typename T> std::string to_string(const T& source) noexcept { return std::to_string(source); }
                // template <> std::string to_string(const std::string& source) { return '"' + source + '"'; }
                template <> std::string to_string(const str& source) noexcept { return '"' + std::string(source) + '"'; }
                template <> std::string to_string(const str_array& source) noexcept { return '"' + string::join("\" \"", source) + '"'; }

                class invalid_option_value : public std::runtime_error { public: using std::runtime_error::runtime_error; };

            } // namespace detail

            // ----------------------------------------------------------------------

            template <typename T> class option : public detail::option_base
            {
              public:
                template <typename... Args> option(argv& parent, Args&&... args) : option_base(parent) { use_args(std::forward<Args>(args)...); }

                constexpr operator const T&() const { if (value_.has_value()) return *value_; else return default_; }
                constexpr const T& get() const { return static_cast<const T&>(*this); }
                constexpr const T* operator->() const { return &static_cast<const T&>(*this); }
                constexpr const T& operator*() const { return static_cast<const T&>(*this); }
                template <typename R> constexpr bool operator == (const R& rhs) const { return static_cast<const T&>(*this) == rhs; }
                template <typename R> constexpr bool operator != (const R& rhs) const { return !operator==(rhs); }
                std::string get_default() const noexcept override { return detail::to_string(default_); }
                bool has_arg() const noexcept override { return true; }
                bool has_value() const noexcept override { return value_.has_value(); }
                bool multiple_values() const noexcept override { return false; }

                bool is_bool() const noexcept override { if constexpr (std::is_same_v<T, bool>) return true; else return false; }

                void add(detail::cmd_line_iter& arg, detail::cmd_line_iter last) override
                {
                    ++arg;
                    if (arg == last)
                        throw detail::invalid_option_value{"requires argument"};
                    add(*arg);
                }

                void add(std::string_view arg) override { value_ = detail::to_value<T>(arg); }

                template <typename Z = T, typename = std::enable_if_t<!std::is_same_v<Z, bool>>> explicit operator bool() const
                {
                    if constexpr (std::is_same_v<T, str>)
                        return has_value() && !get().empty();
                    else if constexpr (std::is_same_v<T, double>)
                        return has_value();
                    else
                        static_assert(std::is_same_v<T, void>, "operator bool not defined for this option type");
                }

              protected:
                using detail::option_base::use_arg;
                constexpr void use_arg(dflt<T>&& def) { default_ = static_cast<T>(def); }

              private:
                std::optional<T> value_;
                T default_;

                template <typename Arg, typename... Args> void use_args(Arg&& arg, Args&&... args)
                {
                    use_arg(std::forward<Arg>(arg));
                    if constexpr (sizeof...(args) > 0)
                        use_args(std::forward<Args>(args)...);
                }
            }; // class option<T>

            template <typename T> inline std::ostream& operator << (std::ostream& out, const option<T>& opt) { return out << opt.get(); }

            template <> void option<bool>::add(detail::cmd_line_iter& /*arg*/, detail::cmd_line_iter /*last*/) { value_ = true; }
            template <> bool option<bool>::has_arg() const noexcept { return false; }
            template <> constexpr option<bool>::operator const bool&() const { if (value_.has_value()) return *value_; return detail::false_; }
            template <> inline std::ostream& operator << (std::ostream& out, const option<bool>& opt) { return out << std::boolalpha << static_cast<const bool&>(opt); }

            template <> void option<str_array>::add(std::string_view arg) { if (!value_) value_ = str_array{arg}; else value_->push_back(arg); }
            template <> bool option<str_array>::multiple_values() const noexcept { return true; }

            template <typename T> using argument = option<T>;

            // ----------------------------------------------------------------------

            class show_help : public std::exception {};
            class errors : public std::exception {};

            class argv
            {
             public:
                using errors_t = std::vector<std::string>;
                enum class on_error { exit, raise, return_false };
                  // returns true on success
                bool parse(int argc, const char* const argv[], on_error on_err = on_error::exit);

                constexpr auto argv0() const { return argv0_; }
                constexpr auto program_name() const { return prog_name_; }
                constexpr const errors_t& errors() const { return errors_; }
                void show_help(std::ostream& out) const;

                virtual ~argv() = default;

             protected:
                argv() = default;

              private:
                std::string_view argv0_;
                std::string_view prog_name_;
                std::vector<detail::option_base*> options_;
                std::vector<std::string_view> args_;
                errors_t errors_;

                option<bool> show_help_{*this, 'h', "help", desc{"show this help screen"}};

                void use(detail::cmd_line_iter& arg, detail::cmd_line_iter last);
                detail::option_base* find(char short_name);
                detail::option_base* find(std::string_view long_name);

                void register_option(detail::option_base* opt);
                friend class detail::option_base;
                friend std::ostream& operator<<(std::ostream& out, const argv& args);

            }; // class argv

            // ----------------------------------------------------------------------

            inline detail::option_base::option_base(argv& parent) { parent.register_option(this); }

            // ----------------------------------------------------------------------

        } // namespace v2
    }     // namespace argv
} // namespace acmacs

// ----------------------------------------------------------------------

template <typename T> struct fmt::formatter<acmacs::argv::option<T>> : fmt::formatter<T> {
    template <typename FormatCtx> auto format(const acmacs::argv::option<T>& opt, FormatCtx& ctx) { return fmt::formatter<T>::format(*opt, ctx); }
};

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>argv improvement<commit_after>#pragma once

#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>
#include <optional>

#include "acmacs-base/string.hh"
#include "acmacs-base/fmt.hh"

// ----------------------------------------------------------------------

namespace acmacs
{
    namespace argv
    {
        inline namespace v2
        {
            class argv;
            using str = std::string_view;
            using str_array = std::vector<std::string_view>;

            struct desc : public std::string_view { using std::string_view::string_view; };
            struct arg_name : public std::string_view { using std::string_view::string_view; };
            enum mandatory { mandatory };
            template <typename T> struct dflt { dflt(T&& val) : value{std::move(val)} {} T value; explicit operator T() const { return value; } };
            dflt(const char*) -> dflt<str>;

            namespace detail
            {
                using cmd_line_iter = std::vector<const char*>::const_iterator;

                constexpr bool false_ = false;

                class option_base
                {
                  public:
                    option_base(argv& parent);
                    virtual ~option_base() = default;

                    virtual void add(cmd_line_iter& arg, cmd_line_iter last) = 0;
                    virtual void add(std::string_view arg) = 0;
                    std::string names() const noexcept;
                    constexpr bool has_name() const noexcept { return short_name_ || !long_name_.empty(); }
                    constexpr std::string_view description() const noexcept { return description_; }
                    virtual std::string get_default() const noexcept = 0;
                    virtual bool has_arg() const noexcept { return true; }
                    virtual bool has_value() const noexcept = 0;
                    virtual bool multiple_values() const noexcept = 0;
                    virtual bool is_bool() const noexcept = 0;
                    constexpr bool mandatory() const noexcept { return mandatory_; }

                    constexpr char short_name() const noexcept { return short_name_; }
                    constexpr std::string_view long_name() const noexcept { return long_name_; }
                    constexpr std::string_view arg_name() const noexcept { return arg_name_; }

                  protected:
                    constexpr void use_arg(char short_name) noexcept { short_name_ = short_name; }
                    constexpr void use_arg(const char* long_name) noexcept { long_name_ = long_name; }
                    constexpr void use_arg(desc&& description) noexcept { description_ = std::move(description); }
                    constexpr void use_arg(struct arg_name&& an) noexcept { arg_name_ = std::move(an); }
                    constexpr void use_arg(enum mandatory&&) noexcept { mandatory_ = true; }

                  private:
                    char short_name_ = 0;
                    std::string_view long_name_;
                    std::string_view description_;
                    std::string_view arg_name_{"ARG"};
                    bool mandatory_ = false;

                }; // class option_base

                template <typename T> T to_value(std::string_view source)
                {
                    if constexpr (std::is_same_v<T, bool>)
                        return std::stoi(std::string(source));
                    else if constexpr (std::is_arithmetic_v<T>)
                        return ::string::from_chars<T>(source);
                    else
                        return source;
                }

                template <typename T> std::string to_string(const T& source) noexcept { return std::to_string(source); }
                // template <> std::string to_string(const std::string& source) { return '"' + source + '"'; }
                template <> std::string to_string(const str& source) noexcept { return fmt::format("\"{}\"", source); }
                template <> std::string to_string(const str_array& source) noexcept { return fmt::format("\"{}\"", string::join("\" \"", source)); }

                class invalid_option_value : public std::runtime_error { public: using std::runtime_error::runtime_error; };

            } // namespace detail

            // ----------------------------------------------------------------------

            template <typename T> class option : public detail::option_base
            {
              public:
                template <typename... Args> option(argv& parent, Args&&... args) : option_base(parent) { use_args(std::forward<Args>(args)...); }

                constexpr operator const T&() const { if (value_.has_value()) return *value_; else return default_; }
                constexpr const T& get() const { return static_cast<const T&>(*this); }
                constexpr const T* operator->() const { return &static_cast<const T&>(*this); }
                constexpr const T& operator*() const { return static_cast<const T&>(*this); }
                template <typename R> constexpr bool operator == (const R& rhs) const { return static_cast<const T&>(*this) == rhs; }
                template <typename R> constexpr bool operator != (const R& rhs) const { return !operator==(rhs); }
                std::string get_default() const noexcept override { return detail::to_string(default_); }
                bool has_arg() const noexcept override { return true; }
                bool has_value() const noexcept override { return value_.has_value(); }
                bool multiple_values() const noexcept override { return false; }

                bool is_bool() const noexcept override { if constexpr (std::is_same_v<T, bool>) return true; else return false; }

                void add(detail::cmd_line_iter& arg, detail::cmd_line_iter last) override
                {
                    ++arg;
                    if (arg == last)
                        throw detail::invalid_option_value{"requires argument"};
                    add(*arg);
                }

                void add(std::string_view arg) override { value_ = detail::to_value<T>(arg); }

                template <typename Z = T, typename = std::enable_if_t<!std::is_same_v<Z, bool>>> explicit operator bool() const
                {
                    if constexpr (std::is_same_v<T, str>)
                        return has_value() && !get().empty();
                    else if constexpr (std::is_same_v<T, double>)
                        return has_value();
                    else
                        static_assert(std::is_same_v<T, void>, "operator bool not defined for this option type");
                }

              protected:
                using detail::option_base::use_arg;
                constexpr void use_arg(dflt<T>&& def) { default_ = static_cast<T>(def); }

              private:
                std::optional<T> value_;
                T default_;

                template <typename Arg, typename... Args> void use_args(Arg&& arg, Args&&... args)
                {
                    use_arg(std::forward<Arg>(arg));
                    if constexpr (sizeof...(args) > 0)
                        use_args(std::forward<Args>(args)...);
                }
            }; // class option<T>

            template <typename T> inline std::ostream& operator << (std::ostream& out, const option<T>& opt) { return out << opt.get(); }

            template <> void option<bool>::add(detail::cmd_line_iter& /*arg*/, detail::cmd_line_iter /*last*/) { value_ = true; }
            template <> bool option<bool>::has_arg() const noexcept { return false; }
            template <> constexpr option<bool>::operator const bool&() const { if (value_.has_value()) return *value_; return detail::false_; }
            template <> inline std::ostream& operator << (std::ostream& out, const option<bool>& opt) { return out << std::boolalpha << static_cast<const bool&>(opt); }

            template <> void option<str_array>::add(std::string_view arg) { if (!value_) value_ = str_array{arg}; else value_->push_back(arg); }
            template <> bool option<str_array>::multiple_values() const noexcept { return true; }

            template <typename T> using argument = option<T>;

            // ----------------------------------------------------------------------

            class show_help : public std::exception {};
            class errors : public std::exception {};

            class argv
            {
             public:
                using errors_t = std::vector<std::string>;
                enum class on_error { exit, raise, return_false };
                  // returns true on success
                bool parse(int argc, const char* const argv[], on_error on_err = on_error::exit);

                constexpr auto argv0() const { return argv0_; }
                constexpr auto program_name() const { return prog_name_; }
                constexpr const errors_t& errors() const { return errors_; }
                void show_help(std::ostream& out) const;

                virtual ~argv() = default;

             protected:
                argv() = default;

              private:
                std::string_view argv0_;
                std::string_view prog_name_;
                std::vector<detail::option_base*> options_;
                std::vector<std::string_view> args_;
                errors_t errors_;

                option<bool> show_help_{*this, 'h', "help", desc{"show this help screen"}};

                void use(detail::cmd_line_iter& arg, detail::cmd_line_iter last);
                detail::option_base* find(char short_name);
                detail::option_base* find(std::string_view long_name);

                void register_option(detail::option_base* opt);
                friend class detail::option_base;
                friend std::ostream& operator<<(std::ostream& out, const argv& args);

            }; // class argv

            // ----------------------------------------------------------------------

            inline detail::option_base::option_base(argv& parent) { parent.register_option(this); }

            // ----------------------------------------------------------------------

        } // namespace v2
    }     // namespace argv
} // namespace acmacs

// ----------------------------------------------------------------------

template <typename T> struct fmt::formatter<acmacs::argv::option<T>> : fmt::formatter<T> {
    template <typename FormatCtx> auto format(const acmacs::argv::option<T>& opt, FormatCtx& ctx) { return fmt::formatter<T>::format(*opt, ctx); }
};

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>/*
    dirservconfigpage.cpp

    This file is part of kleopatra
    Copyright (c) 2004 Klar�vdalens Datakonsult AB

    Libkleopatra 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.

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

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

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

#include "dirservconfigpage.h"
#include "directoryserviceswidget.h"

#include <kleo/cryptobackendfactory.h>

#include <kmessagebox.h>
#include <klocale.h>
#include <kdebug.h>
#include <kconfig.h>
#include <knuminput.h>
#include <kdialog.h>
#include <kcomponentdata.h>

#include <khbox.h>
#include <QLabel>
#include <qdatetimeedit.h>
#include <QCheckBox>
#include <QLayout>
//Added by qt3to4:
#include <QVBoxLayout>

#include <kdemacros.h>

#if 0 // disabled, since it is apparently confusing
// For sync'ing kabldaprc
class KABSynchronizer
{
public:
  KABSynchronizer()
    : mConfig( "kabldaprc" ) {
    mConfig.setGroup( "LDAP" );
  }

  KUrl::List readCurrentList() const {

    KUrl::List lst;
    // stolen from kabc/ldapclient.cpp
    const uint numHosts = mConfig.readEntry( "NumSelectedHosts" );
    for ( uint j = 0; j < numHosts; j++ ) {
      const QString num = QString::number( j );

      KUrl url;
      url.setProtocol( "ldap" );
      url.setPath( "/" ); // workaround KUrl parsing bug
      const QString host = mConfig.readEntry( QString( "SelectedHost" ) + num ).trimmed();
      url.setHost( host );

      const int port = mConfig.readEntry( QString( "SelectedPort" ) + num );
      if ( port != 0 )
        url.setPort( port );

      const QString base = mConfig.readEntry( QString( "SelectedBase" ) + num ).trimmed();
      url.setQuery( base );

      const QString bindDN = mConfig.readEntry( QString( "SelectedBind" ) + num ).trimmed();
      url.setUser( bindDN );

      const QString pwdBindDN = mConfig.readEntry( QString( "SelectedPwdBind" ) + num ).trimmed();
      url.setPass( pwdBindDN );
      lst.append( url );
    }
    return lst;
  }

  void writeList( const KUrl::List& lst ) {

    mConfig.writeEntry( "NumSelectedHosts", lst.count() );

    KUrl::List::const_iterator it = lst.begin();
    KUrl::List::const_iterator end = lst.end();
    unsigned j = 0;
    for( ; it != end; ++it, ++j ) {
      const QString num = QString::number( j );
      KUrl url = *it;

      Q_ASSERT( url.protocol() == "ldap" );
      mConfig.writeEntry( QString( "SelectedHost" ) + num, url.host() );
      mConfig.writeEntry( QString( "SelectedPort" ) + num, url.port() );

      // KUrl automatically encoded the query (e.g. for spaces inside it),
      // so decode it before writing it out
      const QString base = KUrl::decode_string( url.query().mid(1) );
      mConfig.writeEntry( QString( "SelectedBase" ) + num, base );
      mConfig.writeEntry( QString( "SelectedBind" ) + num, url.user() );
      mConfig.writeEntry( QString( "SelectedPwdBind" ) + num, url.pass() );
    }
    mConfig.sync();
  }

private:
  KConfig mConfig;
};

#endif

static const char s_dirserv_componentName[] = "dirmngr";
static const char s_dirserv_groupName[] = "LDAP";
static const char s_dirserv_entryName[] = "LDAP Server";

static const char s_timeout_componentName[] = "dirmngr";
static const char s_timeout_groupName[] = "LDAP";
static const char s_timeout_entryName[] = "ldaptimeout";

static const char s_maxitems_componentName[] = "dirmngr";
static const char s_maxitems_groupName[] = "LDAP";
static const char s_maxitems_entryName[] = "max-replies";

static const char s_addnewservers_componentName[] = "dirmngr";
static const char s_addnewservers_groupName[] = "LDAP";
static const char s_addnewservers_entryName[] = "add-servers";

DirectoryServicesConfigurationPage::DirectoryServicesConfigurationPage( const KComponentData &instance, QWidget *parent, const QStringList &args )
    : KCModule( instance, parent, args )
{
  mConfig = Kleo::CryptoBackendFactory::instance()->config();
  QVBoxLayout* lay = new QVBoxLayout( this );
  lay->setSpacing( KDialog::spacingHint() );
  lay->setMargin( 0 );
  Kleo::CryptoConfigEntry* entry = configEntry( s_dirserv_componentName, s_dirserv_groupName, s_dirserv_entryName,
                                                Kleo::CryptoConfigEntry::ArgType_LDAPURL, true );
  mWidget = new Kleo::DirectoryServicesWidget( entry, this );
  lay->addWidget( mWidget );
  connect( mWidget, SIGNAL( changed() ), this, SLOT( slotChanged() ) );

  // LDAP timeout
  KHBox* box = new KHBox( this );
  box->setSpacing( KDialog::spacingHint() );
  lay->addWidget( box );
  QLabel* label = new QLabel( i18n( "LDAP &timeout (minutes:seconds):" ), box );
  mTimeout = new QTimeEdit( box );
  mTimeout->setDisplayFormat( "mm:ss" );
  connect( mTimeout, SIGNAL( valueChanged( const QTime& ) ), this, SLOT( slotChanged() ) );
  label->setBuddy( mTimeout );
  QWidget* stretch = new QWidget( box );
  box->setStretchFactor( stretch, 2 );

  // Max number of items returned by queries
  box = new KHBox( this );
  box->setSpacing( KDialog::spacingHint() );
  lay->addWidget( box );
  mMaxItems = new KIntNumInput( box );
  mMaxItems->setLabel( i18n( "&Maximum number of items returned by query:" ), Qt::AlignLeft | Qt::AlignVCenter );
  mMaxItems->setMinimum( 0 );
  connect( mMaxItems, SIGNAL( valueChanged(int) ), this, SLOT( slotChanged() ) );
  stretch = new QWidget( box );
  box->setStretchFactor( stretch, 2 );

#ifdef NOT_USEFUL_CURRENTLY
  mAddNewServersCB = new QCheckBox( i18n( "Automatically add &new servers discovered in CRL distribution points" ), this );
  connect( mAddNewServersCB, SIGNAL( clicked() ), this, SLOT( slotChanged() ) );
  lay->addWidget( mAddNewServersCB );
#endif

#ifndef HAVE_UNBROKEN_KCMULTIDIALOG
  load();
#endif
}

void DirectoryServicesConfigurationPage::load()
{
  mWidget->load();

  mTimeoutConfigEntry = configEntry( s_timeout_componentName, s_timeout_groupName, s_timeout_entryName, Kleo::CryptoConfigEntry::ArgType_UInt, false );
  if ( mTimeoutConfigEntry ) {
    QTime time = QTime().addSecs( mTimeoutConfigEntry->uintValue() );
    //kDebug() << "timeout:" << mTimeoutConfigEntry->uintValue() << "  -> " << time << endl;
    mTimeout->setTime( time );
  }

  mMaxItemsConfigEntry = configEntry( s_maxitems_componentName, s_maxitems_groupName, s_maxitems_entryName, Kleo::CryptoConfigEntry::ArgType_UInt, false );
  if ( mMaxItemsConfigEntry ) {
    mMaxItems->blockSignals( true ); // KNumInput emits valueChanged from setValue!
    mMaxItems->setValue( mMaxItemsConfigEntry->uintValue() );
    mMaxItems->blockSignals( false );
  }

#ifdef NOT_USEFUL_CURRENTLY
  mAddNewServersConfigEntry = configEntry( s_addnewservers_componentName, s_addnewservers_groupName, s_addnewservers_entryName, Kleo::CryptoConfigEntry::ArgType_None, false );
  if ( mAddNewServersConfigEntry ) {
    mAddNewServersCB->setChecked( mAddNewServersConfigEntry->boolValue() );
  }
#endif
}

void DirectoryServicesConfigurationPage::save()
{
  mWidget->save();

  QTime time( mTimeout->time() );
  unsigned int timeout = time.minute() * 60 + time.second();
  if ( mTimeoutConfigEntry && mTimeoutConfigEntry->uintValue() != timeout )
    mTimeoutConfigEntry->setUIntValue( timeout );
  if ( mMaxItemsConfigEntry && mMaxItemsConfigEntry->uintValue() != (uint)mMaxItems->value() )
    mMaxItemsConfigEntry->setUIntValue( mMaxItems->value() );
#ifdef NOT_USEFUL_CURRENTLY
  if ( mAddNewServersConfigEntry && mAddNewServersConfigEntry->boolValue() != mAddNewServersCB->isChecked() )
    mAddNewServersConfigEntry->setBoolValue( mAddNewServersCB->isChecked() );
#endif

  mConfig->sync( true );

#if 0
  // Also write the LDAP URLs to kabldaprc so that they are used by kaddressbook
  KABSynchronizer sync;
  const KUrl::List toAdd = mWidget->urlList();
  KUrl::List currentList = sync.readCurrentList();

  KUrl::List::const_iterator it = toAdd.begin();
  KUrl::List::const_iterator end = toAdd.end();
  for( ; it != end; ++it ) {
    // check if the URL is already in currentList
    if ( currentList.find( *it ) == currentList.end() )
      // if not, add it
      currentList.append( *it );
  }
  sync.writeList( currentList );
#endif
}

void DirectoryServicesConfigurationPage::defaults()
{
  mWidget->defaults();
  if ( mTimeoutConfigEntry )
    mTimeoutConfigEntry->resetToDefault();
  if ( mMaxItemsConfigEntry )
    mMaxItemsConfigEntry->resetToDefault();
#ifdef NOT_USEFUL_CURRENTLY
  if ( mAddNewServersConfigEntry )
    mAddNewServersConfigEntry->resetToDefault();
#endif
  load();
}

extern "C"
{
  KDE_EXPORT KCModule *create_kleopatra_config_dirserv( QWidget *parent=0, const QStringList &args=QStringList() )
  {
    DirectoryServicesConfigurationPage *page =
      new DirectoryServicesConfigurationPage( KComponentData( "kleopatra" ), parent, args );
    page->setObjectName( "kleopatra_config_dirserv" );
    return page;
  }
}

// kdelibs-3.2 didn't have the changed signal in KCModule...
void DirectoryServicesConfigurationPage::slotChanged()
{
  emit changed(true);
}

// Find config entry for ldap servers. Implements runtime checks on the configuration option.
Kleo::CryptoConfigEntry* DirectoryServicesConfigurationPage::configEntry( const char* componentName,
                                                                          const char* groupName,
                                                                          const char* entryName,
                                                                          Kleo::CryptoConfigEntry::ArgType argType,
                                                                          bool isList )
{
    Kleo::CryptoConfigEntry* entry = mConfig->entry( componentName, groupName, entryName );
    if ( !entry ) {
        KMessageBox::error( this, i18n( "Backend error: gpgconf does not seem to know the entry for %1/%2/%3", componentName, groupName, entryName ) );
        return 0;
    }
    if( entry->argType() != argType || entry->isList() != isList ) {
        KMessageBox::error( this, i18n( "Backend error: gpgconf has wrong type for %1/%2/%3: %4 %5", componentName, groupName, entryName, entry->argType(), entry->isList() ) );
        return 0;
    }
    return entry;
}

#include "dirservconfigpage.moc"
<commit_msg>Fix signal/slot<commit_after>/*
    dirservconfigpage.cpp

    This file is part of kleopatra
    Copyright (c) 2004 Klar�vdalens Datakonsult AB

    Libkleopatra 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.

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

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

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

#include "dirservconfigpage.h"
#include "directoryserviceswidget.h"

#include <kleo/cryptobackendfactory.h>

#include <kmessagebox.h>
#include <klocale.h>
#include <kdebug.h>
#include <kconfig.h>
#include <knuminput.h>
#include <kdialog.h>
#include <kcomponentdata.h>

#include <khbox.h>
#include <QLabel>
#include <qdatetimeedit.h>
#include <QCheckBox>
#include <QLayout>
//Added by qt3to4:
#include <QVBoxLayout>

#include <kdemacros.h>

#if 0 // disabled, since it is apparently confusing
// For sync'ing kabldaprc
class KABSynchronizer
{
public:
  KABSynchronizer()
    : mConfig( "kabldaprc" ) {
    mConfig.setGroup( "LDAP" );
  }

  KUrl::List readCurrentList() const {

    KUrl::List lst;
    // stolen from kabc/ldapclient.cpp
    const uint numHosts = mConfig.readEntry( "NumSelectedHosts" );
    for ( uint j = 0; j < numHosts; j++ ) {
      const QString num = QString::number( j );

      KUrl url;
      url.setProtocol( "ldap" );
      url.setPath( "/" ); // workaround KUrl parsing bug
      const QString host = mConfig.readEntry( QString( "SelectedHost" ) + num ).trimmed();
      url.setHost( host );

      const int port = mConfig.readEntry( QString( "SelectedPort" ) + num );
      if ( port != 0 )
        url.setPort( port );

      const QString base = mConfig.readEntry( QString( "SelectedBase" ) + num ).trimmed();
      url.setQuery( base );

      const QString bindDN = mConfig.readEntry( QString( "SelectedBind" ) + num ).trimmed();
      url.setUser( bindDN );

      const QString pwdBindDN = mConfig.readEntry( QString( "SelectedPwdBind" ) + num ).trimmed();
      url.setPass( pwdBindDN );
      lst.append( url );
    }
    return lst;
  }

  void writeList( const KUrl::List& lst ) {

    mConfig.writeEntry( "NumSelectedHosts", lst.count() );

    KUrl::List::const_iterator it = lst.begin();
    KUrl::List::const_iterator end = lst.end();
    unsigned j = 0;
    for( ; it != end; ++it, ++j ) {
      const QString num = QString::number( j );
      KUrl url = *it;

      Q_ASSERT( url.protocol() == "ldap" );
      mConfig.writeEntry( QString( "SelectedHost" ) + num, url.host() );
      mConfig.writeEntry( QString( "SelectedPort" ) + num, url.port() );

      // KUrl automatically encoded the query (e.g. for spaces inside it),
      // so decode it before writing it out
      const QString base = KUrl::decode_string( url.query().mid(1) );
      mConfig.writeEntry( QString( "SelectedBase" ) + num, base );
      mConfig.writeEntry( QString( "SelectedBind" ) + num, url.user() );
      mConfig.writeEntry( QString( "SelectedPwdBind" ) + num, url.pass() );
    }
    mConfig.sync();
  }

private:
  KConfig mConfig;
};

#endif

static const char s_dirserv_componentName[] = "dirmngr";
static const char s_dirserv_groupName[] = "LDAP";
static const char s_dirserv_entryName[] = "LDAP Server";

static const char s_timeout_componentName[] = "dirmngr";
static const char s_timeout_groupName[] = "LDAP";
static const char s_timeout_entryName[] = "ldaptimeout";

static const char s_maxitems_componentName[] = "dirmngr";
static const char s_maxitems_groupName[] = "LDAP";
static const char s_maxitems_entryName[] = "max-replies";

static const char s_addnewservers_componentName[] = "dirmngr";
static const char s_addnewservers_groupName[] = "LDAP";
static const char s_addnewservers_entryName[] = "add-servers";

DirectoryServicesConfigurationPage::DirectoryServicesConfigurationPage( const KComponentData &instance, QWidget *parent, const QStringList &args )
    : KCModule( instance, parent, args )
{
  mConfig = Kleo::CryptoBackendFactory::instance()->config();
  QVBoxLayout* lay = new QVBoxLayout( this );
  lay->setSpacing( KDialog::spacingHint() );
  lay->setMargin( 0 );
  Kleo::CryptoConfigEntry* entry = configEntry( s_dirserv_componentName, s_dirserv_groupName, s_dirserv_entryName,
                                                Kleo::CryptoConfigEntry::ArgType_LDAPURL, true );
  mWidget = new Kleo::DirectoryServicesWidget( entry, this );
  lay->addWidget( mWidget );
  connect( mWidget, SIGNAL( changed() ), this, SLOT( slotChanged() ) );

  // LDAP timeout
  KHBox* box = new KHBox( this );
  box->setSpacing( KDialog::spacingHint() );
  lay->addWidget( box );
  QLabel* label = new QLabel( i18n( "LDAP &timeout (minutes:seconds):" ), box );
  mTimeout = new QTimeEdit( box );
  mTimeout->setDisplayFormat( "mm:ss" );
  connect( mTimeout, SIGNAL(timeChanged(const QTime&)), this, SLOT(slotChanged()) );
  label->setBuddy( mTimeout );
  QWidget* stretch = new QWidget( box );
  box->setStretchFactor( stretch, 2 );

  // Max number of items returned by queries
  box = new KHBox( this );
  box->setSpacing( KDialog::spacingHint() );
  lay->addWidget( box );
  mMaxItems = new KIntNumInput( box );
  mMaxItems->setLabel( i18n( "&Maximum number of items returned by query:" ), Qt::AlignLeft | Qt::AlignVCenter );
  mMaxItems->setMinimum( 0 );
  connect( mMaxItems, SIGNAL( valueChanged(int) ), this, SLOT( slotChanged() ) );
  stretch = new QWidget( box );
  box->setStretchFactor( stretch, 2 );

#ifdef NOT_USEFUL_CURRENTLY
  mAddNewServersCB = new QCheckBox( i18n( "Automatically add &new servers discovered in CRL distribution points" ), this );
  connect( mAddNewServersCB, SIGNAL( clicked() ), this, SLOT( slotChanged() ) );
  lay->addWidget( mAddNewServersCB );
#endif

#ifndef HAVE_UNBROKEN_KCMULTIDIALOG
  load();
#endif
}

void DirectoryServicesConfigurationPage::load()
{
  mWidget->load();

  mTimeoutConfigEntry = configEntry( s_timeout_componentName, s_timeout_groupName, s_timeout_entryName, Kleo::CryptoConfigEntry::ArgType_UInt, false );
  if ( mTimeoutConfigEntry ) {
    QTime time = QTime().addSecs( mTimeoutConfigEntry->uintValue() );
    //kDebug() << "timeout:" << mTimeoutConfigEntry->uintValue() << "  -> " << time << endl;
    mTimeout->setTime( time );
  }

  mMaxItemsConfigEntry = configEntry( s_maxitems_componentName, s_maxitems_groupName, s_maxitems_entryName, Kleo::CryptoConfigEntry::ArgType_UInt, false );
  if ( mMaxItemsConfigEntry ) {
    mMaxItems->blockSignals( true ); // KNumInput emits valueChanged from setValue!
    mMaxItems->setValue( mMaxItemsConfigEntry->uintValue() );
    mMaxItems->blockSignals( false );
  }

#ifdef NOT_USEFUL_CURRENTLY
  mAddNewServersConfigEntry = configEntry( s_addnewservers_componentName, s_addnewservers_groupName, s_addnewservers_entryName, Kleo::CryptoConfigEntry::ArgType_None, false );
  if ( mAddNewServersConfigEntry ) {
    mAddNewServersCB->setChecked( mAddNewServersConfigEntry->boolValue() );
  }
#endif
}

void DirectoryServicesConfigurationPage::save()
{
  mWidget->save();

  QTime time( mTimeout->time() );
  unsigned int timeout = time.minute() * 60 + time.second();
  if ( mTimeoutConfigEntry && mTimeoutConfigEntry->uintValue() != timeout )
    mTimeoutConfigEntry->setUIntValue( timeout );
  if ( mMaxItemsConfigEntry && mMaxItemsConfigEntry->uintValue() != (uint)mMaxItems->value() )
    mMaxItemsConfigEntry->setUIntValue( mMaxItems->value() );
#ifdef NOT_USEFUL_CURRENTLY
  if ( mAddNewServersConfigEntry && mAddNewServersConfigEntry->boolValue() != mAddNewServersCB->isChecked() )
    mAddNewServersConfigEntry->setBoolValue( mAddNewServersCB->isChecked() );
#endif

  mConfig->sync( true );

#if 0
  // Also write the LDAP URLs to kabldaprc so that they are used by kaddressbook
  KABSynchronizer sync;
  const KUrl::List toAdd = mWidget->urlList();
  KUrl::List currentList = sync.readCurrentList();

  KUrl::List::const_iterator it = toAdd.begin();
  KUrl::List::const_iterator end = toAdd.end();
  for( ; it != end; ++it ) {
    // check if the URL is already in currentList
    if ( currentList.find( *it ) == currentList.end() )
      // if not, add it
      currentList.append( *it );
  }
  sync.writeList( currentList );
#endif
}

void DirectoryServicesConfigurationPage::defaults()
{
  mWidget->defaults();
  if ( mTimeoutConfigEntry )
    mTimeoutConfigEntry->resetToDefault();
  if ( mMaxItemsConfigEntry )
    mMaxItemsConfigEntry->resetToDefault();
#ifdef NOT_USEFUL_CURRENTLY
  if ( mAddNewServersConfigEntry )
    mAddNewServersConfigEntry->resetToDefault();
#endif
  load();
}

extern "C"
{
  KDE_EXPORT KCModule *create_kleopatra_config_dirserv( QWidget *parent=0, const QStringList &args=QStringList() )
  {
    DirectoryServicesConfigurationPage *page =
      new DirectoryServicesConfigurationPage( KComponentData( "kleopatra" ), parent, args );
    page->setObjectName( "kleopatra_config_dirserv" );
    return page;
  }
}

// kdelibs-3.2 didn't have the changed signal in KCModule...
void DirectoryServicesConfigurationPage::slotChanged()
{
  emit changed(true);
}

// Find config entry for ldap servers. Implements runtime checks on the configuration option.
Kleo::CryptoConfigEntry* DirectoryServicesConfigurationPage::configEntry( const char* componentName,
                                                                          const char* groupName,
                                                                          const char* entryName,
                                                                          Kleo::CryptoConfigEntry::ArgType argType,
                                                                          bool isList )
{
    Kleo::CryptoConfigEntry* entry = mConfig->entry( componentName, groupName, entryName );
    if ( !entry ) {
        KMessageBox::error( this, i18n( "Backend error: gpgconf does not seem to know the entry for %1/%2/%3", componentName, groupName, entryName ) );
        return 0;
    }
    if( entry->argType() != argType || entry->isList() != isList ) {
        KMessageBox::error( this, i18n( "Backend error: gpgconf has wrong type for %1/%2/%3: %4 %5", componentName, groupName, entryName, entry->argType(), entry->isList() ) );
        return 0;
    }
    return entry;
}

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


<commit_before>#include <algorithm>
#include <functional>
#include <iostream>
#include <map>
#include <vector>

class PostingList {
public:
  PostingList(const std::vector<int>& v);
  void init() {
    i_ = v_.begin();
  }
  int next() {
    if (i_ == v_.end()) return -1;
    int ret = *i_;
    ++i_;
    return ret;
  }
  int next(int id) {
    while (i_ != v_.end()) {
      if (*i_ < id) {
	++i_;
      } else {
	int ret = *i_;
	++i_;
	return ret;
      }
    }
    return -1;
  }
private:
  std::vector<int> v_;
  std::vector<int>::const_iterator i_;
};

PostingList::PostingList(const std::vector<int>& v): v_(v), i_(v_.begin()) {}

bool taat(std::vector<PostingList> &posting_lists,
	  std::vector<std::pair<int, int>>& result) {
  result.clear();
  std::map<int, int> accumulator;
  for (auto posting_list = posting_lists.begin();
       posting_list != posting_lists.end();
       ++posting_list) {
    posting_list->init();
    while (true) {
      int tmp_docid = posting_list->next();
      if (tmp_docid == -1) break;
      accumulator[tmp_docid]++;
    }
  }
  std::vector<std::pair<int, int>> tmp_v;

  for (auto i = accumulator.begin();
       i != accumulator.end();
       ++i) {
    tmp_v.push_back(std::make_pair(i->first, i->second));
  }
  std::sort(tmp_v.begin(),
	    tmp_v.end(),
	    [](const std::pair<int, int>& a, const std::pair<int, int>& b) -> bool{
	      if (a.second != b.second) return b.second - a.second < 0;
	      return b.first - a.first > 0;
	    });

  for (auto i = tmp_v.begin();
       i != tmp_v.end();
       ++i) {
    result.push_back(std::make_pair(i->first, i->second));
  }
  return true;
}

int main() {
  std::vector<PostingList> ps;
  ps.push_back(PostingList({1, 2, 3, 4, 5}));
  ps.push_back(PostingList({1, 3, 5}));

  std::vector<std::pair<int, int>> result;
  taat(ps, result);

  for (auto i = result.begin(); i != result.end(); ++i) {
    std::cout << i->first << " " << i->second << std::endl;
  }
  return 0;
}
<commit_msg>improve taat<commit_after>#include <algorithm>
#include <functional>
#include <iostream>
#include <map>
#include <vector>

class PostingList {
public:
  PostingList(const std::vector<int>& v);
  void init() {
    i_ = v_.begin();
  }
  int next() {
    if (i_ == v_.end()) return -1;
    int ret = *i_;
    ++i_;
    return ret;
  }
  int next(int id) {
    while (i_ != v_.end()) {
      if (*i_ < id) {
	++i_;
      } else {
	int ret = *i_;
	++i_;
	return ret;
      }
    }
    return -1;
  }
private:
  std::vector<int> v_;
  std::vector<int>::const_iterator i_;
};

PostingList::PostingList(const std::vector<int>& v): v_(v), i_(v_.begin()) {}

void taat_intersect(PostingList& in,
		    const std::vector<std::pair<int, int>>& accumlator,
		    std::vector<std::pair<int, int>>& next_accumlator) {
  in.init();
  auto i = in.next();
  auto j = accumlator.begin();
  while (i != -1 && j != accumlator.end()) {
    if (i < j->first) {
      next_accumlator.push_back(std::make_pair(i, 1));
      i = in.next();
    } else if(i == j->first) {
      next_accumlator.push_back(std::make_pair(j->first, j->second + 1));
      i = in.next();
      ++j;
    } else {
      next_accumlator.push_back(*j);
      ++j;
    }
  }
  while (i != -1) {
    next_accumlator.push_back(std::make_pair(i, 1));
    i = in.next();
  }
  while (j != accumlator.end()) {
    next_accumlator.push_back(*j);
    ++j;
  }
}

bool taat(std::vector<PostingList> &posting_lists,
	  const int top_k,
	  std::vector<std::pair<int, int>>& result) {
  result.clear();

  for (auto posting_list = posting_lists.begin();
       posting_list != posting_lists.end();
       ++posting_list) {
    posting_list->init();
    std::vector<std::pair<int, int>> next_accumlator;

    taat_intersect(*posting_list, result, next_accumlator);
    next_accumlator.swap(result);
  }

  std::partial_sort(result.begin(),
		     result.begin() + top_k,
		     result.end(),
		     [](const std::pair<int, int>& a, const std::pair<int, int>& b) -> bool{
		       if (a.second != b.second) return b.second - a.second < 0;
		       return b.first - a.first > 0;
		     });
  return true;
}

int main() {
  std::vector<PostingList> ps;
  ps.push_back(PostingList({1, 2, 3, 4, 5}));
  ps.push_back(PostingList({1, 3, 5}));

  std::vector<std::pair<int, int>> result;
  taat(ps, 5, result);

  for (auto i = result.begin(); i != result.end(); ++i) {
    std::cout << i->first << " " << i->second << std::endl;
  }
  return 0;
}
<|endoftext|>


<commit_before>// RUN: %clang_cc1 -std=c++0x -fsyntax-only -verify %s

namespace std { class type_info; };

namespace ExplicitCapture {
  int GlobalVar; // expected-note {{declared here}}

  namespace N {
    int AmbiguousVar; // expected-note {{candidate}}
  }
  int AmbiguousVar; // expected-note {{candidate}}
  using namespace N;

  class C {
    int Member;

    static void Overload(int);
    void Overload();
    virtual C& Overload(float);

    void ExplicitCapture() {
      int foo;

      [foo, foo] () {}; // expected-error {{'foo' can appear only once}} expected-error {{not supported yet}}
      [this, this] () {}; // expected-error {{'this' can appear only once}} expected-error {{not supported yet}}
      [=, foo] () {}; // expected-error {{'&' must precede a capture when}} expected-error {{not supported yet}}
      [=, &foo] () {}; // expected-error {{not supported yet}}
      [=, this] () {}; // expected-error {{'this' cannot appear}} expected-error {{not supported yet}}
      [&, foo] () {}; // expected-error {{not supported yet}}
      [&, &foo] () {}; // expected-error {{'&' cannot precede a capture when}} expected-error {{not supported yet}}
      [&, this] () {}; // expected-error {{not supported yet}}
      [&Overload] () {}; // expected-error {{does not name a variable}} expected-error {{not supported yet}}
      [&GlobalVar] () {}; // expected-error {{does not have automatic storage duration}} expected-error {{not supported yet}}
      [&AmbiguousVar] () {} // expected-error {{reference to 'AmbiguousVar' is ambiguous}} expected-error {{not supported yet}}
      [&Globalvar] () {}; // expected-error {{use of undeclared identifier 'Globalvar'; did you mean 'GlobalVar}}
    }

    void ImplicitThisCapture() {
      [](){(void)Member;}; // expected-error {{'this' cannot be implicitly captured in this context}} expected-error {{not supported yet}}
      [&](){(void)Member;}; // expected-error {{not supported yet}}
      [this](){(void)Member;}; // expected-error {{not supported yet}}
      [this]{[this]{};};// expected-error 2 {{not supported yet}}
      []{[this]{};};// expected-error {{'this' cannot be implicitly captured in this context}} expected-error 2 {{not supported yet}}
      []{Overload(3);}; // expected-error {{not supported yet}}
      []{Overload();}; // expected-error {{'this' cannot be implicitly captured in this context}} expected-error {{not supported yet}}
      []{(void)typeid(Overload());};// expected-error {{not supported yet}}
      []{(void)typeid(Overload(.5f));};// expected-error {{'this' cannot be implicitly captured in this context}} expected-error {{not supported yet}}
    }
  };

  void f() {
    [this] () {}; // expected-error {{invalid use of 'this'}} expected-error {{not supported yet}}
  }
}

namespace ReturnDeduction {
  void test() {
    [](){ return 1; }; // expected-error {{not supported yet}}
    [](){ return 1; }; // expected-error {{not supported yet}}
    [](){ return ({return 1; 1;}); }; // expected-error {{not supported yet}}
    [](){ return ({return 'c'; 1;}); }; // expected-error {{not supported yet}} expected-error {{must match previous return type}}
    []()->int{ return 'c'; return 1; }; // expected-error {{not supported yet}}
    [](){ return 'c'; return 1; }; // expected-error {{not supported yet}} expected-error {{must match previous return type}}
    // FIXME: Need to check structure of lambda body
    [](){ return 1; return 1; }; // expected-error {{not supported yet}}
  }
}
<commit_msg>Add an additional testcase for a lambda with implicit void return type.<commit_after>// RUN: %clang_cc1 -std=c++0x -fsyntax-only -verify %s

namespace std { class type_info; };

namespace ExplicitCapture {
  int GlobalVar; // expected-note {{declared here}}

  namespace N {
    int AmbiguousVar; // expected-note {{candidate}}
  }
  int AmbiguousVar; // expected-note {{candidate}}
  using namespace N;

  class C {
    int Member;

    static void Overload(int);
    void Overload();
    virtual C& Overload(float);

    void ExplicitCapture() {
      int foo;

      [foo, foo] () {}; // expected-error {{'foo' can appear only once}} expected-error {{not supported yet}}
      [this, this] () {}; // expected-error {{'this' can appear only once}} expected-error {{not supported yet}}
      [=, foo] () {}; // expected-error {{'&' must precede a capture when}} expected-error {{not supported yet}}
      [=, &foo] () {}; // expected-error {{not supported yet}}
      [=, this] () {}; // expected-error {{'this' cannot appear}} expected-error {{not supported yet}}
      [&, foo] () {}; // expected-error {{not supported yet}}
      [&, &foo] () {}; // expected-error {{'&' cannot precede a capture when}} expected-error {{not supported yet}}
      [&, this] () {}; // expected-error {{not supported yet}}
      [&Overload] () {}; // expected-error {{does not name a variable}} expected-error {{not supported yet}}
      [&GlobalVar] () {}; // expected-error {{does not have automatic storage duration}} expected-error {{not supported yet}}
      [&AmbiguousVar] () {} // expected-error {{reference to 'AmbiguousVar' is ambiguous}} expected-error {{not supported yet}}
      [&Globalvar] () {}; // expected-error {{use of undeclared identifier 'Globalvar'; did you mean 'GlobalVar}}
    }

    void ImplicitThisCapture() {
      [](){(void)Member;}; // expected-error {{'this' cannot be implicitly captured in this context}} expected-error {{not supported yet}}
      [&](){(void)Member;}; // expected-error {{not supported yet}}
      [this](){(void)Member;}; // expected-error {{not supported yet}}
      [this]{[this]{};};// expected-error 2 {{not supported yet}}
      []{[this]{};};// expected-error {{'this' cannot be implicitly captured in this context}} expected-error 2 {{not supported yet}}
      []{Overload(3);}; // expected-error {{not supported yet}}
      []{Overload();}; // expected-error {{'this' cannot be implicitly captured in this context}} expected-error {{not supported yet}}
      []{(void)typeid(Overload());};// expected-error {{not supported yet}}
      []{(void)typeid(Overload(.5f));};// expected-error {{'this' cannot be implicitly captured in this context}} expected-error {{not supported yet}}
    }
  };

  void f() {
    [this] () {}; // expected-error {{invalid use of 'this'}} expected-error {{not supported yet}}
  }
}

namespace ReturnDeduction {
  void test() {
    [](){ return 1; }; // expected-error {{not supported yet}}
    [](){ return 1; }; // expected-error {{not supported yet}}
    [](){ return ({return 1; 1;}); }; // expected-error {{not supported yet}}
    [](){ return ({return 'c'; 1;}); }; // expected-error {{not supported yet}} expected-error {{must match previous return type}}
    []()->int{ return 'c'; return 1; }; // expected-error {{not supported yet}}
    [](){ return 'c'; return 1; }; // expected-error {{not supported yet}} expected-error {{must match previous return type}}
    []() { return; return (void)0; }; // expected-error {{not supported yet}}
    // FIXME: Need to check structure of lambda body
    [](){ return 1; return 1; }; // expected-error {{not supported yet}}
  }
}
<|endoftext|>


<commit_before>// ft2232spi.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

/* Standard C libraries */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/* OS specific libraries */
#ifdef _WIN32
#include<windows.h>
#endif

/* Include D2XX header*/
#include "ftd2xx.h"

#pragma comment(lib, "FTD2XX.lib")
#pragma comment(lib, "libMPSSE.lib")

/* Include libMPSSE header */
#include "libMPSSE_spi.h"

/* Helper macros */

#define APP_CHECK_STATUS(exp) {if(exp!=FT_OK){printf("%s:%d:%s(): status(0x%x) \
!= FT_OK\n",__FILE__, __LINE__, __FUNCTION__,exp);exit(1);}else{;}};
#define CHECK_NULL(exp){if(exp==NULL){printf("%s:%d:%s():  NULL expression \
encountered \n",__FILE__, __LINE__, __FUNCTION__);exit(1);}else{;}};

/* Definitions */
#define SPI_DEVICE_BUFFER_SIZE		256
#define CHANNEL_TO_OPEN			0	/*0 for first available channel, 1 for next... */
#define SPI_WRITE_COMPLETION_RETRY 100
#define SPI_OPTS               SPI_TRANSFER_OPTIONS_SIZE_IN_BYTES | SPI_TRANSFER_OPTIONS_CHIPSELECT_ENABLE | SPI_TRANSFER_OPTIONS_CHIPSELECT_ENABLE

/* Globals */
static FT_STATUS ftStatus;
static FT_HANDLE ftHandle;
static uint8 wBuffer[SPI_DEVICE_BUFFER_SIZE] = {0};
static uint8 rBuffer[SPI_DEVICE_BUFFER_SIZE] = {0};

int _tmain(int argc, _TCHAR* argv[]) {
	FT_STATUS status = FT_OK;
	FT_DEVICE_LIST_INFO_NODE devList = {0};
	ChannelConfig channelConf = {0};
	uint8 address = 0;
	uint32 channels = 0;
	uint16 data = 0;
	uint8 i = 0;

	channelConf.ClockRate = 400000;
	channelConf.LatencyTimer = 255;
	channelConf.configOptions = SPI_CONFIG_OPTION_MODE0 | SPI_CONFIG_OPTION_CS_DBUS4 | SPI_CONFIG_OPTION_CS_ACTIVELOW;
	channelConf.Pin = 0xFFff0000;/*FinalVal-FinalDir-InitVal-InitDir (for dir 0=in, 1=out)*/
	channelConf.reserved = 0;

	/* init library */
#ifdef _MSC_VER
	Init_libMPSSE();
#endif
	status = SPI_GetNumChannels(&channels);
	APP_CHECK_STATUS(status);
	printf("Number of available SPI channels = %d\n",(int)channels);

	if(channels>0)
	{
#if 0
		for(i=0;i<channels;i++)
		{
			status = SPI_GetChannelInfo(i,&devList);
			APP_CHECK_STATUS(status);
			printf("Information on channel number %d:\n",i);
			/* print the dev info */
			printf("		Flags=0x%x\n",devList.Flags);
			printf("		Type=0x%x\n",devList.Type);
			printf("		ID=0x%x\n",devList.ID);
			printf("		LocId=0x%x\n",devList.LocId);
			printf("		SerialNumber=%s\n",devList.SerialNumber);
			printf("		Description=%s\n",devList.Description);
			printf("		ftHandle=0x%x\n",(unsigned int)devList.ftHandle);/*is 0 unless open*/
		}
#endif

		/* Open the first available channel */
		status = SPI_OpenChannel(CHANNEL_TO_OPEN,&ftHandle);
		APP_CHECK_STATUS(status);
		printf("\nhandle=0x%x status=0x%x\n",(unsigned int)ftHandle,status);
		status = SPI_InitChannel(ftHandle,&channelConf);
		APP_CHECK_STATUS(status);

		// Write some data for the lattice iCE40Ultra EVK demo
		uint32 sizeTransferred;

		// Make sure we are out of programming mode
		status = SPI_Read(ftHandle, rBuffer, 50, &sizeTransferred, SPI_OPTS);
		APP_CHECK_STATUS(status);

		wBuffer[0] = 0x19;
		wBuffer[1] = 0x67; // Color 6 (cyan), brightness 7 (50%)
		wBuffer[2] = 0x20; // Ramp 2, blink rate 0
		status = SPI_ReadWrite(ftHandle, rBuffer, wBuffer, 3, &sizeTransferred, SPI_OPTS);
		APP_CHECK_STATUS(status);
		printf("Wrote/Read %d bytes\r\n", sizeTransferred);
		unsigned long retry = 0;
		bool state=FALSE;
		SPI_IsBusy(ftHandle,&state);
		while((FALSE==state) && (retry<SPI_WRITE_COMPLETION_RETRY))
		{
			printf("SPI device is busy(%u)\n",(unsigned)retry);
			SPI_IsBusy(ftHandle,&state);
			retry++;
		}
		printf("Read %02x %02x %02x\r\n", rBuffer[0], rBuffer[1], rBuffer[2]);

		status = SPI_CloseChannel(ftHandle);
	}

#ifdef _MSC_VER
	Cleanup_libMPSSE();
#endif

#ifndef __linux__
	system("pause");
#endif
	return 0;
}

<commit_msg>Checkpoint.<commit_after>// ft2232spi.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

/* Standard C libraries */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/* OS specific libraries */
#ifdef _WIN32
#include<windows.h>
#endif

/* Include D2XX header*/
#include "ftd2xx.h"

#pragma comment(lib, "FTD2XX.lib")
#pragma comment(lib, "libMPSSE.lib")

/* Include libMPSSE header */
#include "libMPSSE_spi.h"

/* Helper macros */

#define APP_CHECK_STATUS(exp) {if(exp!=FT_OK){printf("%s:%d:%s(): status(0x%x) \
!= FT_OK\n",__FILE__, __LINE__, __FUNCTION__,exp);exit(1);}else{;}};
#define CHECK_NULL(exp){if(exp==NULL){printf("%s:%d:%s():  NULL expression \
encountered \n",__FILE__, __LINE__, __FUNCTION__);exit(1);}else{;}};

/* Definitions */
#define SPI_DEVICE_BUFFER_SIZE		256
#define CHANNEL_TO_OPEN			0	/*0 for first available channel, 1 for next... */
#define SPI_WRITE_COMPLETION_RETRY 100
#define SPI_OPTS               SPI_TRANSFER_OPTIONS_SIZE_IN_BYTES | SPI_TRANSFER_OPTIONS_CHIPSELECT_ENABLE | SPI_TRANSFER_OPTIONS_CHIPSELECT_DISABLE

/* Globals */
static FT_STATUS ftStatus;
static FT_HANDLE ftHandle;
static uint8 wBuffer[SPI_DEVICE_BUFFER_SIZE] = {0};
static uint8 rBuffer[SPI_DEVICE_BUFFER_SIZE] = {0};

int _tmain(int argc, _TCHAR* argv[]) {
	FT_STATUS status = FT_OK;
	FT_DEVICE_LIST_INFO_NODE devList = {0};
	ChannelConfig channelConf = {0};
	uint8 address = 0;
	uint32 channels = 0;
	uint16 data = 0;
	uint8 i = 0;

	channelConf.ClockRate = 400000;
	channelConf.LatencyTimer = 255;
	channelConf.configOptions = SPI_CONFIG_OPTION_MODE0 | SPI_CONFIG_OPTION_CS_DBUS4 | SPI_CONFIG_OPTION_CS_ACTIVELOW;
	channelConf.Pin = 0xFFff0000;/*FinalVal-FinalDir-InitVal-InitDir (for dir 0=in, 1=out)*/
	channelConf.reserved = 0;

	/* init library */
#ifdef _MSC_VER
	Init_libMPSSE();
#endif
	status = SPI_GetNumChannels(&channels);
	APP_CHECK_STATUS(status);
	printf("Number of available SPI channels = %d\n",(int)channels);

	if(channels>0)
	{
#if 0
		for(i=0;i<channels;i++)
		{
			status = SPI_GetChannelInfo(i,&devList);
			APP_CHECK_STATUS(status);
			printf("Information on channel number %d:\n",i);
			/* print the dev info */
			printf("		Flags=0x%x\n",devList.Flags);
			printf("		Type=0x%x\n",devList.Type);
			printf("		ID=0x%x\n",devList.ID);
			printf("		LocId=0x%x\n",devList.LocId);
			printf("		SerialNumber=%s\n",devList.SerialNumber);
			printf("		Description=%s\n",devList.Description);
			printf("		ftHandle=0x%x\n",(unsigned int)devList.ftHandle);/*is 0 unless open*/
		}
#endif

		/* Open the first available channel */
		status = SPI_OpenChannel(CHANNEL_TO_OPEN,&ftHandle);
		APP_CHECK_STATUS(status);
		printf("\nhandle=0x%x status=0x%x\n",(unsigned int)ftHandle,status);
		status = SPI_InitChannel(ftHandle,&channelConf);
		APP_CHECK_STATUS(status);

		// Write some data for the lattice iCE40Ultra EVK demo
		uint32 sizeTransferred;

		wBuffer[0] = 0x7e; // Programming sync pattern
		wBuffer[1] = 0xaa;
		wBuffer[2] = 0x99;
		wBuffer[3] = 0x7e;
		status = SPI_ReadWrite(ftHandle, rBuffer, wBuffer, 4, &sizeTransferred, SPI_OPTS);
		APP_CHECK_STATUS(status);
		printf("Wrote/Read %d bytes\r\n", sizeTransferred);
		unsigned long retry = 0;
		bool state=FALSE;
		SPI_IsBusy(ftHandle,&state);
		while((FALSE==state) && (retry<SPI_WRITE_COMPLETION_RETRY))
		{
			printf("SPI device is busy(%u)\n",(unsigned)retry);
			SPI_IsBusy(ftHandle,&state);
			retry++;
		}
		printf("Read %02x %02x %02x\r\n", rBuffer[0], rBuffer[1], rBuffer[2]);

		status = SPI_CloseChannel(ftHandle);
	}

#ifdef _MSC_VER
	Cleanup_libMPSSE();
#endif

#ifndef __linux__
	system("pause");
#endif
	return 0;
}

<|endoftext|>