<commit_before>// $Id$

//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project        *
//* ALICE Experiment at CERN, All rights reserved.                         *
//*                                                                        *
//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
//*                  for The ALICE HLT Project.                            *
//*                                                                        *
//* Permission to use, copy, modify and distribute this software and its   *
//* documentation strictly for non-commercial purposes is hereby granted   *
//* without fee, provided that the above copyright notice appears in all   *
//* copies and that both the copyright notice and this permission notice   *
//* appear in the supporting documentation. The authors make no claims     *
//* about the suitability of this software for any purpose. It is          *
//* provided "as is" without express or implied warranty.                  *
//**************************************************************************

/** @file   AliHLTRCUAgent.cxx
    @author Matthias Richter
    @date
    @brief  Agent of the libAliHLTRCU library
*/

#include <cassert>
#include "AliHLTRCUAgent.h"
#include "AliHLTConfiguration.h"

// header files of library components
#include "AliHLTAltroChannelSelectorComponent.h"
#include "AliHLTAltroTimebinAverageComponent.h"

/** global instance for agent registration */
AliHLTRCUAgent gAliHLTRCUAgent;

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTRCUAgent)

AliHLTRCUAgent::AliHLTRCUAgent()
  :
  AliHLTModuleAgent("RCU")
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}

AliHLTRCUAgent::~AliHLTRCUAgent()
{
  // see header file for class documentation
}

int AliHLTRCUAgent::CreateConfigurations(AliHLTConfigurationHandler* /*handler*/,
					  AliRawReader* /*rawReader*/,
					  AliRunLoader* /*runloader*/) const
{
  // see header file for class documentation
  return 0;
}

const char* AliHLTRCUAgent::GetReconstructionChains(AliRawReader* /*rawReader*/,
						    AliRunLoader* /*runloader*/) const
{
  // see header file for class documentation
  return NULL;
}

const char* AliHLTRCUAgent::GetRequiredComponentLibraries() const
{
  // see header file for class documentation
  return NULL;
}

int AliHLTRCUAgent::RegisterComponents(AliHLTComponentHandler* pHandler) const
{
  // see header file for class documentation
  assert(pHandler);
  if (!pHandler) return -EINVAL;
  pHandler->AddComponent(new AliHLTAltroChannelSelectorComponent);
  pHandler->AddComponent(new AliHLTAltroTimebinAverageComponent);
  return 0;
}
<commit_msg>removing unnecessary include file<commit_after>// $Id$

//**************************************************************************
//* This file is property of and copyright by the ALICE HLT Project        *
//* ALICE Experiment at CERN, All rights reserved.                         *
//*                                                                        *
//* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no>        *
//*                  for The ALICE HLT Project.                            *
//*                                                                        *
//* Permission to use, copy, modify and distribute this software and its   *
//* documentation strictly for non-commercial purposes is hereby granted   *
//* without fee, provided that the above copyright notice appears in all   *
//* copies and that both the copyright notice and this permission notice   *
//* appear in the supporting documentation. The authors make no claims     *
//* about the suitability of this software for any purpose. It is          *
//* provided "as is" without express or implied warranty.                  *
//**************************************************************************

/** @file   AliHLTRCUAgent.cxx
    @author Matthias Richter
    @date
    @brief  Agent of the libAliHLTRCU library
*/

#include <cassert>
#include "AliHLTRCUAgent.h"

// header files of library components
#include "AliHLTAltroChannelSelectorComponent.h"
#include "AliHLTAltroTimebinAverageComponent.h"

/** global instance for agent registration */
AliHLTRCUAgent gAliHLTRCUAgent;

/** ROOT macro for the implementation of ROOT specific class methods */
ClassImp(AliHLTRCUAgent)

AliHLTRCUAgent::AliHLTRCUAgent()
  :
  AliHLTModuleAgent("RCU")
{
  // see header file for class documentation
  // or
  // refer to README to build package
  // or
  // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt
}

AliHLTRCUAgent::~AliHLTRCUAgent()
{
  // see header file for class documentation
}

int AliHLTRCUAgent::CreateConfigurations(AliHLTConfigurationHandler* /*handler*/,
					  AliRawReader* /*rawReader*/,
					  AliRunLoader* /*runloader*/) const
{
  // see header file for class documentation
  return 0;
}

const char* AliHLTRCUAgent::GetReconstructionChains(AliRawReader* /*rawReader*/,
						    AliRunLoader* /*runloader*/) const
{
  // see header file for class documentation
  return NULL;
}

const char* AliHLTRCUAgent::GetRequiredComponentLibraries() const
{
  // see header file for class documentation
  return NULL;
}

int AliHLTRCUAgent::RegisterComponents(AliHLTComponentHandler* pHandler) const
{
  // see header file for class documentation
  assert(pHandler);
  if (!pHandler) return -EINVAL;
  pHandler->AddComponent(new AliHLTAltroChannelSelectorComponent);
  pHandler->AddComponent(new AliHLTAltroTimebinAverageComponent);
  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: MNSInclude.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2002-10-18 08:51:22 $
 *
 *  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): Willem van Dorp, Darren Kenny
 *
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_MAB_NS_INCLUDE_HXX_
#define _CONNECTIVITY_MAB_NS_INCLUDE_HXX_ 1

//
// Only include Mozilla include files once and using this file...
//

#ifndef BOOL
# define MOZ_BOOL

# define BOOL mozBOOL
# define Bool mozBooL
#endif

// 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

#include <nsDebug.h>

#include <nsCOMPtr.h>
#include <nsISupportsArray.h>
#include <nsStr.h>
#include <nsString.h>
#include <nsString2.h>
#include <nsMemory.h>
#include <prtypes.h>
#include <nsRDFCID.h>
#include <nsXPIDLString.h>
#include <nsIRDFService.h>
#include <nsIRDFResource.h>
#include <nsReadableUtils.h>
#include <msgCore.h>
#include <nsIServiceManager.h>
#include <nsIAbCard.h>
#include <nsAbBaseCID.h>
#include <nsAbAddressCollecter.h>
#include <nsIPref.h>
#include <nsIAddrBookSession.h>
#include <nsIMsgHeaderParser.h>
#include <nsIAddrBookSession.h>
#include <nsIAbDirectory.h>
#include <nsAbDirectoryQuery.h>
#include <nsIAbDirectoryQuery.h>
#include <nsIAbDirectoryQueryProxy.h>
#include <nsIAbDirFactory.h>

#ifdef MOZ_BOOL
# undef BOOL
# undef Bool
#endif

#ifdef DEBUG_WAS_DEFINED
    #define DEBUG DEBUG_WAS_DEFINED
#endif

#ifdef _DEBUG_WAS_DEFINED
    #define _DEBUG _DEBUG_WAS_DEFINED
#endif

#endif // _CONNECTIVITY_MAB_NS_INCLUDE_HXX_
<commit_msg>INTEGRATION: CWS mozab04 (1.7.170); FILE MERGED 2004/04/27 03:13:36 windly 1.7.170.2: #i28398# update Mozilla components from v1.0 to v1.7 2004/04/12 10:15:55 windly 1.7.170.1: #i6883# make mozab driver threadsafe<commit_after>/*************************************************************************
 *
 *  $RCSfile: MNSInclude.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hjs $ $Date: 2004-06-25 18:32:02 $
 *
 *  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): Willem van Dorp, Darren Kenny
 *
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_MAB_NS_INCLUDE_HXX_
#define _CONNECTIVITY_MAB_NS_INCLUDE_HXX_ 1

//
// Only include Mozilla include files once and using this file...
//

#ifndef BOOL
# define MOZ_BOOL

# define BOOL mozBOOL
# define Bool mozBooL
#endif

// 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

#include <nsDebug.h>

#include <nsCOMPtr.h>
#include <nsISupportsArray.h>
#include <nsString.h>
#include <nsMemory.h>
#include <prtypes.h>
#include <nsRDFCID.h>
#include <nsXPIDLString.h>
#include <nsIRDFService.h>
#include <nsIRDFResource.h>
#include <nsReadableUtils.h>
#include <msgCore.h>
#include <nsIServiceManager.h>
#include <nsIAbCard.h>
#include <nsAbBaseCID.h>
#include <nsAbAddressCollecter.h>
#include <nsIPref.h>
#include <nsIAddrBookSession.h>
#include <nsIMsgHeaderParser.h>
#include <nsIAddrBookSession.h>
#include <nsIAbDirectory.h>
#include <nsAbDirectoryQuery.h>
#include <nsIAbDirectoryQuery.h>
#include <nsIAbDirectoryQueryProxy.h>
#include <nsIAbDirFactory.h>
#include <nsIRunnable.h>

#ifdef MOZ_BOOL
# undef BOOL
# undef Bool
#endif

#ifdef DEBUG_WAS_DEFINED
    #define DEBUG DEBUG_WAS_DEFINED
#endif

#ifdef _DEBUG_WAS_DEFINED
    #define _DEBUG _DEBUG_WAS_DEFINED
#endif

#endif // _CONNECTIVITY_MAB_NS_INCLUDE_HXX_
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkGraphLayout.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.

