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

#include "telepathyContactList.h"

#include <KStandardDirs>

#include <QtDeclarative/QDeclarativeEngine>
#include <QtDeclarative/QDeclarativeContext>

#include <TelepathyQt/AccountFactory>
#include <TelepathyQt/ContactFactory>
#include <TelepathyQt/ConnectionFactory>
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/PendingReady>

#include <KTp/Models/accounts-model.h>
#include <KTp/Models/flat-model-proxy.h>

TelepathyContactList::TelepathyContactList(QObject* parent, const QVariantList& args)
    : Applet(parent, args)
    , m_declarative(new Plasma::DeclarativeWidget(this))
    , m_qmlObject(0)
{
    // set plasmoid size
    setMinimumSize(250, 400);
    setAspectRatioMode(Plasma::IgnoreAspectRatio);

    Tp::registerTypes();

        // Start setting up the Telepathy AccountManager.
    Tp::AccountFactoryPtr  accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(),
                                                                       Tp::Features() << Tp::Account::FeatureCore
                                                                       << Tp::Account::FeatureAvatar
                                                                       << Tp::Account::FeatureCapabilities
                                                                       << Tp::Account::FeatureProtocolInfo
                                                                       << Tp::Account::FeatureProfile);

    Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(),
                                                                               Tp::Features() << Tp::Connection::FeatureCore
                                                                               << Tp::Connection::FeatureRosterGroups
                                                                               << Tp::Connection::FeatureRoster
                                                                               << Tp::Connection::FeatureSelfContact);

    Tp::ContactFactoryPtr contactFactory = Tp::ContactFactory::create(Tp::Features()  << Tp::Contact::FeatureAlias
                                                                      << Tp::Contact::FeatureAvatarData
                                                                      << Tp::Contact::FeatureSimplePresence
                                                                      << Tp::Contact::FeatureCapabilities);

    Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus());

     m_accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(),
                                                   accountFactory,
                                                   connectionFactory,
                                                   channelFactory,
                                                   contactFactory);

    connect(m_accountManager->becomeReady(),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onAccountManagerReady(Tp::PendingOperation*)));

    m_model = new AccountsModel(this);
    m_proxyModel = new FlatModelProxy(m_model);

}

TelepathyContactList::~TelepathyContactList()
{
    delete m_declarative;
}

int TelepathyContactList::appletHeight() const
{
    return geometry().height();
}

int TelepathyContactList::appletWidth() const
{
    return geometry().width();
}

void TelepathyContactList::init()
{
    // load QML part of the plasmoid
    if (m_declarative) {
        QString qmlFile = KGlobal::dirs()->findResource("data", "plasma/plasmoids/org.kde.telepathy-contact-list/contents/ui/main.qml");
        qDebug() << "LOADING: " << qmlFile;
        m_declarative->setQmlPath(qmlFile);

        // make C++ Plasma::Applet available to QML for resize signal
        m_declarative->engine()->rootContext()->setContextProperty("TelepathyContactList", this);

        m_declarative->engine()->rootContext()->setContextProperty("contactListModel", m_proxyModel);

        // setup qml object so that we can talk to the declarative part
        m_qmlObject = dynamic_cast<QObject*>(m_declarative->rootObject());

        // connect the qml object to recieve signals from C++ end
        // these two signals are for the plasmoid resize. QML can't determine the Plasma::DeclarativeWidget's boundaries
        connect(this, SIGNAL(widthChanged()), m_qmlObject, SLOT(onWidthChanged()));
        connect(this, SIGNAL(heightChanged()), m_qmlObject, SLOT(onHeightChanged()));

        //FIXME this code is messy, steal from qmlsplashscreen
    }
}

// This is the command that links your applet to the .desktop file
K_EXPORT_PLASMA_APPLET(telepathy-contact-list, TelepathyContactList)

void TelepathyContactList::onAccountManagerReady(Tp::PendingOperation *op)
{
    m_model->setAccountManager(m_accountManager);
    init();
}
<commit_msg>Don't randomly call init twice, it's called by plasma. We shouldn't do it ourselves.<commit_after>/***************************************************************************
 *   Copyright (C) 2011 by Francesco Nwokeka <francesco.nwokeka@gmail.com> *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA            *
 ***************************************************************************/

#include "telepathyContactList.h"

#include <KStandardDirs>

#include <QtDeclarative/QDeclarativeEngine>
#include <QtDeclarative/QDeclarativeContext>

#include <TelepathyQt/AccountFactory>
#include <TelepathyQt/ContactFactory>
#include <TelepathyQt/ConnectionFactory>
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/PendingReady>

#include <KTp/Models/accounts-model.h>
#include <KTp/Models/flat-model-proxy.h>

TelepathyContactList::TelepathyContactList(QObject* parent, const QVariantList& args)
    : Applet(parent, args)
    , m_declarative(new Plasma::DeclarativeWidget(this))
    , m_qmlObject(0)
{
    // set plasmoid size
    setMinimumSize(250, 400);
    setAspectRatioMode(Plasma::IgnoreAspectRatio);

    Tp::registerTypes();

        // Start setting up the Telepathy AccountManager.
    Tp::AccountFactoryPtr  accountFactory = Tp::AccountFactory::create(QDBusConnection::sessionBus(),
                                                                       Tp::Features() << Tp::Account::FeatureCore
                                                                       << Tp::Account::FeatureAvatar
                                                                       << Tp::Account::FeatureCapabilities
                                                                       << Tp::Account::FeatureProtocolInfo
                                                                       << Tp::Account::FeatureProfile);

    Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(QDBusConnection::sessionBus(),
                                                                               Tp::Features() << Tp::Connection::FeatureCore
                                                                               << Tp::Connection::FeatureRosterGroups
                                                                               << Tp::Connection::FeatureRoster
                                                                               << Tp::Connection::FeatureSelfContact);

    Tp::ContactFactoryPtr contactFactory = Tp::ContactFactory::create(Tp::Features()  << Tp::Contact::FeatureAlias
                                                                      << Tp::Contact::FeatureAvatarData
                                                                      << Tp::Contact::FeatureSimplePresence
                                                                      << Tp::Contact::FeatureCapabilities);

    Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus());

     m_accountManager = Tp::AccountManager::create(QDBusConnection::sessionBus(),
                                                   accountFactory,
                                                   connectionFactory,
                                                   channelFactory,
                                                   contactFactory);

    connect(m_accountManager->becomeReady(),
            SIGNAL(finished(Tp::PendingOperation*)),
            SLOT(onAccountManagerReady(Tp::PendingOperation*)));

    m_model = new AccountsModel(this);
    m_proxyModel = new FlatModelProxy(m_model);
}

TelepathyContactList::~TelepathyContactList()
{
    delete m_declarative;
}

int TelepathyContactList::appletHeight() const
{
    return geometry().height();
}

int TelepathyContactList::appletWidth() const
{
    return geometry().width();
}

void TelepathyContactList::init()
{
    // load QML part of the plasmoid
    if (m_declarative) {
        QString qmlFile = KGlobal::dirs()->findResource("data", "plasma/plasmoids/org.kde.telepathy-contact-list/contents/ui/main.qml");
        qDebug() << "LOADING: " << qmlFile;
        m_declarative->setQmlPath(qmlFile);

        // make C++ Plasma::Applet available to QML for resize signal
        m_declarative->engine()->rootContext()->setContextProperty("TelepathyContactList", this);
        m_declarative->engine()->rootContext()->setContextProperty("contactListModel", m_proxyModel);

        // setup qml object so that we can talk to the declarative part
        m_qmlObject = dynamic_cast<QObject*>(m_declarative->rootObject());

        // connect the qml object to recieve signals from C++ end
        // these two signals are for the plasmoid resize. QML can't determine the Plasma::DeclarativeWidget's boundaries
        connect(this, SIGNAL(widthChanged()), m_qmlObject, SLOT(onWidthChanged()));
        connect(this, SIGNAL(heightChanged()), m_qmlObject, SLOT(onHeightChanged()));

        //FIXME this code is messy, steal from qmlsplashscreen
    }
}

// This is the command that links your applet to the .desktop file
K_EXPORT_PLASMA_APPLET(telepathy-contact-list, TelepathyContactList)

void TelepathyContactList::onAccountManagerReady(Tp::PendingOperation *op)
{
    m_model->setAccountManager(m_accountManager);
}
<|endoftext|>


<commit_before>#include <TVirtualMC.h>
#include <TDatabasePDG.h>
#include <TParticle.h>

#include "AliGenReaderHepMC.h"
#include "AliRun.h"
#include "AliStack.h"
#include "AliGenHepMCEventHeader.h"

ClassImp(AliGenReaderHepMC)

AliGenReaderHepMC& AliGenReaderHepMC::operator=(const  AliGenReaderHepMC& rhs)
{
   // Assignment operator
   rhs.Copy(*this);
   return *this;
}

void AliGenReaderHepMC::Copy(TObject&) const
{
   //
   // Copy
   //
   Fatal("Copy","Not implemented!\n");
}

void AliGenReaderHepMC::Init()
{
   // Initialisation
   fEventsHandle = new HepMC::IO_GenEvent(fFileName, std::ios::in);
   fParticleArray = new TClonesArray("TParticle");
   fParticleIterator = new TIter(fParticleArray);
}

Int_t AliGenReaderHepMC::NextEvent()
{
   // Read the next event
   if ((fGenEvent = fEventsHandle->read_next_event())) {
      THepMCParser::ParseGenEvent2TCloneArray(fGenEvent,fParticleArray,false);
      fParticleIterator->Reset();
      THepMCParser::HeavyIonHeader_t heavyIonHeader;
      THepMCParser::PdfHeader_t pdfHeader;
      THepMCParser::ParseGenEvent2HeaderStructs(fGenEvent,heavyIonHeader,pdfHeader,true,true);
      fGenEventHeader = new AliGenHepMCEventHeader(
            heavyIonHeader.Ncoll_hard,
            heavyIonHeader.Npart_proj,
            heavyIonHeader.Npart_targ,
            heavyIonHeader.Ncoll,
            heavyIonHeader.spectator_neutrons,
            heavyIonHeader.spectator_protons,
            heavyIonHeader.N_Nwounded_collisions,
            heavyIonHeader.Nwounded_N_collisions,
            heavyIonHeader.Nwounded_Nwounded_collisions,
            heavyIonHeader.impact_parameter,
            heavyIonHeader.event_plane_angle,
            heavyIonHeader.eccentricity,
            heavyIonHeader.sigma_inel_NN,
            pdfHeader.id1,
            pdfHeader.id2,
            pdfHeader.pdf_id1,
            pdfHeader.pdf_id2,
            pdfHeader.x1,
            pdfHeader.x2,
            pdfHeader.scalePDF,
            pdfHeader.pdf1,
            pdfHeader.pdf2
      );
      return fGenEvent->particles_size();
   }
   return 0;
}

