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

  Program:   Visualization Toolkit
  Module:    vtkSelectionSource.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 "vtkSelectionSource.h"

#include "vtkCommand.h"
#include "vtkIdTypeArray.h"
#include "vtkDoubleArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkSelection.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkTrivialProducer.h"

#include "vtkstd/vector"
#include "vtkstd/set"

vtkCxxRevisionMacro(vtkSelectionSource, "1.9");
vtkStandardNewMacro(vtkSelectionSource);

class vtkSelectionSourceInternals
{
public:
  vtkSelectionSourceInternals()
    {
    this->Values = NULL;
    }

  ~vtkSelectionSourceInternals()
    {
    if (this->Values)
      {
      this->Values->Delete();
      }
    }

  typedef vtkstd::set<vtkIdType> IDSetType;
  typedef vtkstd::vector<IDSetType> IDsType;
  IDsType IDs;

  vtkAbstractArray *Values;
};

//----------------------------------------------------------------------------
vtkSelectionSource::vtkSelectionSource()
{
  this->SetNumberOfInputPorts(0);
  this->Internal = new vtkSelectionSourceInternals;

  this->ContentType = vtkSelection::INDICES;
  this->FieldType = vtkSelection::CELL;
}

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

//----------------------------------------------------------------------------
void vtkSelectionSource::RemoveAllIDs()
{
  this->Internal->IDs.clear();
  this->Modified();
}

//----------------------------------------------------------------------------
void vtkSelectionSource::RemoveAllValues()
{
  if (this->Internal->Values)
    {
    this->Internal->Values->Reset();
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkSelectionSource::AddID(vtkIdType proc, vtkIdType id)
{
  if (this->ContentType != vtkSelection::GLOBALIDS &&
      this->ContentType != vtkSelection::INDICES)
    {
    return;
    }

  // proc == -1 means all processes. All other are stored at index proc+1
  proc++;

  if (proc >= (vtkIdType)this->Internal->IDs.size())
    {
    this->Internal->IDs.resize(proc+1);
    }
  vtkSelectionSourceInternals::IDSetType& idSet = this->Internal->IDs[proc];
  idSet.insert(id);
  this->Modified();
}

//----------------------------------------------------------------------------
void vtkSelectionSource::AddLocation(double x, double y, double z)
{
  if (this->ContentType != vtkSelection::LOCATIONS)
    {
    this->SetContentType(vtkSelection::LOCATIONS);
    }

  vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values);
  if (da)
    {
    da->InsertNextTuple3(x,y,z);
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkSelectionSource::AddThreshold(double min, double max)
{
  if (this->ContentType != vtkSelection::THRESHOLDS)
    {
    this->SetContentType(vtkSelection::THRESHOLDS);
    }

  vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values);
  if (da)
    {
    da->InsertNextValue(min);
    da->InsertNextValue(max);
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkSelectionSource::SetFrustum(double *vertices)
{
  if (this->ContentType != vtkSelection::FRUSTUM)
    {
    this->SetContentType(vtkSelection::FRUSTUM);
    }

  vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values);
  if (da)
    {
    double *data = da->GetPointer(0);
    memcpy(data, vertices, 32*sizeof(double));
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkSelectionSource::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "ContentType: " ;
  switch (this->ContentType)
    {
  case vtkSelection::SELECTIONS:
    os << "SELECTIONS";
    break;
  case vtkSelection::COMPOSITE_SELECTIONS:
    os << "COMPOSITE_SELECTIONS";
    break;
  case vtkSelection::GLOBALIDS:
    os << "GLOBALIDS";
    break;
  case vtkSelection::VALUES:
    os << "VALUES";
    break;
  case vtkSelection::INDICES:
    os << "INDICES";
    break;
  case vtkSelection::FRUSTUM:
    os << "FRUSTUM";
    break;
  case vtkSelection::LOCATIONS:
    os << "LOCATIONS";
    break;
  case vtkSelection::THRESHOLDS:
    os << "THRESHOLDS";
    break;
  default:
    os << "UNKNOWN";
    }
  os << endl;

  os << indent << "FieldType: " ;
  switch (this->FieldType)
    {
  case vtkSelection::CELL:
    os << "CELL";
    break;
  case vtkSelection::POINT:
    os << "POINT";
    break;
  default:
    os << "UNKNOWN";
    }
  os << endl;
}

//----------------------------------------------------------------------------
int vtkSelectionSource::RequestInformation(
  vtkInformation* vtkNotUsed(request),
  vtkInformationVector** vtkNotUsed(inputVector),
  vtkInformationVector* outputVector)
{
  // We can handle multiple piece request.
  vtkInformation* info = outputVector->GetInformationObject(0);
  info->Set(
    vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(), -1);

  return 1;
}

//----------------------------------------------------------------------------
int vtkSelectionSource::RequestData(
  vtkInformation* vtkNotUsed( request ),
  vtkInformationVector** vtkNotUsed( inputVector ),
  vtkInformationVector* outputVector )
{
  vtkSelection* output = vtkSelection::GetData(outputVector);

  vtkInformation* outInfo = outputVector->GetInformationObject(0);
  int piece = 0;
  if (outInfo->Has(
        vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()))
    {
    piece = outInfo->Get(
      vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER());
    }

  if (
    (this->ContentType == vtkSelection::GLOBALIDS) ||
    (this->ContentType == vtkSelection::INDICES))
    {

    // Number of selected items common to all pieces
    vtkIdType numCommonElems = 0;
    if (!this->Internal->IDs.empty())
      {
      numCommonElems = this->Internal->IDs[0].size();
      }
    if (piece+1 >= (int)this->Internal->IDs.size() &&
        numCommonElems == 0)
      {
      vtkDebugMacro("No selection for piece: " << piece);
      return 1;
      }

    // idx == 0 is the list for all pieces
    // idx == piece+1 is the list for the current piece
    size_t pids[2] = {0, piece+1};
    for(int i=0; i<2; i++)
      {
      size_t idx = pids[i];
      if (idx >= this->Internal->IDs.size())
        {
        continue;
        }

      vtkSelectionSourceInternals::IDSetType& selSet =
        this->Internal->IDs[idx];

      if (selSet.size() > 0)
        {
        output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(),
                                     this->ContentType);
        output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),
                                     this->FieldType);
        // Create the selection list
        vtkIdTypeArray* selectionList = vtkIdTypeArray::New();
        selectionList->SetNumberOfTuples(selSet.size());
        // iterate over ids and insert to the selection list
        vtkSelectionSourceInternals::IDSetType::iterator iter =
          selSet.begin();
        for (vtkIdType idx2=0; iter != selSet.end(); iter++, idx2++)
          {
          selectionList->SetValue(idx2, *iter);
          }
        output->SetSelectionList(selectionList);
        selectionList->Delete();
        }
      }
    }

  if (
    (this->ContentType == vtkSelection::LOCATIONS)
    &&
    (this->Internal->Values != 0)
    )
    {
    output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(),
                                 this->ContentType);
    output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),
                                 this->FieldType);
    // Create the selection list
    vtkAbstractArray* selectionList = this->Internal->Values->NewInstance();
    selectionList->DeepCopy(this->Internal->Values);
    output->SetSelectionList(selectionList);
    selectionList->Delete();
    }

  if (
    (this->ContentType == vtkSelection::THRESHOLDS)
    &&
    (this->Internal->Values != 0)
    )
    {
    output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(),
                                 this->ContentType);
    output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),
                                 this->FieldType);
    // Create the selection list
    vtkAbstractArray* selectionList = this->Internal->Values->NewInstance();
    selectionList->DeepCopy(this->Internal->Values);
    output->SetSelectionList(selectionList);
    selectionList->Delete();
    }

  if (
    (this->ContentType == vtkSelection::FRUSTUM)
    &&
    (this->Internal->Values != 0)
    )
    {
    output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(),
                                 this->ContentType);
    output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),
                                 this->FieldType);
    // Create the selection list
    vtkAbstractArray* selectionList = this->Internal->Values->NewInstance();
    selectionList->DeepCopy(this->Internal->Values);
    output->SetSelectionList(selectionList);
    selectionList->Delete();
    }

  return 1;
}

//------------------------------------------------------------------------------
void vtkSelectionSource::SetContentType(int value)
{
  vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting ContentType to " << value);
  if (this->ContentType != value)
    {
    this->ContentType = value;
    this->RemoveAllIDs();
    this->RemoveAllValues();
    if (this->Internal->Values)
      {
      this->Internal->Values->Delete();
      }
    switch (value)
      {
      case vtkSelection::LOCATIONS:
        {
        vtkDoubleArray *da = vtkDoubleArray::New();
        da->SetNumberOfComponents(3);
        da->SetNumberOfTuples(0);
        this->Internal->Values = da;
        break;
        }
      case vtkSelection::THRESHOLDS:
        {
        vtkDoubleArray *da = vtkDoubleArray::New();
        da->SetNumberOfComponents(1);
        da->SetNumberOfTuples(0);
        this->Internal->Values = da;
        break;
        }
      case vtkSelection::FRUSTUM:
        {
        vtkDoubleArray *da = vtkDoubleArray::New();
        da->SetNumberOfComponents(4);
        da->SetNumberOfTuples(8);
        this->Internal->Values = da;
        break;
        }
      default:
        break;
      }
    this->Modified();
    }
}
<commit_msg>BUG: Fix surface selection<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkSelectionSource.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 "vtkSelectionSource.h"