=========================================================================*/
/*----------------------------------------------------------------------------
 Copyright (c) Sandia Corporation
 See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/

#include "vtkGraphLayout.h"

#include <vtkCellArray.h>
#include <vtkCellData.h>
#include <vtkDataArray.h>
#include <vtkEventForwarderCommand.h>
#include <vtkFloatArray.h>
#include <vtkMath.h>
#include <vtkInformation.h>
#include <vtkInformationVector.h>
#include <vtkObjectFactory.h>
#include <vtkPointData.h>

#include "vtkGraphLayoutStrategy.h"

vtkCxxRevisionMacro(vtkGraphLayout, "1.3");
vtkStandardNewMacro(vtkGraphLayout);

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

vtkGraphLayout::vtkGraphLayout()
{
  this->LayoutStrategy = 0;
  this->LastInput = NULL;
  this->LastInputMTime = 0;
  this->InternalGraph = NULL;

  this->ObserverTag = 0;
  this->EventForwarder = vtkEventForwarderCommand::New();
  this->EventForwarder->SetTarget(this);
}

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

vtkGraphLayout::~vtkGraphLayout()
{
  if (this->LayoutStrategy)
    {
    this->LayoutStrategy->Delete();
    }
  if (this->InternalGraph)
    {
    this->InternalGraph->Delete();
    }
  this->EventForwarder->Delete();
}

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

void
vtkGraphLayout::SetLayoutStrategy(vtkGraphLayoutStrategy *strategy)
{
  // This method is a cut and paste of vtkCxxSetObjectMacro
  // except for the call to SetGraph in the middle :)
  if (strategy != this->LayoutStrategy)
    {
    vtkGraphLayoutStrategy *tmp = this->LayoutStrategy;
    this->LayoutStrategy = strategy;
    if (this->LayoutStrategy != NULL)
      {
      this->LayoutStrategy->Register(this);
      this->ObserverTag =
        this->LayoutStrategy->AddObserver(vtkCommand::ProgressEvent,
                                          this->EventForwarder);
      if (this->InternalGraph)
        {
        // Set the graph in the layout strategy
        this->LayoutStrategy->SetGraph(this->InternalGraph);
        }
      }
    if (tmp != NULL)
      {
      tmp->UnRegister(this);
      tmp->RemoveObserver(this->ObserverTag);
      }
    this->Modified();
    }

}

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

unsigned long
vtkGraphLayout::GetMTime()
{
  unsigned long mTime = this->Superclass::GetMTime();
  unsigned long time;

  if (this->LayoutStrategy != NULL)
    {
    time = this->LayoutStrategy->GetMTime();
    mTime = (time > mTime ? time : mTime);
    }
  return mTime;
}

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

int
vtkGraphLayout::IsLayoutComplete()
{
  if (this->LayoutStrategy)
    {
    return this->LayoutStrategy->IsLayoutComplete();
    }

  // This is an error condition
  vtkErrorMacro("IsLayoutComplete called with layout strategy==NULL");
  return 0;
}

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

int
vtkGraphLayout::RequestData(vtkInformation *vtkNotUsed(request),
                            vtkInformationVector **inputVector,
                            vtkInformationVector *outputVector)
{
  if (this->LayoutStrategy == NULL)
    {
    vtkErrorMacro(<< "Layout strategy must me non-null.");
    return 0;
    }

  // get the info objects
  vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  // get the input and output
  vtkAbstractGraph *input = vtkAbstractGraph::SafeDownCast(
    inInfo->Get(vtkDataObject::DATA_OBJECT()));
  vtkAbstractGraph *output = vtkAbstractGraph::SafeDownCast(
    outInfo->Get(vtkDataObject::DATA_OBJECT()));

  // See if the input is the same as the last input
  // Note: This is keeping state and in vtk filter
  // land this is a bad thing. :)
  if ((input != this->LastInput) ||
      (input->GetMTime() != this->LastInputMTime))
    {

    // Okay create an internal graph for supporting
    // iterative graph layout strategies
    if (this->InternalGraph)
      {
      this->InternalGraph->Delete();
      }
    this->InternalGraph = input->NewInstance();

    // Capture info about graph
    this->LastInput = input;
    this->LastInputMTime = input->GetMTime();

    // Shallow copy data to output.
    this->InternalGraph->ShallowCopy(input);

    // Deep copy the point data from input to output
    vtkPoints* oldPoints = input->GetPoints();
    vtkPoints* newPoints = vtkPoints::New();
    newPoints->DeepCopy(oldPoints);
    this->InternalGraph->SetPoints(newPoints);
    newPoints->Delete();

    // Set the graph in the layout strategy
    this->LayoutStrategy->SetGraph(this->InternalGraph);
    }

  this->LayoutStrategy->Layout();
  output->ShallowCopy(this->InternalGraph);

  return 1;
}

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

void vtkGraphLayout::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "LayoutStrategy: " << (this->LayoutStrategy ? "" : "(none)") << endl;
  if (this->LayoutStrategy)
    {
    this->LayoutStrategy->PrintSelf(os, indent.GetNextIndent());
    }
  os << indent << "InternalGraph: " << (this->InternalGraph ? "" : "(none)") << endl;
  if (this->InternalGraph)
    {
    this->InternalGraph->PrintSelf(os, indent.GetNextIndent());
    }
}
<commit_msg>BUG: Don't delete an object and *then* remove the observer... it might      already be gone.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkGraphLayout.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.

=========================================================================*/
/*----------------------------------------------------------------------------
 Copyright (c) Sandia Corporation
 See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
----------------------------------------------------------------------------*/

#include "vtkGraphLayout.h"

#include <vtkCellArray.h>
#include <vtkCellData.h>
#include <vtkDataArray.h>
#include <vtkEventForwarderCommand.h>
#include <vtkFloatArray.h>
#include <vtkMath.h>
#include <vtkInformation.h>
#include <vtkInformationVector.h>
#include <vtkObjectFactory.h>
#include <vtkPointData.h>

#include "vtkGraphLayoutStrategy.h"

vtkCxxRevisionMacro(vtkGraphLayout, "1.4");
vtkStandardNewMacro(vtkGraphLayout);

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

vtkGraphLayout::vtkGraphLayout()
{
  this->LayoutStrategy = 0;
  this->LastInput = NULL;
  this->LastInputMTime = 0;
  this->InternalGraph = NULL;

  this->ObserverTag = 0;
  this->EventForwarder = vtkEventForwarderCommand::New();
  this->EventForwarder->SetTarget(this);
}

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

vtkGraphLayout::~vtkGraphLayout()
{
  if (this->LayoutStrategy)
    {
    this->LayoutStrategy->Delete();
    }
  if (this->InternalGraph)
    {
    this->InternalGraph->Delete();
    }
  this->EventForwarder->Delete();
}

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

void
vtkGraphLayout::SetLayoutStrategy(vtkGraphLayoutStrategy *strategy)
{
  // This method is a cut and paste of vtkCxxSetObjectMacro
  // except for the call to SetGraph in the middle :)
  if (strategy != this->LayoutStrategy)
    {
    vtkGraphLayoutStrategy *tmp = this->LayoutStrategy;
    this->LayoutStrategy = strategy;
    if (this->LayoutStrategy != NULL)
      {
      this->LayoutStrategy->Register(this);
      this->ObserverTag =
        this->LayoutStrategy->AddObserver(vtkCommand::ProgressEvent,
                                          this->EventForwarder);
      if (this->InternalGraph)
        {
        // Set the graph in the layout strategy
        this->LayoutStrategy->SetGraph(this->InternalGraph);
        }
      }
    if (tmp != NULL)
      {
      tmp->RemoveObserver(this->ObserverTag);
      tmp->UnRegister(this);
      }
    this->Modified();
    }

}

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

unsigned long
vtkGraphLayout::GetMTime()
{
  unsigned long mTime = this->Superclass::GetMTime();
  unsigned long time;

  if (this->LayoutStrategy != NULL)
    {
    time = this->LayoutStrategy->GetMTime();
    mTime = (time > mTime ? time : mTime);
    }
  return mTime;
}

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

int
vtkGraphLayout::IsLayoutComplete()
{
  if (this->LayoutStrategy)
    {
    return this->LayoutStrategy->IsLayoutComplete();
    }

  // This is an error condition
  vtkErrorMacro("IsLayoutComplete called with layout strategy==NULL");
  return 0;
}

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

int
vtkGraphLayout::RequestData(vtkInformation *vtkNotUsed(request),
                            vtkInformationVector **inputVector,
                            vtkInformationVector *outputVector)
{
  if (this->LayoutStrategy == NULL)
    {
    vtkErrorMacro(<< "Layout strategy must me non-null.");
    return 0;
    }

  // get the info objects
  vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
  vtkInformation *outInfo = outputVector->GetInformationObject(0);

  // get the input and output
  vtkAbstractGraph *input = vtkAbstractGraph::SafeDownCast(
    inInfo->Get(vtkDataObject::DATA_OBJECT()));
  vtkAbstractGraph *output = vtkAbstractGraph::SafeDownCast(
    outInfo->Get(vtkDataObject::DATA_OBJECT()));

  // See if the input is the same as the last input
  // Note: This is keeping state and in vtk filter
  // land this is a bad thing. :)
  if ((input != this->LastInput) ||
      (input->GetMTime() != this->LastInputMTime))
    {

    // Okay create an internal graph for supporting
    // iterative graph layout strategies
    if (this->InternalGraph)
      {
      this->InternalGraph->Delete();
      }
    this->InternalGraph = input->NewInstance();

    // Capture info about graph
    this->LastInput = input;
    this->LastInputMTime = input->GetMTime();

    // Shallow copy data to output.
    this->InternalGraph->ShallowCopy(input);

    // Deep copy the point data from input to output
    vtkPoints* oldPoints = input->GetPoints();
    vtkPoints* newPoints = vtkPoints::New();
    newPoints->DeepCopy(oldPoints);
    this->InternalGraph->SetPoints(newPoints);
    newPoints->Delete();

    // Set the graph in the layout strategy
    this->LayoutStrategy->SetGraph(this->InternalGraph);
    }

  this->LayoutStrategy->Layout();
  output->ShallowCopy(this->InternalGraph);

  return 1;
}

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