TParticle* AliGenReaderHepMC::NextParticle()
{
   // Read next particle
   TParticle * particle = (TParticle*)fParticleIterator->Next();
   if (particle && particle->GetStatusCode()==1) {
      particle->SetBit(kTransportBit);
   }
   return particle;
}

void AliGenReaderHepMC::RewindEvent()
{
   fParticleIterator->Reset();
}
<commit_msg>Added better output messaging with regards to loading hepmc file.<commit_after>#include <TVirtualMC.h>
#include <TDatabasePDG.h>
#include <TParticle.h>

#include "AliGenReaderHepMC.h"
#include "AliRun.h"
#include "AliStack.h"
#include "AliGenHepMCEventHeader.h"

ClassImp(AliGenReaderHepMC)

AliGenReaderHepMC& AliGenReaderHepMC::operator=(const  AliGenReaderHepMC& rhs)
{
   // Assignment operator
   rhs.Copy(*this);
   return *this;
}

void AliGenReaderHepMC::Copy(TObject&) const
{
   //
   // Copy
   //
   Fatal("Copy","Not implemented!\n");
}

void AliGenReaderHepMC::Init()
{
   // check if file exists, using FILE to avoid (the otherwise faster) POSIX dependencies
   if (FILE *file = fopen(fFileName,"r"))  {
      printf("File %s opened \n", fFileName);
      fclose(file);
   } else {
      printf("Couldn't open input file: %s \n", fFileName);
   }
   // Initialisation
   fEventsHandle = new HepMC::IO_GenEvent(fFileName, std::ios::in);
   fParticleArray = new TClonesArray("TParticle");
   fParticleIterator = new TIter(fParticleArray);
}

Int_t AliGenReaderHepMC::NextEvent()
{
   // Read the next event
   if ((fGenEvent = fEventsHandle->read_next_event())) {
      THepMCParser::ParseGenEvent2TCloneArray(fGenEvent,fParticleArray,false);
      fParticleIterator->Reset();
      THepMCParser::HeavyIonHeader_t heavyIonHeader;
      THepMCParser::PdfHeader_t pdfHeader;
      THepMCParser::ParseGenEvent2HeaderStructs(fGenEvent,heavyIonHeader,pdfHeader,true,true);
      fGenEventHeader = new AliGenHepMCEventHeader(
            heavyIonHeader.Ncoll_hard,
            heavyIonHeader.Npart_proj,
            heavyIonHeader.Npart_targ,
            heavyIonHeader.Ncoll,
            heavyIonHeader.spectator_neutrons,
            heavyIonHeader.spectator_protons,
            heavyIonHeader.N_Nwounded_collisions,
            heavyIonHeader.Nwounded_N_collisions,
            heavyIonHeader.Nwounded_Nwounded_collisions,
            heavyIonHeader.impact_parameter,
            heavyIonHeader.event_plane_angle,
            heavyIonHeader.eccentricity,
            heavyIonHeader.sigma_inel_NN,
            pdfHeader.id1,
            pdfHeader.id2,
            pdfHeader.pdf_id1,
            pdfHeader.pdf_id2,
            pdfHeader.x1,
            pdfHeader.x2,
            pdfHeader.scalePDF,
            pdfHeader.pdf1,
            pdfHeader.pdf2
      );
      printf("Parsed event with %d particles.\n", fGenEvent->particles_size());
      return fGenEvent->particles_size();
   }
   printf("No more events in the file.\n");
   return 0;
}

TParticle* AliGenReaderHepMC::NextParticle()
{
   // Read next particle
   TParticle * particle = (TParticle*)fParticleIterator->Next();
   if (particle && particle->GetStatusCode()==1) {
      particle->SetBit(kTransportBit);
   }
   return particle;
}

void AliGenReaderHepMC::RewindEvent()
{
   fParticleIterator->Reset();
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkAssembly.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

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

// Description:
// Construct object with no children.
vtkAssembly::vtkAssembly()
{
  this->Paths = NULL;
}

vtkAssembly::~vtkAssembly()
{
  this->DeletePaths();
}

// Description:
// Add a part to the list of parts.
void vtkAssembly::AddPart(vtkActor *actor)
{
  if ( ! this->Parts.IsItemPresent(actor) )
    {
    this->Parts.AddItem(actor);
    this->Modified();
    }
}

// Description:
// Remove a part from the list of parts,
void vtkAssembly::RemovePart(vtkActor *actor)
{
  if ( this->Parts.IsItemPresent(actor) )
    {
    this->Parts.RemoveItem(actor);
    this->Modified();
    }
}

// Description:
// Copy another assembly.
vtkAssembly& vtkAssembly::operator=(const vtkAssembly& assembly)
{
  *((vtkActor *)this) = assembly;
  this->DeletePaths();

  return *this;
}

// Description:
// Render this assembly and all its parts. The rendering process is recursive.
// Note that a mapper need not be defined. If not defined, then no geometry
// will be drawn for this assembly. This allows you to create "logical"
// assemblies; that is, assemblies that only serve to group and transform
// its parts.
void vtkAssembly::Render(vtkRenderer *ren)
{
  vtkActor *actor;
  vtkActorCollection *path;

  this->UpdatePaths();

  // render the Paths
  for ( this->Paths->InitTraversal(); (path = this->Paths->GetNextItem()); )
    {
    actor = path->GetLastItem();
    if ( actor->GetVisibility() ) actor->Render(ren);
    }
}

void vtkAssembly::InitPartTraversal()
{
  this->UpdatePaths();
  this->Paths->InitTraversal();
}

// Description:
// Return the next part in the hierarchy of assembly parts.  This method
// returns a properly transformed and updated actor.
vtkActor *vtkAssembly::GetNextPart()
{
  vtkActorCollection *path;

  if ( (path = Paths->GetNextItem()) == NULL )
    {
    return NULL;
    }
  else
    {
    return path->GetLastItem();
    }
}

int vtkAssembly::GetNumberOfParts()
{
  this->UpdatePaths();
  return this->Paths->GetNumberOfItems();
}

// Build the assembly paths if necessary.
void vtkAssembly::UpdatePaths()
{
  if ( this->GetMTime() > this->PathTime )
    {
    this->DeletePaths();
    }

  if ( ! this->Paths )
    {
    this->Paths = new vtkAssemblyPaths;
    vtkActorCollection *path = new vtkActorCollection;
    this->Paths->AddItem(path);

    this->BuildPaths(this->Paths,path);
    this->PathTime.Modified();
    }
}

// Build assembly paths from this current assembly. Paths consist of
// an ordered sequence of actors, with transformations properly concatenated.
void vtkAssembly::BuildPaths(vtkAssemblyPaths *paths, vtkActorCollection *path)
{
  vtkActor *part, *actor, *copy=new vtkActor, *previous;
  vtkMatrix4x4 *matrix;
  vtkActorCollection *childPath;

  *copy = *this;

  if ( path->GetNumberOfItems() < 1 ) //we're starting at the top of the hierarchy
    {
    if ( this->GetUserMatrix() )
      {
      matrix = new vtkMatrix4x4;
      *matrix = *(this->GetUserMatrix());
      copy->SetUserMatrix(matrix);
      }
    }
  else //somewhere in the middle of the assembly hierarchy
    {
    previous = path->GetLastItem();
    matrix = new vtkMatrix4x4;
    previous->GetMatrix(*matrix);
    copy->SetUserMatrix(matrix);
    }

  path->AddItem(copy);

  // add our children to the path (if we're visible).
  if ( this->Visibility )
    {
    for ( this->Parts.InitTraversal(); (part = this->Parts.GetNextItem()); )
      {
      //a new path is created for each child
      childPath = new vtkActorCollection;
      paths->AddItem(childPath);

      // copy incoming path
      for ( path->InitTraversal(); (actor = path->GetNextItem()); )
        {
        copy = new vtkActor;
        *copy = *actor;

        if ( actor->GetUserMatrix() )
          {
          matrix = new vtkMatrix4x4;
          *matrix = *(actor->GetUserMatrix());
          copy->SetUserMatrix(matrix);
          }

        childPath->AddItem(copy);
        }

      // create new paths
      part->BuildPaths(paths,childPath);
      }
    }//if visible
}

// Delete the paths asscoiated with this assembly hierarchy.
void vtkAssembly::DeletePaths()
{
  if ( this->Paths )
    {
    vtkActor *actor;
    vtkActorCollection *path;

    for ( this->Paths->InitTraversal(); (path = this->Paths->GetNextItem()); )
      {
      for ( path->InitTraversal(); (actor = path->GetNextItem()); )
        {
        if ( actor->GetUserMatrix() ) actor->GetUserMatrix()->Delete();
        actor->Delete();
        }
      path->Delete();
      }
    this->Paths->Delete();
    this->Paths = NULL;
    }
}

// Description:
// Get the bounds for the assembly as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).
float *vtkAssembly::GetBounds()
{
  vtkActor *actor;
  vtkMapper *mapper;
  vtkActorCollection *path;
  int i,n;
  float *bounds, bbox[24], *fptr;
  float *result;
  vtkMatrix4x4 matrix;

  this->UpdatePaths();

  // now calculate the new bounds
  if ( this->Mapper )
    {
    vtkActor::GetBounds();
    }
  else
    {
    this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = VTK_LARGE_FLOAT;
    this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_LARGE_FLOAT;
    }

  this->Transform.PostMultiply();
  for ( this->Paths->InitTraversal(); (path = this->Paths->GetNextItem()); )
    {
    actor = path->GetLastItem();

    if ( (mapper = actor->GetMapper()) )
      {
      bounds = mapper->GetBounds();

      // fill out vertices of a bounding box
      bbox[ 0] = bounds[1]; bbox[ 1] = bounds[3]; bbox[ 2] = bounds[5];
      bbox[ 3] = bounds[1]; bbox[ 4] = bounds[2]; bbox[ 5] = bounds[5];
      bbox[ 6] = bounds[0]; bbox[ 7] = bounds[2]; bbox[ 8] = bounds[5];
      bbox[ 9] = bounds[0]; bbox[10] = bounds[3]; bbox[11] = bounds[5];
      bbox[12] = bounds[1]; bbox[13] = bounds[3]; bbox[14] = bounds[4];
      bbox[15] = bounds[1]; bbox[16] = bounds[2]; bbox[17] = bounds[4];
      bbox[18] = bounds[0]; bbox[19] = bounds[2]; bbox[20] = bounds[4];
      bbox[21] = bounds[0]; bbox[22] = bounds[3]; bbox[23] = bounds[4];

      // save the old transform
      actor->GetMatrix(matrix);
      this->Transform.Push();
      this->Transform.Identity();
      this->Transform.Concatenate(matrix);

      // and transform into actors coordinates
      fptr = bbox;
      for (n = 0; n < 8; n++)
        {
        this->Transform.SetPoint(fptr[0],fptr[1],fptr[2],1.0);

        // now store the result
        result = this->Transform.GetPoint();
        fptr[0] = result[0] / result[3];
        fptr[1] = result[1] / result[3];
        fptr[2] = result[2] / result[3];
        fptr += 3;
        }

      this->Transform.Pop();

      for (i = 0; i < 8; i++)
        {
        for (n = 0; n < 3; n++)
          {
          if (bbox[i*3+n] < this->Bounds[n*2]) this->Bounds[n*2] = bbox[i*3+n];
          if (bbox[i*3+n] > this->Bounds[n*2+1]) this->Bounds[n*2+1] = bbox[i*3+n];
          }
        }//for each point of box
      }//if mapper
    }//for each path

  this->Transform.PreMultiply();

  return this->Bounds;
}

unsigned long int vtkAssembly::GetMTime()
{
  unsigned long mTime=this->vtkActor::GetMTime();
  unsigned long time;
  vtkActor *part;

  for (this->Parts.InitTraversal(); (part = this->Parts.GetNextItem()); )
    {
    time = part->GetMTime();
    mTime = ( time > mTime ? time : mTime );
    }

  return mTime;
}

void vtkAssembly::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkActor::PrintSelf(os,indent);

  os << indent << "There are: " << this->Parts.GetNumberOfItems()
     << " parts in this assembly\n";
}