#include "vtkCommand.h"
#include "vtkIdTypeArray.h"
#include "vtkDoubleArray.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkSelection.h"
#include "vtkStreamingDemandDrivenPipeline.h"
#include "vtkTrivialProducer.h"

#include "vtkstd/vector"
#include "vtkstd/set"

vtkCxxRevisionMacro(vtkSelectionSource, "1.10");
vtkStandardNewMacro(vtkSelectionSource);

class vtkSelectionSourceInternals
{
public:
  vtkSelectionSourceInternals()
    {
    this->Values = NULL;
    }

  ~vtkSelectionSourceInternals()
    {
    if (this->Values)
      {
      this->Values->Delete();
      }
    }

  typedef vtkstd::set<vtkIdType> IDSetType;
  typedef vtkstd::vector<IDSetType> IDsType;
  IDsType IDs;

  vtkAbstractArray *Values;
};

//----------------------------------------------------------------------------
vtkSelectionSource::vtkSelectionSource()
{
  this->SetNumberOfInputPorts(0);
  this->Internal = new vtkSelectionSourceInternals;

  this->ContentType = vtkSelection::INDICES;
  this->FieldType = vtkSelection::CELL;
}

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

//----------------------------------------------------------------------------
void vtkSelectionSource::RemoveAllIDs()
{
  this->Internal->IDs.clear();
  this->Modified();
}

//----------------------------------------------------------------------------
void vtkSelectionSource::RemoveAllValues()
{
  if (this->Internal->Values)
    {
    this->Internal->Values->Reset();
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkSelectionSource::AddID(vtkIdType proc, vtkIdType id)
{
  if (this->ContentType != vtkSelection::GLOBALIDS &&
      this->ContentType != vtkSelection::INDICES)
    {
    return;
    }

  // proc == -1 means all processes. All other are stored at index proc+1
  proc++;

  if (proc >= (vtkIdType)this->Internal->IDs.size())
    {
    this->Internal->IDs.resize(proc+1);
    }
  vtkSelectionSourceInternals::IDSetType& idSet = this->Internal->IDs[proc];
  idSet.insert(id);
  this->Modified();
}

//----------------------------------------------------------------------------
void vtkSelectionSource::AddLocation(double x, double y, double z)
{
  if (this->ContentType != vtkSelection::LOCATIONS)
    {
    return;
    }

  vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values);
  if (da)
    {
    da->InsertNextTuple3(x,y,z);
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkSelectionSource::AddThreshold(double min, double max)
{
  if (this->ContentType != vtkSelection::THRESHOLDS)
    {
    return;
    }

  vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values);
  if (da)
    {
    da->InsertNextValue(min);
    da->InsertNextValue(max);
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkSelectionSource::SetFrustum(double *vertices)
{
  if (this->ContentType != vtkSelection::FRUSTUM)
    {
    return;
    }

  vtkDoubleArray *da = vtkDoubleArray::SafeDownCast(this->Internal->Values);
  if (da)
    {
    double *data = da->GetPointer(0);
    memcpy(data, vertices, 32*sizeof(double));
    this->Modified();
    }
}

//----------------------------------------------------------------------------
void vtkSelectionSource::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "ContentType: " ;
  switch (this->ContentType)
    {
  case vtkSelection::SELECTIONS:
    os << "SELECTIONS";
    break;
  case vtkSelection::COMPOSITE_SELECTIONS:
    os << "COMPOSITE_SELECTIONS";
    break;
  case vtkSelection::GLOBALIDS:
    os << "GLOBALIDS";
    break;
  case vtkSelection::VALUES:
    os << "VALUES";
    break;
  case vtkSelection::INDICES:
    os << "INDICES";
    break;
  case vtkSelection::FRUSTUM:
    os << "FRUSTUM";
    break;
  case vtkSelection::LOCATIONS:
    os << "LOCATIONS";
    break;
  case vtkSelection::THRESHOLDS:
    os << "THRESHOLDS";
    break;
  default:
    os << "UNKNOWN";
    }
  os << endl;

  os << indent << "FieldType: " ;
  switch (this->FieldType)
    {
  case vtkSelection::CELL:
    os << "CELL";
    break;
  case vtkSelection::POINT:
    os << "POINT";
    break;
  default:
    os << "UNKNOWN";
    }
  os << endl;
}

//----------------------------------------------------------------------------
int vtkSelectionSource::RequestInformation(
  vtkInformation* vtkNotUsed(request),
  vtkInformationVector** vtkNotUsed(inputVector),
  vtkInformationVector* outputVector)
{
  // We can handle multiple piece request.
  vtkInformation* info = outputVector->GetInformationObject(0);
  info->Set(
    vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(), -1);

  return 1;
}

//----------------------------------------------------------------------------
int vtkSelectionSource::RequestData(
  vtkInformation* vtkNotUsed( request ),
  vtkInformationVector** vtkNotUsed( inputVector ),
  vtkInformationVector* outputVector )
{
  vtkSelection* output = vtkSelection::GetData(outputVector);

  vtkInformation* outInfo = outputVector->GetInformationObject(0);
  int piece = 0;
  if (outInfo->Has(
        vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()))
    {
    piece = outInfo->Get(
      vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER());
    }

  if (
    (this->ContentType == vtkSelection::GLOBALIDS) ||
    (this->ContentType == vtkSelection::INDICES))
    {

    // Number of selected items common to all pieces
    vtkIdType numCommonElems = 0;
    if (!this->Internal->IDs.empty())
      {
      numCommonElems = this->Internal->IDs[0].size();
      }
    if (piece+1 >= (int)this->Internal->IDs.size() &&
        numCommonElems == 0)
      {
      vtkDebugMacro("No selection for piece: " << piece);
      return 1;
      }

    // idx == 0 is the list for all pieces
    // idx == piece+1 is the list for the current piece
    size_t pids[2] = {0, piece+1};
    for(int i=0; i<2; i++)
      {
      size_t idx = pids[i];
      if (idx >= this->Internal->IDs.size())
        {
        continue;
        }

      vtkSelectionSourceInternals::IDSetType& selSet =
        this->Internal->IDs[idx];

      if (selSet.size() > 0)
        {
        output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(),
                                     this->ContentType);
        output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),
                                     this->FieldType);
        // Create the selection list
        vtkIdTypeArray* selectionList = vtkIdTypeArray::New();
        selectionList->SetNumberOfTuples(selSet.size());
        // iterate over ids and insert to the selection list
        vtkSelectionSourceInternals::IDSetType::iterator iter =
          selSet.begin();
        for (vtkIdType idx2=0; iter != selSet.end(); iter++, idx2++)
          {
          selectionList->SetValue(idx2, *iter);
          }
        output->SetSelectionList(selectionList);
        selectionList->Delete();
        }
      }
    }

  if (
    (this->ContentType == vtkSelection::LOCATIONS)
    &&
    (this->Internal->Values != 0)
    )
    {
    output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(),
                                 this->ContentType);
    output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),
                                 this->FieldType);
    // Create the selection list
    vtkAbstractArray* selectionList = this->Internal->Values->NewInstance();
    selectionList->DeepCopy(this->Internal->Values);
    output->SetSelectionList(selectionList);
    selectionList->Delete();
    }

  if (
    (this->ContentType == vtkSelection::THRESHOLDS)
    &&
    (this->Internal->Values != 0)
    )
    {
    output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(),
                                 this->ContentType);
    output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),
                                 this->FieldType);
    // Create the selection list
    vtkAbstractArray* selectionList = this->Internal->Values->NewInstance();
    selectionList->DeepCopy(this->Internal->Values);
    output->SetSelectionList(selectionList);
    selectionList->Delete();
    }

  if (
    (this->ContentType == vtkSelection::FRUSTUM)
    &&
    (this->Internal->Values != 0)
    )
    {
    output->GetProperties()->Set(vtkSelection::CONTENT_TYPE(),
                                 this->ContentType);
    output->GetProperties()->Set(vtkSelection::FIELD_TYPE(),
                                 this->FieldType);
    // Create the selection list
    vtkAbstractArray* selectionList = this->Internal->Values->NewInstance();
    selectionList->DeepCopy(this->Internal->Values);
    output->SetSelectionList(selectionList);
    selectionList->Delete();
    }

  return 1;
}