void vtkGraphLayout::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "LayoutStrategy: " << (this->LayoutStrategy ? "" : "(none)") << endl;
  if (this->LayoutStrategy)
    {
    this->LayoutStrategy->PrintSelf(os, indent.GetNextIndent());
    }
  os << indent << "InternalGraph: " << (this->InternalGraph ? "" : "(none)") << endl;
  if (this->InternalGraph)
    {
    this->InternalGraph->PrintSelf(os, indent.GetNextIndent());
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/api/serial/serial_connection.h"

#include <windows.h>

#include <string>

namespace extensions {

namespace {

int BitrateToSpeedConstant(int bitrate) {
#define BITRATE_TO_SPEED_CASE(x) case x: return CBR_ ## x;
  switch (bitrate) {
    BITRATE_TO_SPEED_CASE(110);
    BITRATE_TO_SPEED_CASE(300);
    BITRATE_TO_SPEED_CASE(600);
    BITRATE_TO_SPEED_CASE(1200);
    BITRATE_TO_SPEED_CASE(2400);
    BITRATE_TO_SPEED_CASE(4800);
    BITRATE_TO_SPEED_CASE(9600);
    BITRATE_TO_SPEED_CASE(14400);
    BITRATE_TO_SPEED_CASE(19200);
    BITRATE_TO_SPEED_CASE(38400);
    BITRATE_TO_SPEED_CASE(57600);
    BITRATE_TO_SPEED_CASE(115200);
    BITRATE_TO_SPEED_CASE(128000);
    BITRATE_TO_SPEED_CASE(256000);
    default:
      // If the bitrate doesn't match that of one of the standard
      // index constants, it may be provided as-is to the DCB
      // structure, according to MSDN.
      return bitrate;
  }
#undef BITRATE_TO_SPEED_CASE
}

int DataBitsEnumToConstant(api::serial::DataBits data_bits) {
  switch (data_bits) {
    case api::serial::DATA_BITS_SEVEN:
      return 7;
    case api::serial::DATA_BITS_EIGHT:
    default:
      return 8;
  }
}

int ParityBitEnumToConstant(api::serial::ParityBit parity_bit) {
  switch (parity_bit) {
    case api::serial::PARITY_BIT_EVEN:
      return EVENPARITY;
    case api::serial::PARITY_BIT_ODD:
      return SPACEPARITY;
    case api::serial::PARITY_BIT_NO:
    default:
      return NOPARITY;
  }
}

int StopBitsEnumToConstant(api::serial::StopBits stop_bits) {
  switch (stop_bits) {
    case api::serial::STOP_BITS_TWO:
      return TWOSTOPBITS;
    case api::serial::STOP_BITS_ONE:
    default:
      return ONESTOPBIT;
  }
}

int SpeedConstantToBitrate(int speed) {
#define SPEED_TO_BITRATE_CASE(x) case CBR_ ## x: return x;
  switch (speed) {
    SPEED_TO_BITRATE_CASE(110);
    SPEED_TO_BITRATE_CASE(300);
    SPEED_TO_BITRATE_CASE(600);
    SPEED_TO_BITRATE_CASE(1200);
    SPEED_TO_BITRATE_CASE(2400);
    SPEED_TO_BITRATE_CASE(4800);
    SPEED_TO_BITRATE_CASE(9600);
    SPEED_TO_BITRATE_CASE(14400);
    SPEED_TO_BITRATE_CASE(19200);
    SPEED_TO_BITRATE_CASE(38400);
    SPEED_TO_BITRATE_CASE(57600);
    SPEED_TO_BITRATE_CASE(115200);
    SPEED_TO_BITRATE_CASE(128000);
    SPEED_TO_BITRATE_CASE(256000);
    default:
      // If it's not one of the standard index constants,
      // it should be an integral baud rate, according to
      // MSDN.
      return speed;
  }
#undef SPEED_TO_BITRATE_CASE
}

api::serial::DataBits DataBitsConstantToEnum(int data_bits) {
  switch (data_bits) {
    case 7:
      return api::serial::DATA_BITS_SEVEN;
    case 8:
    default:
      return api::serial::DATA_BITS_EIGHT;
  }
}

api::serial::ParityBit ParityBitConstantToEnum(int parity_bit) {
  switch (parity_bit) {
    case EVENPARITY:
      return api::serial::PARITY_BIT_EVEN;
    case ODDPARITY:
      return api::serial::PARITY_BIT_ODD;
    case NOPARITY:
    default:
      return api::serial::PARITY_BIT_NO;
  }
}

api::serial::StopBits StopBitsConstantToEnum(int stop_bits) {
  switch (stop_bits) {
    case TWOSTOPBITS:
      return api::serial::STOP_BITS_TWO;
    case ONESTOPBIT:
    default:
      return api::serial::STOP_BITS_ONE;
  }
}

}  // namespace

bool SerialConnection::ConfigurePort(
    const api::serial::ConnectionOptions& options) {
  DCB config = { 0 };
  config.DCBlength = sizeof(config);
  if (!GetCommState(file_, &config)) {
    return false;
  }
  if (options.bitrate.get())
    config.BaudRate = BitrateToSpeedConstant(*options.bitrate);
  if (options.data_bits != api::serial::DATA_BITS_NONE)
    config.ByteSize = DataBitsEnumToConstant(options.data_bits);
  if (options.parity_bit != api::serial::PARITY_BIT_NONE)
    config.Parity = ParityBitEnumToConstant(options.parity_bit);
  if (options.stop_bits != api::serial::STOP_BITS_NONE)
    config.StopBits = StopBitsEnumToConstant(options.stop_bits);
  if (options.cts_flow_control.get()) {
    if (*options.cts_flow_control) {
      config.fOutxCtsFlow = TRUE;
      config.fRtsControl = RTS_CONTROL_HANDSHAKE;
    } else {
      config.fOutxCtsFlow = FALSE;
      config.fRtsControl = RTS_CONTROL_ENABLE;
    }
  }
  return SetCommState(file_, &config) != 0;
}

bool SerialConnection::PostOpen() {
  // Set a very brief read interval timeout. This prevents the asynchronous I/O
  // system from being way too eager to fire off completion events which would
  // in turn result in a lot of onReceive events being fired (i.e., one for
  // every individual byte received on the serial buffer.)
  COMMTIMEOUTS timeouts = { 0 };
  timeouts.ReadIntervalTimeout = 10;
  if (!::SetCommTimeouts(file_, &timeouts)) {
    return false;
  }

  DCB config = { 0 };
  config.DCBlength = sizeof(config);
  if (!GetCommState(file_, &config)) {
    return false;
  }
  // Setup some sane default state.
  config.fBinary = TRUE;
  config.fParity = FALSE;
  config.fAbortOnError = TRUE;
  config.fOutxCtsFlow = FALSE;
  config.fOutxDsrFlow = FALSE;
  config.fRtsControl = RTS_CONTROL_ENABLE;
  config.fDtrControl = DTR_CONTROL_ENABLE;
  config.fDsrSensitivity = FALSE;
  config.fOutX = FALSE;
  config.fInX = FALSE;
  return SetCommState(file_, &config) != 0;
}

bool SerialConnection::Flush() const {
  return PurgeComm(file_, PURGE_RXCLEAR | PURGE_TXCLEAR) != 0;
}

bool SerialConnection::GetControlSignals(
    api::serial::DeviceControlSignals* signals) const {
  DWORD status;
  if (!GetCommModemStatus(file_, &status)) {
    return false;
  }
  signals->dcd = (status & MS_RLSD_ON) != 0;
  signals->cts = (status & MS_CTS_ON) != 0;
  signals->dsr = (status & MS_DSR_ON) != 0;
  signals->ri = (status & MS_RING_ON) != 0;
  return true;
}

bool SerialConnection::SetControlSignals(
    const api::serial::HostControlSignals& signals) {
  if (signals.dtr.get()) {
    if (!EscapeCommFunction(file_, *signals.dtr ? SETDTR : CLRDTR)) {
      return false;
    }
  }
  if (signals.rts.get()) {
    if (!EscapeCommFunction(file_, *signals.rts ? SETRTS : CLRRTS)) {
      return false;
    }
  }
  return true;
}

bool SerialConnection::GetPortInfo(api::serial::ConnectionInfo* info) const {
  DCB config = { 0 };
  config.DCBlength = sizeof(config);
  if (!GetCommState(file_, &config)) {
    return false;
  }
  info->bitrate.reset(new int(SpeedConstantToBitrate(config.BaudRate)));
  info->data_bits = DataBitsConstantToEnum(config.ByteSize);
  info->parity_bit = ParityBitConstantToEnum(config.Parity);
  info->stop_bits = StopBitsConstantToEnum(config.StopBits);
  info->cts_flow_control.reset(new bool(config.fOutxCtsFlow != 0));
  return true;
}

std::string SerialConnection::MaybeFixUpPortName(
    const std::string &port_name) {
  // For COM numbers less than 9, CreateFile is called with a string such as
  // "COM1". For numbers greater than 9, a prefix of "\\\\.\\" must be added.
  if (port_name.length() > std::string("COM9").length())
    return std::string("\\\\.\\").append(port_name);

  return port_name;
}

}  // namespace extensions
<commit_msg>Remove timeout behavior from Windows serial I/O<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/api/serial/serial_connection.h"

#include <windows.h>

#include <string>

namespace extensions {

namespace {

int BitrateToSpeedConstant(int bitrate) {
#define BITRATE_TO_SPEED_CASE(x) case x: return CBR_ ## x;
  switch (bitrate) {
    BITRATE_TO_SPEED_CASE(110);
    BITRATE_TO_SPEED_CASE(300);
    BITRATE_TO_SPEED_CASE(600);
    BITRATE_TO_SPEED_CASE(1200);
    BITRATE_TO_SPEED_CASE(2400);
    BITRATE_TO_SPEED_CASE(4800);
    BITRATE_TO_SPEED_CASE(9600);
    BITRATE_TO_SPEED_CASE(14400);
    BITRATE_TO_SPEED_CASE(19200);
    BITRATE_TO_SPEED_CASE(38400);
    BITRATE_TO_SPEED_CASE(57600);
    BITRATE_TO_SPEED_CASE(115200);
    BITRATE_TO_SPEED_CASE(128000);
    BITRATE_TO_SPEED_CASE(256000);
    default:
      // If the bitrate doesn't match that of one of the standard
      // index constants, it may be provided as-is to the DCB
      // structure, according to MSDN.
      return bitrate;
  }
#undef BITRATE_TO_SPEED_CASE
}

int DataBitsEnumToConstant(api::serial::DataBits data_bits) {
  switch (data_bits) {
    case api::serial::DATA_BITS_SEVEN:
      return 7;
    case api::serial::DATA_BITS_EIGHT:
    default:
      return 8;
  }
}

int ParityBitEnumToConstant(api::serial::ParityBit parity_bit) {
  switch (parity_bit) {
    case api::serial::PARITY_BIT_EVEN:
      return EVENPARITY;
    case api::serial::PARITY_BIT_ODD:
      return SPACEPARITY;
    case api::serial::PARITY_BIT_NO:
    default:
      return NOPARITY;
  }
}

int StopBitsEnumToConstant(api::serial::StopBits stop_bits) {
  switch (stop_bits) {
    case api::serial::STOP_BITS_TWO:
      return TWOSTOPBITS;
    case api::serial::STOP_BITS_ONE:
    default:
      return ONESTOPBIT;
  }
}

int SpeedConstantToBitrate(int speed) {
#define SPEED_TO_BITRATE_CASE(x) case CBR_ ## x: return x;
  switch (speed) {
    SPEED_TO_BITRATE_CASE(110);
    SPEED_TO_BITRATE_CASE(300);
    SPEED_TO_BITRATE_CASE(600);
    SPEED_TO_BITRATE_CASE(1200);
    SPEED_TO_BITRATE_CASE(2400);
    SPEED_TO_BITRATE_CASE(4800);
    SPEED_TO_BITRATE_CASE(9600);
    SPEED_TO_BITRATE_CASE(14400);
    SPEED_TO_BITRATE_CASE(19200);
    SPEED_TO_BITRATE_CASE(38400);
    SPEED_TO_BITRATE_CASE(57600);
    SPEED_TO_BITRATE_CASE(115200);
    SPEED_TO_BITRATE_CASE(128000);
    SPEED_TO_BITRATE_CASE(256000);
    default:
      // If it's not one of the standard index constants,
      // it should be an integral baud rate, according to
      // MSDN.
      return speed;
  }
#undef SPEED_TO_BITRATE_CASE
}

api::serial::DataBits DataBitsConstantToEnum(int data_bits) {
  switch (data_bits) {
    case 7:
      return api::serial::DATA_BITS_SEVEN;
    case 8:
    default:
      return api::serial::DATA_BITS_EIGHT;
  }
}

api::serial::ParityBit ParityBitConstantToEnum(int parity_bit) {
  switch (parity_bit) {
    case EVENPARITY:
      return api::serial::PARITY_BIT_EVEN;
    case ODDPARITY:
      return api::serial::PARITY_BIT_ODD;
    case NOPARITY:
    default:
      return api::serial::PARITY_BIT_NO;
  }
}

api::serial::StopBits StopBitsConstantToEnum(int stop_bits) {
  switch (stop_bits) {
    case TWOSTOPBITS:
      return api::serial::STOP_BITS_TWO;
    case ONESTOPBIT:
    default:
      return api::serial::STOP_BITS_ONE;
  }
}

}  // namespace

bool SerialConnection::ConfigurePort(
    const api::serial::ConnectionOptions& options) {
  DCB config = { 0 };
  config.DCBlength = sizeof(config);
  if (!GetCommState(file_, &config)) {
    return false;
  }
  if (options.bitrate.get())
    config.BaudRate = BitrateToSpeedConstant(*options.bitrate);
  if (options.data_bits != api::serial::DATA_BITS_NONE)
    config.ByteSize = DataBitsEnumToConstant(options.data_bits);
  if (options.parity_bit != api::serial::PARITY_BIT_NONE)
    config.Parity = ParityBitEnumToConstant(options.parity_bit);
  if (options.stop_bits != api::serial::STOP_BITS_NONE)
    config.StopBits = StopBitsEnumToConstant(options.stop_bits);
  if (options.cts_flow_control.get()) {
    if (*options.cts_flow_control) {
      config.fOutxCtsFlow = TRUE;
      config.fRtsControl = RTS_CONTROL_HANDSHAKE;
    } else {
      config.fOutxCtsFlow = FALSE;
      config.fRtsControl = RTS_CONTROL_ENABLE;
    }
  }
  return SetCommState(file_, &config) != 0;
}

bool SerialConnection::PostOpen() {
  // A ReadIntervalTimeout of MAXDWORD will cause async reads to complete
  // immediately with any data that's available, even if there is none.
  // This is OK because we never issue a read request until WaitCommEvent
  // signals that data is available.
  COMMTIMEOUTS timeouts = { 0 };
  timeouts.ReadIntervalTimeout = MAXDWORD;
  if (!::SetCommTimeouts(file_, &timeouts)) {
    return false;
  }

  DCB config = { 0 };
  config.DCBlength = sizeof(config);
  if (!GetCommState(file_, &config)) {
    return false;
  }
  // Setup some sane default state.
  config.fBinary = TRUE;
  config.fParity = FALSE;
  config.fAbortOnError = TRUE;
  config.fOutxCtsFlow = FALSE;
  config.fOutxDsrFlow = FALSE;
  config.fRtsControl = RTS_CONTROL_ENABLE;
  config.fDtrControl = DTR_CONTROL_ENABLE;
  config.fDsrSensitivity = FALSE;
  config.fOutX = FALSE;
  config.fInX = FALSE;
  return SetCommState(file_, &config) != 0;
}

bool SerialConnection::Flush() const {
  return PurgeComm(file_, PURGE_RXCLEAR | PURGE_TXCLEAR) != 0;
}

bool SerialConnection::GetControlSignals(
    api::serial::DeviceControlSignals* signals) const {
  DWORD status;
  if (!GetCommModemStatus(file_, &status)) {
    return false;
  }
  signals->dcd = (status & MS_RLSD_ON) != 0;
  signals->cts = (status & MS_CTS_ON) != 0;
  signals->dsr = (status & MS_DSR_ON) != 0;
  signals->ri = (status & MS_RING_ON) != 0;
  return true;
}

bool SerialConnection::SetControlSignals(
    const api::serial::HostControlSignals& signals) {
  if (signals.dtr.get()) {
    if (!EscapeCommFunction(file_, *signals.dtr ? SETDTR : CLRDTR)) {
      return false;
    }
  }
  if (signals.rts.get()) {
    if (!EscapeCommFunction(file_, *signals.rts ? SETRTS : CLRRTS)) {
      return false;
    }
  }
  return true;
}

bool SerialConnection::GetPortInfo(api::serial::ConnectionInfo* info) const {
  DCB config = { 0 };
  config.DCBlength = sizeof(config);
  if (!GetCommState(file_, &config)) {
    return false;
  }
  info->bitrate.reset(new int(SpeedConstantToBitrate(config.BaudRate)));
  info->data_bits = DataBitsConstantToEnum(config.ByteSize);
  info->parity_bit = ParityBitConstantToEnum(config.Parity);
  info->stop_bits = StopBitsConstantToEnum(config.StopBits);
  info->cts_flow_control.reset(new bool(config.fOutxCtsFlow != 0));
  return true;
}

std::string SerialConnection::MaybeFixUpPortName(
    const std::string &port_name) {
  // For COM numbers less than 9, CreateFile is called with a string such as
  // "COM1". For numbers greater than 9, a prefix of "\\\\.\\" must be added.
  if (port_name.length() > std::string("COM9").length())
    return std::string("\\\\.\\").append(port_name);

  return port_name;
}

}  // namespace extensions
<|endoftext|>


<commit_before><commit_msg>Fix issue with selecting proper JNI libraries<commit_after><|endoftext|>


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

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

*******************************************************************************/

//==============================================================================
// Lexer for the pretty CellML format
//==============================================================================

#include "prettycellmlviewlexer.h"
#include "qscintillawidget.h"

//==============================================================================

#include <QRegularExpression>

//==============================================================================

namespace OpenCOR {
namespace PrettyCellMLView {

//==============================================================================

PrettyCellmlViewLexer::PrettyCellmlViewLexer(QObject *pParent) :
    QsciLexerCustom(pParent),
    mFullText(QString())
{
    // Some initialisations

    mKeywords = QStringList() << "as" << "comp" << "def" << "enddef" << "model" << "unit";
    mCellmlKeywords = QStringList() << "base"
                                    << "ampere" << "candela" << "coulomb" << "joule" << "kelvin" << "kilogram" << "liter" << "litre" << "lumen" << "meter" << "metre" << "mole" << "newton" << "second" << "steradian" << "volt" << "watt" << "weber";
    mParameterKeywords = QStringList() << "pref" << "expo" << "mult" << "off";
    mParameterValueKeywords = QStringList() << "milli";
}

//==============================================================================

const char * PrettyCellmlViewLexer::language() const
{
    // Return the language for our lexer

    return "Pretty CellML";
}

//==============================================================================

QString PrettyCellmlViewLexer::description(int pStyle) const
{
    // Return the given style's description

    switch (pStyle) {
    case Default:
        return QObject::tr("Default");
    case Comment:
        return QObject::tr("Comment");
    case Keyword:
        return QObject::tr("Keyword");
    case CellmlKeyword:
        return QObject::tr("CellML keyword");
    case Number:
        return QObject::tr("Number");
    case ParameterGroup:
        return QObject::tr("Parameter group");
    case ParameterKeyword:
        return QObject::tr("Parameter keyword");
    case ParameterValueKeyword:
        return QObject::tr("Parameter value keyword");
    case ParameterNumber:
        return QObject::tr("Parameter number");
    }

    return QString();
}

//==============================================================================

QColor PrettyCellmlViewLexer::color(int pStyle) const
{
    // Return the given style's colour

    switch (pStyle) {
    case Default:
    case ParameterGroup:
        return QColor(0x1f, 0x1f, 0x1f);
    case Comment:
        return QColor(0x00, 0x7f, 0x00);
    case Keyword:
    case ParameterKeyword:
        return QColor(0x00, 0x00, 0x7f);
    case CellmlKeyword:
    case ParameterValueKeyword:
        return QColor(0x7f, 0x00, 0x7f);
    case Number:
    case ParameterNumber:
        return QColor(0x7f, 0x7f, 0x00);
    }

    return QsciLexerCustom::color(pStyle);
}

//==============================================================================

QFont PrettyCellmlViewLexer::font(int pStyle) const
{
    // Return the given style's colour

    QFont res = QsciLexer::font(pStyle);

    switch (pStyle) {
    case ParameterGroup:
    case ParameterKeyword:
    case ParameterValueKeyword:
    case ParameterNumber:
        res.setItalic(true);

        break;
    }

    return res;
}

//==============================================================================

void PrettyCellmlViewLexer::styleText(int pStart, int pEnd)
{
    // Make sure that we have an editor

    if (!editor())
        return;

    // Retrieve the text to style

    char *data = new char[pEnd-pStart+1];

    editor()->SendScintilla(QsciScintilla::SCI_GETTEXTRANGE, pStart, pEnd, data);

    QString text = QString(data);

    delete[] data;

    if (text.isEmpty())
        return;

    // Effectively style our text

    mFullText = editor()->text();

    doStyleText(pStart, pEnd, text, false);
}

//==============================================================================

void PrettyCellmlViewLexer::doStyleText(int pStart, int pEnd, QString pText,
                                        bool pParameterGroup)
{
    // Make sure that we are given some text to style

    if (pText.trimmed().isEmpty())
        return;

    // Check whether a /* XXX */ comment started before or at the beginning of
    // the given text

    static const QString StartCommentString = "/*";
    static const QString EndCommentString = "*/";
    static const int StartCommentLength = StartCommentString.length();
    static const int EndCommentLength = EndCommentString.length();

    int commentStartPosition = mFullText.lastIndexOf(StartCommentString, pStart+StartCommentLength);

    if (commentStartPosition != -1) {
        // A /* XXX */ comment started before or at the beginning of the given
        // text, so now look for where it ends

        int commentEndPosition = mFullText.indexOf(EndCommentString, commentStartPosition+StartCommentLength);

        if (commentEndPosition == -1)
            commentEndPosition = mFullText.length();

        if ((commentStartPosition <= pStart) && (pStart <= commentEndPosition)) {
            // The beginning of the given text is a comment, so style it

            int realEnd = commentEndPosition+EndCommentLength;
            int end = qMin(pEnd, realEnd);

            startStyling(pStart, 0x1f);
            setStyling(end-pStart, Comment);

            // Style everything that is behind the comment, if anything

            if (end == realEnd)
                doStyleText(end, pEnd, pText.right(pEnd-end), pParameterGroup);

            return;
        }
    }

    // Check whether a parameter group started before or at the beginning of the
    // given text

    static const QString StartParameterGroupString = "{";
    static const QString EndParameterGroupString = "}";
    static const int StartParameterGroupLength = StartParameterGroupString.length();
    static const int EndParameterGroupLength = EndParameterGroupString.length();

    int parameterGroupStartPosition = mFullText.lastIndexOf(StartParameterGroupString, pStart+StartParameterGroupLength);

    if (parameterGroupStartPosition != -1) {
        // A parameter group started before or at the beginning of the given
        // text, so now look for where it ends

        int parameterGroupEndPosition = mFullText.indexOf(EndParameterGroupString, parameterGroupStartPosition+StartParameterGroupLength);

        if (parameterGroupEndPosition == -1)
            parameterGroupEndPosition = mFullText.length();

        if ((parameterGroupStartPosition <= pStart) && (pStart <= parameterGroupEndPosition)) {
            // The beginning of the given text is a parameter group, so style
            // everything that is behind the parameter group, if anything

            int realEnd = parameterGroupEndPosition+EndParameterGroupLength;
            int end = qMin(pEnd, realEnd);

            if (end == realEnd)
                doStyleText(end, pEnd, pText.right(pEnd-end), pParameterGroup);

            // Style the beginning and the end of the parameter group

            startStyling(pStart, 0x1f);
            setStyling(StartParameterGroupLength, ParameterGroup);

            if (end == realEnd) {
                startStyling(end-EndParameterGroupLength, 0x1f);
                setStyling(EndParameterGroupLength, ParameterGroup);
            }

            // Now style the contents of the parameter group

            int startShift = pText.left(StartParameterGroupLength).compare(StartParameterGroupString)?0:StartParameterGroupLength;

            pStart += startShift;
            pEnd = end-(pText.mid(end-EndParameterGroupLength, EndParameterGroupLength).compare(EndParameterGroupString)?0:EndParameterGroupLength);
            pText = pText.mid(startShift, pEnd-pStart);
            pParameterGroup = true;
        }
    }

    // Check whether the given text contains a // comment

    static const QString CommentString = "//";

    int commentPosition = pText.indexOf(CommentString);

    if (commentPosition != -1) {
        // There is a // comment to style, so first style everything that is
        // before the // comment

        doStyleText(pStart, pStart+commentPosition, pText.left(commentPosition),
                    pParameterGroup);

        // Now, style everything that is after the // comment, if anything, by
        // looking for the end of the line on which the // comment is

        QString eolString = qobject_cast<QScintillaSupport::QScintillaWidget *>(editor())->eolString();
        int eolStringLength = eolString.length();
        int eolPosition = pText.indexOf(eolString, commentPosition+eolStringLength);

        if (eolPosition != -1) {
            int start = pStart+eolPosition+eolStringLength;

            doStyleText(start, pEnd, pText.right(pEnd-start), pParameterGroup);
        }

        // Style the // comment itself

        int start = pStart+commentPosition;

        startStyling(start, 0x1f);
        setStyling(((eolPosition == -1)?pEnd:pStart+eolPosition)-start, Comment);

        return;
    }

    // Check whether the given text contains a /* XXX */ comment

    commentStartPosition = pText.indexOf(StartCommentString);

    if (commentStartPosition != -1) {
        // There is a /* XXX */ comment to style, so first style everything that
        // is before it

        doStyleText(pStart, pStart+commentStartPosition,
                    pText.left(commentStartPosition), pParameterGroup);

        // Now style everything from the comment onwards
        // Note: to style everything from the comment onwards means that we will
        //       find that a /* XXX */ comment starts at the beginning of the
        //       'new' given text...

        doStyleText(pStart+commentStartPosition, pEnd,
                    pText.right(pEnd-pStart-commentStartPosition),
                    pParameterGroup);

        return;
    }

    // Check whether the given text contains a parameter group

    parameterGroupStartPosition = pText.indexOf(StartParameterGroupString);

    if (parameterGroupStartPosition != -1) {
        // There is a parameter group, so first style everything that is before
        // it

        doStyleText(pStart, pStart+parameterGroupStartPosition,
                    pText.left(parameterGroupStartPosition), pParameterGroup);

        // Now style everything from the parameter group onwards
        // Note: to style everything from the parameter group onwards means that
        //       we will find that a parameter group starts at the beginning of
        //       the 'new' given text...

        doStyleText(pStart+parameterGroupStartPosition, pEnd,
                    pText.right(pEnd-pStart-parameterGroupStartPosition),
                    pParameterGroup);

        return;
    }

    // Use a default style for the given text

    startStyling(pStart, 0x1f);
    setStyling(pEnd-pStart, pParameterGroup?ParameterGroup:Default);

    // Check whether the given text contains keywords from various categories

    doStyleTextKeyword(pStart, pText, mKeywords, Keyword);
    doStyleTextKeyword(pStart, pText, mCellmlKeywords, CellmlKeyword);
    doStyleTextKeyword(pStart, pText, mParameterKeywords, ParameterKeyword);
    doStyleTextKeyword(pStart, pText, mParameterValueKeywords, ParameterValueKeyword);
}

//==============================================================================

void PrettyCellmlViewLexer::doStyleTextKeyword(int pStart,
                                               const QString &pText,
                                               const QStringList pKeywords,
                                               const int &pKeywordStyle)
{
    // Check whether the given text contains some of the given keywords

    foreach (const QString &keyword, pKeywords) {
        QRegularExpressionMatchIterator regExMatchIter = QRegularExpression("\\b"+keyword+"\\b").globalMatch(pText);

        while (regExMatchIter.hasNext()) {
            QRegularExpressionMatch regExMatch = regExMatchIter.next();

            // We found a keyword, so style it as such

            startStyling(pStart+regExMatch.capturedStart(), 0x1f);
            setStyling(regExMatch.capturedLength(), pKeywordStyle);
        }
    }
}

//==============================================================================

}   // namespace PrettyCellMLView
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<commit_msg>Pretty CellML view: some work on providing syntax highlighting for the pretty CellML format (#530) [ci skip].<commit_after>/*******************************************************************************

Licensed to the OpenCOR team under one or more contributor license agreements.
See the NOTICE.txt file distributed with this work for additional information
regarding copyright ownership. The OpenCOR team licenses this file to you under
the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.

*******************************************************************************/

//==============================================================================
// Lexer for the pretty CellML format
//==============================================================================

#include "prettycellmlviewlexer.h"
#include "qscintillawidget.h"

//==============================================================================

#include <QRegularExpression>

//==============================================================================

namespace OpenCOR {
namespace PrettyCellMLView {

//==============================================================================

PrettyCellmlViewLexer::PrettyCellmlViewLexer(QObject *pParent) :
    QsciLexerCustom(pParent),
    mFullText(QString())
{
    // Some initialisations

    mKeywords = QStringList() << "as" << "comp" << "def" << "enddef" << "model" << "unit";
    mCellmlKeywords = QStringList() << "base"
                                    << "ampere" << "candela" << "coulomb" << "joule" << "kelvin" << "kilogram" << "liter" << "litre" << "lumen" << "meter" << "metre" << "mole" << "newton" << "second" << "steradian" << "volt" << "watt" << "weber";
    mParameterKeywords = QStringList() << "pref" << "expo" << "mult" << "off";
    mParameterValueKeywords = QStringList() << "milli";
}

//==============================================================================

const char * PrettyCellmlViewLexer::language() const
{
    // Return the language for our lexer

    return "Pretty CellML";
}

//==============================================================================

QString PrettyCellmlViewLexer::description(int pStyle) const
{
    // Return the given style's description

    switch (pStyle) {
    case Default:
        return QObject::tr("Default");
    case Comment:
        return QObject::tr("Comment");
    case Keyword:
        return QObject::tr("Keyword");
    case CellmlKeyword:
        return QObject::tr("CellML keyword");
    case Number:
        return QObject::tr("Number");
    case ParameterGroup:
        return QObject::tr("Parameter group");
    case ParameterKeyword:
        return QObject::tr("Parameter keyword");
    case ParameterValueKeyword:
        return QObject::tr("Parameter value keyword");
    case ParameterNumber:
        return QObject::tr("Parameter number");
    }

    return QString();
}

//==============================================================================

QColor PrettyCellmlViewLexer::color(int pStyle) const
{
    // Return the given style's colour

    switch (pStyle) {
    case Default:
    case ParameterGroup:
        return QColor(0x1f, 0x1f, 0x1f);
    case Comment:
        return QColor(0x00, 0x7f, 0x00);
    case Keyword:
    case ParameterKeyword:
        return QColor(0x00, 0x00, 0x7f);
    case CellmlKeyword:
    case ParameterValueKeyword:
        return QColor(0x7f, 0x00, 0x7f);
    case Number:
    case ParameterNumber:
        return QColor(0x7f, 0x7f, 0x00);
    }

    return QsciLexerCustom::color(pStyle);
}

//==============================================================================

QFont PrettyCellmlViewLexer::font(int pStyle) const
{
    // Return the given style's colour

    QFont res = QsciLexer::font(pStyle);

    switch (pStyle) {
    case ParameterGroup:
    case ParameterKeyword:
    case ParameterValueKeyword:
    case ParameterNumber:
        res.setItalic(true);

        break;
    }

    return res;
}

//==============================================================================

void PrettyCellmlViewLexer::styleText(int pStart, int pEnd)
{
    // Make sure that we have an editor

    if (!editor())
        return;

    // Retrieve the text to style

    char *data = new char[pEnd-pStart+1];

    editor()->SendScintilla(QsciScintilla::SCI_GETTEXTRANGE, pStart, pEnd, data);

    QString text = QString(data);

    delete[] data;

    if (text.isEmpty())
        return;

    // Effectively style our text

    mFullText = editor()->text();

    doStyleText(pStart, pEnd, text, false);
}

//==============================================================================

void PrettyCellmlViewLexer::doStyleText(int pStart, int pEnd, QString pText,
                                        bool pParameterGroup)
{
    // Make sure that we are given some text to style

    if (pText.trimmed().isEmpty())
        return;

    // Check whether a /* XXX */ comment started before or at the beginning of
    // the given text

    static const QString StartCommentString = "/*";
    static const QString EndCommentString = "*/";
    static const int StartCommentLength = StartCommentString.length();
    static const int EndCommentLength = EndCommentString.length();

    int commentStartPosition = mFullText.lastIndexOf(StartCommentString, pStart+StartCommentLength);

    if (commentStartPosition != -1) {
        // A /* XXX */ comment started before or at the beginning of the given
        // text, so now look for where it ends

        int commentEndPosition = mFullText.indexOf(EndCommentString, commentStartPosition+StartCommentLength);

        if (commentEndPosition == -1)
            commentEndPosition = mFullText.length();

        if ((commentStartPosition <= pStart) && (pStart <= commentEndPosition)) {
            // The beginning of the given text is a comment, so style it

            int realEnd = commentEndPosition+EndCommentLength;
            int end = qMin(pEnd, realEnd);

            startStyling(pStart, 0x1f);
            setStyling(end-pStart, Comment);

            // Style everything that is behind the comment, if anything

            if (end == realEnd)
                doStyleText(end, pEnd, pText.right(pEnd-end), pParameterGroup);

            return;
        }
    }

    // Check whether a parameter group started before or at the beginning of the
    // given text

    static const QString StartParameterGroupString = "{";
    static const QString EndParameterGroupString = "}";
    static const int StartParameterGroupLength = StartParameterGroupString.length();
    static const int EndParameterGroupLength = EndParameterGroupString.length();

    int parameterGroupStartPosition = mFullText.lastIndexOf(StartParameterGroupString, pStart+StartParameterGroupLength);

    if (parameterGroupStartPosition != -1) {
        // A parameter group started before or at the beginning of the given
        // text, so now look for where it ends

        int parameterGroupEndPosition = mFullText.indexOf(EndParameterGroupString, parameterGroupStartPosition+StartParameterGroupLength);

        if (parameterGroupEndPosition == -1)
            parameterGroupEndPosition = mFullText.length();

        if ((parameterGroupStartPosition <= pStart) && (pStart <= parameterGroupEndPosition)) {
            // The beginning of the given text is a parameter group, so style
            // everything that is behind the parameter group, if anything

            int realEnd = parameterGroupEndPosition+EndParameterGroupLength;
            int end = qMin(pEnd, realEnd);

            if (end == realEnd)
                doStyleText(end, pEnd, pText.right(pEnd-end), pParameterGroup);

            // Style the beginning and the end of the parameter group

            startStyling(pStart, 0x1f);
            setStyling(StartParameterGroupLength, ParameterGroup);

            if (end == realEnd) {
                startStyling(end-EndParameterGroupLength, 0x1f);
                setStyling(EndParameterGroupLength, ParameterGroup);
            }

            // Now style the contents of the parameter group

            int startShift = pText.left(StartParameterGroupLength).compare(StartParameterGroupString)?0:StartParameterGroupLength;

            pStart += startShift;
            pEnd = end-(pText.mid(end-EndParameterGroupLength, EndParameterGroupLength).compare(EndParameterGroupString)?0:EndParameterGroupLength);
            pText = pText.mid(startShift, pEnd-pStart);
            pParameterGroup = true;
        }
    }

    // Check whether the given text contains a // comment

    static const QString CommentString = "//";

    int commentPosition = pText.indexOf(CommentString);

    if (commentPosition != -1) {
        // There is a // comment to style, so first style everything that is
        // before the // comment

        doStyleText(pStart, pStart+commentPosition, pText.left(commentPosition),
                    pParameterGroup);

        // Now, style everything that is after the // comment, if anything, by
        // looking for the end of the line on which the // comment is

        QString eolString = qobject_cast<QScintillaSupport::QScintillaWidget *>(editor())->eolString();
        int eolStringLength = eolString.length();
        int eolPosition = pText.indexOf(eolString, commentPosition+eolStringLength);

        if (eolPosition != -1) {
            int start = pStart+eolPosition+eolStringLength;

            doStyleText(start, pEnd, pText.right(pEnd-start), pParameterGroup);
        }

        // Style the // comment itself

        int start = pStart+commentPosition;

        startStyling(start, 0x1f);
        setStyling(((eolPosition == -1)?pEnd:pStart+eolPosition)-start, Comment);

        return;
    }

    // Check whether the given text contains a /* XXX */ comment

    commentStartPosition = pText.indexOf(StartCommentString);

    if (commentStartPosition != -1) {
        // There is a /* XXX */ comment to style, so first style everything that
        // is before it

        doStyleText(pStart, pStart+commentStartPosition,
                    pText.left(commentStartPosition), pParameterGroup);

        // Now style everything from the comment onwards
        // Note: to style everything from the comment onwards means that we will
        //       find that a /* XXX */ comment starts at the beginning of the
        //       'new' given text...

        doStyleText(pStart+commentStartPosition, pEnd,
                    pText.right(pEnd-pStart-commentStartPosition),
                    pParameterGroup);

        return;
    }

    // Check whether the given text contains a parameter group

    parameterGroupStartPosition = pText.indexOf(StartParameterGroupString);

    if (parameterGroupStartPosition != -1) {
        // There is a parameter group, so first style everything that is before
        // it

        doStyleText(pStart, pStart+parameterGroupStartPosition,
                    pText.left(parameterGroupStartPosition), pParameterGroup);

        // Now style everything from the parameter group onwards
        // Note: to style everything from the parameter group onwards means that
        //       we will find that a parameter group starts at the beginning of
        //       the 'new' given text...

        doStyleText(pStart+parameterGroupStartPosition, pEnd,
                    pText.right(pEnd-pStart-parameterGroupStartPosition),
                    pParameterGroup);

        return;
    }

    // Use a default style for the given text

    startStyling(pStart, 0x1f);
    setStyling(pEnd-pStart, pParameterGroup?ParameterGroup:Default);

    // Check whether the given text contains keywords from various categories

    doStyleTextKeyword(pStart, pText, mKeywords, pParameterGroup?ParameterGroup:Keyword);
    doStyleTextKeyword(pStart, pText, mCellmlKeywords, pParameterGroup?ParameterGroup:CellmlKeyword);
    doStyleTextKeyword(pStart, pText, mParameterKeywords, pParameterGroup?ParameterKeyword:Default);
    doStyleTextKeyword(pStart, pText, mParameterValueKeywords, pParameterGroup?ParameterValueKeyword:Default);
}

//==============================================================================

void PrettyCellmlViewLexer::doStyleTextKeyword(int pStart,
                                               const QString &pText,
                                               const QStringList pKeywords,
                                               const int &pKeywordStyle)
{
    // Check whether the given text contains some of the given keywords

    foreach (const QString &keyword, pKeywords) {
        QRegularExpressionMatchIterator regExMatchIter = QRegularExpression("\\b"+keyword+"\\b").globalMatch(pText);

        while (regExMatchIter.hasNext()) {
            QRegularExpressionMatch regExMatch = regExMatchIter.next();

            // We found a keyword, so style it as such

            startStyling(pStart+regExMatch.capturedStart(), 0x1f);
            setStyling(regExMatch.capturedLength(), pKeywordStyle);
        }
    }
}

//==============================================================================

}   // namespace PrettyCellMLView
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<|endoftext|>


<commit_before>/*
 * Rooms Model - A model of chatrooms.
 * Copyright (C) 2012  Dominik Cermak <d.cermak@arcor.de>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "rooms-model.h"
#include <KIcon>
#include <KLocale>

// RoomsModel
KTp::RoomsModel::RoomsModel(QObject *parent): QAbstractListModel(parent)
{
}

int KTp::RoomsModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid()) {
        return 0;
    } else {
        return m_roomInfoList.size();
    }
}

int KTp::RoomsModel::columnCount(const QModelIndex &parent) const
{
    if (parent.isValid()) {
        return 0;
    } else {
        return 4;
    }
}

QVariant KTp::RoomsModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid()) {
        return QVariant();
    }

    if (index.row() >= m_roomInfoList.count()) {
        return QVariant();
    }

    const int row = index.row();
    const Tp::RoomInfo &roomInfo = m_roomInfoList.at(row);

    // this is handled here because when putting it in the switch below
    // all columns get an empty space for the decoration
    if (index.column() == PasswordColumn) {
        switch (role) {
        case Qt::DecorationRole:
            if (roomInfo.info.value(QLatin1String("password")).toBool()) {
                return KIcon(QLatin1String("object-locked"));
            } else {
                return QVariant();
            }
        case Qt::ToolTipRole:
            if (roomInfo.info.value(QLatin1String("password")).toBool()) {
                return i18n("Password required");
            } else {
                return i18n("No password required");
            }
        }
    }

    switch(role) {
    case Qt::DisplayRole:
        switch (index.column()) {
        case PasswordColumn:
            return QVariant();
        case NameColumn:
            return roomInfo.info.value(QLatin1String("name"));
        case DescriptionColumn:
            return roomInfo.info.value(QLatin1String("description"));
        case MembersColumn:
            return roomInfo.info.value(QLatin1String("members"));
        }
    case Qt::ToolTipRole:
        switch (index.column()) {
        case MembersColumn:
            return i18n("Member count");
        }
    case RoomsModel::HandleNameRole:
        return roomInfo.info.value(QLatin1String("handle-name"));
    }

    return QVariant();
}

QVariant KTp::RoomsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role != Qt::DisplayRole && role != Qt::DecorationRole) {
        return QVariant();
    }

    if (orientation == Qt::Horizontal) {
        switch (role) {
        case Qt::DisplayRole:
            switch (section) {
            case NameColumn:
                return i18nc("Chatrooms name", "Name");
            case DescriptionColumn:
                return i18nc("Chatrooms description", "Description");
            }
        case Qt::DecorationRole:
            switch (section) {
            case PasswordColumn:
                return KIcon(QLatin1String("object-locked"));
            case MembersColumn:
                return KIcon(QLatin1String("meeting-participant"));
            }
        }
    }

    return QVariant();
}

void KTp::RoomsModel::addRooms(const Tp::RoomInfoList newRoomList)
{
    if (newRoomList.size() > 0) {
        beginInsertRows(QModelIndex(), m_roomInfoList.size(), m_roomInfoList.size() + newRoomList.size() - 1);
        m_roomInfoList.append(newRoomList);
        endInsertRows();
    }
}

void KTp::RoomsModel::clearRoomInfoList()
{
    if (m_roomInfoList.size() > 0) {
        beginRemoveRows(QModelIndex(), 0, m_roomInfoList.size() - 1);
        m_roomInfoList.clear();
        endRemoveRows();
    }
}

// FavoriteRoomsModel
KTp::FavoriteRoomsModel::FavoriteRoomsModel(QObject *parent): QAbstractListModel(parent)
{
}

int KTp::FavoriteRoomsModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid()) {
        return 0;
    } else {
        return m_favoriteRoomsList.size();
    }
}

int KTp::FavoriteRoomsModel::columnCount(const QModelIndex &parent) const
{
    if (parent.isValid()) {
        return 0;
    } else {
        return 3;
    }
}

QVariant KTp::FavoriteRoomsModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid()) {
        return QVariant();
    }

    if (index.row() >= m_favoriteRoomsList.size()) {
        return QVariant();
    }

    const int row = index.row();
    const QVariantMap &room = m_favoriteRoomsList.at(row);

    switch(role) {
    case Qt::DisplayRole:
        switch (index.column()) {
        case NameColumn:
            return room.value(QLatin1String("name"));
        case HandleNameColumn:
            return room.value(QLatin1String("handle-name"));
        case AccountIdentifierColumn:
            return room.value(QLatin1String("account-identifier"));
        }
    case Qt::ToolTipRole:
        return room.value(QLatin1String("handle-name"));
    case FavoriteRoomsModel::HandleNameRole:
        return room.value(QLatin1String("handle-name"));
    case FavoriteRoomsModel::NameRole:
        return room.value(QLatin1String("name"));
    case FavoriteRoomsModel::AccountRole:
        return room.value(QLatin1String("account-identifier"));
    case FavoriteRoomsModel::FavoriteRoomRole:
        return QVariant::fromValue<QVariantMap>(room);
    }

    return QVariant();
}

bool KTp::FavoriteRoomsModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (!index.isValid() || index.row() >= m_favoriteRoomsList.size()) {
        return false;
    }

    const int row = index.row();
    QVariantMap &room = m_favoriteRoomsList[row];

    if (role == Qt::EditRole) {
        switch (index.column()) {
        case NameColumn:
            room.insert(QLatin1String("name"), value);
            break;
        case HandleNameColumn:
            room.insert(QLatin1String("handle-name"), value);
            break;
        case AccountIdentifierColumn:
            room.insert(QLatin1String("account-identifier"), value);
            break;
        default:
            return false;
        }
        Q_EMIT dataChanged(index, index);
        return true;
    }
    return false;
}

Qt::ItemFlags KTp::FavoriteRoomsModel::flags(const QModelIndex &index) const {
    Q_UNUSED(index);
    return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}

void KTp::FavoriteRoomsModel::addRooms(const QList<QVariantMap> newRoomList)
{
    if (newRoomList.size() > 0) {
        beginInsertRows(QModelIndex(), m_favoriteRoomsList.size(), m_favoriteRoomsList.size() + newRoomList.size() - 1);
        m_favoriteRoomsList.append(newRoomList);
        endInsertRows();
    }
}

void KTp::FavoriteRoomsModel::addRoom(const QVariantMap &room)
{
    beginInsertRows(QModelIndex(), m_favoriteRoomsList.size(), m_favoriteRoomsList.size());
    m_favoriteRoomsList.append(room);
    endInsertRows();
}

void KTp::FavoriteRoomsModel::removeRoom(const QVariantMap &room)
{
    int row = m_favoriteRoomsList.indexOf(room);
    beginRemoveRows(QModelIndex(), row, row);
    m_favoriteRoomsList.removeOne(room);
    endRemoveRows();
}

bool KTp::FavoriteRoomsModel::containsRoom(const QString &handle, const QString &account) const
{
    bool contains = false;

    Q_FOREACH(const QVariantMap &room, m_favoriteRoomsList) {
        if ((room.value(QLatin1String("handle-name")) == handle) && (room.value(QLatin1String("account-identifier")) == account)) {
            contains = true;
        }
    }

    return contains;
}

int KTp::FavoriteRoomsModel::countForAccount(const QString &account) const
{
    int count = 0;

    Q_FOREACH (const QVariantMap &room, m_favoriteRoomsList) {
        if (room.value(QLatin1String("account-identifier")) == account) {
            count++;
        }
    }

    return count;
}
<commit_msg>FavoriteRoomsModel: Return DisplayRole values for EditRole as well.<commit_after>/*
 * Rooms Model - A model of chatrooms.
 * Copyright (C) 2012  Dominik Cermak <d.cermak@arcor.de>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "rooms-model.h"
#include <KIcon>
#include <KLocale>

// RoomsModel
KTp::RoomsModel::RoomsModel(QObject *parent): QAbstractListModel(parent)
{
}

int KTp::RoomsModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid()) {
        return 0;
    } else {
        return m_roomInfoList.size();
    }
}

int KTp::RoomsModel::columnCount(const QModelIndex &parent) const
{
    if (parent.isValid()) {
        return 0;
    } else {
        return 4;
    }
}

QVariant KTp::RoomsModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid()) {
        return QVariant();
    }

    if (index.row() >= m_roomInfoList.count()) {
        return QVariant();
    }

    const int row = index.row();
    const Tp::RoomInfo &roomInfo = m_roomInfoList.at(row);

    // this is handled here because when putting it in the switch below
    // all columns get an empty space for the decoration
    if (index.column() == PasswordColumn) {
        switch (role) {
        case Qt::DecorationRole:
            if (roomInfo.info.value(QLatin1String("password")).toBool()) {
                return KIcon(QLatin1String("object-locked"));
            } else {
                return QVariant();
            }
        case Qt::ToolTipRole:
            if (roomInfo.info.value(QLatin1String("password")).toBool()) {
                return i18n("Password required");
            } else {
                return i18n("No password required");
            }
        }
    }

    switch(role) {
    case Qt::DisplayRole:
        switch (index.column()) {
        case PasswordColumn:
            return QVariant();
        case NameColumn:
            return roomInfo.info.value(QLatin1String("name"));
        case DescriptionColumn:
            return roomInfo.info.value(QLatin1String("description"));
        case MembersColumn:
            return roomInfo.info.value(QLatin1String("members"));
        }
    case Qt::ToolTipRole:
        switch (index.column()) {
        case MembersColumn:
            return i18n("Member count");
        }
    case RoomsModel::HandleNameRole:
        return roomInfo.info.value(QLatin1String("handle-name"));
    }

    return QVariant();
}

QVariant KTp::RoomsModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role != Qt::DisplayRole && role != Qt::DecorationRole) {
        return QVariant();
    }

    if (orientation == Qt::Horizontal) {
        switch (role) {
        case Qt::DisplayRole:
            switch (section) {
            case NameColumn:
                return i18nc("Chatrooms name", "Name");
            case DescriptionColumn:
                return i18nc("Chatrooms description", "Description");
            }
        case Qt::DecorationRole:
            switch (section) {
            case PasswordColumn:
                return KIcon(QLatin1String("object-locked"));
            case MembersColumn:
                return KIcon(QLatin1String("meeting-participant"));
            }
        }
    }

    return QVariant();
}

void KTp::RoomsModel::addRooms(const Tp::RoomInfoList newRoomList)
{
    if (newRoomList.size() > 0) {
        beginInsertRows(QModelIndex(), m_roomInfoList.size(), m_roomInfoList.size() + newRoomList.size() - 1);
        m_roomInfoList.append(newRoomList);
        endInsertRows();
    }
}

void KTp::RoomsModel::clearRoomInfoList()
{
    if (m_roomInfoList.size() > 0) {
        beginRemoveRows(QModelIndex(), 0, m_roomInfoList.size() - 1);
        m_roomInfoList.clear();
        endRemoveRows();
    }
}

// FavoriteRoomsModel
KTp::FavoriteRoomsModel::FavoriteRoomsModel(QObject *parent): QAbstractListModel(parent)
{
}

int KTp::FavoriteRoomsModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid()) {
        return 0;
    } else {
        return m_favoriteRoomsList.size();
    }
}

int KTp::FavoriteRoomsModel::columnCount(const QModelIndex &parent) const
{
    if (parent.isValid()) {
        return 0;
    } else {
        return 3;
    }
}

QVariant KTp::FavoriteRoomsModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid()) {
        return QVariant();
    }

    if (index.row() >= m_favoriteRoomsList.size()) {
        return QVariant();
    }

    const int row = index.row();
    const QVariantMap &room = m_favoriteRoomsList.at(row);

    switch(role) {
    case Qt::EditRole: // Return same values for both Display and Edit roles
    case Qt::DisplayRole:
        switch (index.column()) {
        case NameColumn:
            return room.value(QLatin1String("name"));
        case HandleNameColumn:
            return room.value(QLatin1String("handle-name"));
        case AccountIdentifierColumn:
            return room.value(QLatin1String("account-identifier"));
        }
    case Qt::ToolTipRole:
        return room.value(QLatin1String("handle-name"));
    case FavoriteRoomsModel::HandleNameRole:
        return room.value(QLatin1String("handle-name"));
    case FavoriteRoomsModel::NameRole:
        return room.value(QLatin1String("name"));
    case FavoriteRoomsModel::AccountRole:
        return room.value(QLatin1String("account-identifier"));
    case FavoriteRoomsModel::FavoriteRoomRole:
        return QVariant::fromValue<QVariantMap>(room);
    }

    return QVariant();
}

bool KTp::FavoriteRoomsModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (!index.isValid() || index.row() >= m_favoriteRoomsList.size()) {
        return false;
    }

    const int row = index.row();
    QVariantMap &room = m_favoriteRoomsList[row];

    if (role == Qt::EditRole) {
        switch (index.column()) {
        case NameColumn:
            room.insert(QLatin1String("name"), value);
            break;
        case HandleNameColumn:
            room.insert(QLatin1String("handle-name"), value);
            break;
        case AccountIdentifierColumn:
            room.insert(QLatin1String("account-identifier"), value);
            break;
        default:
            return false;
        }
        Q_EMIT dataChanged(index, index);
        return true;
    }
    return false;
}

Qt::ItemFlags KTp::FavoriteRoomsModel::flags(const QModelIndex &index) const {
    Q_UNUSED(index);
    return Qt::ItemIsEditable | Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}

void KTp::FavoriteRoomsModel::addRooms(const QList<QVariantMap> newRoomList)
{
    if (newRoomList.size() > 0) {
        beginInsertRows(QModelIndex(), m_favoriteRoomsList.size(), m_favoriteRoomsList.size() + newRoomList.size() - 1);
        m_favoriteRoomsList.append(newRoomList);
        endInsertRows();
    }
}

void KTp::FavoriteRoomsModel::addRoom(const QVariantMap &room)
{
    beginInsertRows(QModelIndex(), m_favoriteRoomsList.size(), m_favoriteRoomsList.size());
    m_favoriteRoomsList.append(room);
    endInsertRows();
}

void KTp::FavoriteRoomsModel::removeRoom(const QVariantMap &room)
{
    int row = m_favoriteRoomsList.indexOf(room);
    beginRemoveRows(QModelIndex(), row, row);
    m_favoriteRoomsList.removeOne(room);
    endRemoveRows();
}

bool KTp::FavoriteRoomsModel::containsRoom(const QString &handle, const QString &account) const
{
    bool contains = false;

    Q_FOREACH(const QVariantMap &room, m_favoriteRoomsList) {
        if ((room.value(QLatin1String("handle-name")) == handle) && (room.value(QLatin1String("account-identifier")) == account)) {
            contains = true;
        }
    }

    return contains;
}

int KTp::FavoriteRoomsModel::countForAccount(const QString &account) const
{
    int count = 0;

    Q_FOREACH (const QVariantMap &room, m_favoriteRoomsList) {
        if (room.value(QLatin1String("account-identifier")) == account) {
            count++;
        }
    }

    return count;
}
<|endoftext|>