<commit_msg>ERR: Compute initial bounds properly when actor is off<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkAssembly.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-1996 Ken Martin, Will Schroeder, Bill Lorensen.

This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen.
The following terms apply to all files associated with the software unless
explicitly disclaimed in individual files. This copyright specifically does
not apply to the related textbook "The Visualization Toolkit" ISBN
013199837-4 published by Prentice Hall which is covered by its own copyright.

The authors hereby grant permission to use, copy, and distribute this
software and its documentation for any purpose, provided that existing
copyright notices are retained in all copies and that this notice is included
verbatim in any distributions. Additionally, the authors grant permission to
modify this software and its documentation for any purpose, provided that
such modifications are not distributed without the explicit consent of the
authors and that existing copyright notices are retained in all copies. Some
of the algorithms implemented by this software are patented, observe all
applicable patent law.

IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF,
EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON AN
"AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE
MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.

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

// Description:
// Construct object with no children.
vtkAssembly::vtkAssembly()
{
  this->Paths = NULL;
}

vtkAssembly::~vtkAssembly()
{
  this->DeletePaths();
}

// Description:
// Add a part to the list of parts.
void vtkAssembly::AddPart(vtkActor *actor)
{
  if ( ! this->Parts.IsItemPresent(actor) )
    {
    this->Parts.AddItem(actor);
    this->Modified();
    }
}

// Description:
// Remove a part from the list of parts,
void vtkAssembly::RemovePart(vtkActor *actor)
{
  if ( this->Parts.IsItemPresent(actor) )
    {
    this->Parts.RemoveItem(actor);
    this->Modified();
    }
}

// Description:
// Copy another assembly.
vtkAssembly& vtkAssembly::operator=(const vtkAssembly& assembly)
{
  *((vtkActor *)this) = assembly;
  this->DeletePaths();

  return *this;
}

// Description:
// Render this assembly and all its parts. The rendering process is recursive.
// Note that a mapper need not be defined. If not defined, then no geometry
// will be drawn for this assembly. This allows you to create "logical"
// assemblies; that is, assemblies that only serve to group and transform
// its parts.
void vtkAssembly::Render(vtkRenderer *ren)
{
  vtkActor *actor;
  vtkActorCollection *path;

  this->UpdatePaths();

  // render the Paths
  for ( this->Paths->InitTraversal(); (path = this->Paths->GetNextItem()); )
    {
    actor = path->GetLastItem();
    if ( actor->GetVisibility() ) actor->Render(ren);
    }
}

void vtkAssembly::InitPartTraversal()
{
  this->UpdatePaths();
  this->Paths->InitTraversal();
}

// Description:
// Return the next part in the hierarchy of assembly parts.  This method
// returns a properly transformed and updated actor.
vtkActor *vtkAssembly::GetNextPart()
{
  vtkActorCollection *path;

  if ( (path = Paths->GetNextItem()) == NULL )
    {
    return NULL;
    }
  else
    {
    return path->GetLastItem();
    }
}

int vtkAssembly::GetNumberOfParts()
{
  this->UpdatePaths();
  return this->Paths->GetNumberOfItems();
}

// Build the assembly paths if necessary.
void vtkAssembly::UpdatePaths()
{
  if ( this->GetMTime() > this->PathTime )
    {
    this->DeletePaths();
    }

  if ( ! this->Paths )
    {
    this->Paths = new vtkAssemblyPaths;
    vtkActorCollection *path = new vtkActorCollection;
    this->Paths->AddItem(path);

    this->BuildPaths(this->Paths,path);
    this->PathTime.Modified();
    }
}

// Build assembly paths from this current assembly. Paths consist of
// an ordered sequence of actors, with transformations properly concatenated.
void vtkAssembly::BuildPaths(vtkAssemblyPaths *paths, vtkActorCollection *path)
{
  vtkActor *part, *actor, *copy=new vtkActor, *previous;
  vtkMatrix4x4 *matrix;
  vtkActorCollection *childPath;

  *copy = *this;

  if ( path->GetNumberOfItems() < 1 ) //we're starting at the top of the hierarchy
    {
    if ( this->GetUserMatrix() )
      {
      matrix = new vtkMatrix4x4;
      *matrix = *(this->GetUserMatrix());
      copy->SetUserMatrix(matrix);
      }
    }
  else //somewhere in the middle of the assembly hierarchy
    {
    previous = path->GetLastItem();
    matrix = new vtkMatrix4x4;
    previous->GetMatrix(*matrix);
    copy->SetUserMatrix(matrix);
    }

  path->AddItem(copy);

  // add our children to the path (if we're visible).
  if ( this->Visibility )
    {
    for ( this->Parts.InitTraversal(); (part = this->Parts.GetNextItem()); )
      {
      //a new path is created for each child
      childPath = new vtkActorCollection;
      paths->AddItem(childPath);

      // copy incoming path
      for ( path->InitTraversal(); (actor = path->GetNextItem()); )
        {
        copy = new vtkActor;
        *copy = *actor;

        if ( actor->GetUserMatrix() )
          {
          matrix = new vtkMatrix4x4;
          *matrix = *(actor->GetUserMatrix());
          copy->SetUserMatrix(matrix);
          }

        childPath->AddItem(copy);
        }

      // create new paths
      part->BuildPaths(paths,childPath);
      }
    }//if visible
}

// Delete the paths asscoiated with this assembly hierarchy.
void vtkAssembly::DeletePaths()
{
  if ( this->Paths )
    {
    vtkActor *actor;
    vtkActorCollection *path;

    for ( this->Paths->InitTraversal(); (path = this->Paths->GetNextItem()); )
      {
      for ( path->InitTraversal(); (actor = path->GetNextItem()); )
        {
        if ( actor->GetUserMatrix() ) actor->GetUserMatrix()->Delete();
        actor->Delete();
        }
      path->Delete();
      }
    this->Paths->Delete();
    this->Paths = NULL;
    }
}