//------------------------------------------------------------------------------
void vtkSelectionSource::SetContentType(int value)
{
  vtkDebugMacro(<< this->GetClassName() << " (" << this << "): setting ContentType to " << value);
  if (this->ContentType != value)
    {
    this->ContentType = value;
    this->RemoveAllIDs();
    this->RemoveAllValues();
    if (this->Internal->Values)
      {
      this->Internal->Values->Delete();
      }
    switch (value)
      {
      case vtkSelection::LOCATIONS:
        {
        vtkDoubleArray *da = vtkDoubleArray::New();
        da->SetNumberOfComponents(3);
        da->SetNumberOfTuples(0);
        this->Internal->Values = da;
        break;
        }
      case vtkSelection::THRESHOLDS:
        {
        vtkDoubleArray *da = vtkDoubleArray::New();
        da->SetNumberOfComponents(1);
        da->SetNumberOfTuples(0);
        this->Internal->Values = da;
        break;
        }
      case vtkSelection::FRUSTUM:
        {
        vtkDoubleArray *da = vtkDoubleArray::New();
        da->SetNumberOfComponents(4);
        da->SetNumberOfTuples(8);
        this->Internal->Values = da;
        break;
        }
      default:
        break;
      }
    this->Modified();
    }
}
<|endoftext|>


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

/*
 * Turn off DEBUG Assertions
 */
#ifdef _DEBUG
    #define _DEBUG_WAS_DEFINED _DEBUG
    #undef _DEBUG
#else
    #undef _DEBUG_WAS_DEFINED
#endif

/*
 * and turn off the additional virtual methods which are part of some interfaces when compiled
 * with debug
 */
#ifdef DEBUG
    #define DEBUG_WAS_DEFINED DEBUG
    #undef DEBUG
#else
    #undef DEBUG_WAS_DEFINED
#endif

/*
 * header files needed for getCurrentProfilePath
 */
/*
#include "nsIServiceManager.h"
#include "nsIProfileInternal.h"
#include "nsString.h"
#include "nsEmbedAPI.h"
*/

#include <sal/types.h>

#include "seinitializer_nssimpl.hxx"

#include "securityenvironment_nssimpl.hxx"

#include "nspr.h"
#include "prtypes.h"
#include "pk11func.h"
#include "cert.h"
#include "cryptohi.h"
#include "certdb.h"
#include "nss.h"

namespace cssu = com::sun::star::uno;
namespace cssl = com::sun::star::lang;
namespace cssxc = com::sun::star::xml::crypto;

using namespace com::sun::star;

#define SERVICE_NAME "com.sun.star.xml.crypto.SEInitializer"
#define IMPLEMENTATION_NAME "com.sun.star.xml.security.bridge.xmlsec.SEInitializer_NssImpl"
#define SECURITY_ENVIRONMENT "com.sun.star.xml.crypto.SecurityEnvironment"
#define SECURITY_CONTEXT "com.sun.star.xml.crypto.XMLSecurityContext"

/*
 * MM : get the current user profile
 */

// MM : By now, the XPCOM is initialized only once in the current thread, and it will
//      not be shutdown until StarOffice exits.
//      This is a bug, because any other component who will initialize the XPCOM afterward
//      will always fail.
//      This bug will be fixed when there is solution.
#if 0
static nsIServiceManager           *sServiceManager = nsnull;
static nsIDirectoryServiceProvider *appFileLocProvider = nsnull;
static NS_DEFINE_CID(kProfileCID, NS_PROFILE_CID);

char* getCurrentProfilePath( )
{
/*
        nsCOMPtr<nsILocalFile> binDir;

        // Note: if getenv() returns NULL, mozilla will default to using MOZILLA_FIVE_HOME in the NS_InitXPCOM2()
        // The NS_NewNativeLocalFile() will accept NULL as its first parameter.
        char * env = getenv("OPENOFFICE_MOZILLA_FIVE_HOME");
        if (env)
        {
        nsDependentCString sPath(env);
        nsresult rv = NS_NewNativeLocalFile(sPath, PR_TRUE, getter_AddRefs(binDir));
        if (NS_FAILED(rv))
            return NULL;
        }

    if (sServiceManager == nsnull)
    {
        NS_InitXPCOM2(&sServiceManager, binDir, appFileLocProvider);
    }

    if (!sServiceManager)
        return NULL;

    nsresult rv;
    nsCOMPtr< nsIProfile > theProfile = do_GetService( kProfileCID, &rv );
    if (NS_SUCCEEDED(rv))
    {
        nsXPIDLString profileName;
        rv = theProfile->GetCurrentProfile(getter_Copies(profileName));
        if (NS_SUCCEEDED(rv))
        {
            nsCOMPtr<nsIFile> curProfileDir;
            PRBool exists = PR_FALSE;
            nsCOMPtr<nsIProfileInternal> profileInternal=do_QueryInterface(theProfile);
            if (NS_SUCCEEDED(rv))
            {
                rv = profileInternal->GetProfileDir(profileName, getter_AddRefs(curProfileDir));
                if (NS_SUCCEEDED(rv))
                {
                    nsCOMPtr<nsILocalFile> localFile(do_QueryInterface(curProfileDir));

                    nsAutoString path;
                    rv = localFile->GetPath(path);
                    if (NS_SUCCEEDED(rv))
                    {
                        char cs[1024];
                        path.ToCString(cs, 1024);

                        // MM : I can't shutdown, because the XPCom can't be initialized twice in
                        //      one program
                        //NS_RELEASE(sServiceManager);
                        //NS_ShutdownXPCOM(sServiceManager);

                        return (strdup(cs));
                    }
                }
            }
        }
    }

    // MM : I can't shutdown, because the XPCom can't be initialized twice in
    //      one program
    //NS_RELEASE(sServiceManager);
    //NS_ShutdownXPCOM(sServiceManager);
    */

    return NULL;
}

/*
 * get the current user profile (end)
 */

#endif

bool getMozillaCurrentProfile(rtl::OUString& profilePath);

SEInitializer_NssImpl::SEInitializer_NssImpl(
    const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > &rxMSF)
    :mxMSF( rxMSF )
{
}

SEInitializer_NssImpl::~SEInitializer_NssImpl()
{
}

/* XSEInitializer */
cssu::Reference< cssxc::XXMLSecurityContext > SAL_CALL
    SEInitializer_NssImpl::createSecurityContext(
    const rtl::OUString& sCertDB )
    throw (cssu::RuntimeException)
{
    CERTCertDBHandle*   pCertHandle = NULL ;
    PK11SlotInfo*       pSlot = NULL ;

    rtl::OString sCertDir;
    if( sCertDB.getLength() > 0 )
    {
        sCertDir = rtl::OString(sCertDB, sCertDB.getLength(), RTL_TEXTENCODING_ASCII_US);
    }
    else
    {
        if (!getMozillaCurrentProfile((rtl::OUString&)sCertDir))
        {
            return NULL;
        }

        /*
        char *pCurrentProfilePath = getCurrentProfilePath();

        if (pCurrentProfilePath == NULL)
        {
            return NULL;
        }
        else
        {
            sCertDir = rtl::OString(pCurrentProfilePath);
            free(pCurrentProfilePath);
        }
        */
    }

    /* Initialize NSPR and NSS */
    PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1 ) ;

    if (NSS_Init(sCertDir.getStr()) != SECSuccess )
    {
        PK11_LogoutAll();
        return NULL;
    }

    pCertHandle = CERT_GetDefaultCertDB() ;
    pSlot = PK11_GetInternalKeySlot() ;

    if (pSlot == NULL)
    {
        PK11_LogoutAll();
        NSS_Shutdown();
        return NULL;
    }

    PK11SymKey* pSymKey = PK11_KeyGen( pSlot , CKM_DES3_CBC, NULL, 128, NULL ) ;
    if( pSymKey == NULL )
    {
        PK11_FreeSlot( pSlot ) ;
        PK11_LogoutAll();
        NSS_Shutdown();
        return NULL;
    }

    try
    {
        /* Build Security Environment */
        const rtl::OUString sSecyrutyEnvironment ( RTL_CONSTASCII_USTRINGPARAM( SECURITY_ENVIRONMENT ) );
        cssu::Reference< cssxc::XSecurityEnvironment > xSecEnv( mxMSF->createInstance ( sSecyrutyEnvironment ), cssu::UNO_QUERY );
        if( !xSecEnv.is() )
        {
            PK11_FreeSymKey( pSymKey ) ;
            PK11_FreeSlot( pSlot ) ;
            PK11_LogoutAll();
            NSS_Shutdown();
            return NULL;
        }

        /* Setup key slot and certDb */
        cssu::Reference< cssl::XUnoTunnel > xEnvTunnel( xSecEnv , cssu::UNO_QUERY ) ;
        if( !xEnvTunnel.is() )
        {
            PK11_FreeSymKey( pSymKey ) ;
            PK11_FreeSlot( pSlot ) ;
            PK11_LogoutAll();
            NSS_Shutdown();
            return NULL;
        }

        SecurityEnvironment_NssImpl* pSecEnv = ( SecurityEnvironment_NssImpl* )xEnvTunnel->getSomething( SecurityEnvironment_NssImpl::getUnoTunnelId() ) ;
        if( pSecEnv == NULL )
        {
            PK11_FreeSymKey( pSymKey ) ;
            PK11_FreeSlot( pSlot ) ;
            PK11_LogoutAll();
            NSS_Shutdown();
            return NULL;
        }

        pSecEnv->setCryptoSlot( pSlot ) ;
        PK11_FreeSlot( pSlot ) ;
        pSlot = NULL;

        pSecEnv->setCertDb( pCertHandle ) ;

        pSecEnv->adoptSymKey( pSymKey ) ;
        PK11_FreeSymKey( pSymKey ) ;
        pSymKey = NULL;

        /* Build XML Security Context */
        const rtl::OUString sSecyrutyContext ( RTL_CONSTASCII_USTRINGPARAM( SECURITY_CONTEXT ) );
        cssu::Reference< cssxc::XXMLSecurityContext > xSecCtx( mxMSF->createInstance ( sSecyrutyContext ), cssu::UNO_QUERY );
        if( !xSecCtx.is() )
        {
            PK11_LogoutAll();
            NSS_Shutdown();
            return NULL;
        }

        xSecCtx->setSecurityEnvironment( xSecEnv ) ;
        return xSecCtx;
    }
    catch( cssu::Exception& )
    {
        if (pSymKey != NULL)
        {
            PK11_FreeSymKey( pSymKey ) ;
        }

        if (pSlot != NULL)
        {
            PK11_FreeSlot( pSlot ) ;
        }

        PK11_LogoutAll();
        NSS_Shutdown();
        return NULL;
    }
}

