<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: w1par.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 06:03:03 $
 *
 *  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 _W1PAR_HXX
#define _W1PAR_HXX

#ifndef _FLTSHELL_HXX
#include <fltshell.hxx>
#endif
#ifndef _W1CLASS_HXX
#include <w1class.hxx>
#endif

////////////////////////////////////////////////////////////// Ww1Shell
class Ww1Shell : public SwFltShell
{
public:
    Ww1Shell(SwDoc&, SwPaM&, const String& rBaseURL, BOOL bNew, ULONG nFieldFlags);
};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.3.1202); FILE MERGED 2008/04/01 12:54:45 thb 1.3.1202.2: #i85898# Stripping all external header guards 2008/03/31 16:55:48 rt 1.3.1202.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: w1par.hxx,v $
 * $Revision: 1.4 $
 *
 * 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 _W1PAR_HXX
#define _W1PAR_HXX

#include <fltshell.hxx>
#ifndef _W1CLASS_HXX
#include <w1class.hxx>
#endif

////////////////////////////////////////////////////////////// Ww1Shell
class Ww1Shell : public SwFltShell
{
public:
    Ww1Shell(SwDoc&, SwPaM&, const String& rBaseURL, BOOL bNew, ULONG nFieldFlags);
};

#endif

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: labprt.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 07:30:25 $
 *
 *  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
 *
 ************************************************************************/

#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif

#pragma hdrstop

#ifndef _SV_PRNSETUP_HXX_ //autogen
#include <svtools/prnsetup.hxx>
#endif
#ifndef _SV_PRINT_HXX
#include <vcl/print.hxx>
#endif

#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _LABEL_HXX
#include <label.hxx>
#endif
#ifndef _LABPRT_HXX
#include <labprt.hxx>
#endif
#ifndef _LABIMG_HXX
#include <labimg.hxx>
#endif
#ifndef _LABIMP_HXX
#include "swuilabimp.hxx" //CHINA001
#endif

#ifndef _CMDID_H
#include <cmdid.h>
#endif
#ifndef _LABPRT_HRC
#include <labprt.hrc>
#endif

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

SwLabPrtPage::SwLabPrtPage(Window* pParent, const SfxItemSet& rSet) :

    SfxTabPage(pParent, SW_RES(TP_LAB_PRT), rSet),

    pPrinter( 0 ),
    aPageButton    (this, SW_RES(BTN_PAGE   )),
    aSingleButton  (this, SW_RES(BTN_SINGLE )),
    aColText       (this, SW_RES(TXT_COL    )),
    aColField      (this, SW_RES(FLD_COL    )),
    aRowText       (this, SW_RES(TXT_ROW    )),
    aRowField      (this, SW_RES(FLD_ROW    )),
    aSynchronCB    (this, SW_RES(CB_SYNCHRON)),
    aFLDontKnow    (this, SW_RES(FL_DONTKNOW)),
    aPrinterInfo   (this, SW_RES(INF_PRINTER)),
    aPrtSetup      (this, SW_RES(BTN_PRTSETUP)),
    aFLPrinter     (this, SW_RES(FL_PRINTER ))

{
    FreeResource();
    SetExchangeSupport();

    // Handler installieren
    Link aLk = LINK(this, SwLabPrtPage, CountHdl);
    aPageButton  .SetClickHdl( aLk );
    aSingleButton.SetClickHdl( aLk );

    aPrtSetup.SetClickHdl( aLk );
}

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

SwLabPrtPage::~SwLabPrtPage()
{
    if (pPrinter)
        delete pPrinter;
}

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

IMPL_LINK( SwLabPrtPage, CountHdl, Button *, pButton )
{
    if (pButton == &aPrtSetup)
    {
        // Druck-Setup aufrufen
        if (!pPrinter)
            pPrinter = new Printer;

        PrinterSetupDialog* pDlg = new PrinterSetupDialog(this );
        pDlg->SetPrinter(pPrinter);
        pDlg->Execute();
        delete pDlg;
        GrabFocus();
        aPrinterInfo.SetText(pPrinter->GetName());
        return 0;
    }
    const BOOL bEnable = pButton == &aSingleButton;
    aColText .Enable(bEnable);
    aColField.Enable(bEnable);
    aRowText .Enable(bEnable);
    aRowField.Enable(bEnable);
    aSynchronCB.Enable(!bEnable);

    if ( bEnable )
        aColField.GrabFocus();
#ifndef PRODUCT
    else
        ASSERT( pButton == &aPageButton, "NewButton?" );
#endif
    return 0;
}

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

SfxTabPage* SwLabPrtPage::Create(Window* pParent, const SfxItemSet& rSet)
{
    return new SwLabPrtPage( pParent, rSet );
}

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

void SwLabPrtPage::ActivatePage( const SfxItemSet& rSet )
{
    Reset(rSet);
}

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

int SwLabPrtPage::DeactivatePage(SfxItemSet* pSet)
{
    if ( pSet )
        FillItemSet(*pSet);

    return TRUE;
}

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

void SwLabPrtPage::FillItem(SwLabItem& rItem)
{
    rItem.bPage = aPageButton.IsChecked();
    rItem.nCol  = (USHORT) aColField.GetValue();
    rItem.nRow  = (USHORT) aRowField.GetValue();
    rItem.bSynchron = aSynchronCB.IsChecked() && aSynchronCB.IsEnabled();
}

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

BOOL SwLabPrtPage::FillItemSet(SfxItemSet& rSet)
{
    SwLabItem aItem;
    GetParent()->GetLabItem(aItem);
    FillItem(aItem);
    rSet.Put(aItem);

    return TRUE;
}

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

void SwLabPrtPage::Reset(const SfxItemSet& rSet)
{
    SwLabItem aItem;
    GetParent()->GetLabItem(aItem);

    aColField.SetValue   (aItem.nCol);
    aRowField.SetValue   (aItem.nRow);

    if (aItem.bPage)
    {
        aPageButton.Check();
        aPageButton.GetClickHdl().Call(&aPageButton);
    }
    else
    {
        aSingleButton.GetClickHdl().Call(&aSingleButton);
        aSingleButton.Check();
    }

    if (pPrinter)
    {
        // Drucker anzeigen
        aPrinterInfo.SetText(pPrinter->GetName());
    }
    else
        aPrinterInfo.SetText(Printer::GetDefaultPrinterName());

    aColField.SetMax(aItem.nCols);
    aRowField.SetMax(aItem.nRows);

    aColField.SetLast(aColField.GetMax());
    aRowField.SetLast(aRowField.GetMax());

    aSynchronCB.Check(aItem.bSynchron);
}

<commit_msg>INTEGRATION: CWS c06 (1.7.6); FILE MERGED 2005/10/19 07:44:38 kso 1.7.6.1: #126240# - printer section now removed if "Print" slot is disabled.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: labprt.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2005-11-11 11:47:05 $
 *
 *  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
 *
 ************************************************************************/

#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif

#pragma hdrstop

#ifndef _SV_PRNSETUP_HXX_ //autogen
#include <svtools/prnsetup.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_CMDOPTIONS_HXX
#include <svtools/cmdoptions.hxx>
#endif
#ifndef _SV_PRINT_HXX
#include <vcl/print.hxx>
#endif

#ifndef _WRTSH_HXX
#include <wrtsh.hxx>
#endif
#ifndef _LABEL_HXX
#include <label.hxx>
#endif
#ifndef _LABPRT_HXX
#include <labprt.hxx>
#endif
#ifndef _LABIMG_HXX
#include <labimg.hxx>
#endif
#ifndef _LABIMP_HXX
#include "swuilabimp.hxx" //CHINA001
#endif

#ifndef _CMDID_H
#include <cmdid.h>
#endif
#ifndef _LABPRT_HRC
#include <labprt.hrc>
#endif

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

SwLabPrtPage::SwLabPrtPage(Window* pParent, const SfxItemSet& rSet) :

    SfxTabPage(pParent, SW_RES(TP_LAB_PRT), rSet),

    pPrinter( 0 ),
    aPageButton    (this, SW_RES(BTN_PAGE   )),
    aSingleButton  (this, SW_RES(BTN_SINGLE )),
    aColText       (this, SW_RES(TXT_COL    )),
    aColField      (this, SW_RES(FLD_COL    )),
    aRowText       (this, SW_RES(TXT_ROW    )),
    aRowField      (this, SW_RES(FLD_ROW    )),
    aSynchronCB    (this, SW_RES(CB_SYNCHRON)),
    aFLDontKnow    (this, SW_RES(FL_DONTKNOW)),
    aPrinterInfo   (this, SW_RES(INF_PRINTER)),
    aPrtSetup      (this, SW_RES(BTN_PRTSETUP)),
    aFLPrinter     (this, SW_RES(FL_PRINTER ))