// Description:
// Get the bounds for the assembly as (Xmin,Xmax,Ymin,Ymax,Zmin,Zmax).
float *vtkAssembly::GetBounds()
{
  vtkActor *actor;
  vtkMapper *mapper;
  vtkActorCollection *path;
  int i,n;
  float *bounds, bbox[24], *fptr;
  float *result;
  vtkMatrix4x4 matrix;
  int actorVisible=0;

  this->UpdatePaths();

  // now calculate the new bounds
  if ( this->Mapper )
    {
    vtkActor::GetBounds();
    }
  else
    {
    this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = VTK_LARGE_FLOAT;
    this->Bounds[1] = this->Bounds[3] = this->Bounds[5] = -VTK_LARGE_FLOAT;
    }

  this->Transform.PostMultiply();
  for ( this->Paths->InitTraversal(); (path = this->Paths->GetNextItem()); )
    {
    actor = path->GetLastItem();

    if ( actor->GetVisibility() && (mapper = actor->GetMapper()) )
      {
      actorVisible = 1;
      bounds = mapper->GetBounds();

      // fill out vertices of a bounding box
      bbox[ 0] = bounds[1]; bbox[ 1] = bounds[3]; bbox[ 2] = bounds[5];
      bbox[ 3] = bounds[1]; bbox[ 4] = bounds[2]; bbox[ 5] = bounds[5];
      bbox[ 6] = bounds[0]; bbox[ 7] = bounds[2]; bbox[ 8] = bounds[5];
      bbox[ 9] = bounds[0]; bbox[10] = bounds[3]; bbox[11] = bounds[5];
      bbox[12] = bounds[1]; bbox[13] = bounds[3]; bbox[14] = bounds[4];
      bbox[15] = bounds[1]; bbox[16] = bounds[2]; bbox[17] = bounds[4];
      bbox[18] = bounds[0]; bbox[19] = bounds[2]; bbox[20] = bounds[4];
      bbox[21] = bounds[0]; bbox[22] = bounds[3]; bbox[23] = bounds[4];

      // save the old transform
      actor->GetMatrix(matrix);
      this->Transform.Push();
      this->Transform.Identity();
      this->Transform.Concatenate(matrix);

      // and transform into actors coordinates
      fptr = bbox;
      for (n = 0; n < 8; n++)
        {
        this->Transform.SetPoint(fptr[0],fptr[1],fptr[2],1.0);

        // now store the result
        result = this->Transform.GetPoint();
        fptr[0] = result[0] / result[3];
        fptr[1] = result[1] / result[3];
        fptr[2] = result[2] / result[3];
        fptr += 3;
        }

      this->Transform.Pop();

      for (i = 0; i < 8; i++)
        {
        for (n = 0; n < 3; n++)
          {
          if (bbox[i*3+n] < this->Bounds[n*2]) this->Bounds[n*2] = bbox[i*3+n];
          if (bbox[i*3+n] > this->Bounds[n*2+1]) this->Bounds[n*2+1] = bbox[i*3+n];
          }
        }//for each point of box
      }//if mapper
    }//for each path

  this->Transform.PreMultiply();

  if ( ! actorVisible )
    {
    this->Bounds[0] = this->Bounds[2] = this->Bounds[4] = -1.0;
    this->Bounds[1] = this->Bounds[3] = this->Bounds[5] =  1.0;
    }

  return this->Bounds;
}

unsigned long int vtkAssembly::GetMTime()
{
  unsigned long mTime=this->vtkActor::GetMTime();
  unsigned long time;
  vtkActor *part;

  for (this->Parts.InitTraversal(); (part = this->Parts.GetNextItem()); )
    {
    time = part->GetMTime();
    mTime = ( time > mTime ? time : mTime );
    }

  return mTime;
}

void vtkAssembly::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkActor::PrintSelf(os,indent);

  os << indent << "There are: " << this->Parts.GetNumberOfItems()
     << " parts in this assembly\n";
}

<|endoftext|>


<commit_before><commit_msg>Invert the speech input API enable check and enable only on dev channel. For official builds, enable speech input only on the dev channel. For non-official builds it is enabled by default and that remains the same.<commit_after><|endoftext|>


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

  Library: XNAT/Core

  Copyright (c) University College London,
    Centre for Medical Image Computing

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

=============================================================================*/

#include "ctkXnatObject.h"
#include "ctkXnatObjectPrivate.h"

#include "ctkXnatDataModel.h"
#include "ctkXnatSession.h"
#include "ctkXnatDefaultSchemaTypes.h"

#include <QDateTime>
#include <QDebug>
#include <QStringList>
#include <QVariant>

//----------------------------------------------------------------------------
ctkXnatObject::ctkXnatObject(const ctkXnatObject&)
{
  throw ctkRuntimeException("Copy constructor not implemented");
}

//----------------------------------------------------------------------------
ctkXnatObject::ctkXnatObject(ctkXnatObject* parent, const QString& schemaType)
: d_ptr(new ctkXnatObjectPrivate())
{
  this->setParent(parent);
  this->setSchemaType(schemaType);
}

//----------------------------------------------------------------------------
ctkXnatObject::ctkXnatObject(ctkXnatObjectPrivate& dd, ctkXnatObject* parent, const QString& schemaType)
: d_ptr(&dd)
{
  this->setParent(parent);
  this->setSchemaType(schemaType);
}

//----------------------------------------------------------------------------
ctkXnatObject::~ctkXnatObject()
{
  Q_D(ctkXnatObject);
  foreach (ctkXnatObject* child, d->children)
  {
    delete child;
  }
}

//----------------------------------------------------------------------------
QString ctkXnatObject::id() const
{
  return property("id");
}

//----------------------------------------------------------------------------
void ctkXnatObject::setId(const QString& id)
{
  setProperty("id", id);
}

//----------------------------------------------------------------------------
QString ctkXnatObject::name() const
{
  return property("name");
}

//----------------------------------------------------------------------------
void ctkXnatObject::setName(const QString& name)
{
  setProperty("name", name);
}

//----------------------------------------------------------------------------
QString ctkXnatObject::description() const
{
  return property("description");
}

//----------------------------------------------------------------------------
void ctkXnatObject::setDescription(const QString& description)
{
  setProperty("description", description);
}

//----------------------------------------------------------------------------
QString ctkXnatObject::childDataType() const
{
  return "Resources";
}

QDateTime ctkXnatObject::lastModifiedTime()
{
  Q_D(ctkXnatObject);
  QUuid queryId = this->session()->httpHead(this->resourceUri());
  QMap<QByteArray, QByteArray> header = this->session()->httpHeadSync(queryId);
  QVariant lastModifiedHeader = header.value("Last-Modified");
  QDateTime lastModifiedTime;

  if (lastModifiedHeader.isValid())
  {
    QStringList dateformates;
    // In case http date formate RFC 822 ( "Sun, 06 Nov 1994 08:49:37 GMT" )
    dateformates<<"ddd, dd MMM yyyy HH:mm:ss";
    // In case http date formate ANSI ( "Sun Nov  6 08:49:37 1994" )
    dateformates<<"ddd MMM  d HH:mm:ss yyyy";
    // In case http date formate RFC 850 ( "Sunday, 06-Nov-94 08:49:37 GMT" )
    dateformates<<"dddd, dd-MMM-yy HH:mm:ss";

    QString dateText = lastModifiedHeader.toString();
    // Remove "GMT" addition at the end of the http timestamp
    if (dateText.indexOf("GMT") != -1)
    {
      dateText = dateText.left(dateText.length()-4);
    }

    foreach (QString format, dateformates)
    {
      lastModifiedTime = QDateTime::fromString(dateText, format);
      if (lastModifiedTime.isValid())
        break;
    }
  }

  if (lastModifiedTime.isValid() && d->lastModifiedTime < lastModifiedTime)
    this->setLastModifiedTime(lastModifiedTime);
  return lastModifiedTime;
}

void ctkXnatObject::setLastModifiedTime(const QDateTime &lastModifiedTime)
{
  Q_D(ctkXnatObject);
  if (d->lastModifiedTime < lastModifiedTime)
  {
    d->lastModifiedTime = lastModifiedTime;
  }
}

//----------------------------------------------------------------------------
QString ctkXnatObject::property(const QString& name) const
{
  Q_D(const ctkXnatObject);
  ctkXnatObjectPrivate::PropertyMapConstInterator iter = d->properties.find(name);
  if (iter != d->properties.end())
  {
    return iter.value();
  }
  return QString::null;
}

//----------------------------------------------------------------------------
void ctkXnatObject::setProperty(const QString& name, const QVariant& value)
{
  Q_D(ctkXnatObject);
  d->properties.insert(name, value.toString());
}

//----------------------------------------------------------------------------
const QMap<QString, QString>& ctkXnatObject::properties() const
{
  Q_D(const ctkXnatObject);
  return d->properties;
}

//----------------------------------------------------------------------------
ctkXnatObject* ctkXnatObject::parent() const
{
  Q_D(const ctkXnatObject);
  return d->parent;
}

//----------------------------------------------------------------------------
void ctkXnatObject::setParent(ctkXnatObject* parent)
{
  Q_D(ctkXnatObject);
  if (d->parent != parent)
  {
    if (d->parent)
    {
      d->parent->remove(this);
    }
    if (parent)
    {
      parent->add(this);
    }
  }
}

//----------------------------------------------------------------------------
QList<ctkXnatObject*> ctkXnatObject::children() const
{
  Q_D(const ctkXnatObject);
  return d->children;
}

//----------------------------------------------------------------------------
void ctkXnatObject::add(ctkXnatObject* child)
{
  Q_D(ctkXnatObject);
  if (child->parent() != this)
  {
    child->d_func()->parent = this;
  }
  if (!d->children.contains(child))
  {
    d->children.push_back(child);
  }
  else
  {
    qWarning() << "ctkXnatObject::add(): Child already exists";
  }
}

//----------------------------------------------------------------------------
void ctkXnatObject::remove(ctkXnatObject* child)
{
  Q_D(ctkXnatObject);
  if (!d->children.removeOne(child))
  {
    qWarning() << "ctkXnatObject::remove(): Child does not exist";
  }
}

//----------------------------------------------------------------------------
void ctkXnatObject::reset()
{
  Q_D(ctkXnatObject);
  // d->properties.clear();
  d->children.clear();
  d->fetched = false;
}

//----------------------------------------------------------------------------
bool ctkXnatObject::isFetched() const
{
  Q_D(const ctkXnatObject);
  return d->fetched;
}

//----------------------------------------------------------------------------
QString ctkXnatObject::schemaType() const
{
  return this->property("xsiType");
}

//----------------------------------------------------------------------------
void ctkXnatObject::fetch()
{
  Q_D(ctkXnatObject);
  if (!d->fetched)
  {
    this->fetchImpl();
    d->fetched = true;
  }
}

//----------------------------------------------------------------------------
ctkXnatSession* ctkXnatObject::session() const
{
  const ctkXnatObject* xnatObject = this;
  while (ctkXnatObject* parent = xnatObject->parent())
  {
    xnatObject = parent;
  }
  const ctkXnatDataModel* dataModel = dynamic_cast<const ctkXnatDataModel*>(xnatObject);
  return dataModel ? dataModel->session() : NULL;
}

//----------------------------------------------------------------------------
void ctkXnatObject::setSchemaType(const QString& schemaType)
{
  this->setProperty("xsiType", schemaType);
}