void SAL_CALL SEInitializer_NssImpl::freeSecurityContext( const cssu::Reference< cssxc::XXMLSecurityContext >& securityContext )
    throw (cssu::RuntimeException)
{
    /*
     * because the security context will free all its content when it
     * is destructed, so here no free process for the security context
     * is needed.
     */
    PK11_LogoutAll();
    NSS_Shutdown();
}

rtl::OUString SEInitializer_NssImpl_getImplementationName ()
    throw (cssu::RuntimeException)
{
    return rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( IMPLEMENTATION_NAME ) );
}

sal_Bool SAL_CALL SEInitializer_NssImpl_supportsService( const rtl::OUString& ServiceName )
    throw (cssu::RuntimeException)
{
    return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ));
}

cssu::Sequence< rtl::OUString > SAL_CALL SEInitializer_NssImpl_getSupportedServiceNames(  )
    throw (cssu::RuntimeException)
{
    cssu::Sequence < rtl::OUString > aRet(1);
    rtl::OUString* pArray = aRet.getArray();
    pArray[0] =  rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );
    return aRet;
}
#undef SERVICE_NAME

cssu::Reference< cssu::XInterface > SAL_CALL SEInitializer_NssImpl_createInstance( const cssu::Reference< cssl::XMultiServiceFactory > & rSMgr)
    throw( cssu::Exception )
{
    return (cppu::OWeakObject*) new SEInitializer_NssImpl(rSMgr);
}

/* XServiceInfo */
rtl::OUString SAL_CALL SEInitializer_NssImpl::getImplementationName(  )
    throw (cssu::RuntimeException)
{
    return SEInitializer_NssImpl_getImplementationName();
}
sal_Bool SAL_CALL SEInitializer_NssImpl::supportsService( const rtl::OUString& rServiceName )
    throw (cssu::RuntimeException)
{
    return SEInitializer_NssImpl_supportsService( rServiceName );
}
cssu::Sequence< rtl::OUString > SAL_CALL SEInitializer_NssImpl::getSupportedServiceNames(  )
    throw (cssu::RuntimeException)
{
    return SEInitializer_NssImpl_getSupportedServiceNames();
}

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

/*
 * Turn off DEBUG Assertions
 */
#ifdef _DEBUG
    #define _DEBUG_WAS_DEFINED _DEBUG
    #undef _DEBUG
#else
    #undef _DEBUG_WAS_DEFINED
#endif

/*
 * and turn off the additional virtual methods which are part of some interfaces when compiled
 * with debug
 */
#ifdef DEBUG
    #define DEBUG_WAS_DEFINED DEBUG
    #undef DEBUG
#else
    #undef DEBUG_WAS_DEFINED
#endif

/*
 * header files needed for getCurrentProfilePath
 */
/*
#include "nsIServiceManager.h"
#include "nsIProfileInternal.h"
#include "nsString.h"
#include "nsEmbedAPI.h"
*/

#include <sal/types.h>

#include "seinitializer_nssimpl.hxx"

#include "securityenvironment_nssimpl.hxx"

#include "nspr.h"
#include "prtypes.h"
#include "pk11func.h"
#include "cert.h"
#include "cryptohi.h"
#include "certdb.h"
#include "nss.h"

namespace cssu = com::sun::star::uno;
namespace cssl = com::sun::star::lang;
namespace cssxc = com::sun::star::xml::crypto;

using namespace com::sun::star;

#define SERVICE_NAME "com.sun.star.xml.crypto.SEInitializer"
#define IMPLEMENTATION_NAME "com.sun.star.xml.security.bridge.xmlsec.SEInitializer_NssImpl"
#define SECURITY_ENVIRONMENT "com.sun.star.xml.crypto.SecurityEnvironment"
#define SECURITY_CONTEXT "com.sun.star.xml.crypto.XMLSecurityContext"

/*
 * MM : get the current user profile
 */

// MM : By now, the XPCOM is initialized only once in the current thread, and it will
//      not be shutdown until StarOffice exits.
//      This is a bug, because any other component who will initialize the XPCOM afterward
//      will always fail.
//      This bug will be fixed when there is solution.
#if 0
static nsIServiceManager           *sServiceManager = nsnull;
static nsIDirectoryServiceProvider *appFileLocProvider = nsnull;
static NS_DEFINE_CID(kProfileCID, NS_PROFILE_CID);

char* getCurrentProfilePath( )
{
/*
        nsCOMPtr<nsILocalFile> binDir;

        // Note: if getenv() returns NULL, mozilla will default to using MOZILLA_FIVE_HOME in the NS_InitXPCOM2()
        // The NS_NewNativeLocalFile() will accept NULL as its first parameter.
        char * env = getenv("OPENOFFICE_MOZILLA_FIVE_HOME");
        if (env)
        {
        nsDependentCString sPath(env);
        nsresult rv = NS_NewNativeLocalFile(sPath, PR_TRUE, getter_AddRefs(binDir));
        if (NS_FAILED(rv))
            return NULL;
        }

    if (sServiceManager == nsnull)
    {
        NS_InitXPCOM2(&sServiceManager, binDir, appFileLocProvider);
    }

    if (!sServiceManager)
        return NULL;

    nsresult rv;
    nsCOMPtr< nsIProfile > theProfile = do_GetService( kProfileCID, &rv );
    if (NS_SUCCEEDED(rv))
    {
        nsXPIDLString profileName;
        rv = theProfile->GetCurrentProfile(getter_Copies(profileName));
        if (NS_SUCCEEDED(rv))
        {
            nsCOMPtr<nsIFile> curProfileDir;
            PRBool exists = PR_FALSE;
            nsCOMPtr<nsIProfileInternal> profileInternal=do_QueryInterface(theProfile);
            if (NS_SUCCEEDED(rv))
            {
                rv = profileInternal->GetProfileDir(profileName, getter_AddRefs(curProfileDir));
                if (NS_SUCCEEDED(rv))
                {
                    nsCOMPtr<nsILocalFile> localFile(do_QueryInterface(curProfileDir));

                    nsAutoString path;
                    rv = localFile->GetPath(path);
                    if (NS_SUCCEEDED(rv))
                    {
                        char cs[1024];
                        path.ToCString(cs, 1024);

                        // MM : I can't shutdown, because the XPCom can't be initialized twice in
                        //      one program
                        //NS_RELEASE(sServiceManager);
                        //NS_ShutdownXPCOM(sServiceManager);

                        return (strdup(cs));
                    }
                }
            }
        }
    }

    // MM : I can't shutdown, because the XPCom can't be initialized twice in
    //      one program
    //NS_RELEASE(sServiceManager);
    //NS_ShutdownXPCOM(sServiceManager);
    */

    return NULL;
}

/*
 * get the current user profile (end)
 */

#endif

bool getMozillaCurrentProfile(rtl::OUString& profilePath);

SEInitializer_NssImpl::SEInitializer_NssImpl(
    const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > &rxMSF)
    :mxMSF( rxMSF )
{
}

SEInitializer_NssImpl::~SEInitializer_NssImpl()
{
}