{
    FreeResource();
    SetExchangeSupport();

    // Handler installieren
    Link aLk = LINK(this, SwLabPrtPage, CountHdl);
    aPageButton  .SetClickHdl( aLk );
    aSingleButton.SetClickHdl( aLk );

    aPrtSetup.SetClickHdl( aLk );

    SvtCommandOptions aCmdOpts;
    if ( aCmdOpts.Lookup(
             SvtCommandOptions::CMDOPTION_DISABLED,
             rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Print"  ) ) ) )
    {
        aPrinterInfo.Hide();
        aPrtSetup.Hide();
        aFLPrinter.Hide();
    }
}

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

SwLabPrtPage::~SwLabPrtPage()
{
    if (pPrinter)
        delete pPrinter;
}

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

IMPL_LINK( SwLabPrtPage, CountHdl, Button *, pButton )
{
    if (pButton == &aPrtSetup)
    {
        // Druck-Setup aufrufen
        if (!pPrinter)
            pPrinter = new Printer;

        PrinterSetupDialog* pDlg = new PrinterSetupDialog(this );
        pDlg->SetPrinter(pPrinter);
        pDlg->Execute();
        delete pDlg;
        GrabFocus();
        aPrinterInfo.SetText(pPrinter->GetName());
        return 0;
    }
    const BOOL bEnable = pButton == &aSingleButton;
    aColText .Enable(bEnable);
    aColField.Enable(bEnable);
    aRowText .Enable(bEnable);
    aRowField.Enable(bEnable);
    aSynchronCB.Enable(!bEnable);

    if ( bEnable )
        aColField.GrabFocus();
#ifndef PRODUCT
    else
        ASSERT( pButton == &aPageButton, "NewButton?" );
#endif
    return 0;
}

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

SfxTabPage* SwLabPrtPage::Create(Window* pParent, const SfxItemSet& rSet)
{
    return new SwLabPrtPage( pParent, rSet );
}

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

void SwLabPrtPage::ActivatePage( const SfxItemSet& rSet )
{
    Reset(rSet);
}

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

int SwLabPrtPage::DeactivatePage(SfxItemSet* pSet)
{
    if ( pSet )
        FillItemSet(*pSet);

    return TRUE;
}

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

void SwLabPrtPage::FillItem(SwLabItem& rItem)
{
    rItem.bPage = aPageButton.IsChecked();
    rItem.nCol  = (USHORT) aColField.GetValue();
    rItem.nRow  = (USHORT) aRowField.GetValue();
    rItem.bSynchron = aSynchronCB.IsChecked() && aSynchronCB.IsEnabled();
}

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

BOOL SwLabPrtPage::FillItemSet(SfxItemSet& rSet)
{
    SwLabItem aItem;
    GetParent()->GetLabItem(aItem);
    FillItem(aItem);
    rSet.Put(aItem);

    return TRUE;
}

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

void SwLabPrtPage::Reset(const SfxItemSet& rSet)
{
    SwLabItem aItem;
    GetParent()->GetLabItem(aItem);

    aColField.SetValue   (aItem.nCol);
    aRowField.SetValue   (aItem.nRow);

    if (aItem.bPage)
    {
        aPageButton.Check();
        aPageButton.GetClickHdl().Call(&aPageButton);
    }
    else
    {
        aSingleButton.GetClickHdl().Call(&aSingleButton);
        aSingleButton.Check();
    }

    if (pPrinter)
    {
        // Drucker anzeigen
        aPrinterInfo.SetText(pPrinter->GetName());
    }
    else
        aPrinterInfo.SetText(Printer::GetDefaultPrinterName());

    aColField.SetMax(aItem.nCols);
    aRowField.SetMax(aItem.nRows);

    aColField.SetLast(aColField.GetMax());
    aRowField.SetLast(aRowField.GetMax());

    aSynchronCB.Check(aItem.bSynchron);
}

<|endoftext|>


<commit_before>/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://www.visualizationlibrary.org                                               */
/*                                                                                */
/*  Copyright (c) 2005-2010, Michele Bosi                                             */
/*  All rights reserved.                                                              */
/*                                                                                */
/*  Redistribution and use in source and binary forms, with or without modification,  */
/*  are permitted provided that the following conditions are met:                     */
/*                                                                                */
/*  - Redistributions of source code must retain the above copyright notice, this     */
/*  list of conditions and the following disclaimer.                                  */
/*                                                                                */
/*  - Redistributions in binary form must reproduce the above copyright notice, this  */
/*  list of conditions and the following disclaimer in the documentation and/or       */
/*  other materials provided with the distribution.                                   */
/*                                                                                */
/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND   */
/*  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED     */
/*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE            */
/*  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR  */
/*  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    */
/*  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;      */
/*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON    */
/*  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT           */
/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS     */
/*  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                      */
/*                                                                                */
/**************************************************************************************/

#ifndef expandResourceDatabase_INCLUDE_ONCE
#define expandResourceDatabase_INCLUDE_ONCE

namespace vl
{
  class ResourceDatabase;
  //! Extracts and sorts Shaders, Effects, Renderables, RenderStates, Transforms etc. from their parent objects.
  void expandResourceDatabase(ResourceDatabase* db);
}

#endif
<commit_msg>fixed DLL compilation<commit_after>/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://www.visualizationlibrary.org                                               */
/*                                                                                */
/*  Copyright (c) 2005-2010, Michele Bosi                                             */
/*  All rights reserved.                                                              */
/*                                                                                */
/*  Redistribution and use in source and binary forms, with or without modification,  */
/*  are permitted provided that the following conditions are met:                     */
/*                                                                                */
/*  - Redistributions of source code must retain the above copyright notice, this     */
/*  list of conditions and the following disclaimer.                                  */
/*                                                                                */
/*  - Redistributions in binary form must reproduce the above copyright notice, this  */
/*  list of conditions and the following disclaimer in the documentation and/or       */
/*  other materials provided with the distribution.                                   */
/*                                                                                */
/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND   */
/*  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED     */
/*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE            */
/*  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR  */
/*  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    */
/*  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;      */
/*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON    */
/*  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT           */
/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS     */
/*  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                      */
/*                                                                                */
/**************************************************************************************/

#ifndef expandResourceDatabase_INCLUDE_ONCE
#define expandResourceDatabase_INCLUDE_ONCE

#include <vlGraphics/link_config.hpp>

namespace vl
{
  class ResourceDatabase;
  //! Extracts and sorts Shaders, Effects, Renderables, RenderStates, Transforms etc. from their parent objects.
  VLGRAPHICS_EXPORT void expandResourceDatabase(ResourceDatabase* db);
}

#endif
<|endoftext|>


<commit_before><commit_msg>SwRedlineAcceptDlg::InsertChildren: fix previous commit:<commit_after><|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkMapServerSource.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkMapServerSource.h"

#include "vtkPolyData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkSmartPointer.h"
#include "vtkTransform.h"
#include "vtkTransformPolyDataFilter.h"
#include "vtkNew.h"

#include <vtkIdList.h>
#include <vtkCellArray.h>
#include <vtkPoints.h>
#include <vtkDoubleArray.h>
#include <vtkFloatArray.h>
#include <vtkPointData.h>

#include <Eigen/Dense>
#include <boost/shared_ptr.hpp>
#include <boost/thread/thread.hpp>

#include <lcm/lcm-cpp.hpp>

//#include <lcmtypes/drc_lcmtypes.hpp>
#include <lcmtypes/drc/map_image_t.hpp>
#include <lcmtypes/drc/map_cloud_t.hpp>

#include <maps/LcmTranslator.hpp>
#include <maps/DepthImageView.hpp>
#include <maps/PointCloudView.hpp>

#include <sys/select.h>
#include <deque>

namespace
{

//----------------------------------------------------------------------------
vtkSmartPointer<vtkCellArray> NewVertexCells(vtkIdType numberOfVerts)
{
  vtkNew<vtkIdTypeArray> cells;
  cells->SetNumberOfValues(numberOfVerts*2);
  vtkIdType* ids = cells->GetPointer(0);
  for (vtkIdType i = 0; i < numberOfVerts; ++i)
    {
    ids[i*2] = 1;
    ids[i*2+1] = i;
    }

  vtkSmartPointer<vtkCellArray> cellArray = vtkSmartPointer<vtkCellArray>::New();
  cellArray->SetCells(numberOfVerts, cells.GetPointer());
  return cellArray;
}

//----------------------------------------------------------------------------
vtkSmartPointer<vtkPolyData> PolyDataFromPointCloud(pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud)
{
  vtkIdType nr_points = cloud->points.size();

  vtkNew<vtkPoints> points;
  points->SetDataTypeToFloat();
  points->SetNumberOfPoints(nr_points);

  vtkNew<vtkUnsignedCharArray> rgbArray;
  rgbArray->SetName("rgb_colors");
  rgbArray->SetNumberOfComponents(3);
  rgbArray->SetNumberOfTuples(nr_points);

  if (cloud->is_dense)
  {
    for (vtkIdType i = 0; i < nr_points; ++i) {
      float point[3] = {cloud->points[i].x, cloud->points[i].y, cloud->points[i].z};
      unsigned char color[3] = {cloud->points[i].r, cloud->points[i].g, cloud->points[i].b};
      points->SetPoint(i, point);
      rgbArray->SetTupleValue(i, color);
    }
  }
  else
  {
    vtkIdType j = 0;    // true point index
    for (vtkIdType i = 0; i < nr_points; ++i)
    {
      // Check if the point is invalid
      if (!pcl_isfinite (cloud->points[i].x) ||
          !pcl_isfinite (cloud->points[i].y) ||
          !pcl_isfinite (cloud->points[i].z))
        continue;

      float point[3] = {cloud->points[i].x, cloud->points[i].y, cloud->points[i].z};
      unsigned char color[3] = {cloud->points[i].r, cloud->points[i].g, cloud->points[i].b};
      points->SetPoint(j, point);
      rgbArray->SetTupleValue(j, color);
      j++;
    }
    nr_points = j;
    points->SetNumberOfPoints(nr_points);
    rgbArray->SetNumberOfTuples(nr_points);
  }

  vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();
  polyData->SetPoints(points.GetPointer());
  polyData->GetPointData()->AddArray(rgbArray.GetPointer());
  polyData->SetVerts(NewVertexCells(nr_points));
  return polyData;
}

//----------------------------------------------------------------------------
class MapData
{
public:
  uint64_t Id;
  vtkSmartPointer<vtkPolyData> Data;
};

//----------------------------------------------------------------------------
class LCMListener
{
public:

  LCMListener()
  {
    this->ShouldStop = true;
    this->NewData = false;
    this->MaxNumberOfDatasets = 100;
    this->CurrentMapId = -1;

    this->LCMHandle = boost::shared_ptr<lcm::LCM>(new lcm::LCM);
    if(!this->LCMHandle->good())
    {
      std::cerr <<"ERROR: lcm is not good()" <<std::endl;
    }

    this->LCMHandle->subscribe( "MAP_DEPTH", &LCMListener::depthHandler, this);
    this->LCMHandle->subscribe( "MAP_CLOUD", &LCMListener::cloudHandler, this);
  }

  void cloudHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const drc::map_cloud_t* msg)
  {
    this->HandleNewData(msg);
  }

  void depthHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const drc::map_image_t* msg)
  {
    this->HandleNewData(msg);
  }

  bool CheckForNewData()
  {
    boost::lock_guard<boost::mutex> lock(this->Mutex);
    bool newData = this->NewData;
    this->NewData = false;
    return newData;
  }

  bool WaitForLCM(double timeout)
  {
    int lcmFd = this->LCMHandle->getFileno();

    timeval tv;
    tv.tv_sec = 0;
    tv.tv_usec = timeout * 1e6;

    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(lcmFd, &fds);

    int status = select(lcmFd + 1, &fds, 0, 0, &tv);
    return (status != 0 && FD_ISSET(lcmFd, &fds));
  }

  void ThreadLoopWithSelect()
  {
    while (!this->ShouldStop)
    {
      const double timeoutInSeconds = 0.3;
      bool lcmReady = this->WaitForLCM(timeoutInSeconds);

      if (this->ShouldStop)
      {
        break;
      }

      if (lcmReady)
      {
        if (this->LCMHandle->handle() != 0)
        {
          printf("lcm->handle() returned non-zero\n");
          break;
        }
      }
    }

  }

  void ThreadLoop()
  {
    while (!this->ShouldStop)
    {
      if (this->LCMHandle->handle() != 0)
      {
        printf("lcm->handle() returned non-zero\n");
        break;
      }
    }
  }

  void Start()
  {
    if (this->Thread)
      {
      return;
      }

    printf("starting\n");

    this->ShouldStop = false;
    this->Thread = boost::shared_ptr<boost::thread>(
      new boost::thread(boost::bind(&LCMListener::ThreadLoopWithSelect, this)));
  }

  void Stop()
  {
    if (this->Thread)
      {
      printf("stopping thread...\n");
      this->ShouldStop = true;
      this->Thread->interrupt();
      this->Thread->join();
      this->Thread.reset();
      printf("done.\n");
      }
  }

  std::vector<vtkSmartPointer<vtkPolyData> > GetDatasets()
  {
    std::vector<vtkSmartPointer<vtkPolyData> > datasets;

    boost::lock_guard<boost::mutex> lock(this->Mutex);
    for (size_t i = 0; i < this->Datasets.size(); ++i)
      {
      datasets.push_back(this->Datasets[i].Data);
      }

    return datasets;
  }

  std::vector<double> GetTimesteps()
  {
    boost::lock_guard<boost::mutex> lock(this->Mutex);

    std::vector<double> timesteps;
    for (int i = 0; i < this->Datasets.size(); ++i)
      {
      timesteps.push_back(i);
      }
    return timesteps;
  }

  vtkSmartPointer<vtkPolyData> GetDatasetForTime(int timestep)
  {
    boost::lock_guard<boost::mutex> lock(this->Mutex);
    if (timestep >= 0 && timestep < this->Datasets.size())
      {
      return this->Datasets[timestep].Data;
      }
    else
      {
      return 0;
      }
  }

  vtkIdType GetCurrentMapId()
  {
    return this->CurrentMapId;
  }

  void GetDataForMapId(vtkIdType mapId, vtkPolyData* polyData)
  {
    if (!polyData)
      {
      return;
      }

    boost::lock_guard<boost::mutex> lock(this->Mutex);
    for (size_t i = 0; i < this->Datasets.size(); ++i)
      {
      if (this->Datasets[i].Id == mapId)
        {
        polyData->DeepCopy(this->Datasets[i].Data);
        }
      }
  }

protected:

  void UpdateDequeSize()
  {
    if (this->MaxNumberOfDatasets <= 0)
      {
      return;
      }
    while (this->Datasets.size() >= this->MaxNumberOfDatasets)
      {
      this->Datasets.pop_front();
      }
  }

  void HandleNewData(const drc::map_image_t* msg)
  {
    maps::DepthImageView depthImage;
    maps::LcmTranslator::fromLcm(*msg, depthImage);

    maps::PointCloud::Ptr pointCloud = depthImage.getAsPointCloud();

    MapData mapData;
    mapData.Id = ++this->CurrentMapId;
    mapData.Data = PolyDataFromPointCloud(pointCloud);

    printf("storing depth map id: %d.  %d points\n", mapData.Id, mapData.Data->GetNumberOfPoints());

    // store data
    boost::lock_guard<boost::mutex> lock(this->Mutex);
    this->Datasets.push_back(mapData);
    this->UpdateDequeSize();
    this->NewData = true;
  }

  void HandleNewData(const drc::map_cloud_t* msg)
  {
    maps::PointCloudView cloudView;
    maps::LcmTranslator::fromLcm(*msg, cloudView);

    maps::PointCloud::Ptr pointCloud = cloudView.getAsPointCloud();

    MapData mapData;
    mapData.Id = ++this->CurrentMapId;
    mapData.Data = PolyDataFromPointCloud(pointCloud);

    printf("storing cloud map id: %d.  %d points\n", mapData.Id, mapData.Data->GetNumberOfPoints());

    // store data
    boost::lock_guard<boost::mutex> lock(this->Mutex);
    this->Datasets.push_back(mapData);
    this->UpdateDequeSize();
    this->NewData = true;
  }

  bool NewData;
  bool ShouldStop;
  int MaxNumberOfDatasets;
  vtkIdType CurrentMapId;

  boost::mutex Mutex;

  std::deque<MapData> Datasets;

  boost::shared_ptr<lcm::LCM> LCMHandle;

  boost::shared_ptr<boost::thread> Thread;

};

} // end namespace