//----------------------------------------------------------------------------
void ctkXnatObject::download(const QString& /*zipFilename*/)
{
}

//----------------------------------------------------------------------------
void ctkXnatObject::upload(const QString& /*zipFilename*/)
{
}

//----------------------------------------------------------------------------
bool ctkXnatObject::exists() const
{
  return this->session()->exists(this);
}

//----------------------------------------------------------------------------
void ctkXnatObject::save()
{
  this->session()->save(this);
}

//----------------------------------------------------------------------------
void ctkXnatObject::fetchResources(const QString& path)
{
  QString query = this->resourceUri() + path;
  ctkXnatSession* const session = this->session();
  QUuid queryId = session->httpGet(query);

  QList<ctkXnatObject*> resources = session->httpResults(queryId,
                                                           ctkXnatDefaultSchemaTypes::XSI_RESOURCE);

  foreach (ctkXnatObject* resource, resources)
  {
    QString label = resource->property("label");
    if (label.isEmpty())
    {
      label = "NO NAME";
    }

    resource->setProperty("label", label);
    this->add(resource);
  }
}

//----------------------------------------------------------------------------
void ctkXnatObject::erase()
{
  this->session()->remove(this);
  this->parent()->remove(this);
}
<commit_msg>Use constants for accessing the properties of an object<commit_after>/*=============================================================================

  Library: XNAT/Core

  Copyright (c) University College London,
    Centre for Medical Image Computing

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

=============================================================================*/

#include "ctkXnatObject.h"
#include "ctkXnatObjectPrivate.h"

#include "ctkXnatConstants.h"
#include "ctkXnatDataModel.h"
#include "ctkXnatDefaultSchemaTypes.h"
#include "ctkXnatSession.h"

#include <QDateTime>
#include <QDebug>
#include <QStringList>
#include <QVariant>

//----------------------------------------------------------------------------
ctkXnatObject::ctkXnatObject(const ctkXnatObject&)
{
  throw ctkRuntimeException("Copy constructor not implemented");
}

//----------------------------------------------------------------------------
ctkXnatObject::ctkXnatObject(ctkXnatObject* parent, const QString& schemaType)
: d_ptr(new ctkXnatObjectPrivate())
{
  this->setParent(parent);
  this->setSchemaType(schemaType);
}

//----------------------------------------------------------------------------
ctkXnatObject::ctkXnatObject(ctkXnatObjectPrivate& dd, ctkXnatObject* parent, const QString& schemaType)
: d_ptr(&dd)
{
  this->setParent(parent);
  this->setSchemaType(schemaType);
}

//----------------------------------------------------------------------------
ctkXnatObject::~ctkXnatObject()
{
  Q_D(ctkXnatObject);
  foreach (ctkXnatObject* child, d->children)
  {
    delete child;
  }
}

//----------------------------------------------------------------------------
QString ctkXnatObject::id() const
{
  return property("id");
}

//----------------------------------------------------------------------------
void ctkXnatObject::setId(const QString& id)
{
  setProperty("id", id);
}

//----------------------------------------------------------------------------
QString ctkXnatObject::name() const
{
  return property(ctkXnatObjectFields::NAME);
}

//----------------------------------------------------------------------------
void ctkXnatObject::setName(const QString& name)
{
  setProperty(ctkXnatObjectFields::NAME, name);
}

//----------------------------------------------------------------------------
QString ctkXnatObject::description() const
{
  return property("description");
}

//----------------------------------------------------------------------------
void ctkXnatObject::setDescription(const QString& description)
{
  setProperty("description", description);
}

//----------------------------------------------------------------------------
QString ctkXnatObject::childDataType() const
{
  return "Resources";
}

QDateTime ctkXnatObject::lastModifiedTime()
{
  Q_D(ctkXnatObject);
  QUuid queryId = this->session()->httpHead(this->resourceUri());
  QMap<QByteArray, QByteArray> header = this->session()->httpHeadSync(queryId);
  QVariant lastModifiedHeader = header.value("Last-Modified");
  QDateTime lastModifiedTime;

  if (lastModifiedHeader.isValid())
  {
    QStringList dateformates;
    // In case http date formate RFC 822 ( "Sun, 06 Nov 1994 08:49:37 GMT" )
    dateformates<<"ddd, dd MMM yyyy HH:mm:ss";
    // In case http date formate ANSI ( "Sun Nov  6 08:49:37 1994" )
    dateformates<<"ddd MMM  d HH:mm:ss yyyy";
    // In case http date formate RFC 850 ( "Sunday, 06-Nov-94 08:49:37 GMT" )
    dateformates<<"dddd, dd-MMM-yy HH:mm:ss";

    QString dateText = lastModifiedHeader.toString();
    // Remove "GMT" addition at the end of the http timestamp
    if (dateText.indexOf("GMT") != -1)
    {
      dateText = dateText.left(dateText.length()-4);
    }

    foreach (QString format, dateformates)
    {
      lastModifiedTime = QDateTime::fromString(dateText, format);
      if (lastModifiedTime.isValid())
        break;
    }
  }

  if (lastModifiedTime.isValid() && d->lastModifiedTime < lastModifiedTime)
    this->setLastModifiedTime(lastModifiedTime);
  return lastModifiedTime;
}

void ctkXnatObject::setLastModifiedTime(const QDateTime &lastModifiedTime)
{
  Q_D(ctkXnatObject);
  if (d->lastModifiedTime < lastModifiedTime)
  {
    d->lastModifiedTime = lastModifiedTime;
  }
}

//----------------------------------------------------------------------------
QString ctkXnatObject::property(const QString& name) const
{
  Q_D(const ctkXnatObject);
  ctkXnatObjectPrivate::PropertyMapConstInterator iter = d->properties.find(name);
  if (iter != d->properties.end())
  {
    return iter.value();
  }
  return QString::null;
}

//----------------------------------------------------------------------------
void ctkXnatObject::setProperty(const QString& name, const QVariant& value)
{
  Q_D(ctkXnatObject);
  d->properties.insert(name, value.toString());
}

//----------------------------------------------------------------------------
const QMap<QString, QString>& ctkXnatObject::properties() const
{
  Q_D(const ctkXnatObject);
  return d->properties;
}

//----------------------------------------------------------------------------
ctkXnatObject* ctkXnatObject::parent() const
{
  Q_D(const ctkXnatObject);
  return d->parent;
}

//----------------------------------------------------------------------------
void ctkXnatObject::setParent(ctkXnatObject* parent)
{
  Q_D(ctkXnatObject);
  if (d->parent != parent)
  {
    if (d->parent)
    {
      d->parent->remove(this);
    }
    if (parent)
    {
      parent->add(this);
    }
  }
}

//----------------------------------------------------------------------------
QList<ctkXnatObject*> ctkXnatObject::children() const
{
  Q_D(const ctkXnatObject);
  return d->children;
}

//----------------------------------------------------------------------------
void ctkXnatObject::add(ctkXnatObject* child)
{
  Q_D(ctkXnatObject);
  if (child->parent() != this)
  {
    child->d_func()->parent = this;
  }
  if (!d->children.contains(child))
  {
    d->children.push_back(child);
  }
  else
  {
    qWarning() << "ctkXnatObject::add(): Child already exists";
  }
}

//----------------------------------------------------------------------------
void ctkXnatObject::remove(ctkXnatObject* child)
{
  Q_D(ctkXnatObject);
  if (!d->children.removeOne(child))
  {
    qWarning() << "ctkXnatObject::remove(): Child does not exist";
  }
}

//----------------------------------------------------------------------------
void ctkXnatObject::reset()
{
  Q_D(ctkXnatObject);
  // d->properties.clear();
  d->children.clear();
  d->fetched = false;
}

//----------------------------------------------------------------------------
bool ctkXnatObject::isFetched() const
{
  Q_D(const ctkXnatObject);
  return d->fetched;
}

//----------------------------------------------------------------------------
QString ctkXnatObject::schemaType() const
{
  return this->property("xsiType");
}

//----------------------------------------------------------------------------
void ctkXnatObject::setSchemaType(const QString& schemaType)
{
  this->setProperty("xsiType", schemaType);
}

//----------------------------------------------------------------------------
void ctkXnatObject::fetch()
{
  Q_D(ctkXnatObject);
  if (!d->fetched)
  {
    this->fetchImpl();
    d->fetched = true;
  }
}

//----------------------------------------------------------------------------
ctkXnatSession* ctkXnatObject::session() const
{
  const ctkXnatObject* xnatObject = this;
  while (ctkXnatObject* parent = xnatObject->parent())
  {
    xnatObject = parent;
  }
  const ctkXnatDataModel* dataModel = dynamic_cast<const ctkXnatDataModel*>(xnatObject);
  return dataModel ? dataModel->session() : NULL;
}

//----------------------------------------------------------------------------
void ctkXnatObject::download(const QString& /*zipFilename*/)
{
}

//----------------------------------------------------------------------------
void ctkXnatObject::upload(const QString& /*zipFilename*/)
{
}

//----------------------------------------------------------------------------
bool ctkXnatObject::exists() const
{
  return this->session()->exists(this);
}

//----------------------------------------------------------------------------
void ctkXnatObject::save()
{
  this->session()->save(this);
}

//----------------------------------------------------------------------------
void ctkXnatObject::fetchResources(const QString& path)
{
  QString query = this->resourceUri() + path;
  ctkXnatSession* const session = this->session();
  QUuid queryId = session->httpGet(query);

  QList<ctkXnatObject*> resources = session->httpResults(queryId,
                                                           ctkXnatDefaultSchemaTypes::XSI_RESOURCE);

  foreach (ctkXnatObject* resource, resources)
  {
    QString label = resource->property(ctkXnatObjectFields::LABEL);
    if (label.isEmpty())
    {
      label = "NO NAME";
    }

    resource->setProperty(ctkXnatObjectFields::LABEL, label);
    this->add(resource);
  }
}