/* XSEInitializer */
cssu::Reference< cssxc::XXMLSecurityContext > SAL_CALL
    SEInitializer_NssImpl::createSecurityContext(
    const rtl::OUString& sCertDB )
    throw (cssu::RuntimeException)
{
    CERTCertDBHandle*   pCertHandle = NULL ;
    PK11SlotInfo*       pSlot = NULL ;

    rtl::OString sCertDir;
    if( sCertDB.getLength() > 0 )
    {
        sCertDir = rtl::OString(sCertDB, sCertDB.getLength(), RTL_TEXTENCODING_ASCII_US);
    }
    else
    {
        rtl::OUString ouCertDir;
        if (!getMozillaCurrentProfile(ouCertDir))
        {
            return NULL;
        }

        sCertDir = rtl::OString(ouCertDir, ouCertDir.getLength(), RTL_TEXTENCODING_ASCII_US);

        /*
        char *pCurrentProfilePath = getCurrentProfilePath();

        if (pCurrentProfilePath == NULL)
        {
            return NULL;
        }
        else
        {
            sCertDir = rtl::OString(pCurrentProfilePath);
            free(pCurrentProfilePath);
        }
        */
    }

    /* Initialize NSPR and NSS */
    PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1 ) ;

    if (NSS_Init(sCertDir.getStr()) != SECSuccess )
    {
        PK11_LogoutAll();
        return NULL;
    }

    pCertHandle = CERT_GetDefaultCertDB() ;
    pSlot = PK11_GetInternalKeySlot() ;

    if (pSlot == NULL)
    {
        PK11_LogoutAll();
        NSS_Shutdown();
        return NULL;
    }

    PK11SymKey* pSymKey = PK11_KeyGen( pSlot , CKM_DES3_CBC, NULL, 128, NULL ) ;
    if( pSymKey == NULL )
    {
        PK11_FreeSlot( pSlot ) ;
        PK11_LogoutAll();
        NSS_Shutdown();
        return NULL;
    }

    try
    {
        /* Build Security Environment */
        const rtl::OUString sSecyrutyEnvironment ( RTL_CONSTASCII_USTRINGPARAM( SECURITY_ENVIRONMENT ) );
        cssu::Reference< cssxc::XSecurityEnvironment > xSecEnv( mxMSF->createInstance ( sSecyrutyEnvironment ), cssu::UNO_QUERY );
        if( !xSecEnv.is() )
        {
            PK11_FreeSymKey( pSymKey ) ;
            PK11_FreeSlot( pSlot ) ;
            PK11_LogoutAll();
            NSS_Shutdown();
            return NULL;
        }

        /* Setup key slot and certDb */
        cssu::Reference< cssl::XUnoTunnel > xEnvTunnel( xSecEnv , cssu::UNO_QUERY ) ;
        if( !xEnvTunnel.is() )
        {
            PK11_FreeSymKey( pSymKey ) ;
            PK11_FreeSlot( pSlot ) ;
            PK11_LogoutAll();
            NSS_Shutdown();
            return NULL;
        }

        SecurityEnvironment_NssImpl* pSecEnv = ( SecurityEnvironment_NssImpl* )xEnvTunnel->getSomething( SecurityEnvironment_NssImpl::getUnoTunnelId() ) ;
        if( pSecEnv == NULL )
        {
            PK11_FreeSymKey( pSymKey ) ;
            PK11_FreeSlot( pSlot ) ;
            PK11_LogoutAll();
            NSS_Shutdown();
            return NULL;
        }

        pSecEnv->setCryptoSlot( pSlot ) ;
        PK11_FreeSlot( pSlot ) ;
        pSlot = NULL;

        pSecEnv->setCertDb( pCertHandle ) ;

        pSecEnv->adoptSymKey( pSymKey ) ;
        PK11_FreeSymKey( pSymKey ) ;
        pSymKey = NULL;

        /* Build XML Security Context */
        const rtl::OUString sSecyrutyContext ( RTL_CONSTASCII_USTRINGPARAM( SECURITY_CONTEXT ) );
        cssu::Reference< cssxc::XXMLSecurityContext > xSecCtx( mxMSF->createInstance ( sSecyrutyContext ), cssu::UNO_QUERY );
        if( !xSecCtx.is() )
        {
            PK11_LogoutAll();
            NSS_Shutdown();
            return NULL;
        }

        xSecCtx->setSecurityEnvironment( xSecEnv ) ;
        return xSecCtx;
    }
    catch( cssu::Exception& )
    {
        if (pSymKey != NULL)
        {
            PK11_FreeSymKey( pSymKey ) ;
        }

        if (pSlot != NULL)
        {
            PK11_FreeSlot( pSlot ) ;
        }

        PK11_LogoutAll();
        NSS_Shutdown();
        return NULL;
    }
}

void SAL_CALL SEInitializer_NssImpl::freeSecurityContext( const cssu::Reference< cssxc::XXMLSecurityContext >& securityContext )
    throw (cssu::RuntimeException)
{
    /*
     * because the security context will free all its content when it
     * is destructed, so here no free process for the security context
     * is needed.
     */
    PK11_LogoutAll();
    NSS_Shutdown();
}

rtl::OUString SEInitializer_NssImpl_getImplementationName ()
    throw (cssu::RuntimeException)
{
    return rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( IMPLEMENTATION_NAME ) );
}

sal_Bool SAL_CALL SEInitializer_NssImpl_supportsService( const rtl::OUString& ServiceName )
    throw (cssu::RuntimeException)
{
    return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ));
}

cssu::Sequence< rtl::OUString > SAL_CALL SEInitializer_NssImpl_getSupportedServiceNames(  )
    throw (cssu::RuntimeException)
{
    cssu::Sequence < rtl::OUString > aRet(1);
    rtl::OUString* pArray = aRet.getArray();
    pArray[0] =  rtl::OUString ( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) );
    return aRet;
}
#undef SERVICE_NAME

cssu::Reference< cssu::XInterface > SAL_CALL SEInitializer_NssImpl_createInstance( const cssu::Reference< cssl::XMultiServiceFactory > & rSMgr)
    throw( cssu::Exception )
{
    return (cppu::OWeakObject*) new SEInitializer_NssImpl(rSMgr);
}

/* XServiceInfo */
rtl::OUString SAL_CALL SEInitializer_NssImpl::getImplementationName(  )
    throw (cssu::RuntimeException)
{
    return SEInitializer_NssImpl_getImplementationName();
}
sal_Bool SAL_CALL SEInitializer_NssImpl::supportsService( const rtl::OUString& rServiceName )
    throw (cssu::RuntimeException)
{
    return SEInitializer_NssImpl_supportsService( rServiceName );
}
cssu::Sequence< rtl::OUString > SAL_CALL SEInitializer_NssImpl::getSupportedServiceNames(  )
    throw (cssu::RuntimeException)
{
    return SEInitializer_NssImpl_getSupportedServiceNames();
}

<|endoftext|>


<commit_before>/* Copyright 2014 Andrew Schwartzmeyer
 *
 * Header file for base problem class
 */

#ifndef _SCHWEFEL_PROBLEM_H_
#define _SCHWEFEL_PROBLEM_H_

#include "problem.hpp"

class Schwefel: public Problem {
public:
  Schwefel(const long i = 100000000,
	   const parameter g = 0.90,
	   const parameter f = 0.65,
	   const parameter d = 0.1,
	   const parameter h = 0.50,
	   const int c = 10000): Problem(-512.03, 511.97,
					 0, 21000, true,
					 i, g, f, d, h, c) {};

  parameter problem(const Individual & subject) const;
};

#endif /* _SCHWEFEL_PROBLEM_H_ */
<commit_msg>Petty trailing 0 fix<commit_after>/* Copyright 2014 Andrew Schwartzmeyer
 *
 * Header file for base problem class
 */

#ifndef _SCHWEFEL_PROBLEM_H_
#define _SCHWEFEL_PROBLEM_H_

#include "problem.hpp"

class Schwefel: public Problem {
public:
  Schwefel(const long i = 100000000,
	   const parameter g = 0.90,
	   const parameter f = 0.65,
	   const parameter d = 0.1,
	   const parameter h = 0.5,
	   const int c = 10000): Problem(-512.03, 511.97,
					 0, 21000, true,
					 i, g, f, d, h, c) {};

  parameter problem(const Individual & subject) const;
};

#endif /* _SCHWEFEL_PROBLEM_H_ */
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////////
// oxygen.cpp
// -------------------
//
// Copyright (c) 2009 Hugo Pereira Da Costa <hugo.pereira@free.fr>
// Copyright (c) 2006, 2007 Riccardo Iaconelli <riccardo@kde.org>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//////////////////////////////////////////////////////////////////////////////

#include "oxygenfactory.h"
#include "oxygenfactory.moc"
#include "oxygenclient.h"
#include "oxygenexceptionlist.h"

#include <KSharedConfig>
#include <KConfigGroup>
#include <KDebug>
#include <KGlobal>
#include <KWindowInfo>
#include <kdeversion.h>

KWIN_DECORATION(Oxygen::Factory)

namespace Oxygen
{

    //___________________________________________________
    Factory::Factory():
        _initialized( false ),
        _helper( "oxygenDeco" ),
        _shadowCache( _helper )
    {
        readConfig();
        setInitialized( true );
    }

    //___________________________________________________
    Factory::~Factory()
    { setInitialized( false ); }

    //___________________________________________________
    KDecoration* Factory::createDecoration(KDecorationBridge* bridge )
    { return (new Client( bridge, this ))->decoration(); }

    //___________________________________________________
    bool Factory::reset(unsigned long changed)
    {

        if( changed & SettingColors )
        { _shadowCache.invalidateCaches(); }

        // read in the configuration
        setInitialized( false );
        readConfig();
        setInitialized( true );
        return true;

    }