//----------------------------------------------------------------------------
class vtkMapServerSource::vtkInternal
{
public:

  vtkInternal()
  {
    this->Listener = boost::shared_ptr<LCMListener>(new LCMListener);
  }

  ~vtkInternal()
  {
  }

  boost::shared_ptr<LCMListener> Listener;
};

//----------------------------------------------------------------------------
vtkStandardNewMacro(vtkMapServerSource);

//----------------------------------------------------------------------------
vtkMapServerSource::vtkMapServerSource()
{
  this->Internal = new vtkInternal;
  this->SetNumberOfInputPorts(0);
  this->SetNumberOfOutputPorts(1);
}

//----------------------------------------------------------------------------
vtkMapServerSource::~vtkMapServerSource()
{
  this->Stop();
  delete this->Internal;
}

//----------------------------------------------------------------------------
void vtkMapServerSource::Start()
{
  this->Internal->Listener->Start();
}

//----------------------------------------------------------------------------
void vtkMapServerSource::Stop()
{
  this->Internal->Listener->Stop();
}

//----------------------------------------------------------------------------
void vtkMapServerSource::Poll()
{
  if (this->Internal->Listener->CheckForNewData())
    {
    this->Modified();
    }
}

//-----------------------------------------------------------------------------
int vtkMapServerSource::GetNumberOfDatasets()
{
  return this->Internal->Listener->GetDatasets().size();
}

//-----------------------------------------------------------------------------
vtkIdType vtkMapServerSource::GetCurrentMapId()
{
  return this->Internal->Listener->GetCurrentMapId();
}

//-----------------------------------------------------------------------------
void vtkMapServerSource::GetDataForMapId(vtkIdType mapId, vtkPolyData* polyData)
{
  return this->Internal->Listener->GetDataForMapId(mapId, polyData);
}

//-----------------------------------------------------------------------------
vtkPolyData* vtkMapServerSource::GetDataset(int i)
{
  return this->Internal->Listener->GetDatasetForTime(i);
}

//-----------------------------------------------------------------------------
int vtkMapServerSource::RequestInformation(vtkInformation *request,
                                     vtkInformationVector **inputVector,
                                     vtkInformationVector *outputVector)
{
  vtkInformation *info = outputVector->GetInformationObject(0);

  printf("requst info\n");

  std::vector<double> timesteps = this->Internal->Listener->GetTimesteps();
  if (timesteps.size())
    {
    double timeRange[2] = {timesteps.front(), timesteps.back()};

    printf("time range: [%f, %f]\n", timeRange[0], timeRange[1]);

    info->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), &timesteps.front(), timesteps.size());
    info->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(), timeRange, 2);
    }
  else
    {
    printf("no timesteps available\n");
    info->Remove(vtkStreamingDemandDrivenPipeline::TIME_STEPS());
    info->Remove(vtkStreamingDemandDrivenPipeline::TIME_RANGE());
    }

  return 1;
}

//----------------------------------------------------------------------------
int vtkMapServerSource::RequestData(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **inputVector,
  vtkInformationVector *outputVector)
{
  printf("request data\n");

  vtkInformation *info = outputVector->GetInformationObject(0);
  vtkDataSet *output = vtkDataSet::SafeDownCast(info->Get(vtkDataObject::DATA_OBJECT()));

  int timestep = 0;
  if (info->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEPS()))
    {
    double timeRequest = info->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEPS())[0];
    timestep = static_cast<int>(floor(timeRequest+0.5));
    }

  vtkSmartPointer<vtkPolyData> polyData = this->Internal->Listener->GetDatasetForTime(timestep);
  if (polyData)
    {
    output->ShallowCopy(polyData);
    }
  else
    {
    printf("no data\n");
    }

  return 1;
}

//----------------------------------------------------------------------------
void vtkMapServerSource::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}
<commit_msg>fix lcm select in vtkMapServerSource.cxx<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkMapServerSource.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkMapServerSource.h"

#include "vtkPolyData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkSmartPointer.h"
#include "vtkTransform.h"
#include "vtkTransformPolyDataFilter.h"
#include "vtkNew.h"

#include <vtkIdList.h>
#include <vtkCellArray.h>
#include <vtkPoints.h>
#include <vtkDoubleArray.h>
#include <vtkFloatArray.h>
#include <vtkPointData.h>

#include <Eigen/Dense>
#include <boost/shared_ptr.hpp>
#include <boost/thread/thread.hpp>

#include <lcm/lcm-cpp.hpp>

//#include <lcmtypes/drc_lcmtypes.hpp>
#include <lcmtypes/drc/map_image_t.hpp>
#include <lcmtypes/drc/map_cloud_t.hpp>

#include <maps/LcmTranslator.hpp>
#include <maps/DepthImageView.hpp>
#include <maps/PointCloudView.hpp>

#include <sys/select.h>
#include <deque>

namespace
{

//----------------------------------------------------------------------------
vtkSmartPointer<vtkCellArray> NewVertexCells(vtkIdType numberOfVerts)
{
  vtkNew<vtkIdTypeArray> cells;
  cells->SetNumberOfValues(numberOfVerts*2);
  vtkIdType* ids = cells->GetPointer(0);
  for (vtkIdType i = 0; i < numberOfVerts; ++i)
    {
    ids[i*2] = 1;
    ids[i*2+1] = i;
    }

  vtkSmartPointer<vtkCellArray> cellArray = vtkSmartPointer<vtkCellArray>::New();
  cellArray->SetCells(numberOfVerts, cells.GetPointer());
  return cellArray;
}

//----------------------------------------------------------------------------
vtkSmartPointer<vtkPolyData> PolyDataFromPointCloud(pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr cloud)
{
  vtkIdType nr_points = cloud->points.size();

  vtkNew<vtkPoints> points;
  points->SetDataTypeToFloat();
  points->SetNumberOfPoints(nr_points);

  vtkNew<vtkUnsignedCharArray> rgbArray;
  rgbArray->SetName("rgb_colors");
  rgbArray->SetNumberOfComponents(3);
  rgbArray->SetNumberOfTuples(nr_points);

  if (cloud->is_dense)
  {
    for (vtkIdType i = 0; i < nr_points; ++i) {
      float point[3] = {cloud->points[i].x, cloud->points[i].y, cloud->points[i].z};
      unsigned char color[3] = {cloud->points[i].r, cloud->points[i].g, cloud->points[i].b};
      points->SetPoint(i, point);
      rgbArray->SetTupleValue(i, color);
    }
  }
  else
  {
    vtkIdType j = 0;    // true point index
    for (vtkIdType i = 0; i < nr_points; ++i)
    {
      // Check if the point is invalid
      if (!pcl_isfinite (cloud->points[i].x) ||
          !pcl_isfinite (cloud->points[i].y) ||
          !pcl_isfinite (cloud->points[i].z))
        continue;

      float point[3] = {cloud->points[i].x, cloud->points[i].y, cloud->points[i].z};
      unsigned char color[3] = {cloud->points[i].r, cloud->points[i].g, cloud->points[i].b};
      points->SetPoint(j, point);
      rgbArray->SetTupleValue(j, color);
      j++;
    }
    nr_points = j;
    points->SetNumberOfPoints(nr_points);
    rgbArray->SetNumberOfTuples(nr_points);
  }

  vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New();
  polyData->SetPoints(points.GetPointer());
  polyData->GetPointData()->AddArray(rgbArray.GetPointer());
  polyData->SetVerts(NewVertexCells(nr_points));
  return polyData;
}

//----------------------------------------------------------------------------
class MapData
{
public:
  uint64_t Id;
  vtkSmartPointer<vtkPolyData> Data;
};

//----------------------------------------------------------------------------
class LCMListener
{
public:

  LCMListener()
  {
    this->ShouldStop = true;
    this->NewData = false;
    this->MaxNumberOfDatasets = 100;
    this->CurrentMapId = -1;

    this->LCMHandle = boost::shared_ptr<lcm::LCM>(new lcm::LCM);
    if(!this->LCMHandle->good())
    {
      std::cerr <<"ERROR: lcm is not good()" <<std::endl;
    }

    this->LCMHandle->subscribe( "MAP_DEPTH", &LCMListener::depthHandler, this);
    this->LCMHandle->subscribe( "MAP_CLOUD", &LCMListener::cloudHandler, this);
  }