//----------------------------------------------------------------------------
void ctkXnatObject::erase()
{
  this->session()->remove(this);
  this->parent()->remove(this);
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "contacteditor.h"

#include <QtGui>

ContactEditor::ContactEditor(QWidget *parent)
        : QWidget(parent)
{
    m_manager = 0;
    m_contactId = QContactLocalId(0);

    m_saveBtn = new QPushButton("Save", this);
    connect(m_saveBtn, SIGNAL(clicked()), this, SLOT(saveClicked()));
    m_deleteBtn = new QPushButton("Delete", this);
    connect(m_deleteBtn, SIGNAL(clicked()), this, SLOT(deleteClicked()));
    m_cancelBtn = new QPushButton("Cancel", this);
    connect(m_cancelBtn, SIGNAL(clicked()), this, SLOT(cancelClicked()));

    m_nameEdit = new QLineEdit(this);
    m_phoneEdit = new QLineEdit(this);
    m_emailEdit = new QLineEdit(this);
    m_addrEdit = new QLineEdit(this);
    m_avatarBtn = new QPushButton(this);
    m_avatarBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    connect(m_avatarBtn, SIGNAL(clicked()), this, SLOT(avatarClicked()));

    m_detailsArea = new QScrollArea(this);
    m_detailsArea->setWidgetResizable(true);
    QFormLayout *detailsLayout = new QFormLayout;
    detailsLayout->addRow("Name", m_nameEdit);
    detailsLayout->addRow("Phone", m_phoneEdit);
    detailsLayout->addRow("Email", m_emailEdit);
    detailsLayout->addRow("Address", m_addrEdit);
    detailsLayout->addRow("Avatar", m_avatarBtn);
    detailsLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
    detailsLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
    m_detailsArea->setLayout(detailsLayout);

    QHBoxLayout *btnLayout = new QHBoxLayout;
    btnLayout->addWidget(m_saveBtn);
    btnLayout->addWidget(m_deleteBtn);
    btnLayout->addWidget(m_cancelBtn);

    QVBoxLayout *editLayout = new QVBoxLayout;
    editLayout->addWidget(m_detailsArea);
    editLayout->addLayout(btnLayout);

    setLayout(editLayout);
}

ContactEditor::~ContactEditor()
{
}

void ContactEditor::setCurrentContact(QContactManager* manager, QContactLocalId currentId)
{
    m_manager = manager;
    m_contactId = currentId;
    m_newAvatarPath = QString();

    if (manager == 0 || currentId == 0) {
        // clear the UI and return.
        m_nameEdit->setText("");
        m_phoneEdit->setText("");
        m_emailEdit->setText("");
        m_addrEdit->setText("");
        m_avatarBtn->setIcon(QIcon());

        if (manager == 0)
            m_saveBtn->setEnabled(false);
        m_deleteBtn->setEnabled(false);

        return;
    }

    // enable the UI.
    m_saveBtn->setEnabled(true);
    m_deleteBtn->setEnabled(true);

    // otherwise, build from the contact details.
    QContact curr = manager->contact(m_contactId);
    QContactName nm = curr.detail(QContactName::DefinitionName);
    QContactPhoneNumber phn = curr.detail(QContactPhoneNumber::DefinitionName);
    QContactEmailAddress em = curr.detail(QContactEmailAddress::DefinitionName);
    QContactAddress adr = curr.detail(QContactAddress::DefinitionName);
    QContactAvatar av = curr.detail(QContactAvatar::DefinitionName);

    m_nameEdit->setText(manager->synthesizeDisplayLabel(curr));
    m_phoneEdit->setText(phn.value(QContactPhoneNumber::FieldNumber));
    m_emailEdit->setText(em.value(QContactEmailAddress::FieldEmailAddress));
    m_addrEdit->setText(adr.value(QContactAddress::FieldStreet)); // ugly hack.
    m_avatarBtn->setIcon(QIcon(av.value(QContactAvatar::FieldAvatar)));
}

QString ContactEditor::nameField()
{
    // return the field which the name data should be saved in.
    if (!m_manager)
        return QString();

    QMap<QString, QContactDetailDefinition> defs = m_manager->detailDefinitions(QContactType::TypeContact);
    QContactDetailDefinition nameDef = defs.value(QContactName::DefinitionName);
    if (nameDef.fields().keys().contains(QContactName::FieldCustomLabel)) {
        return QString(QLatin1String(QContactName::FieldCustomLabel));
    } else if (nameDef.fields().keys().contains(QContactName::FieldFirst)) {
        return QString(QLatin1String(QContactName::FieldFirst));
    } else {
        return QString();
    }
}

void ContactEditor::avatarClicked()
{
    // put up a file dialog, and update the new avatar path.
    QString fileName = QFileDialog::getOpenFileName(this,
       tr("Select Avatar Image"), ".", tr("Image Files (*.png *.jpg *.bmp)"));

    m_newAvatarPath = fileName;
    m_avatarBtn->setIcon(QIcon(m_newAvatarPath));
}

void ContactEditor::saveClicked()
{
    if (!m_manager) {
        qWarning() << "No manager selected; cannot save.";
    } else {
        QContact curr;
        if (m_contactId != QContactLocalId(0))
            curr = m_manager->contact(m_contactId);
        QContactName nm = curr.detail(QContactName::DefinitionName);
        QContactPhoneNumber phn = curr.detail(QContactPhoneNumber::DefinitionName);
        QContactEmailAddress em = curr.detail(QContactEmailAddress::DefinitionName);
        QContactAddress adr = curr.detail(QContactAddress::DefinitionName);
        QContactAvatar av = curr.detail(QContactAvatar::DefinitionName);

        QString saveNameField = nameField();
        if (!saveNameField.isEmpty()) {
            // if the name has changed (ie, is different to the synthed label) then save it as a custom label.
            if (m_nameEdit->text() != m_manager->synthesizeDisplayLabel(curr)) {
                nm.setValue(nameField(), m_nameEdit->text());
            }
        }
        phn.setNumber(m_phoneEdit->text());
        em.setEmailAddress(m_emailEdit->text());
        adr.setStreet(m_addrEdit->text());
        av.setAvatar(m_newAvatarPath);

        curr.saveDetail(&nm);
        curr.saveDetail(&phn);
        curr.saveDetail(&em);
        curr.saveDetail(&adr);
        curr.saveDetail(&av);

        bool success = m_manager->saveContact(&curr);
        if (success)
            QMessageBox::information(this, "Success!", "Contact saved successfully!");
        else
            QMessageBox::information(this, "Failed!", "Failed to save contact!");
    }

    emit showListPage();
}

void ContactEditor::deleteClicked()
{
    if (!m_manager) {
        qWarning() << "No manager selected; cannot delete.";
    } else {
        if (m_contactId == QContactLocalId(0))
            qWarning() << "Contact is invalid; cannot delete.";

        bool success = m_manager->removeContact(m_contactId);
        if (success)
            QMessageBox::information(this, "Success!", "Contact deleted successfully!");
        else
            QMessageBox::information(this, "Failed!", "Failed to delete contact!");
    }

    emit showListPage();
}

void ContactEditor::cancelClicked()
{
    emit showListPage();
}
<commit_msg>add pixmap support for avatar<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "contacteditor.h"

#include <QtGui>

ContactEditor::ContactEditor(QWidget *parent)
        : QWidget(parent)
{
    m_manager = 0;
    m_contactId = QContactLocalId(0);

    m_saveBtn = new QPushButton("Save", this);
    connect(m_saveBtn, SIGNAL(clicked()), this, SLOT(saveClicked()));
    m_deleteBtn = new QPushButton("Delete", this);
    connect(m_deleteBtn, SIGNAL(clicked()), this, SLOT(deleteClicked()));
    m_cancelBtn = new QPushButton("Cancel", this);
    connect(m_cancelBtn, SIGNAL(clicked()), this, SLOT(cancelClicked()));

    m_nameEdit = new QLineEdit(this);
    m_phoneEdit = new QLineEdit(this);
    m_emailEdit = new QLineEdit(this);
    m_addrEdit = new QLineEdit(this);
    m_avatarBtn = new QPushButton(this);
    m_avatarBtn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    connect(m_avatarBtn, SIGNAL(clicked()), this, SLOT(avatarClicked()));

    m_detailsArea = new QScrollArea(this);
    m_detailsArea->setWidgetResizable(true);
    QFormLayout *detailsLayout = new QFormLayout;
    detailsLayout->addRow("Name", m_nameEdit);
    detailsLayout->addRow("Phone", m_phoneEdit);
    detailsLayout->addRow("Email", m_emailEdit);
    detailsLayout->addRow("Address", m_addrEdit);
    detailsLayout->addRow("Avatar", m_avatarBtn);
    detailsLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
    detailsLayout->setSizeConstraint(QLayout::SetMinAndMaxSize);
    m_detailsArea->setLayout(detailsLayout);

    QHBoxLayout *btnLayout = new QHBoxLayout;
    btnLayout->addWidget(m_saveBtn);
    btnLayout->addWidget(m_deleteBtn);
    btnLayout->addWidget(m_cancelBtn);

    QVBoxLayout *editLayout = new QVBoxLayout;
    editLayout->addWidget(m_detailsArea);
    editLayout->addLayout(btnLayout);

    setLayout(editLayout);
}

ContactEditor::~ContactEditor()
{
}

void ContactEditor::setCurrentContact(QContactManager* manager, QContactLocalId currentId)
{
    m_manager = manager;
    m_contactId = currentId;
    m_newAvatarPath = QString();

    if (manager == 0 || currentId == 0) {
        // clear the UI and return.
        m_nameEdit->setText("");
        m_phoneEdit->setText("");
        m_emailEdit->setText("");
        m_addrEdit->setText("");
        m_avatarBtn->setIcon(QIcon());

        if (manager == 0)
            m_saveBtn->setEnabled(false);
        m_deleteBtn->setEnabled(false);

        return;
    }

    // enable the UI.
    m_saveBtn->setEnabled(true);
    m_deleteBtn->setEnabled(true);

    // otherwise, build from the contact details.
    QContact curr = manager->contact(m_contactId);
    QContactName nm = curr.detail(QContactName::DefinitionName);
    QContactPhoneNumber phn = curr.detail(QContactPhoneNumber::DefinitionName);
    QContactEmailAddress em = curr.detail(QContactEmailAddress::DefinitionName);
    QContactAddress adr = curr.detail(QContactAddress::DefinitionName);
    QContactAvatar av = curr.detail(QContactAvatar::DefinitionName);

    m_nameEdit->setText(manager->synthesizeDisplayLabel(curr));
    m_phoneEdit->setText(phn.value(QContactPhoneNumber::FieldNumber));
    m_emailEdit->setText(em.value(QContactEmailAddress::FieldEmailAddress));
    m_addrEdit->setText(adr.value(QContactAddress::FieldStreet)); // ugly hack.
    m_avatarBtn->setIcon(QIcon(av.value(QContactAvatar::FieldAvatar)));
}

QString ContactEditor::nameField()
{
    // return the field which the name data should be saved in.
    if (!m_manager)
        return QString();

    QMap<QString, QContactDetailDefinition> defs = m_manager->detailDefinitions(QContactType::TypeContact);
    QContactDetailDefinition nameDef = defs.value(QContactName::DefinitionName);
    if (nameDef.fields().keys().contains(QContactName::FieldCustomLabel)) {
        return QString(QLatin1String(QContactName::FieldCustomLabel));
    } else if (nameDef.fields().keys().contains(QContactName::FieldFirst)) {
        return QString(QLatin1String(QContactName::FieldFirst));
    } else {
        return QString();
    }
}

void ContactEditor::avatarClicked()
{
    // put up a file dialog, and update the new avatar path.
    QString fileName = QFileDialog::getOpenFileName(this,
       tr("Select Avatar Image"), ".", tr("Image Files (*.png *.jpg *.bmp)"));

    m_newAvatarPath = fileName;
    m_avatarBtn->setIcon(QIcon(m_newAvatarPath));
}

void ContactEditor::saveClicked()
{
    if (!m_manager) {
        qWarning() << "No manager selected; cannot save.";
    } else {
        QContact curr;
        if (m_contactId != QContactLocalId(0))
            curr = m_manager->contact(m_contactId);
        QContactName nm = curr.detail(QContactName::DefinitionName);
        QContactPhoneNumber phn = curr.detail(QContactPhoneNumber::DefinitionName);
        QContactEmailAddress em = curr.detail(QContactEmailAddress::DefinitionName);
        QContactAddress adr = curr.detail(QContactAddress::DefinitionName);
        QContactAvatar av = curr.detail(QContactAvatar::DefinitionName);

        QString saveNameField = nameField();
        if (!saveNameField.isEmpty()) {
            // if the name has changed (ie, is different to the synthed label) then save it as a custom label.
            if (m_nameEdit->text() != m_manager->synthesizeDisplayLabel(curr)) {
                nm.setValue(nameField(), m_nameEdit->text());
            }
        }
        phn.setNumber(m_phoneEdit->text());
        em.setEmailAddress(m_emailEdit->text());
        adr.setStreet(m_addrEdit->text());
        av.setAvatar(m_newAvatarPath);
        QPixmap pix;
        pix.load(m_newAvatarPath);

        av.setPixmap(pix);

        curr.saveDetail(&nm);
        curr.saveDetail(&phn);
        curr.saveDetail(&em);
        curr.saveDetail(&adr);
        curr.saveDetail(&av);

        bool success = m_manager->saveContact(&curr);
        if (success)
            QMessageBox::information(this, "Success!", "Contact saved successfully!");
        else
            QMessageBox::information(this, "Failed!", "Failed to save contact!");
    }

    emit showListPage();
}

void ContactEditor::deleteClicked()
{
    if (!m_manager) {
        qWarning() << "No manager selected; cannot delete.";
    } else {
        if (m_contactId == QContactLocalId(0))
            qWarning() << "Contact is invalid; cannot delete.";

        bool success = m_manager->removeContact(m_contactId);
        if (success)
            QMessageBox::information(this, "Success!", "Contact deleted successfully!");
        else
            QMessageBox::information(this, "Failed!", "Failed to delete contact!");
    }

    emit showListPage();
}

void ContactEditor::cancelClicked()
{
    emit showListPage();
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2010 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2007-2008 The Florida State University
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Stephen Hines
 */
#ifndef __ARCH_ARM_INSTS_STATICINST_HH__
#define __ARCH_ARM_INSTS_STATICINST_HH__

#include "base/trace.hh"
#include "cpu/static_inst.hh"

namespace ArmISA
{
class ArmStaticInst : public StaticInst
{
  protected:
    int32_t shift_rm_imm(uint32_t base, uint32_t shamt,
                         uint32_t type, uint32_t cfval) const;
    int32_t shift_rm_rs(uint32_t base, uint32_t shamt,
                        uint32_t type, uint32_t cfval) const;

    bool shift_carry_imm(uint32_t base, uint32_t shamt,
                         uint32_t type, uint32_t cfval) const;
    bool shift_carry_rs(uint32_t base, uint32_t shamt,
                        uint32_t type, uint32_t cfval) const;

    template<int width>
    static bool
    saturateOp(int32_t &res, int64_t op1, int64_t op2, bool sub=false)
    {
        int64_t midRes = sub ? (op1 - op2) : (op1 + op2);
        if (bits(midRes, width) != bits(midRes, width - 1)) {
            if (midRes > 0)
                res = (LL(1) << (width - 1)) - 1;
            else
                res = -(LL(1) << (width - 1));
            return true;
        } else {
            res = midRes;
            return false;
        }
    }

    static bool
    satInt(int32_t &res, int64_t op, int width)
    {
        width--;
        if (op >= (LL(1) << width)) {
            res = (LL(1) << width) - 1;
            return true;
        } else if (op < -(LL(1) << width)) {
            res = -(LL(1) << width);
            return true;
        } else {
            res = op;
            return false;
        }
    }

    template<int width>
    static bool
    uSaturateOp(uint32_t &res, int64_t op1, int64_t op2, bool sub=false)
    {
        int64_t midRes = sub ? (op1 - op2) : (op1 + op2);
        if (midRes >= (LL(1) << width)) {
            res = (LL(1) << width) - 1;
            return true;
        } else if (midRes < 0) {
            res = 0;
            return true;
        } else {
            res = midRes;
            return false;
        }
    }

    static bool
    uSatInt(int32_t &res, int64_t op, int width)
    {
        if (op >= (LL(1) << width)) {
            res = (LL(1) << width) - 1;
            return true;
        } else if (op < 0) {
            res = 0;
            return true;
        } else {
            res = op;
            return false;
        }
    }

    // Constructor
    ArmStaticInst(const char *mnem, ExtMachInst _machInst,
                  OpClass __opClass)
        : StaticInst(mnem, _machInst, __opClass)
    {
    }

    /// Print a register name for disassembly given the unique
    /// dependence tag number (FP or int).
    void printReg(std::ostream &os, int reg) const;
    void printMnemonic(std::ostream &os,
                       const std::string &suffix = "",
                       bool withPred = true) const;
    void printMemSymbol(std::ostream &os, const SymbolTable *symtab,
                        const std::string &prefix, const Addr addr,
                        const std::string &suffix) const;
    void printShiftOperand(std::ostream &os, IntRegIndex rm,
                           bool immShift, uint32_t shiftAmt,
                           IntRegIndex rs, ArmShiftType type) const;

    void printDataInst(std::ostream &os, bool withImm) const;
    void printDataInst(std::ostream &os, bool withImm, bool immShift, bool s,
                       IntRegIndex rd, IntRegIndex rn, IntRegIndex rm,
                       IntRegIndex rs, uint32_t shiftAmt, ArmShiftType type,
                       uint32_t imm) const;

    std::string generateDisassembly(Addr pc, const SymbolTable *symtab) const;

    static uint32_t
    cpsrWriteByInstr(CPSR cpsr, uint32_t val,
            uint8_t byteMask, bool affectState)
    {
        bool privileged = (cpsr.mode != MODE_USER);

        uint32_t bitMask = 0;

        if (bits(byteMask, 3)) {
            unsigned lowIdx = affectState ? 24 : 27;
            bitMask = bitMask | mask(31, lowIdx);
        }
        if (bits(byteMask, 2)) {
            bitMask = bitMask | mask(19, 16);
        }
        if (bits(byteMask, 1)) {
            unsigned highIdx = affectState ? 15 : 9;
            unsigned lowIdx = privileged ? 8 : 9;
            bitMask = bitMask | mask(highIdx, lowIdx);
        }
        if (bits(byteMask, 0)) {
            if (privileged) {
                bitMask = bitMask | mask(7, 6);
                bitMask = bitMask | mask(5);
            }
            if (affectState)
                bitMask = bitMask | (1 << 5);
        }

        return ((uint32_t)cpsr & ~bitMask) | (val & bitMask);
    }

    static uint32_t
    spsrWriteByInstr(uint32_t spsr, uint32_t val,
            uint8_t byteMask, bool affectState)
    {
        uint32_t bitMask = 0;

        if (bits(byteMask, 3))
            bitMask = bitMask | mask(31, 24);
        if (bits(byteMask, 2))
            bitMask = bitMask | mask(19, 16);
        if (bits(byteMask, 1))
            bitMask = bitMask | mask(15, 8);
        if (bits(byteMask, 0))
            bitMask = bitMask | mask(7, 0);

        return ((spsr & ~bitMask) | (val & bitMask));
    }

    template<class XC>
    static Addr
    readPC(XC *xc)
    {
        Addr pc = xc->readPC();
        Addr tBit = pc & (ULL(1) << PcTBitShift);
        if (tBit)
            return pc + 4;
        else
            return pc + 8;
    }

    // Perform an regular branch.
    template<class XC>
    static void
    setNextPC(XC *xc, Addr val)
    {
        Addr npc = xc->readNextPC();
        if (npc & (ULL(1) << PcTBitShift)) {
            val &= ~mask(1);
        } else {
            val &= ~mask(2);
        }
        xc->setNextPC((npc & PcModeMask) |
                      (val & ~PcModeMask));
    }

    template<class T>
    static T
    cSwap(T val, bool big)
    {
        if (big) {
            return gtobe(val);
        } else {
            return gtole(val);
        }
    }

    // Perform an interworking branch.
    template<class XC>
    static void
    setIWNextPC(XC *xc, Addr val)
    {
        Addr stateBits = xc->readPC() & PcModeMask;
        Addr jBit = (ULL(1) << PcJBitShift);
        Addr tBit = (ULL(1) << PcTBitShift);
        bool thumbEE = (stateBits == (tBit | jBit));

        Addr newPc = (val & ~PcModeMask);
        if (thumbEE) {
            if (bits(newPc, 0)) {
                newPc = newPc & ~mask(1);
            } else {
                panic("Bad thumbEE interworking branch address %#x.\n", newPc);
            }
        } else {
            if (bits(newPc, 0)) {
                stateBits = tBit;
                newPc = newPc & ~mask(1);
            } else if (!bits(newPc, 1)) {
                stateBits = 0;
            } else {
                warn("Bad interworking branch address %#x.\n", newPc);
            }
        }
        newPc = newPc | stateBits;
        xc->setNextPC(newPc);
    }

    // Perform an interworking branch in ARM mode, a regular branch
    // otherwise.
    template<class XC>
    static void
    setAIWNextPC(XC *xc, Addr val)
    {
        Addr stateBits = xc->readPC() & PcModeMask;
        Addr jBit = (ULL(1) << PcJBitShift);
        Addr tBit = (ULL(1) << PcTBitShift);
        if (!jBit && !tBit) {
            setIWNextPC(xc, val);
        } else {
            setNextPC(xc, val);
        }
    }
};
}

#endif //__ARCH_ARM_INSTS_STATICINST_HH__
<commit_msg>ARM: Ignore writing a bad mode to CPSR with MSR.<commit_after>/*
 * Copyright (c) 2010 ARM Limited
 * All rights reserved
 *
 * The license below extends only to copyright in the software and shall
 * not be construed as granting a license to any other intellectual
 * property including but not limited to intellectual property relating
 * to a hardware implementation of the functionality of the software
 * licensed hereunder.  You may use the software subject to the license
 * terms below provided that you ensure that this notice is replicated
 * unmodified and in its entirety in all distributions of the software,
 * modified or unmodified, in source code or in binary form.
 *
 * Copyright (c) 2007-2008 The Florida State University
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Stephen Hines
 */
#ifndef __ARCH_ARM_INSTS_STATICINST_HH__
#define __ARCH_ARM_INSTS_STATICINST_HH__

#include "base/trace.hh"
#include "cpu/static_inst.hh"

namespace ArmISA
{
class ArmStaticInst : public StaticInst
{
  protected:
    int32_t shift_rm_imm(uint32_t base, uint32_t shamt,
                         uint32_t type, uint32_t cfval) const;
    int32_t shift_rm_rs(uint32_t base, uint32_t shamt,
                        uint32_t type, uint32_t cfval) const;

    bool shift_carry_imm(uint32_t base, uint32_t shamt,
                         uint32_t type, uint32_t cfval) const;
    bool shift_carry_rs(uint32_t base, uint32_t shamt,
                        uint32_t type, uint32_t cfval) const;

    template<int width>
    static bool
    saturateOp(int32_t &res, int64_t op1, int64_t op2, bool sub=false)
    {
        int64_t midRes = sub ? (op1 - op2) : (op1 + op2);
        if (bits(midRes, width) != bits(midRes, width - 1)) {
            if (midRes > 0)
                res = (LL(1) << (width - 1)) - 1;
            else
                res = -(LL(1) << (width - 1));
            return true;
        } else {
            res = midRes;
            return false;
        }
    }

    static bool
    satInt(int32_t &res, int64_t op, int width)
    {
        width--;
        if (op >= (LL(1) << width)) {
            res = (LL(1) << width) - 1;
            return true;
        } else if (op < -(LL(1) << width)) {
            res = -(LL(1) << width);
            return true;
        } else {
            res = op;
            return false;
        }
    }

    template<int width>
    static bool
    uSaturateOp(uint32_t &res, int64_t op1, int64_t op2, bool sub=false)
    {
        int64_t midRes = sub ? (op1 - op2) : (op1 + op2);
        if (midRes >= (LL(1) << width)) {
            res = (LL(1) << width) - 1;
            return true;
        } else if (midRes < 0) {
            res = 0;
            return true;
        } else {
            res = midRes;
            return false;
        }
    }

    static bool
    uSatInt(int32_t &res, int64_t op, int width)
    {
        if (op >= (LL(1) << width)) {
            res = (LL(1) << width) - 1;
            return true;
        } else if (op < 0) {
            res = 0;
            return true;
        } else {
            res = op;
            return false;
        }
    }

    // Constructor
    ArmStaticInst(const char *mnem, ExtMachInst _machInst,
                  OpClass __opClass)
        : StaticInst(mnem, _machInst, __opClass)
    {
    }

    /// Print a register name for disassembly given the unique
    /// dependence tag number (FP or int).
    void printReg(std::ostream &os, int reg) const;
    void printMnemonic(std::ostream &os,
                       const std::string &suffix = "",
                       bool withPred = true) const;
    void printMemSymbol(std::ostream &os, const SymbolTable *symtab,
                        const std::string &prefix, const Addr addr,
                        const std::string &suffix) const;
    void printShiftOperand(std::ostream &os, IntRegIndex rm,
                           bool immShift, uint32_t shiftAmt,
                           IntRegIndex rs, ArmShiftType type) const;

    void printDataInst(std::ostream &os, bool withImm) const;
    void printDataInst(std::ostream &os, bool withImm, bool immShift, bool s,
                       IntRegIndex rd, IntRegIndex rn, IntRegIndex rm,
                       IntRegIndex rs, uint32_t shiftAmt, ArmShiftType type,
                       uint32_t imm) const;

    std::string generateDisassembly(Addr pc, const SymbolTable *symtab) const;

    static uint32_t
    cpsrWriteByInstr(CPSR cpsr, uint32_t val,
            uint8_t byteMask, bool affectState)
    {
        bool privileged = (cpsr.mode != MODE_USER);

        uint32_t bitMask = 0;

        if (bits(byteMask, 3)) {
            unsigned lowIdx = affectState ? 24 : 27;
            bitMask = bitMask | mask(31, lowIdx);
        }
        if (bits(byteMask, 2)) {
            bitMask = bitMask | mask(19, 16);
        }
        if (bits(byteMask, 1)) {
            unsigned highIdx = affectState ? 15 : 9;
            unsigned lowIdx = privileged ? 8 : 9;
            bitMask = bitMask | mask(highIdx, lowIdx);
        }
        if (bits(byteMask, 0)) {
            if (privileged) {
                bitMask = bitMask | mask(7, 6);
                if (!badMode((OperatingMode)(val & mask(5)))) {
                    bitMask = bitMask | mask(5);
                } else {
                    warn_once("Ignoring write of bad mode to CPSR.\n");
                }
            }
            if (affectState)
                bitMask = bitMask | (1 << 5);
        }

        return ((uint32_t)cpsr & ~bitMask) | (val & bitMask);
    }

    static uint32_t
    spsrWriteByInstr(uint32_t spsr, uint32_t val,
            uint8_t byteMask, bool affectState)
    {
        uint32_t bitMask = 0;

        if (bits(byteMask, 3))
            bitMask = bitMask | mask(31, 24);
        if (bits(byteMask, 2))
            bitMask = bitMask | mask(19, 16);
        if (bits(byteMask, 1))
            bitMask = bitMask | mask(15, 8);
        if (bits(byteMask, 0))
            bitMask = bitMask | mask(7, 0);

        return ((spsr & ~bitMask) | (val & bitMask));
    }

    template<class XC>
    static Addr
    readPC(XC *xc)
    {
        Addr pc = xc->readPC();
        Addr tBit = pc & (ULL(1) << PcTBitShift);
        if (tBit)
            return pc + 4;
        else
            return pc + 8;
    }

    // Perform an regular branch.
    template<class XC>
    static void
    setNextPC(XC *xc, Addr val)
    {
        Addr npc = xc->readNextPC();
        if (npc & (ULL(1) << PcTBitShift)) {
            val &= ~mask(1);
        } else {
            val &= ~mask(2);
        }
        xc->setNextPC((npc & PcModeMask) |
                      (val & ~PcModeMask));
    }

    template<class T>
    static T
    cSwap(T val, bool big)
    {
        if (big) {
            return gtobe(val);
        } else {
            return gtole(val);
        }
    }

    // Perform an interworking branch.
    template<class XC>
    static void
    setIWNextPC(XC *xc, Addr val)
    {
        Addr stateBits = xc->readPC() & PcModeMask;
        Addr jBit = (ULL(1) << PcJBitShift);
        Addr tBit = (ULL(1) << PcTBitShift);
        bool thumbEE = (stateBits == (tBit | jBit));

        Addr newPc = (val & ~PcModeMask);
        if (thumbEE) {
            if (bits(newPc, 0)) {
                newPc = newPc & ~mask(1);
            } else {
                panic("Bad thumbEE interworking branch address %#x.\n", newPc);
            }
        } else {
            if (bits(newPc, 0)) {
                stateBits = tBit;
                newPc = newPc & ~mask(1);
            } else if (!bits(newPc, 1)) {
                stateBits = 0;
            } else {
                warn("Bad interworking branch address %#x.\n", newPc);
            }
        }
        newPc = newPc | stateBits;
        xc->setNextPC(newPc);
    }

    // Perform an interworking branch in ARM mode, a regular branch
    // otherwise.
    template<class XC>
    static void
    setAIWNextPC(XC *xc, Addr val)
    {
        Addr stateBits = xc->readPC() & PcModeMask;
        Addr jBit = (ULL(1) << PcJBitShift);
        Addr tBit = (ULL(1) << PcTBitShift);
        if (!jBit && !tBit) {
            setIWNextPC(xc, val);
        } else {
            setNextPC(xc, val);
        }
    }
};
}

#endif //__ARCH_ARM_INSTS_STATICINST_HH__
<|endoftext|>