    //___________________________________________________
    void Factory::readConfig()
    {

        /*
        always reload helper
        this is needed to properly handle
        color contrast settings changed
        */
        helper().invalidateCaches();
        helper().reloadConfig();

        // initialize default configuration and read
        if( !_defaultConfiguration ) _defaultConfiguration = ConfigurationPtr(new Configuration());
        _defaultConfiguration->setCurrentGroup( "Windeco" );
        _defaultConfiguration->readConfig();

        // create a config object
        KSharedConfig::Ptr config( KSharedConfig::openConfig( "oxygenrc" ) );
        if( _defaultConfiguration->opacityFromStyle() )
        {
            // read 'common' opacity
            KConfigGroup group( config->group("Common") );
            _defaultConfiguration->setBackgroundOpacity( group.readEntry( "BackgroundOpacity", 255 ) );
        }

        // clear exceptions and read
        ExceptionList exceptions;
        exceptions.readConfig( config );
        _exceptions = exceptions.get();

        // read shadowCache configuration
        _shadowCache.readConfig();
        _shadowCache.setAnimationsDuration( _defaultConfiguration->shadowAnimationsDuration() );

        // background pixmap
        {
            KConfigGroup group( config->group("Common") );
            helper().setBackgroundPixmap( group.readEntry( "BackgroundPixmap", "" ) );
        }

    }

    //_________________________________________________________________
    bool Factory::supports( Ability ability ) const
    {
        switch( ability )
        {

            // announce
            case AbilityAnnounceButtons:
            case AbilityAnnounceColors:

            // buttons
            case AbilityButtonMenu:
            case AbilityButtonApplicationMenu:
            case AbilityButtonHelp:
            case AbilityButtonMinimize:
            case AbilityButtonMaximize:
            case AbilityButtonClose:
            case AbilityButtonOnAllDesktops:
            case AbilityButtonAboveOthers:
            case AbilityButtonBelowOthers:
            case AbilityButtonSpacer:
            case AbilityButtonShade:

            // compositing
            case AbilityProvidesShadow:
            return true;

            case AbilityUsesAlphaChannel:
            case AbilityAnnounceAlphaChannel:
            return true;

            // tabs
            case AbilityTabbing:
            return true;

            #if KDE_IS_VERSION( 4, 5, 76 )
            case AbilityUsesBlurBehind:
            return _defaultConfiguration->backgroundOpacity() < 255;
            #endif

            // no colors supported at this time
            default:
            return false;
        };
    }

    //____________________________________________________________________
    Factory::ConfigurationPtr Factory::configuration( const Client& client )
    {

        QString windowTitle;
        QString className;
        foreach( const ConfigurationPtr& configuration, _exceptions )
        {

            // discard disabled exceptions
            if( !configuration->enabled() ) continue;

            // discard exceptions with empty exception pattern
            if( configuration->exceptionPattern().isEmpty() ) continue;

            /*
            decide which value is to be compared
            to the regular expression, based on exception type
            */
            QString value;
            switch( configuration->exceptionType() )
            {
                case Configuration::ExceptionWindowTitle:
                {
                    value = windowTitle.isEmpty() ? (windowTitle = client.caption()):windowTitle;
                    break;
                }

                default:
                case Configuration::ExceptionWindowClassName:
                {
                    if( className.isEmpty() )
                    {
                        // retrieve class name
                        KWindowInfo info( client.windowId(), 0, NET::WM2WindowClass );
                        QString window_className( info.windowClassName() );
                        QString window_class( info.windowClassClass() );
                        className = window_className + ' ' + window_class;
                    }

                    value = className;
                    break;
                }

            }

            // check matching
            if( QRegExp( configuration->exceptionPattern() ).indexIn( value ) >= 0 )
            { return configuration; }

        }

        return _defaultConfiguration;

    }

}
<commit_msg>fixed applying style opacity to exceptions.<commit_after>//////////////////////////////////////////////////////////////////////////////
// oxygen.cpp
// -------------------
//
// Copyright (c) 2009 Hugo Pereira Da Costa <hugo.pereira@free.fr>
// Copyright (c) 2006, 2007 Riccardo Iaconelli <riccardo@kde.org>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//////////////////////////////////////////////////////////////////////////////

#include "oxygenfactory.h"
#include "oxygenfactory.moc"
#include "oxygenclient.h"
#include "oxygenexceptionlist.h"

#include <KSharedConfig>
#include <KConfigGroup>
#include <KDebug>
#include <KGlobal>
#include <KWindowInfo>
#include <kdeversion.h>

KWIN_DECORATION(Oxygen::Factory)

namespace Oxygen
{

    //___________________________________________________
    Factory::Factory():
        _initialized( false ),
        _helper( "oxygenDeco" ),
        _shadowCache( _helper )
    {
        readConfig();
        setInitialized( true );
    }

    //___________________________________________________
    Factory::~Factory()
    { setInitialized( false ); }

    //___________________________________________________
    KDecoration* Factory::createDecoration(KDecorationBridge* bridge )
    { return (new Client( bridge, this ))->decoration(); }

    //___________________________________________________
    bool Factory::reset(unsigned long changed)
    {

        if( changed & SettingColors )
        { _shadowCache.invalidateCaches(); }

        // read in the configuration
        setInitialized( false );
        readConfig();
        setInitialized( true );
        return true;

    }

    //___________________________________________________
    void Factory::readConfig()
    {

        /*
        always reload helper
        this is needed to properly handle
        color contrast settings changed
        */
        helper().invalidateCaches();
        helper().reloadConfig();

        // initialize default configuration and read
        if( !_defaultConfiguration ) _defaultConfiguration = ConfigurationPtr(new Configuration());
        _defaultConfiguration->setCurrentGroup( "Windeco" );
        _defaultConfiguration->readConfig();

        // create a config object
        KSharedConfig::Ptr config( KSharedConfig::openConfig( "oxygenrc" ) );

        // clear exceptions and read
        ExceptionList exceptions;
        exceptions.readConfig( config );
        _exceptions = exceptions.get();

        // read opacity from style, if required
        if( _defaultConfiguration->opacityFromStyle() )
        {

            KConfigGroup group( config->group("Common") );
            const int styleOpacity( group.readEntry( "BackgroundOpacity", 255 ) );

            _defaultConfiguration->setBackgroundOpacity( styleOpacity );

            foreach( const ConfigurationPtr& configuration, _exceptions )
            { configuration->setBackgroundOpacity( styleOpacity ); }

        }

        // read shadowCache configuration
        _shadowCache.readConfig();
        _shadowCache.setAnimationsDuration( _defaultConfiguration->shadowAnimationsDuration() );

        // background pixmap
        {
            KConfigGroup group( config->group("Common") );
            helper().setBackgroundPixmap( group.readEntry( "BackgroundPixmap", "" ) );
        }

    }

    //_________________________________________________________________
    bool Factory::supports( Ability ability ) const
    {
        switch( ability )
        {

            // announce
            case AbilityAnnounceButtons:
            case AbilityAnnounceColors:

            // buttons
            case AbilityButtonMenu:
            case AbilityButtonApplicationMenu:
            case AbilityButtonHelp:
            case AbilityButtonMinimize:
            case AbilityButtonMaximize:
            case AbilityButtonClose:
            case AbilityButtonOnAllDesktops:
            case AbilityButtonAboveOthers:
            case AbilityButtonBelowOthers:
            case AbilityButtonSpacer:
            case AbilityButtonShade:

            // compositing
            case AbilityProvidesShadow:
            return true;

            case AbilityUsesAlphaChannel:
            case AbilityAnnounceAlphaChannel:
            return true;

            // tabs
            case AbilityTabbing:
            return true;

            #if KDE_IS_VERSION( 4, 5, 76 )
            case AbilityUsesBlurBehind:
            return _defaultConfiguration->backgroundOpacity() < 255;
            #endif

            // no colors supported at this time
            default:
            return false;
        };
    }

    //____________________________________________________________________
    Factory::ConfigurationPtr Factory::configuration( const Client& client )
    {

        QString windowTitle;
        QString className;
        foreach( const ConfigurationPtr& configuration, _exceptions )
        {

            // discard disabled exceptions
            if( !configuration->enabled() ) continue;

            // discard exceptions with empty exception pattern
            if( configuration->exceptionPattern().isEmpty() ) continue;

            /*
            decide which value is to be compared
            to the regular expression, based on exception type
            */
            QString value;
            switch( configuration->exceptionType() )
            {
                case Configuration::ExceptionWindowTitle:
                {
                    value = windowTitle.isEmpty() ? (windowTitle = client.caption()):windowTitle;
                    break;
                }

                default:
                case Configuration::ExceptionWindowClassName:
                {
                    if( className.isEmpty() )
                    {
                        // retrieve class name
                        KWindowInfo info( client.windowId(), 0, NET::WM2WindowClass );
                        QString window_className( info.windowClassName() );
                        QString window_class( info.windowClassClass() );
                        className = window_className + ' ' + window_class;
                    }

                    value = className;
                    break;
                }

            }

            // check matching
            if( QRegExp( configuration->exceptionPattern() ).indexIn( value ) >= 0 )
            { return configuration; }

        }

        return _defaultConfiguration;

    }

}
<|endoftext|>