  void cloudHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const drc::map_cloud_t* msg)
  {
    this->HandleNewData(msg);
  }

  void depthHandler(const lcm::ReceiveBuffer* rbuf, const std::string& channel, const drc::map_image_t* msg)
  {
    this->HandleNewData(msg);
  }

  bool CheckForNewData()
  {
    boost::lock_guard<boost::mutex> lock(this->Mutex);
    bool newData = this->NewData;
    this->NewData = false;
    return newData;
  }

  bool WaitForLCM(double timeout)
  {
    int lcmFd = this->LCMHandle->getFileno();

    timeval tv;
    tv.tv_sec = 0;
    tv.tv_usec = timeout * 1e6;

    fd_set fds;
    FD_ZERO(&fds);
    FD_SET(lcmFd, &fds);

    int status = select(lcmFd + 1, &fds, 0, 0, &tv);
    if (status == -1 && errno != EINTR)
    {
      printf("select() returned error: %d\n", errno);
    }
    else if (status == -1 && errno == EINTR)
    {
      printf("select() interrupted\n");
    }
    return (status > 0 && FD_ISSET(lcmFd, &fds));
  }

  void ThreadLoopWithSelect()
  {
    while (!this->ShouldStop)
    {
      const double timeoutInSeconds = 0.3;
      bool lcmReady = this->WaitForLCM(timeoutInSeconds);

      if (this->ShouldStop)
      {
        break;
      }

      if (lcmReady)
      {
        if (this->LCMHandle->handle() != 0)
        {
          printf("lcm->handle() returned non-zero\n");
          break;
        }
      }
    }

  }

  void ThreadLoop()
  {
    while (!this->ShouldStop)
    {
      if (this->LCMHandle->handle() != 0)
      {
        printf("lcm->handle() returned non-zero\n");
        break;
      }
    }
  }

  void Start()
  {
    if (this->Thread)
      {
      return;
      }

    printf("starting\n");

    this->ShouldStop = false;
    this->Thread = boost::shared_ptr<boost::thread>(
      new boost::thread(boost::bind(&LCMListener::ThreadLoopWithSelect, this)));
  }

  void Stop()
  {
    if (this->Thread)
      {
      printf("stopping thread...\n");
      this->ShouldStop = true;
      this->Thread->interrupt();
      this->Thread->join();
      this->Thread.reset();
      printf("done.\n");
      }
  }

  std::vector<vtkSmartPointer<vtkPolyData> > GetDatasets()
  {
    std::vector<vtkSmartPointer<vtkPolyData> > datasets;

    boost::lock_guard<boost::mutex> lock(this->Mutex);
    for (size_t i = 0; i < this->Datasets.size(); ++i)
      {
      datasets.push_back(this->Datasets[i].Data);
      }

    return datasets;
  }

  std::vector<double> GetTimesteps()
  {
    boost::lock_guard<boost::mutex> lock(this->Mutex);

    std::vector<double> timesteps;
    for (int i = 0; i < this->Datasets.size(); ++i)
      {
      timesteps.push_back(i);
      }
    return timesteps;
  }

  vtkSmartPointer<vtkPolyData> GetDatasetForTime(int timestep)
  {
    boost::lock_guard<boost::mutex> lock(this->Mutex);
    if (timestep >= 0 && timestep < this->Datasets.size())
      {
      return this->Datasets[timestep].Data;
      }
    else
      {
      return 0;
      }
  }

  vtkIdType GetCurrentMapId()
  {
    return this->CurrentMapId;
  }

  void GetDataForMapId(vtkIdType mapId, vtkPolyData* polyData)
  {
    if (!polyData)
      {
      return;
      }

    boost::lock_guard<boost::mutex> lock(this->Mutex);
    for (size_t i = 0; i < this->Datasets.size(); ++i)
      {
      if (this->Datasets[i].Id == mapId)
        {
        polyData->DeepCopy(this->Datasets[i].Data);
        }
      }
  }

protected:

  void UpdateDequeSize()
  {
    if (this->MaxNumberOfDatasets <= 0)
      {
      return;
      }
    while (this->Datasets.size() >= this->MaxNumberOfDatasets)
      {
      this->Datasets.pop_front();
      }
  }

  void HandleNewData(const drc::map_image_t* msg)
  {
    maps::DepthImageView depthImage;
    maps::LcmTranslator::fromLcm(*msg, depthImage);

    maps::PointCloud::Ptr pointCloud = depthImage.getAsPointCloud();

    MapData mapData;
    mapData.Id = ++this->CurrentMapId;
    mapData.Data = PolyDataFromPointCloud(pointCloud);

    printf("storing depth map id: %d.  %d points\n", mapData.Id, mapData.Data->GetNumberOfPoints());

    // store data
    boost::lock_guard<boost::mutex> lock(this->Mutex);
    this->Datasets.push_back(mapData);
    this->UpdateDequeSize();
    this->NewData = true;
  }

  void HandleNewData(const drc::map_cloud_t* msg)
  {
    maps::PointCloudView cloudView;
    maps::LcmTranslator::fromLcm(*msg, cloudView);

    maps::PointCloud::Ptr pointCloud = cloudView.getAsPointCloud();

    MapData mapData;
    mapData.Id = ++this->CurrentMapId;
    mapData.Data = PolyDataFromPointCloud(pointCloud);

    printf("storing cloud map id: %d.  %d points\n", mapData.Id, mapData.Data->GetNumberOfPoints());

    // store data
    boost::lock_guard<boost::mutex> lock(this->Mutex);
    this->Datasets.push_back(mapData);
    this->UpdateDequeSize();
    this->NewData = true;
  }

  bool NewData;
  bool ShouldStop;
  int MaxNumberOfDatasets;
  vtkIdType CurrentMapId;

  boost::mutex Mutex;

  std::deque<MapData> Datasets;

  boost::shared_ptr<lcm::LCM> LCMHandle;

  boost::shared_ptr<boost::thread> Thread;

};

} // end namespace

//----------------------------------------------------------------------------
class vtkMapServerSource::vtkInternal
{
public:

  vtkInternal()
  {
    this->Listener = boost::shared_ptr<LCMListener>(new LCMListener);
  }

  ~vtkInternal()
  {
  }

  boost::shared_ptr<LCMListener> Listener;
};

//----------------------------------------------------------------------------
vtkStandardNewMacro(vtkMapServerSource);

//----------------------------------------------------------------------------
vtkMapServerSource::vtkMapServerSource()
{
  this->Internal = new vtkInternal;
  this->SetNumberOfInputPorts(0);
  this->SetNumberOfOutputPorts(1);
}

//----------------------------------------------------------------------------
vtkMapServerSource::~vtkMapServerSource()
{
  this->Stop();
  delete this->Internal;
}

//----------------------------------------------------------------------------
void vtkMapServerSource::Start()
{
  this->Internal->Listener->Start();
}

//----------------------------------------------------------------------------
void vtkMapServerSource::Stop()
{
  this->Internal->Listener->Stop();
}

//----------------------------------------------------------------------------
void vtkMapServerSource::Poll()
{
  if (this->Internal->Listener->CheckForNewData())
    {
    this->Modified();
    }
}

//-----------------------------------------------------------------------------
int vtkMapServerSource::GetNumberOfDatasets()
{
  return this->Internal->Listener->GetDatasets().size();
}

//-----------------------------------------------------------------------------
vtkIdType vtkMapServerSource::GetCurrentMapId()
{
  return this->Internal->Listener->GetCurrentMapId();
}

//-----------------------------------------------------------------------------
void vtkMapServerSource::GetDataForMapId(vtkIdType mapId, vtkPolyData* polyData)
{
  return this->Internal->Listener->GetDataForMapId(mapId, polyData);
}

//-----------------------------------------------------------------------------
vtkPolyData* vtkMapServerSource::GetDataset(int i)
{
  return this->Internal->Listener->GetDatasetForTime(i);
}

//-----------------------------------------------------------------------------
int vtkMapServerSource::RequestInformation(vtkInformation *request,
                                     vtkInformationVector **inputVector,
                                     vtkInformationVector *outputVector)
{
  vtkInformation *info = outputVector->GetInformationObject(0);

  printf("requst info\n");

  std::vector<double> timesteps = this->Internal->Listener->GetTimesteps();
  if (timesteps.size())
    {
    double timeRange[2] = {timesteps.front(), timesteps.back()};

    printf("time range: [%f, %f]\n", timeRange[0], timeRange[1]);

    info->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(), &timesteps.front(), timesteps.size());
    info->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(), timeRange, 2);
    }
  else
    {
    printf("no timesteps available\n");
    info->Remove(vtkStreamingDemandDrivenPipeline::TIME_STEPS());
    info->Remove(vtkStreamingDemandDrivenPipeline::TIME_RANGE());
    }

  return 1;
}

//----------------------------------------------------------------------------
int vtkMapServerSource::RequestData(
  vtkInformation *vtkNotUsed(request),
  vtkInformationVector **inputVector,
  vtkInformationVector *outputVector)
{
  printf("request data\n");

  vtkInformation *info = outputVector->GetInformationObject(0);
  vtkDataSet *output = vtkDataSet::SafeDownCast(info->Get(vtkDataObject::DATA_OBJECT()));

  int timestep = 0;
  if (info->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEPS()))
    {
    double timeRequest = info->Get(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEPS())[0];
    timestep = static_cast<int>(floor(timeRequest+0.5));
    }

  vtkSmartPointer<vtkPolyData> polyData = this->Internal->Listener->GetDatasetForTime(timestep);
  if (polyData)
    {
    output->ShallowCopy(polyData);
    }
  else
    {
    printf("no data\n");
    }

  return 1;
}

//----------------------------------------------------------------------------
void vtkMapServerSource::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}
<|endoftext|>


<commit_before>/**
 * @file
 *
 * @brief
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 */

#include "tcl.hpp"

#include <key.hpp>
#include <keyset.hpp>

#include <fstream>

#include "errno.h"

#include <boost/spirit/include/qi_expect.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>

using namespace ckdb;
#include <kdberrors.h>