<commit_before>/*$Id$
 *
 * This source file is a part of the Berlin Project.
 * Copyright (C) 1999 Stefan Seefeld <stefan@berlin-consortium.org>
 * http://www.berlin-consortium.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */

#include <Warsaw/config.hh>
#include <Warsaw/Command.hh>
#include <Warsaw/Desktop.hh>
#include <Warsaw/MainController.hh>
#include "PrimitiveDemo.hh"

using namespace Warsaw;

namespace
{
class Forward : public Application::CommandImpl
{
 public:
  Forward(Warsaw::BoundedValue_ptr v) : value(Warsaw::BoundedValue::_duplicate(v)) {}
  void execute(const CORBA::Any &) { value->forward();}
 private:
  Warsaw::BoundedValue_var value;
};

class Backward : public Application::CommandImpl
{
 public:
  Backward(Warsaw::BoundedValue_ptr v) : value(Warsaw::BoundedValue::_duplicate(v)) {}
  void execute(const CORBA::Any &) { value->backward();}
 private:
  Warsaw::BoundedValue_var value;
};

};

PrimitiveDemo::Rotator::Rotator(BoundedValue_ptr v, Graphic_ptr c, Graphic_ptr p, Axis a)
  : value(BoundedValue::_duplicate(v)),
    child(Graphic::_duplicate(c)),
    parent(Graphic::_duplicate(p)),
    axis(a)
{
  CORBA::Any dummy;
  update(dummy);
}

void PrimitiveDemo::Rotator::update(const CORBA::Any &)
{
  Coord ydegree = value->value();
  Transform_var tx = child->transformation();
  tx->load_identity();
  tx->rotate(ydegree, axis);
  parent->need_redraw();
}

PrimitiveDemo::PrimitiveDemo(Application *a)
  : Demo(a),
    tx1(new TransformImpl),
    tx2(new TransformImpl)
{
  LayoutKit_var layout = application->layout();
  ToolKit_var   tools = application->tool();
  WidgetKit_var widgets = application->widget();
  ImageKit_var  images = application->image();
  PrimitiveKit_var primitives = application->primitive();
  CommandKit_var commands = application->command();

  phi = commands->bvalue(0., 360., 0., 5., 5.);
  psi = commands->bvalue(0., 360., 0., 5., 5.);

  Coord a = 2000.;
  Vertex offset;
  offset.x = -a/2., offset.y = -3./2.*a, offset.z = 0.;
  Warsaw::Mesh mesh;
  mesh.nodes.length(4);
  Coord w = 3000.;
  Coord h = 3000.;
  Coord d = 3000.;
  mesh.nodes[0].x = -w/2, mesh.nodes[0].y = -h/2, mesh.nodes[0].z = -d/2;
  mesh.nodes[1].x =  w/2, mesh.nodes[1].y = -h/2, mesh.nodes[1].z = -d/2;
  mesh.nodes[2].x =  0, mesh.nodes[2].y = -h/2, mesh.nodes[2].z =  d/2;
  mesh.nodes[3].x =  0, mesh.nodes[3].y =  h/2, mesh.nodes[3].z = 0;
  mesh.triangles.length(4);
  mesh.triangles[0].a = 0, mesh.triangles[0].b = 1, mesh.triangles[0].c = 3;
  mesh.triangles[1].a = 1, mesh.triangles[1].b = 2, mesh.triangles[1].c = 3;
  mesh.triangles[2].a = 2, mesh.triangles[2].b = 0, mesh.triangles[2].c = 3;
  mesh.triangles[3].a = 0, mesh.triangles[3].b = 2, mesh.triangles[3].c = 1;
  mesh.normals.length(4);
  mesh.normals[0].x = 0., mesh.normals[0].y = .8, mesh.normals[0].z = .2;
  mesh.normals[1].x = .8, mesh.normals[1].y = .2, mesh.normals[1].z = .2;
  mesh.normals[2].x = -.2, mesh.normals[2].y = .2, mesh.normals[2].z = .2;
  mesh.normals[3].x = 0., mesh.normals[3].y = -1., mesh.normals[3].z = 0.;

  Primitive::Geometry_var triangle = primitives->geometry(mesh);
  Graphic_var transformer1 = primitives->transformer(Graphic_var(tools->rgb(triangle, 0.6, 0.6, 1.0)));
  Graphic_var transformer2 = primitives->transformer(Graphic_var(transformer1));

  Graphic_var root = primitives->root(transformer2);

  rotator1 = new Rotator(phi, transformer1, root, zaxis);
  phi->attach(Observer_var(rotator1->_this()));
  rotator2 = new Rotator(psi, transformer2, root, yaxis);
  psi->attach(Observer_var(rotator2->_this()));

  Graphic_var hbox1 = layout->hbox();
  hbox1->append_graphic(Graphic_var(layout->hfill()));
  hbox1->append_graphic(Graphic_var(widgets->slider(phi, xaxis)));
  hbox1->append_graphic(Graphic_var(layout->hfill()));
  Graphic_var hbox2 = layout->hbox();
  hbox2->append_graphic(Graphic_var(layout->hfill()));
  hbox2->append_graphic(Graphic_var(widgets->slider(psi, xaxis)));
  hbox2->append_graphic(Graphic_var(layout->hfill()));
  Graphic_var box = layout->vbox();
  box->append_graphic(Graphic_var(layout->align(root, 0., 0.)));
  box->append_graphic(hbox1);
  box->append_graphic(hbox2);
  ToolKit::FrameSpec spec;
  spec.brightness(0.5); spec._d(ToolKit::inset);
  Graphic_var foo = tools->frame(box, 10., spec, true);
  MainController_var bar = tools->group(foo);
  application->append(bar, Babylon::String("3D demo"));
}

Graphic_ptr PrimitiveDemo::make_controller(BoundedValue_ptr value, const Color &color)
{
  ToolKit_var tool = application->tool();
  WidgetKit_var widget = application->widget();
  LayoutKit_var layout = application->layout();
  Graphic_var gauge = widget->gauge(value);
  Forward *forward = new Forward(value);
  Backward *backward = new Backward(value);
  Graphic_var rectangle = layout->fixed_size(Graphic_var(Graphic::_nil()), 200., 200.);
  ToolKit::FrameSpec spec;
  spec.brightness(0.5); spec._d(ToolKit::inset);
  Controller_var begin = tool->stepper(Graphic_var(tool->frame(rectangle, 10., spec, true)), Command_var(backward->_this()));
  Controller_var end = tool->stepper(Graphic_var(tool->frame(rectangle, 10., spec, true)), Command_var(forward->_this()));
  Graphic_var box = layout->hbox();
  box->append_graphic(begin);
  box->append_graphic(gauge);
  box->append_graphic(end);
  return Graphic::_duplicate(box);
}
<commit_msg>fiat lux...<commit_after>/*$Id$
 *
 * This source file is a part of the Berlin Project.
 * Copyright (C) 1999 Stefan Seefeld <stefan@berlin-consortium.org>
 * http://www.berlin-consortium.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */

#include <Warsaw/config.hh>
#include <Warsaw/Command.hh>
#include <Warsaw/Desktop.hh>
#include <Warsaw/MainController.hh>
#include "PrimitiveDemo.hh"

using namespace Warsaw;

namespace
{
class Forward : public Application::CommandImpl
{
 public:
  Forward(Warsaw::BoundedValue_ptr v) : value(Warsaw::BoundedValue::_duplicate(v)) {}
  void execute(const CORBA::Any &) { value->forward();}
 private:
  Warsaw::BoundedValue_var value;
};

class Backward : public Application::CommandImpl
{
 public:
  Backward(Warsaw::BoundedValue_ptr v) : value(Warsaw::BoundedValue::_duplicate(v)) {}
  void execute(const CORBA::Any &) { value->backward();}
 private:
  Warsaw::BoundedValue_var value;
};

};

PrimitiveDemo::Rotator::Rotator(BoundedValue_ptr v, Graphic_ptr c, Graphic_ptr p, Axis a)
  : value(BoundedValue::_duplicate(v)),
    child(Graphic::_duplicate(c)),
    parent(Graphic::_duplicate(p)),
    axis(a)
{
  CORBA::Any dummy;
  update(dummy);
}

void PrimitiveDemo::Rotator::update(const CORBA::Any &)
{
  Coord ydegree = value->value();
  Transform_var tx = child->transformation();
  tx->load_identity();
  tx->rotate(ydegree, axis);
  cout << "parent needs redraw..." << endl;
  parent->need_redraw();
}

PrimitiveDemo::PrimitiveDemo(Application *a)
  : Demo(a),
    tx1(new TransformImpl),
    tx2(new TransformImpl)
{
  LayoutKit_var layout = application->layout();
  ToolKit_var   tools = application->tool();
  WidgetKit_var widgets = application->widget();
  ImageKit_var  images = application->image();
  PrimitiveKit_var primitives = application->primitive();
  CommandKit_var commands = application->command();

  phi = commands->bvalue(0., 360., 0., 5., 5.);
  psi = commands->bvalue(0., 360., 0., 5., 5.);

  Coord a = 2000.;
  Vertex offset;
  offset.x = -a/2., offset.y = -3./2.*a, offset.z = 0.;
  Warsaw::Mesh mesh;
  mesh.nodes.length(4);
  Coord w = 3000.;
  Coord h = 3000.;
  Coord d = 3000.;
  mesh.nodes[0].x = -w/2, mesh.nodes[0].y = -h/2, mesh.nodes[0].z = -d/2;
  mesh.nodes[1].x =  w/2, mesh.nodes[1].y = -h/2, mesh.nodes[1].z = -d/2;
  mesh.nodes[2].x =  0, mesh.nodes[2].y = -h/2, mesh.nodes[2].z =  d/2;
  mesh.nodes[3].x =  0, mesh.nodes[3].y =  h/2, mesh.nodes[3].z = 0;
  mesh.triangles.length(4);
  mesh.triangles[0].a = 0, mesh.triangles[0].b = 1, mesh.triangles[0].c = 3;
  mesh.triangles[1].a = 1, mesh.triangles[1].b = 2, mesh.triangles[1].c = 3;
  mesh.triangles[2].a = 2, mesh.triangles[2].b = 0, mesh.triangles[2].c = 3;
  mesh.triangles[3].a = 0, mesh.triangles[3].b = 2, mesh.triangles[3].c = 1;
  mesh.normals.length(4);
  mesh.normals[0].x = 0., mesh.normals[0].y = .8, mesh.normals[0].z = .2;
  mesh.normals[1].x = .8, mesh.normals[1].y = .2, mesh.normals[1].z = .2;
  mesh.normals[2].x = -.2, mesh.normals[2].y = .2, mesh.normals[2].z = .2;
  mesh.normals[3].x = 0., mesh.normals[3].y = -1., mesh.normals[3].z = 0.;

  Primitive::Geometry_var triangle = primitives->geometry(mesh);
  Graphic_var transformer1 = primitives->transformer(Graphic_var(tools->rgb(triangle, 0.6, 0.6, 1.0)));
  Graphic_var transformer2 = primitives->transformer(Graphic_var(transformer1));
  Color white = {1., 1., 1., 1.};
  Vertex direction = {5., 5., 10.};
  Graphic_var light = primitives->directional_light(transformer2, white, 1., direction);

  Graphic_var root = primitives->root(light);

  rotator1 = new Rotator(phi, transformer1, root, zaxis);
  phi->attach(Observer_var(rotator1->_this()));
  rotator2 = new Rotator(psi, transformer2, root, yaxis);
  psi->attach(Observer_var(rotator2->_this()));

  Graphic_var hbox1 = layout->hbox();
  hbox1->append_graphic(Graphic_var(layout->hfill()));
  hbox1->append_graphic(Graphic_var(widgets->slider(phi, xaxis)));
  hbox1->append_graphic(Graphic_var(layout->hfill()));
  Graphic_var hbox2 = layout->hbox();
  hbox2->append_graphic(Graphic_var(layout->hfill()));
  hbox2->append_graphic(Graphic_var(widgets->slider(psi, xaxis)));
  hbox2->append_graphic(Graphic_var(layout->hfill()));
  Graphic_var box = layout->vbox();
  box->append_graphic(Graphic_var(layout->align(root, 0., 0.)));
  box->append_graphic(hbox1);
  box->append_graphic(hbox2);
  ToolKit::FrameSpec spec;
  spec.brightness(0.5); spec._d(ToolKit::inset);
  Graphic_var foo = tools->frame(box, 10., spec, true);
  MainController_var bar = tools->group(foo);
  application->append(bar, Babylon::String("3D demo"));
}

Graphic_ptr PrimitiveDemo::make_controller(BoundedValue_ptr value, const Color &color)
{
  ToolKit_var tool = application->tool();
  WidgetKit_var widget = application->widget();
  LayoutKit_var layout = application->layout();
  Graphic_var gauge = widget->gauge(value);
  Forward *forward = new Forward(value);
  Backward *backward = new Backward(value);
  Graphic_var rectangle = layout->fixed_size(Graphic_var(Graphic::_nil()), 200., 200.);
  ToolKit::FrameSpec spec;
  spec.brightness(0.5); spec._d(ToolKit::inset);
  Controller_var begin = tool->stepper(Graphic_var(tool->frame(rectangle, 10., spec, true)), Command_var(backward->_this()));
  Controller_var end = tool->stepper(Graphic_var(tool->frame(rectangle, 10., spec, true)), Command_var(forward->_this()));
  Graphic_var box = layout->hbox();
  box->append_graphic(begin);
  box->append_graphic(gauge);
  box->append_graphic(end);
  return Graphic::_duplicate(box);
}
<|endoftext|>


<commit_before>/*$Id$
 *
 * This source file is a part of the Berlin Project.
 * Copyright (C) 1999,2000 Tobias Hunger <Tobias@berlin-consortium.org>
 * http://www.berlin-consortium.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */

#include "TextConverter.hh"

TextConverter::TextConverter(const std::string & file) {
    tree_map = new Prague::MMap(file,
				-1,
				Prague::MMap::read,
				Prague::MMap::shared,
				0,
				0);
    tree = (node *)tree_map->addr();
    tree_size = tree_map->size() / sizeof(node);
}

Babylon::String
TextConverter::convert(const Babylon::String & pinyin) const {
    Babylon::String result;

    if (pinyin.empty()) return result;

    size_t cur_start = 0;
    size_t cur_end = 0;

    Babylon::String::const_iterator i = pinyin.begin();
    while (i != pinyin.end()) {
	if (i->value() > 127) return result;

	if (cur_start != 0) cur_start = tree[cur_start].Next;

	cur_start = find_char(char(i->value()), cur_start, tree[cur_start].Next);
	if (cur_start == 0xFFFF) return result;

	++i;
    }

    cur_end = tree[cur_start + 1].Next;
    cur_start = tree[cur_start].Next;

    for (size_t i = cur_start; i <= cur_end; i++)
	if (tree[i].Unicode != 0)
	    result.push_back(tree[i].Unicode);
    return result;
}

size_t
TextConverter::find_char(const char p,
		  const size_t s,
		  const size_t e) const {
    size_t start = s;
    size_t end;
    if (e < tree_size) end = e - 1; // Next points to the Beginning of the next.
                                    // Wow, what a useful comment!
    else end = tree_size;

    size_t pos = start;
    while ((start < end) && tree[pos].Char != p) {
	pos = (start + end) / 2;
	if (p < tree[pos].Char)
	    end = pos - 1;
	else if (p > tree[pos].Char)
	    start = pos + 1;
    }

    if (p == tree[pos].Char)
	return pos;

    return size_t(0xFFFF);
}
<commit_msg>fix to make it compilable with gcc 2.95.2<commit_after>/*$Id$
 *
 * This source file is a part of the Berlin Project.
 * Copyright (C) 1999,2000 Tobias Hunger <Tobias@berlin-consortium.org>
 * http://www.berlin-consortium.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */

#include "TextConverter.hh"

TextConverter::TextConverter(const std::string & file) {
    tree_map = new Prague::MMap(file,
				-1,
				Prague::MMap::read,
				Prague::MMap::shared,
				0,
				0);
    tree = (node *)tree_map->addr();
    tree_size = tree_map->size() / sizeof(node);
}

Babylon::String
TextConverter::convert(const Babylon::String & pinyin) const {
    Babylon::String result;

    if (pinyin.empty()) return result;

    size_t cur_start = 0;
    size_t cur_end = 0;

    Babylon::String::const_iterator i = pinyin.begin();
    while (i != pinyin.end()) {
	if (i->value() > 127) return result;

	if (cur_start != 0) cur_start = tree[cur_start].Next;

	cur_start = find_char(char(i->value()), cur_start, tree[cur_start].Next);
	if (cur_start == 0xFFFF) return result;

	++i;
    }

    cur_end = tree[cur_start + 1].Next;
    cur_start = tree[cur_start].Next;

    for (size_t i = cur_start; i <= cur_end; i++)
	if (tree[i].Unicode != 0)
	  result += tree[i].Unicode;
    return result;
}

size_t
TextConverter::find_char(const char p,
		  const size_t s,
		  const size_t e) const {
    size_t start = s;
    size_t end;
    if (e < tree_size) end = e - 1; // Next points to the Beginning of the next.
                                    // Wow, what a useful comment!
    else end = tree_size;

    size_t pos = start;
    while ((start < end) && tree[pos].Char != p) {
	pos = (start + end) / 2;
	if (p < tree[pos].Char)
	    end = pos - 1;
	else if (p > tree[pos].Char)
	    start = pos + 1;
    }

    if (p == tree[pos].Char)
	return pos;

    return size_t(0xFFFF);
}
<|endoftext|>