extern "C" {

int elektraTclGet (Plugin *, KeySet * returned, Key * parentKey)
{
	std::string cur = keyName (parentKey);
	if (cur == "system/elektra/modules/tcl")
	{
		/* get config */
		KeySet * n;
		ksAppend (returned,
			  n = ksNew (30, keyNew ("system/elektra/modules/tcl", KEY_VALUE, "tcl plugin waits for your orders", KEY_END),
				     keyNew ("system/elektra/modules/tcl/exports", KEY_END),
				     keyNew ("system/elektra/modules/tcl/exports/get", KEY_FUNC, elektraTclGet, KEY_END),
				     keyNew ("system/elektra/modules/tcl/exports/set", KEY_FUNC, elektraTclSet, KEY_END),
				     keyNew ("system/elektra/modules/tcl/exports/cpp_serialise", KEY_SIZE, sizeof (&elektra::serialise),
					     KEY_BINARY, KEY_VALUE, &elektra::serialise, KEY_END),
				     keyNew ("system/elektra/modules/tcl/exports/cpp_unserialise", KEY_SIZE, sizeof (&elektra::unserialise),
					     KEY_BINARY, KEY_VALUE, &elektra::unserialise, KEY_END),
#include "readme_tcl.c"
				     keyNew ("system/elektra/modules/tcl/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END));
		ksDel (n);
	}
	/* get all keys */

	int errnosave = errno;
	std::ifstream in (keyString (parentKey), std::ios::binary); // we get our input from this file
	if (!in.is_open ())
	{
		ELEKTRA_SET_ERROR_GET (parentKey);
		errno = errnosave;
		return -1;
	}

	kdb::KeySet input (returned);

	int ret = 0;
	try
	{
		elektra::unserialise (in, input);
	}
	catch (boost::spirit::qi::expectation_failure<boost::spirit::istream_iterator> const & e)
	{
		ELEKTRA_SET_ERROR (61, parentKey,
				   std::string (std::string ("file: ") + keyString (parentKey) +
						" could not be parsed because: " + std::string (e.first, e.last))
					   .c_str ());
		ret = -1;
	}
	catch (std::exception const & e)
	{
		ELEKTRA_SET_ERROR (
			61, parentKey,
			std::string (std::string ("file: ") + keyString (parentKey) + " could not be parsed because: " + e.what ())
				.c_str ());
		ret = -1;
	}
	input.release ();

	return ret;
}

int elektraTclSet (Plugin *, KeySet * returned, Key * parentKey)
{
	/* set all keys */

	int errnosave = errno;
	std::ofstream ofs (keyString (parentKey), std::ios::binary);
	if (!ofs.is_open ())
	{
		ELEKTRA_SET_ERROR_SET (parentKey);
		errno = errnosave;
		return -1;
	}

	kdb::KeySet output (returned);

	elektra::serialise (ofs, output);
	output.release ();

	return 1; /* success */
}

Plugin * ELEKTRA_PLUGIN_EXPORT (tcl)
{
	// clang-format off
	return elektraPluginExport("tcl",
		ELEKTRA_PLUGIN_GET,	&elektraTclGet,
		ELEKTRA_PLUGIN_SET,	&elektraTclSet,
		ELEKTRA_PLUGIN_END);
}

} // end extern "C"
<commit_msg>Tcl: Use C++ `Key` type for parent key<commit_after>/**
 * @file
 *
 * @brief
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 */

#include "tcl.hpp"

#include <key.hpp>
#include <keyset.hpp>

#include <fstream>

#include "errno.h"

#include <boost/spirit/include/qi_expect.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>

using namespace ckdb;
#include <kdberrors.h>

extern "C" {

int elektraTclGet (Plugin *, KeySet * returned, Key * parentKey)
{
	kdb::Key parent (parentKey);
	if (parent.getName () == "system/elektra/modules/tcl")
	{
		/* get config */
		KeySet * n;
		ksAppend (returned,
			  n = ksNew (30, keyNew ("system/elektra/modules/tcl", KEY_VALUE, "tcl plugin waits for your orders", KEY_END),
				     keyNew ("system/elektra/modules/tcl/exports", KEY_END),
				     keyNew ("system/elektra/modules/tcl/exports/get", KEY_FUNC, elektraTclGet, KEY_END),
				     keyNew ("system/elektra/modules/tcl/exports/set", KEY_FUNC, elektraTclSet, KEY_END),
				     keyNew ("system/elektra/modules/tcl/exports/cpp_serialise", KEY_SIZE, sizeof (&elektra::serialise),
					     KEY_BINARY, KEY_VALUE, &elektra::serialise, KEY_END),
				     keyNew ("system/elektra/modules/tcl/exports/cpp_unserialise", KEY_SIZE, sizeof (&elektra::unserialise),
					     KEY_BINARY, KEY_VALUE, &elektra::unserialise, KEY_END),
#include "readme_tcl.c"
				     keyNew ("system/elektra/modules/tcl/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END));
		ksDel (n);
	}
	/* get all keys */

	int errnosave = errno;
	std::ifstream in (parent.getString (), std::ios::binary); // we get our input from this file
	if (!in.is_open ())
	{
		ELEKTRA_SET_ERROR_GET (*parent);
		errno = errnosave;
		parent.release ();
		return -1;
	}

	kdb::KeySet input (returned);

	int ret = 0;
	try
	{
		elektra::unserialise (in, input);
	}
	catch (boost::spirit::qi::expectation_failure<boost::spirit::istream_iterator> const & e)
	{
		ELEKTRA_SET_ERROR (61, *parent,
				   std::string (std::string ("file: ") + parent.getString () +
						" could not be parsed because: " + std::string (e.first, e.last))
					   .c_str ());
		ret = -1;
	}
	catch (std::exception const & e)
	{
		ELEKTRA_SET_ERROR (
			61, *parent,
			std::string (std::string ("file: ") + parent.getString () + " could not be parsed because: " + e.what ()).c_str ());
		ret = -1;
	}
	input.release ();
	parent.release ();

	return ret;
}

int elektraTclSet (Plugin *, KeySet * returned, Key * parentKey)
{
	/* set all keys */

	int errnosave = errno;
	kdb::Key parent (parentKey);
	std::ofstream ofs (parent.getString (), std::ios::binary);
	if (!ofs.is_open ())
	{
		ELEKTRA_SET_ERROR_SET (*parent);
		errno = errnosave;
		return -1;
	}

	kdb::KeySet output (returned);

	elektra::serialise (ofs, output);
	parent.release ();
	output.release ();

	return 1; /* success */
}

Plugin * ELEKTRA_PLUGIN_EXPORT (tcl)
{
	// clang-format off
	return elektraPluginExport("tcl",
		ELEKTRA_PLUGIN_GET,	&elektraTclGet,
		ELEKTRA_PLUGIN_SET,	&elektraTclSet,
		ELEKTRA_PLUGIN_END);
}

} // end extern "C"
<|endoftext|>


<commit_before>#include "../../ppasskeeper-module.h"
#include "../../tokenizer.h"
#include "list_pwd.h"
#include <string>
#include <iostream>

#include <kwallet.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>

//local functions
std::string* last_error()
{
	static std::string last_err;
	return &last_err;
}

void setError(std::string error)
{
	*(last_error())="PPK_KWallet : " + error;
}

extern "C" ppk_boolean isWritable()
{
	return PPK_TRUE;
}

extern "C" ppk_security_level securityLevel(const char* module_id)
{
	return ppk_sec_safe;
}

//Get available flags
extern "C" unsigned int readFlagsAvailable()
{
	return ppk_rf_none|ppk_rf_silent;
}

extern "C" unsigned int writeFlagsAvailable()
{
	return ppk_wf_none|ppk_wf_silent;
}

extern "C" unsigned int listingFlagsAvailable()
{
	return ppk_lf_none|ppk_lf_silent;
}

KWallet::Wallet* openWallet(unsigned int flags)
{
	if(KWallet::Wallet::isEnabled())
	{
		KWallet::Wallet* wallet=NULL;

		//OPen the wallet only if it won't annoy people who don't want to be prompted
		if(KWallet::Wallet::isOpen(KWallet::Wallet::NetworkWallet()) || (int)(flags&ppk_lf_silent)>0 || (int)(flags&ppk_rf_silent)>0 || (int)(flags&ppk_wf_silent)>0)
		{
			wallet=KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(),0);

			//if the wallet is oppened
			if(wallet!=NULL)
			{
				return wallet;
			}
			else
			{
				setError("openWallet : openWallet failed");
				return NULL;
			}
		}
		else
		{
			setError("openWallet : openWallet was not performed because it wasn't silent to do so.");
			return NULL;
		}
	}
	else
	{
		setError("openWallet : KWallet is not available");
		return NULL;
	}
}

const char* _getPassword(const char* key, unsigned int flags)
{
	static QString pwd;

	KWallet::Wallet* wallet=openWallet(flags);
	if(wallet!=NULL)
	{
		//Get the password
		if(wallet->readPassword(key,pwd)==0)
			return pwd.toLocal8Bit().data();
		else
		{
			setError("getPwd : wallet->readPassword failed, key="+toString(key));
			return NULL;
		}
	}
}

bool _setPassword(const char* key, const char* pwd, unsigned int flags)
{
	if((int)(flags&ppk_wf_silent)==0)
	{
		KWallet::Wallet* wallet=openWallet(flags);
		if(wallet!=NULL)
		{
			//Set the password
			if(wallet->writePassword(key,pwd)==0)
				return true;
			else
			{
				setError("getPwd : wallet->writePassword failed, key="+toString(key));
				return false;
			}
		}
	}
	else
		return NULL;
}

bool _removePassword(const char* key, unsigned int flags)
{
	if((int)(flags&ppk_lf_silent)==0)
	{
		KWallet::Wallet* wallet=openWallet(flags);
		if(wallet!=NULL)
		{
			//Set the password
			if(wallet->removeEntry(key)==0)
				return true;
			else
			{
				setError("getPwd : wallet->writePassword failed, key="+toString(key));
				return false;
			}
		}
	}
	else
		return false;
}

bool init_kde(unsigned int flags)
{
	//Init KDE
	KAboutData about(QByteArray("ppasskeeper-kwallet"),QByteArray("ppasskeeper-kwallet"),KLocalizedString(),QByteArray("1.0"));
	KComponentData kcd(about);

	return true;
}
const char* getPassword(const char* key, unsigned int flags)
{
	//Init KDE Application
	if(init_kde(flags))
		return _getPassword(key, flags);
	else
		return NULL;
}

bool setPassword(const char* key, const char* pwd, unsigned int flags)
{
	//Init KDE Application
	if(init_kde(flags))
		return _setPassword(key, pwd, flags);
	else
		return false;
}

bool removePassword(const char* key, unsigned int flags)
{
	//Init KDE Application
	if(init_kde(flags))
		return _removePassword(key, flags);
	else
		return false;
}

std::string prefix(ppk_entry_type type)
{
	static const char* ppk_network_string = "ppasskeeper_network://";
	static const char* ppk_app_string = "ppasskeeper_app://";
	static const char* ppk_item_string = "ppasskeeper_item://";

	switch(type)
	{
		case ppk_network:
			return ppk_network_string;
			break;
		case ppk_application:
			return ppk_app_string;
			break;
		case ppk_item:
			return ppk_item_string;
			break;
	}
	return std::string();
}

std::string generateNetworkKey(std::string server, int port, std::string username)
{
	return prefix(ppk_network)+username+"@"+server+":"+toString(port);
}

std::string generateApplicationKey(std::string application_name, std::string username)
{
	return prefix(ppk_application)+username+"@"+application_name;
}

std::string generateItemKey(std::string key)
{
	return prefix(ppk_item)+key;
}

//functions
extern "C" const char* getModuleID()
{
	return "KWallet4";
}

extern "C" const char* getModuleName()
{
	return "KWallet - Store it into KDE's Wallet";
}

extern "C" const int getABIVersion()
{
	return 1;
}

extern "C" unsigned int getEntryListCount(unsigned int entry_types, unsigned int flags)
{
	//Init KDE Application
	if(init_kde(flags))
	{
		//Open the wallet
		KWallet::Wallet* wallet=openWallet(ppk_rf_silent);
		if(wallet!=NULL)
		{
			static ListPwd pwdl;
			return pwdl.getEntryListCount(wallet, entry_types, flags);
		}
		else
			return 0;
	}
	else
		return 0;
}

extern "C" unsigned int getEntryList(unsigned int entry_types, ppk_entry *entryList, unsigned int nbEntries, unsigned int flags)
{
	//Init KDE Application
	if(init_kde(flags))
	{
		//Open the wallet
		KWallet::Wallet* wallet=openWallet(flags);
		if(wallet!=NULL)
		{
			static ListPwd pwdl;
			return pwdl.getEntryList(wallet, entry_types, entryList, nbEntries, flags);
		}
		else
			return 0;
	}
	else
		return 0;
}

extern "C" ppk_boolean getEntry(const ppk_entry entry, ppk_data *edata, unsigned int flags)
{
	edata->type=ppk_string;
	if(entry.type == ppk_network)
	{
		edata->string=getPassword(generateNetworkKey(entry.net.host, entry.net.port, entry.net.login).c_str(), flags);
		return edata->string!=NULL?PPK_TRUE:PPK_FALSE;
	}
	else if(entry.type == ppk_application)
	{
		edata->string=getPassword(generateApplicationKey(entry.app.app_name, entry.app.username).c_str(), flags);
		return edata->string!=NULL?PPK_TRUE:PPK_FALSE;
	}
	else if(entry.type == ppk_item)
	{
		edata->string=getPassword(generateItemKey(entry.item).c_str(), flags);
		return edata->string!=NULL?PPK_TRUE:PPK_FALSE;
	}
	else
		return PPK_FALSE;
}

extern "C" ppk_boolean setEntry(const ppk_entry entry, const ppk_data edata, unsigned int flags)
{
	if(entry.type == ppk_network)
		return setPassword(generateNetworkKey(entry.net.host, entry.net.port, entry.net.login).c_str(), edata.string, flags)?PPK_TRUE:PPK_FALSE;
	else if(entry.type == ppk_application)
		return setPassword(generateApplicationKey(entry.app.app_name, entry.app.username).c_str(), edata.string, flags)?PPK_TRUE:PPK_FALSE;
	else if(entry.type == ppk_item)
		return setPassword(generateItemKey(entry.item).c_str(), edata.string, flags)?PPK_TRUE:PPK_FALSE;
	else
		return PPK_FALSE;

}

extern "C" ppk_boolean removeEntry(const ppk_entry entry, unsigned int flags)
{
	std::cout << "Debug : KWallet's removeEntry is not implemented yet, please do it ASAP" << std::endl;

	return PPK_FALSE;
}

extern "C" ppk_boolean entryExists(const ppk_entry entry, unsigned int flags)
{
	std::cout << "Debug : KWallet's entryExists is not implemented yet, please do it ASAP" << std::endl;

	return PPK_FALSE;
}

extern "C" unsigned int maxDataSize(ppk_data_type type)
{
	switch(type)
	{
		case ppk_string:
			return -1;
		case ppk_blob:
			return 0;
	}

	return 0;
}

extern "C" const char* getLastError()
{
	return last_error()->c_str();
}
<commit_msg>kwallet : fixed getEntry and ListEntryCount<commit_after>#include "../../ppasskeeper-module.h"
#include "../../tokenizer.h"
#include "list_pwd.h"
#include <string>
#include <iostream>

#include <kwallet.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>

//local functions
std::string* last_error()
{
	static std::string last_err;
	return &last_err;
}

void setError(std::string error)
{
	*(last_error())="PPK_KWallet : " + error;
}

extern "C" ppk_boolean isWritable()
{
	return PPK_TRUE;
}

extern "C" ppk_security_level securityLevel(const char* module_id)
{
	return ppk_sec_safe;
}

//Get available flags
extern "C" unsigned int readFlagsAvailable()
{
	return ppk_rf_none|ppk_rf_silent;
}

extern "C" unsigned int writeFlagsAvailable()
{
	return ppk_wf_none|ppk_wf_silent;
}

extern "C" unsigned int listingFlagsAvailable()
{
	return ppk_lf_none|ppk_lf_silent;
}

KWallet::Wallet* openWallet(unsigned int flags)
{
	if(KWallet::Wallet::isEnabled())
	{
		KWallet::Wallet* wallet=NULL;

		//OPen the wallet only if it won't annoy people who don't want to be prompted
		if(KWallet::Wallet::isOpen(KWallet::Wallet::NetworkWallet()) || (int)(flags&ppk_lf_silent)>0 || (int)(flags&ppk_rf_silent)>0 || (int)(flags&ppk_wf_silent)>0)
		{
			wallet=KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(),0);

			//if the wallet is oppened
			if(wallet!=NULL)
			{
				return wallet;
			}
			else
			{
				setError("openWallet : openWallet failed");
				return NULL;
			}
		}
		else
		{
			setError("openWallet : openWallet was not performed because it wasn't silent to do so.");
			return NULL;
		}
	}
	else
	{
		setError("openWallet : KWallet is not available");
		return NULL;
	}
}

const char* _getPassword(const char* key, unsigned int flags)
{
	static QString pwd;

	KWallet::Wallet* wallet=openWallet(flags);
	if(wallet!=NULL)
	{
		//Get the password
		if(wallet->readPassword(key,pwd)==0)
			return pwd.toLocal8Bit().data();
		else
		{
			setError("getPwd : wallet->readPassword failed, key="+toString(key));
			return NULL;
		}
	}
}

bool _setPassword(const char* key, const char* pwd, unsigned int flags)
{
	if((int)(flags&ppk_wf_silent)==0)
	{
		KWallet::Wallet* wallet=openWallet(flags);
		if(wallet!=NULL)
		{
			//Set the password
			if(wallet->writePassword(key,pwd)==0)
				return true;
			else
			{
				setError("getPwd : wallet->writePassword failed, key="+toString(key));
				return false;
			}
		}
	}
	else
		return NULL;
}

bool _removePassword(const char* key, unsigned int flags)
{
	if((int)(flags&ppk_lf_silent)==0)
	{
		KWallet::Wallet* wallet=openWallet(flags);
		if(wallet!=NULL)
		{
			//Set the password
			if(wallet->removeEntry(key)==0)
				return true;
			else
			{
				setError("getPwd : wallet->removePassword failed, key="+toString(key));
				return false;
			}
		}
	}
	else
		return false;
}

bool init_kde(unsigned int flags)
{
	//Init KDE
	KAboutData about(QByteArray("ppasskeeper-kwallet"),QByteArray("ppasskeeper-kwallet"),KLocalizedString(),QByteArray("1.0"));
	KComponentData kcd(about);

	return true;
}
const char* getPassword(const char* key, unsigned int flags)
{
	//Init KDE Application
	if(init_kde(flags))
		return _getPassword(key, flags);
	else
		return NULL;
}

bool setPassword(const char* key, const char* pwd, unsigned int flags)
{
	//Init KDE Application
	if(init_kde(flags))
		return _setPassword(key, pwd, flags);
	else
		return false;
}

bool removePassword(const char* key, unsigned int flags)
{
	//Init KDE Application
	if(init_kde(flags))
		return _removePassword(key, flags);
	else
		return false;
}

std::string prefix(ppk_entry_type type)
{
	static const char* ppk_network_string = "ppasskeeper_network://";
	static const char* ppk_app_string = "ppasskeeper_app://";
	static const char* ppk_item_string = "ppasskeeper_item://";

	switch(type)
	{
		case ppk_network:
			return ppk_network_string;
			break;
		case ppk_application:
			return ppk_app_string;
			break;
		case ppk_item:
			return ppk_item_string;
			break;
	}
	return std::string();
}

std::string generateNetworkKey(std::string server, int port, std::string username)
{
	return prefix(ppk_network)+username+"@"+server+":"+toString(port);
}

std::string generateApplicationKey(std::string application_name, std::string username)
{
	return prefix(ppk_application)+username+"@"+application_name;
}

std::string generateItemKey(std::string key)
{
	return prefix(ppk_item)+key;
}

//functions
extern "C" const char* getModuleID()
{
	return "KWallet4";
}

extern "C" const char* getModuleName()
{
	return "KWallet - Store it into KDE's Wallet";
}

extern "C" const int getABIVersion()
{
	return 1;
}

extern "C" unsigned int getEntryListCount(unsigned int entry_types, unsigned int flags)
{
	//Init KDE Application
	if(init_kde(flags))
	{
		//Open the wallet
		KWallet::Wallet* wallet=openWallet(ppk_rf_silent);
		if(wallet!=NULL)
		{
			static ListPwd pwdl;
			return pwdl.getEntryListCount(wallet, entry_types, flags);
		}
		else
			return 0;
	}
	else
		return 0;
}

extern "C" unsigned int getEntryList(unsigned int entry_types, ppk_entry *entryList, unsigned int nbEntries, unsigned int flags)
{
	//Init KDE Application
	if(init_kde(flags))
	{
		//Open the wallet
		KWallet::Wallet* wallet=openWallet(flags);
		if(wallet!=NULL)
		{
			static ListPwd pwdl;
			return pwdl.getEntryList(wallet, entry_types, entryList, nbEntries, flags);
		}
		else
			return 0;
	}
	else
		return 0;
}

extern "C" ppk_boolean getEntry(const ppk_entry entry, ppk_data *edata, unsigned int flags)
{
	edata->type=ppk_string;
	if(entry.type == ppk_network)
	{
		edata->string=getPassword(generateNetworkKey(entry.net.host, entry.net.port, entry.net.login).c_str(), flags);
		return edata->string!=NULL?PPK_TRUE:PPK_FALSE;
	}
	else if(entry.type == ppk_application)
	{
		edata->string=getPassword(generateApplicationKey(entry.app.app_name, entry.app.username).c_str(), flags);
		return edata->string!=NULL?PPK_TRUE:PPK_FALSE;
	}
	else if(entry.type == ppk_item)
	{
		edata->string=getPassword(generateItemKey(entry.item).c_str(), flags);
		return edata->string!=NULL?PPK_TRUE:PPK_FALSE;
	}
	else
		return PPK_FALSE;
}

extern "C" ppk_boolean setEntry(const ppk_entry entry, const ppk_data edata, unsigned int flags)
{
	if(entry.type == ppk_network)
		return setPassword(generateNetworkKey(entry.net.host, entry.net.port, entry.net.login).c_str(), edata.string, flags)?PPK_TRUE:PPK_FALSE;
	else if(entry.type == ppk_application)
		return setPassword(generateApplicationKey(entry.app.app_name, entry.app.username).c_str(), edata.string, flags)?PPK_TRUE:PPK_FALSE;
	else if(entry.type == ppk_item)
		return setPassword(generateItemKey(entry.item).c_str(), edata.string, flags)?PPK_TRUE:PPK_FALSE;
	else
		return PPK_FALSE;

}

extern "C" ppk_boolean removeEntry(const ppk_entry entry, unsigned int flags)
{
	if(entry.type == ppk_network)
		return removePassword(generateNetworkKey(entry.net.host, entry.net.port, entry.net.login).c_str(), flags)?PPK_TRUE:PPK_FALSE;
	else if(entry.type == ppk_application)
		return removePassword(generateApplicationKey(entry.app.app_name, entry.app.username).c_str(), flags)?PPK_TRUE:PPK_FALSE;
	else if(entry.type == ppk_item)
		return removePassword(generateItemKey(entry.item).c_str(), flags)?PPK_TRUE:PPK_FALSE;
	else
		return PPK_FALSE;
}

extern "C" ppk_boolean entryExists(const ppk_entry entry, unsigned int flags)
{
	std::cout << "Debug : KWallet's entryExists is not implemented yet, please do it ASAP" << std::endl;

	return PPK_FALSE;
}

extern "C" unsigned int maxDataSize(ppk_data_type type)
{
	switch(type)
	{
		case ppk_string:
			return -1;
		case ppk_blob:
			return 0;
	}

	return 0;
}

extern "C" const char* getLastError()
{
	return last_error()->c_str();
}
<|endoftext|>


<commit_before>#include "../../ppasskeeper-module.h"
#include "../../tokenizer.h"
#include "list_pwd.h"
#include <string>
#include <iostream>

#include <kwallet.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>

//plugin data
KWallet::Wallet* _wallet;

//local functions
std::string* last_error()
{
	static std::string last_err;
	return &last_err;
}

void setError(std::string error)
{
	*(last_error())="PPK_KWallet : " + error;
}

extern "C" void constructor()
{
	//lazy initialization
	_wallet=NULL;

	//Init KDE
	KAboutData about(QByteArray("ppasskeeper-kwallet"),QByteArray("ppasskeeper-kwallet"),KLocalizedString(),QByteArray("1.0"));
	KComponentData kcd(about);
}

extern "C" void destructor()
{
	if (_wallet)
		delete _wallet;
}

extern "C" ppk_boolean isWritable()
{
	return PPK_TRUE;
}

extern "C" ppk_security_level securityLevel(const char* module_id)
{
	return ppk_sec_safe;
}

//Get available flags
extern "C" unsigned int readFlagsAvailable()
{
	return ppk_rf_none|ppk_rf_silent;
}

extern "C" unsigned int writeFlagsAvailable()
{
	return ppk_wf_none|ppk_wf_silent;
}

extern "C" unsigned int listingFlagsAvailable()
{
	return ppk_lf_none|ppk_lf_silent;
}

KWallet::Wallet* openWallet(unsigned int flags)
{
	if (flags & ppk_lf_silent || flags & ppk_rf_silent || flags & ppk_wf_silent)
	{
		//continue only if it won't annoy people who don't want to be prompted
		setError("openWallet : openWallet was not performed because it wasn't silent to do so.");
		return NULL;
	}

	if (_wallet == NULL)
	{
		//lazy init
		_wallet = KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(),0);
		if (_wallet == NULL)
		{
			setError("openWallet : openWallet failed");
			return NULL;
		}
	}

	if (! KWallet::Wallet::isOpen(KWallet::Wallet::NetworkWallet()))
	{
		//is the wallet still open? if not, try to reinitialize it
		delete _wallet;
		_wallet = KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(),0);
		if (_wallet == NULL)
		{
			setError("openWallet : openWallet failed");
			return NULL;
		}
	}

	return _wallet;
}

const char* getPassword(const char* key, unsigned int flags)
{
	static QString pwd;

	KWallet::Wallet* wallet=openWallet(flags);
	if(wallet!=NULL)
	{
		//Get the password
		if(wallet->readPassword(key,pwd)==0)
			return pwd.toLocal8Bit().data();
		else
		{
			setError("Get Entry : wallet->readPassword failed, key="+toString(key));
			return NULL;
		}
	}
	else
		return false;
}

const char* getBlob(const char *key, int *size, unsigned int flags)
{
	static QByteArray blob;

	KWallet::Wallet* wallet=openWallet(flags);
	if(wallet!=NULL)
	{
		if(wallet->readEntry(key, blob)==0)
		{
			*size = blob.size();
			return blob;
		}
	}

	return NULL;
}

bool setPassword(const char* key, const char* pwd, unsigned int flags)
{
	if((int)(flags&ppk_wf_silent)==0)
	{
		KWallet::Wallet* wallet=openWallet(flags);
		if(wallet!=NULL)
		{
			//Set the password
			if(wallet->writePassword(key,pwd)==0)
				return true;
			else
			{
				setError("Set Entry: wallet->writePassword failed, key="+toString(key));
				return false;
			}
		}
	}

	return NULL;
}

bool setBlob(const char *key, const void *data, unsigned long size, unsigned int flags)
{
	if((int)(flags&ppk_wf_silent)==0)
	{
		KWallet::Wallet* wallet=openWallet(flags);
		if(wallet!=NULL)
		{
			//Set the password
			QByteArray blobData((const char *) data, size);
			if(wallet->writeEntry(key, blobData)==0)
				return true;
			else
			{
				setError("Set Entry: wallet->writeEntry failed, key="+toString(key));
				return false;
			}
		}
	}

	return NULL;
}

bool removePassword(const char* key, unsigned int flags)
{
	if((int)(flags&ppk_lf_silent)==0)
	{
		KWallet::Wallet* wallet=openWallet(flags);
		if(wallet!=NULL)
		{
			//Set the password
			if(wallet->removeEntry(key)==0)
				return true;
			else
			{
				setError("Remove Entry : wallet->removeEntry failed, key="+toString(key));
				return false;
			}
		}
	}

	return false;
}

bool passwordExists(const char* key, unsigned int flags)
{
	static QString pwd;

	KWallet::Wallet* wallet=openWallet(flags);
	if(wallet!=NULL)
	{
		//Get the password
		if(wallet->hasEntry(key)==0)
			return true;
		else
		{
			setError("Entry Exists : wallet->hasEntry failed, key="+toString(key));
			return false;
		}
	}
	else
		return false;
}

std::string prefix(ppk_entry_type type)
{
	static const char* ppk_network_string = "ppasskeeper_network://";
	static const char* ppk_app_string = "ppasskeeper_app://";
	static const char* ppk_item_string = "ppasskeeper_item://";

	switch(type)
	{
		case ppk_network:
			return ppk_network_string;
			break;
		case ppk_application:
			return ppk_app_string;
			break;
		case ppk_item:
			return ppk_item_string;
			break;
	}
	return std::string();
}

std::string generateNetworkKey(std::string server, int port, std::string username)
{
	return prefix(ppk_network)+username+"@"+server+":"+toString(port);
}

std::string generateApplicationKey(std::string application_name, std::string username)
{
	return prefix(ppk_application)+username+"@"+application_name;
}

std::string generateItemKey(std::string key)
{
	return prefix(ppk_item)+key;
}

//functions
extern "C" const char* getModuleID()
{
	return "KWallet4";
}

extern "C" const char* getModuleName()
{
	return "KWallet - Store it into KDE's Wallet";
}

extern "C" const int getABIVersion()
{
	return 1;
}

extern "C" unsigned int getEntryListCount(unsigned int entry_types, unsigned int flags)
{
	//Open the wallet
	KWallet::Wallet* wallet=openWallet(ppk_rf_silent);
	if(wallet!=NULL)
	{
		static ListPwd pwdl;
		return pwdl.getEntryListCount(wallet, entry_types, flags);
	}
	else
		return 0;
}

extern "C" unsigned int getEntryList(unsigned int entry_types, ppk_entry *entryList, unsigned int nbEntries, unsigned int flags)
{
	//Open the wallet
	KWallet::Wallet* wallet=openWallet(flags);
	if(wallet!=NULL)
	{
		static ListPwd pwdl;
		return pwdl.getEntryList(wallet, entry_types, entryList, nbEntries, flags);
	}
	else
		return 0;
}

static bool generateKey(const ppk_entry entry, std::string &generatedKey)
{
	switch (entry.type)
	{
	case ppk_network:
		generatedKey = generateNetworkKey(entry.net.host, entry.net.port, entry.net.login);
		break;
	case ppk_application:
		generatedKey = generateApplicationKey(entry.app.app_name, entry.app.username);
		break;
	case ppk_item:
		generatedKey = generateItemKey(entry.item);
		break;
	default:
		return PPK_FALSE;
	}

	return PPK_TRUE;
}

extern "C" ppk_boolean getEntry(const ppk_entry entry, ppk_data *edata, unsigned int flags)
{
	std::string generatedKey;
	if (generateKey(entry, generatedKey) == PPK_FALSE)
	{
		return PPK_FALSE;
	}

	KWallet::Wallet *wallet = openWallet(flags);
	if (wallet == NULL)
		return PPK_FALSE;

	KWallet::Wallet::EntryType entryType = wallet->entryType(generatedKey.c_str());

	if (entryType == KWallet::Wallet::Password)
	{
		edata->type = ppk_string;
		edata->string=getPassword(generatedKey.c_str(), flags);
		return edata->string!=NULL?PPK_TRUE:PPK_FALSE;
	}
	else if (entryType == KWallet::Wallet::Stream)
	{
		int size;
		edata->type = ppk_blob;
		edata->blob.data = (const void *) getBlob(generatedKey.c_str(), &size, flags);
		edata->blob.size = size;
		return edata->blob.data != NULL?PPK_TRUE:PPK_FALSE;
	}

	return PPK_FALSE;
}

extern "C" ppk_boolean setEntry(const ppk_entry entry, const ppk_data edata, unsigned int flags)
{
	std::string generatedKey;
	if (generateKey(entry, generatedKey) == PPK_FALSE)
	{
		return PPK_FALSE;
	}

	if (edata.type == ppk_string)
	{
		return setPassword(generatedKey.c_str(), edata.string, flags)?PPK_TRUE:PPK_FALSE;
	}
	else if (edata.type == ppk_blob)
	{
		return setBlob(generatedKey.c_str(), edata.blob.data, edata.blob.size, flags)?PPK_TRUE:PPK_FALSE;
	}
	else
	{
		return PPK_FALSE;
	}
}

extern "C" ppk_boolean removeEntry(const ppk_entry entry, unsigned int flags)
{
	if(entry.type == ppk_network)
		return removePassword(generateNetworkKey(entry.net.host, entry.net.port, entry.net.login).c_str(), flags)?PPK_TRUE:PPK_FALSE;
	else if(entry.type == ppk_application)
		return removePassword(generateApplicationKey(entry.app.app_name, entry.app.username).c_str(), flags)?PPK_TRUE:PPK_FALSE;
	else if(entry.type == ppk_item)
		return removePassword(generateItemKey(entry.item).c_str(), flags)?PPK_TRUE:PPK_FALSE;
	else
		return PPK_FALSE;
}

extern "C" ppk_boolean entryExists(const ppk_entry entry, unsigned int flags)
{
	if(entry.type == ppk_network)
		return passwordExists(generateNetworkKey(entry.net.host, entry.net.port, entry.net.login).c_str(), flags)?PPK_TRUE:PPK_FALSE;
	else if(entry.type == ppk_application)
		return passwordExists(generateApplicationKey(entry.app.app_name, entry.app.username).c_str(), flags)?PPK_TRUE:PPK_FALSE;
	else if(entry.type == ppk_item)
		return passwordExists(generateItemKey(entry.item).c_str(), flags)?PPK_TRUE:PPK_FALSE;
	else
		return PPK_FALSE;
}

extern "C" unsigned int maxDataSize(ppk_data_type type)
{
	switch(type)
	{
		case ppk_string:
			return -1;
		case ppk_blob:
			return 0;
	}

	return 0;
}

extern "C" const char* getLastError()
{
	return last_error()->c_str();
}
<commit_msg>KWallet fix<commit_after>#include "../../ppasskeeper-module.h"
#include "../../tokenizer.h"
#include "list_pwd.h"
#include <string>
#include <iostream>

#include <kwallet.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <klocale.h>

//plugin data
KWallet::Wallet* _wallet;
QApplication *_app;

//local functions
std::string* last_error()
{
	static std::string last_err;
	return &last_err;
}

void setError(std::string error)
{
	*(last_error())="PPK_KWallet : " + error;
}

extern "C" void constructor()
{
	//lazy initialization
	_wallet=NULL;
	_app=NULL;

	if (! qApp)
	{
		//we are not under a KApplication or a QApplication, so we create one
		int argc = 0;
		_app = new QApplication(argc, (char **) NULL);
	}

	if (! KApplication::instance())
	{
		//we are under QApplication, so do some additional initialization
		KAboutData about(QByteArray("ppasskeeper-kwallet"),QByteArray("ppasskeeper-kwallet"),KLocalizedString(),QByteArray("1.0"));
		KComponentData kcd(about);
		KCmdLineArgs::init(&about);
	}
}

extern "C" void destructor()
{
	if (_wallet)
		delete _wallet;

	if (_app)
		delete _app;
}

extern "C" ppk_boolean isWritable()
{
	return PPK_TRUE;
}

extern "C" ppk_security_level securityLevel(const char* module_id)
{
	return ppk_sec_safe;
}

//Get available flags
extern "C" unsigned int readFlagsAvailable()
{
	return ppk_rf_none|ppk_rf_silent;
}

extern "C" unsigned int writeFlagsAvailable()
{
	return ppk_wf_none|ppk_wf_silent;
}

extern "C" unsigned int listingFlagsAvailable()
{
	return ppk_lf_none|ppk_lf_silent;
}

KWallet::Wallet* openWallet(unsigned int flags)
{
	if (flags & ppk_lf_silent || flags & ppk_rf_silent || flags & ppk_wf_silent)
	{
		//continue only if it won't annoy people who don't want to be prompted
		setError("openWallet : openWallet was not performed because it wasn't silent to do so.");
		return NULL;
	}

	if (_wallet == NULL)
	{
		//lazy init
		_wallet = KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(),0);
		if (_wallet == NULL)
		{
			setError("openWallet : openWallet failed");
			return NULL;
		}
	}

	if (! KWallet::Wallet::isOpen(KWallet::Wallet::NetworkWallet()))
	{
		//is the wallet still open? if not, try to reinitialize it
		delete _wallet;
		_wallet = KWallet::Wallet::openWallet(KWallet::Wallet::NetworkWallet(),0);
		if (_wallet == NULL)
		{
			setError("openWallet : openWallet failed");
			return NULL;
		}
	}

	return _wallet;
}

const char* getPassword(const char* key, unsigned int flags)
{
	static QString pwd;

	KWallet::Wallet* wallet=openWallet(flags);
	if(wallet!=NULL)
	{
		//Get the password
		if(wallet->readPassword(key,pwd)==0)
			return pwd.toLocal8Bit().data();
		else
		{
			setError("Get Entry : wallet->readPassword failed, key="+toString(key));
			return NULL;
		}
	}
	else
		return false;
}

const char* getBlob(const char *key, int *size, unsigned int flags)
{
	static QByteArray blob;

	KWallet::Wallet* wallet=openWallet(flags);
	if(wallet!=NULL)
	{
		if(wallet->readEntry(key, blob)==0)
		{
			*size = blob.size();
			return blob;
		}
	}

	return NULL;
}

bool setPassword(const char* key, const char* pwd, unsigned int flags)
{
	if((int)(flags&ppk_wf_silent)==0)
	{
		KWallet::Wallet* wallet=openWallet(flags);
		if(wallet!=NULL)
		{
			//Set the password
			if(wallet->writePassword(key,pwd)==0)
				return true;
			else
			{
				setError("Set Entry: wallet->writePassword failed, key="+toString(key));
				return false;
			}
		}
	}

	return NULL;
}

bool setBlob(const char *key, const void *data, unsigned long size, unsigned int flags)
{
	if((int)(flags&ppk_wf_silent)==0)
	{
		KWallet::Wallet* wallet=openWallet(flags);
		if(wallet!=NULL)
		{
			//Set the password
			QByteArray blobData((const char *) data, size);
			if(wallet->writeEntry(key, blobData)==0)
				return true;
			else
			{
				setError("Set Entry: wallet->writeEntry failed, key="+toString(key));
				return false;
			}
		}
	}

	return NULL;
}

bool removePassword(const char* key, unsigned int flags)
{
	if((int)(flags&ppk_lf_silent)==0)
	{
		KWallet::Wallet* wallet=openWallet(flags);
		if(wallet!=NULL)
		{
			//Set the password
			if(wallet->removeEntry(key)==0)
				return true;
			else
			{
				setError("Remove Entry : wallet->removeEntry failed, key="+toString(key));
				return false;
			}
		}
	}

	return false;
}

bool passwordExists(const char* key, unsigned int flags)
{
	static QString pwd;

	KWallet::Wallet* wallet=openWallet(flags);
	if(wallet!=NULL)
	{
		//Get the password
		if(wallet->hasEntry(key)==0)
			return true;
		else
		{
			setError("Entry Exists : wallet->hasEntry failed, key="+toString(key));
			return false;
		}
	}
	else
		return false;
}

std::string prefix(ppk_entry_type type)
{
	static const char* ppk_network_string = "ppasskeeper_network://";
	static const char* ppk_app_string = "ppasskeeper_app://";
	static const char* ppk_item_string = "ppasskeeper_item://";

	switch(type)
	{
		case ppk_network:
			return ppk_network_string;
			break;
		case ppk_application:
			return ppk_app_string;
			break;
		case ppk_item:
			return ppk_item_string;
			break;
	}
	return std::string();
}

std::string generateNetworkKey(std::string server, int port, std::string username)
{
	return prefix(ppk_network)+username+"@"+server+":"+toString(port);
}

std::string generateApplicationKey(std::string application_name, std::string username)
{
	return prefix(ppk_application)+username+"@"+application_name;
}

std::string generateItemKey(std::string key)
{
	return prefix(ppk_item)+key;
}

//functions
extern "C" const char* getModuleID()
{
	return "KWallet4";
}

extern "C" const char* getModuleName()
{
	return "KWallet - Store it into KDE's Wallet";
}

extern "C" const int getABIVersion()
{
	return 1;
}

extern "C" unsigned int getEntryListCount(unsigned int entry_types, unsigned int flags)
{
	//Open the wallet
	KWallet::Wallet* wallet=openWallet(ppk_rf_silent);
	if(wallet!=NULL)
	{
		static ListPwd pwdl;
		return pwdl.getEntryListCount(wallet, entry_types, flags);
	}
	else
		return 0;
}

extern "C" unsigned int getEntryList(unsigned int entry_types, ppk_entry *entryList, unsigned int nbEntries, unsigned int flags)
{
	//Open the wallet
	KWallet::Wallet* wallet=openWallet(flags);
	if(wallet!=NULL)
	{
		static ListPwd pwdl;
		return pwdl.getEntryList(wallet, entry_types, entryList, nbEntries, flags);
	}
	else
		return 0;
}

static bool generateKey(const ppk_entry entry, std::string &generatedKey)
{
	switch (entry.type)
	{
	case ppk_network:
		generatedKey = generateNetworkKey(entry.net.host, entry.net.port, entry.net.login);
		break;
	case ppk_application:
		generatedKey = generateApplicationKey(entry.app.app_name, entry.app.username);
		break;
	case ppk_item:
		generatedKey = generateItemKey(entry.item);
		break;
	default:
		return PPK_FALSE;
	}

	return PPK_TRUE;
}

extern "C" ppk_boolean getEntry(const ppk_entry entry, ppk_data *edata, unsigned int flags)
{
	std::string generatedKey;
	if (generateKey(entry, generatedKey) == PPK_FALSE)
	{
		return PPK_FALSE;
	}

	KWallet::Wallet *wallet = openWallet(flags);
	if (wallet == NULL)
		return PPK_FALSE;

	KWallet::Wallet::EntryType entryType = wallet->entryType(generatedKey.c_str());

	if (entryType == KWallet::Wallet::Password)
	{
		edata->type = ppk_string;
		edata->string=getPassword(generatedKey.c_str(), flags);
		return edata->string!=NULL?PPK_TRUE:PPK_FALSE;
	}
	else if (entryType == KWallet::Wallet::Stream)
	{
		int size;
		edata->type = ppk_blob;
		edata->blob.data = (const void *) getBlob(generatedKey.c_str(), &size, flags);
		edata->blob.size = size;
		return edata->blob.data != NULL?PPK_TRUE:PPK_FALSE;
	}

	return PPK_FALSE;
}

extern "C" ppk_boolean setEntry(const ppk_entry entry, const ppk_data edata, unsigned int flags)
{
	std::string generatedKey;
	if (generateKey(entry, generatedKey) == PPK_FALSE)
	{
		return PPK_FALSE;
	}

	if (edata.type == ppk_string)
	{
		return setPassword(generatedKey.c_str(), edata.string, flags)?PPK_TRUE:PPK_FALSE;
	}
	else if (edata.type == ppk_blob)
	{
		return setBlob(generatedKey.c_str(), edata.blob.data, edata.blob.size, flags)?PPK_TRUE:PPK_FALSE;
	}
	else
	{
		return PPK_FALSE;
	}
}

extern "C" ppk_boolean removeEntry(const ppk_entry entry, unsigned int flags)
{
	if(entry.type == ppk_network)
		return removePassword(generateNetworkKey(entry.net.host, entry.net.port, entry.net.login).c_str(), flags)?PPK_TRUE:PPK_FALSE;
	else if(entry.type == ppk_application)
		return removePassword(generateApplicationKey(entry.app.app_name, entry.app.username).c_str(), flags)?PPK_TRUE:PPK_FALSE;
	else if(entry.type == ppk_item)
		return removePassword(generateItemKey(entry.item).c_str(), flags)?PPK_TRUE:PPK_FALSE;
	else
		return PPK_FALSE;
}

extern "C" ppk_boolean entryExists(const ppk_entry entry, unsigned int flags)
{
	if(entry.type == ppk_network)
		return passwordExists(generateNetworkKey(entry.net.host, entry.net.port, entry.net.login).c_str(), flags)?PPK_TRUE:PPK_FALSE;
	else if(entry.type == ppk_application)
		return passwordExists(generateApplicationKey(entry.app.app_name, entry.app.username).c_str(), flags)?PPK_TRUE:PPK_FALSE;
	else if(entry.type == ppk_item)
		return passwordExists(generateItemKey(entry.item).c_str(), flags)?PPK_TRUE:PPK_FALSE;
	else
		return PPK_FALSE;
}

extern "C" unsigned int maxDataSize(ppk_data_type type)
{
	switch(type)
	{
		case ppk_string:
			return -1;
		case ppk_blob:
			return 0;
	}

	return 0;
}

extern "C" const char* getLastError()
{
	return last_error()->c_str();
}
<|endoftext|>