<commit_before>#include "fcenterwindow.h"
#include<QPushButton>
#include<QVBoxLayout>
#include<QPropertyAnimation>
#include<QParallelAnimationGroup>
#include<QEasingCurve>
#include<QLabel>
#include<QTime>
#include"ftitlebar.h"

FCenterWindow::FCenterWindow(QWidget *parent)
    :QFrame(parent)
{
    qDebug("FCenterWindow init");
    initData();
    initUI();
    initConnect();
}

void FCenterWindow::initData()
{
    preindex = 0;
}

void FCenterWindow::initUI()
{
    setObjectName(QString("FCenterWindow"));
    navagationBar = new FNavgationBar();
    stackWidget = new QStackedWidget();

    navlayout = new QBoxLayout(QBoxLayout::TopToBottom);
    navlayout->addWidget(navagationBar);
    navlayout->addWidget(stackWidget);
    navlayout->setContentsMargins(0, 0 ,0 ,0);
    navlayout->setSpacing(0);

    mainLayout = new QVBoxLayout;
    mainLayout->addWidget(FTitleBar::getInstace());
    mainLayout->addLayout(navlayout);
    mainLayout->setContentsMargins(0, 0 ,0 ,0);
    mainLayout->setSpacing(0);
    setLayout(mainLayout);
}

void FCenterWindow::swicthLayout(QBoxLayout::Direction direction)
{
    navlayout->setDirection(direction);
}

void FCenterWindow::setAlignment(Alignment_Direction direction)
{
    switch (direction) {
    case TopLeft:
        navagationBar->setObjectName(QString("FNavgationBar_bottom"));
        navagationBar->setAlignment_topLeft();
        navagationBar->resize(QSize(stackWidget->width(), navagationBar->height()));
        swicthLayout(QBoxLayout::TopToBottom);
        break;
    case TopCenter:
        navagationBar->setObjectName(QString("FNavgationBar_bottom"));
        navagationBar->setAlignment_topCenter();
        swicthLayout(QBoxLayout::TopToBottom);
        break;
    case TopRight:
        navagationBar->setObjectName(QString("FNavgationBar_bottom"));
        navagationBar->setAlignment_topRight();
        swicthLayout(QBoxLayout::TopToBottom);
        break;
    case RightTop:
        navagationBar->setObjectName(QString("FNavgationBar_left"));
        navagationBar->setAlignment_rightTop();
        swicthLayout(QBoxLayout::RightToLeft);
        navagationBar->resize(QSize(navagationBar->width(), stackWidget->height()));
        break;
    case RightCenter:
        navagationBar->setObjectName(QString("FNavgationBar_left"));
        navagationBar->setAlignment_rightCenter();
        swicthLayout(QBoxLayout::RightToLeft);
        navagationBar->resize(QSize(navagationBar->width(), stackWidget->height()));
        break;
    case RightBottom:
        navagationBar->setObjectName(QString("FNavgationBar_left"));
        navagationBar->setAlignment_rightBottom();
        swicthLayout(QBoxLayout::RightToLeft);
        navagationBar->resize(QSize(navagationBar->width(), stackWidget->height()));
        break;
    case BottomRight:
        navagationBar->setObjectName(QString("FNavgationBar_top"));
        navagationBar->setAlignment_bottomRight();
        swicthLayout(QBoxLayout::BottomToTop);
        break;
    case BottomCenter:
        navagationBar->setObjectName(QString("FNavgationBar_top"));
        navagationBar->setAlignment_bottomCenter();
        swicthLayout(QBoxLayout::BottomToTop);
        break;
    case BottomLeft:
        navagationBar->setObjectName(QString("FNavgationBar_top"));
        navagationBar->setAlignment_bottomLeft();
        swicthLayout(QBoxLayout::BottomToTop);
        break;
    case LeftBottom:
        navagationBar->setObjectName(QString("FNavgationBar_right"));
        navagationBar->setAlignment_leftBottom();
        swicthLayout(QBoxLayout::LeftToRight);
        break;
    case LeftCenter:
        navagationBar->setObjectName(QString("FNavgationBar_right"));
        navagationBar->setAlignment_leftCenter();
        swicthLayout(QBoxLayout::LeftToRight);
        break;
    case LeftTop:
        navagationBar->setObjectName(QString("FNavgationBar_right"));
        navagationBar->setAlignment_leftTop();
        swicthLayout(QBoxLayout::LeftToRight);
        break;
    default:
        break;
    }
}

void FCenterWindow::initConnect()
{
    connect(navagationBar, SIGNAL(indexChanged(int)), this, SLOT(switchscreen(int)));
}

void FCenterWindow::addWidget(const QString &tile, const QString &obejctName, QWidget *widget)
{
    navagationBar->addNavgationTile(tile, obejctName);
    widget->setObjectName(obejctName);
    stackWidget->addWidget(widget);
}

FNavgationBar* FCenterWindow::getNavgationBar(){
    return navagationBar;
}

void FCenterWindow::switchscreen(const int index)
{
    int n = 0;
    if (index == stackWidget->currentIndex())
    {
        return;
    }
    else if(index > stackWidget->currentIndex())
    {
        n = 2;
    }
    else if (index < stackWidget->currentIndex())
    {
        n = 6;
    }

    stackWidget->setCurrentIndex(index);

//    QTime time;
//    time= QTime::currentTime();
//    qsrand(time.msec()+time.second()*1000);
//    int n = qrand()%9;
//    n = 0;
    switch (n) {
    case 0:
        cloudAntimation(animationTop);
        break;
    case 1:
        cloudAntimation(animationTopRight);
        break;
    case 2:
        cloudAntimation(animationRight);
        break;
    case 3:
        cloudAntimation(animationBottomRight);
        break;
    case 4:
        cloudAntimation(animationBottom);
        break;
    case 5:
        cloudAntimation(animationBottomLeft);
        break;
    case 6:
        cloudAntimation(animationLeft);
        break;
    case 7:
        cloudAntimation(animationTopLeft);
        break;
    case 8:
        cloudAntimation(animationCenter);
        break;
    default:
        break;
    }
    preindex = index;

}

void FCenterWindow::switchscreen()
{
    stackWidget->setCurrentIndex(currentIndex);
}

void FCenterWindow::cloudAntimation(animation_Direction direction)
{
    QLabel* circle = new QLabel(stackWidget->currentWidget());
    QLabel* line = new QLabel(this);
    line->setObjectName(QString("line"));
    line->resize(0, 2);
    line->show();
    line->setStyleSheet(QString("QLabel{background-color: white;}"));

    circle->setPixmap(stackWidget->widget(preindex)->grab());
    circle->show();
    circle->resize(stackWidget->currentWidget()->size());
    QPropertyAnimation *animation = new QPropertyAnimation(circle, "geometry");

    animation->setDuration(1000);
    animation->setStartValue(circle->geometry());

    QPropertyAnimation* animation_line = new QPropertyAnimation(line, "size");
    animation_line->setDuration(1000);
    animation_line->setEasingCurve(QEasingCurve::OutCubic);

    switch (direction) {
    case animationTop:
        animation->setEndValue(QRect(circle->x(), circle->y() - 10, circle->width(), 0));
        break;
    case animationTopRight:
        animation->setEndValue(QRect(circle->width(), 0, 0, 0));
        break;
    case animationRight:
        line->move(0, stackWidget->y() - 2);
        animation->setEndValue(QRect(circle->width() + 3, 0, 0, circle->height()));
        animation_line->setStartValue(QSize(0, 2));
        animation_line->setEndValue(QSize(stackWidget->width(), 2));
        break;
    case animationBottomRight:
        animation->setEndValue(QRect(circle->width(), circle->height(), 0, 0));
        break;
    case animationBottom:
        animation->setEndValue(QRect(0, circle->height() + 10, circle->width(), 0));
        break;
    case animationBottomLeft:
        animation->setEndValue(QRect(0, circle->height(), 0, 0));
        break;
    case animationLeft:
        animation->setEndValue(QRect(-3, 0, 0, circle->height()));
        line->move(stackWidget->x(), stackWidget->y() - 2);
        animation_line->setStartValue(QSize(0, 2));
        animation_line->setEndValue(QSize(stackWidget->width(), 2));
        break;
    case animationTopLeft:
        animation->setEndValue(QRect(0, 0, 0, 0));
        break;
    case animationCenter:
        animation->setEndValue(QRect(circle->width()/2, circle->height()/2, 0, 0));
        break;
    default:
        break;
    }
    animation->setEasingCurve(QEasingCurve::OutCubic);

    QPropertyAnimation* animation_opacity = new QPropertyAnimation(circle, "windowOpacity");
    animation_opacity->setDuration(1000);
    animation_opacity->setStartValue(1);
    animation_opacity->setEndValue(0);
    animation_opacity->setEasingCurve(QEasingCurve::OutCubic);

    QParallelAnimationGroup *group = new QParallelAnimationGroup;

    connect(group,SIGNAL(finished()), circle, SLOT(hide()));
    connect(group,SIGNAL(finished()), circle, SLOT(deleteLater()));
    connect(group,SIGNAL(finished()), line, SLOT(deleteLater()));
    connect(group,SIGNAL(finished()), group, SLOT(deleteLater()));
    connect(group,SIGNAL(finished()), animation, SLOT(deleteLater()));
    connect(group,SIGNAL(finished()), animation_opacity, SLOT(deleteLater()));
    connect(group,SIGNAL(finished()), animation_line, SLOT(deleteLater()));
    group->addAnimation(animation);
    group->addAnimation(animation_opacity);
    group->addAnimation(animation_line);
    group->start();
}
<commit_msg>qLabel setContentsScale<commit_after>#include "fcenterwindow.h"
#include<QPushButton>
#include<QVBoxLayout>
#include<QPropertyAnimation>
#include<QParallelAnimationGroup>
#include<QEasingCurve>
#include<QLabel>
#include<QTime>
#include"ftitlebar.h"

FCenterWindow::FCenterWindow(QWidget *parent)
    :QFrame(parent)
{
    qDebug("FCenterWindow init");
    initData();
    initUI();
    initConnect();
}

void FCenterWindow::initData()
{
    preindex = 0;
}

void FCenterWindow::initUI()
{
    setObjectName(QString("FCenterWindow"));
    navagationBar = new FNavgationBar();
    stackWidget = new QStackedWidget();

    navlayout = new QBoxLayout(QBoxLayout::TopToBottom);
    navlayout->addWidget(navagationBar);
    navlayout->addWidget(stackWidget);
    navlayout->setContentsMargins(0, 0 ,0 ,0);
    navlayout->setSpacing(0);

    mainLayout = new QVBoxLayout;
    mainLayout->addWidget(FTitleBar::getInstace());
    mainLayout->addLayout(navlayout);
    mainLayout->setContentsMargins(0, 0 ,0 ,0);
    mainLayout->setSpacing(0);
    setLayout(mainLayout);
}

void FCenterWindow::swicthLayout(QBoxLayout::Direction direction)
{
    navlayout->setDirection(direction);
}

void FCenterWindow::setAlignment(Alignment_Direction direction)
{
    switch (direction) {
    case TopLeft:
        navagationBar->setObjectName(QString("FNavgationBar_bottom"));
        navagationBar->setAlignment_topLeft();
        navagationBar->resize(QSize(stackWidget->width(), navagationBar->height()));
        swicthLayout(QBoxLayout::TopToBottom);
        break;
    case TopCenter:
        navagationBar->setObjectName(QString("FNavgationBar_bottom"));
        navagationBar->setAlignment_topCenter();
        swicthLayout(QBoxLayout::TopToBottom);
        break;
    case TopRight:
        navagationBar->setObjectName(QString("FNavgationBar_bottom"));
        navagationBar->setAlignment_topRight();
        swicthLayout(QBoxLayout::TopToBottom);
        break;
    case RightTop:
        navagationBar->setObjectName(QString("FNavgationBar_left"));
        navagationBar->setAlignment_rightTop();
        swicthLayout(QBoxLayout::RightToLeft);
        navagationBar->resize(QSize(navagationBar->width(), stackWidget->height()));
        break;
    case RightCenter:
        navagationBar->setObjectName(QString("FNavgationBar_left"));
        navagationBar->setAlignment_rightCenter();
        swicthLayout(QBoxLayout::RightToLeft);
        navagationBar->resize(QSize(navagationBar->width(), stackWidget->height()));
        break;
    case RightBottom:
        navagationBar->setObjectName(QString("FNavgationBar_left"));
        navagationBar->setAlignment_rightBottom();
        swicthLayout(QBoxLayout::RightToLeft);
        navagationBar->resize(QSize(navagationBar->width(), stackWidget->height()));
        break;
    case BottomRight:
        navagationBar->setObjectName(QString("FNavgationBar_top"));
        navagationBar->setAlignment_bottomRight();
        swicthLayout(QBoxLayout::BottomToTop);
        break;
    case BottomCenter:
        navagationBar->setObjectName(QString("FNavgationBar_top"));
        navagationBar->setAlignment_bottomCenter();
        swicthLayout(QBoxLayout::BottomToTop);
        break;
    case BottomLeft:
        navagationBar->setObjectName(QString("FNavgationBar_top"));
        navagationBar->setAlignment_bottomLeft();
        swicthLayout(QBoxLayout::BottomToTop);
        break;
    case LeftBottom:
        navagationBar->setObjectName(QString("FNavgationBar_right"));
        navagationBar->setAlignment_leftBottom();
        swicthLayout(QBoxLayout::LeftToRight);
        break;
    case LeftCenter:
        navagationBar->setObjectName(QString("FNavgationBar_right"));
        navagationBar->setAlignment_leftCenter();
        swicthLayout(QBoxLayout::LeftToRight);
        break;
    case LeftTop:
        navagationBar->setObjectName(QString("FNavgationBar_right"));
        navagationBar->setAlignment_leftTop();
        swicthLayout(QBoxLayout::LeftToRight);
        break;
    default:
        break;
    }
}

void FCenterWindow::initConnect()
{
    connect(navagationBar, SIGNAL(indexChanged(int)), this, SLOT(switchscreen(int)));
}

void FCenterWindow::addWidget(const QString &tile, const QString &obejctName, QWidget *widget)
{
    navagationBar->addNavgationTile(tile, obejctName);
    widget->setObjectName(obejctName);
    stackWidget->addWidget(widget);
}

FNavgationBar* FCenterWindow::getNavgationBar(){
    return navagationBar;
}

void FCenterWindow::switchscreen(const int index)
{
    int n = 0;
    if (index == stackWidget->currentIndex())
    {
        return;
    }
    else if(index > stackWidget->currentIndex())
    {
        n = 2;
    }
    else if (index < stackWidget->currentIndex())
    {
        n = 6;
    }

    stackWidget->setCurrentIndex(index);

//    QTime time;
//    time= QTime::currentTime();
//    qsrand(time.msec()+time.second()*1000);
//    int n = qrand()%9;
//    n = 0;
    switch (n) {
    case 0:
        cloudAntimation(animationTop);
        break;
    case 1:
        cloudAntimation(animationTopRight);
        break;
    case 2:
        cloudAntimation(animationRight);
        break;
    case 3:
        cloudAntimation(animationBottomRight);
        break;
    case 4:
        cloudAntimation(animationBottom);
        break;
    case 5:
        cloudAntimation(animationBottomLeft);
        break;
    case 6:
        cloudAntimation(animationLeft);
        break;
    case 7:
        cloudAntimation(animationTopLeft);
        break;
    case 8:
        cloudAntimation(animationCenter);
        break;
    default:
        break;
    }
    preindex = index;

}

void FCenterWindow::switchscreen()
{
    stackWidget->setCurrentIndex(currentIndex);
}

void FCenterWindow::cloudAntimation(animation_Direction direction)
{
    QLabel* circle = new QLabel(stackWidget->currentWidget());
    QLabel* line = new QLabel(this);
    line->setObjectName(QString("line"));
    line->resize(0, 2);
    line->show();
    line->setStyleSheet(QString("QLabel{background-color: white;}"));

    circle->setPixmap(stackWidget->widget(preindex)->grab());
//    circle->setScaledContents(true);
    circle->show();
    circle->resize(stackWidget->currentWidget()->size());
    QPropertyAnimation *animation = new QPropertyAnimation(circle, "geometry");

    animation->setDuration(1000);
    animation->setStartValue(circle->geometry());

    QPropertyAnimation* animation_line = new QPropertyAnimation(line, "size");
    animation_line->setDuration(1000);
    animation_line->setEasingCurve(QEasingCurve::OutCubic);

    switch (direction) {
    case animationTop:
        animation->setEndValue(QRect(circle->x(), circle->y() - 10, circle->width(), 0));
        break;
    case animationTopRight:
        animation->setEndValue(QRect(circle->width(), 0, 0, 0));
        break;
    case animationRight:
        line->move(0, stackWidget->y() - 2);
        animation->setEndValue(QRect(circle->width() + 3, 0, 0, circle->height()));
        animation_line->setStartValue(QSize(0, 2));
        animation_line->setEndValue(QSize(stackWidget->width(), 2));
        break;
    case animationBottomRight:
        animation->setEndValue(QRect(circle->width(), circle->height(), 0, 0));
        break;
    case animationBottom:
        animation->setEndValue(QRect(0, circle->height() + 10, circle->width(), 0));
        break;
    case animationBottomLeft:
        animation->setEndValue(QRect(0, circle->height(), 0, 0));
        break;
    case animationLeft:
        animation->setEndValue(QRect(-3, 0, 0, circle->height()));
        line->move(stackWidget->x(), stackWidget->y() - 2);
        animation_line->setStartValue(QSize(0, 2));
        animation_line->setEndValue(QSize(stackWidget->width(), 2));
        break;
    case animationTopLeft:
        animation->setEndValue(QRect(0, 0, 0, 0));
        break;
    case animationCenter:
        animation->setEndValue(QRect(circle->width()/2, circle->height()/2, 0, 0));
        break;
    default:
        break;
    }
    animation->setEasingCurve(QEasingCurve::OutCubic);

    QPropertyAnimation* animation_opacity = new QPropertyAnimation(circle, "windowOpacity");
    animation_opacity->setDuration(1000);
    animation_opacity->setStartValue(1);
    animation_opacity->setEndValue(0);
    animation_opacity->setEasingCurve(QEasingCurve::OutCubic);

    QParallelAnimationGroup *group = new QParallelAnimationGroup;

    connect(group,SIGNAL(finished()), circle, SLOT(hide()));
    connect(group,SIGNAL(finished()), circle, SLOT(deleteLater()));
    connect(group,SIGNAL(finished()), line, SLOT(deleteLater()));
    connect(group,SIGNAL(finished()), group, SLOT(deleteLater()));
    connect(group,SIGNAL(finished()), animation, SLOT(deleteLater()));
    connect(group,SIGNAL(finished()), animation_opacity, SLOT(deleteLater()));
    connect(group,SIGNAL(finished()), animation_line, SLOT(deleteLater()));
    group->addAnimation(animation);
    group->addAnimation(animation_opacity);
    group->addAnimation(animation_line);
    group->start();
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-2000, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/*
   $Log$
   Revision 1.3  2001/12/05 14:53:34  hristov
   Destructor corrected

   Revision 1.2  2001/11/07 14:50:31  hristov
   Minor correction of the Log part

   Revision 1.1  2001/11/02 15:37:26  hristov
   Digitizer class created. Code cleaning and bug fixes (J.Chudoba)
*/
#include <iostream>

#include <TTree.h>
#include <TObjArray.h>
#include <TFile.h>
#include <TDirectory.h>
#include <TParticle.h>

#include "AliRICHDigitizer.h"
#include "AliRICHChamber.h"
#include "AliHitMap.h"
#include "AliRICHHitMapA1.h"
#include "AliRICH.h"
#include "AliRICHHit.h"
#include "AliRICHSDigit.h"
#include "AliRICHDigit.h"
#include "AliRICHTransientDigit.h"
#include "AliRun.h"
#include "AliPDG.h"
#include "AliRunDigitizer.h"

ClassImp(AliRICHDigitizer)

//___________________________________________
  AliRICHDigitizer::AliRICHDigitizer()
{
// Default constructor - don't use it
  fHits = 0;
  fSDigits = 0;
  fHitMap = 0;
  fTDList = 0;
}

////////////////////////////////////////////////////////////////////////
AliRICHDigitizer::AliRICHDigitizer(AliRunDigitizer* manager)
    :AliDigitizer(manager)
{
// ctor which should be used
  fHits = 0;
  fSDigits = 0;
  fHitMap = 0;
  fTDList = 0;
  fDebug   = 0;
  if (GetDebug()>2)
    cerr<<"AliRICHDigitizer::AliRICHDigitizer"
	<<"(AliRunDigitizer* manager) was processed"<<endl;
}

////////////////////////////////////////////////////////////////////////
AliRICHDigitizer::~AliRICHDigitizer()
{
// Destructor
    if (fHits) {
	fHits->Delete();
	delete fHits;
    }
    if (fSDigits) {
	fSDigits->Delete();
	delete fSDigits;
    }
    for (Int_t i=0; i<kNCH; i++ )
	delete fHitMap[i];
    delete [] fHitMap;
    if (fTDList) {
	fTDList->Delete();
	delete fTDList;
  }
}

//------------------------------------------------------------------------
Bool_t AliRICHDigitizer::Exists(const AliRICHSDigit *padhit)
{
  return (fHitMap[fNch]->TestHit(padhit->PadX(),padhit->PadY()));
}

//------------------------------------------------------------------------
void AliRICHDigitizer::Update(AliRICHSDigit *padhit)
{
  AliRICHTransientDigit *pdigit =
    static_cast<AliRICHTransientDigit*>(
      fHitMap[fNch]->GetHit(padhit->PadX(),padhit->PadY()));

  // update charge
  //
  Int_t iqpad    = Int_t(padhit->QPad()); // charge per pad
  pdigit->AddSignal(iqpad);
  pdigit->AddPhysicsSignal(iqpad);

  // update list of tracks
  //
  Int_t track, charge;
  track = fTrack+fMask;
  if (fSignal) {
    charge = iqpad;
  } else {
    charge = kBgTag;
  }
  pdigit->UpdateTrackList(track,charge);
}

//------------------------------------------------------------------------
void AliRICHDigitizer::CreateNew(AliRICHSDigit *padhit)
{
  fTDList->AddAtAndExpand(
    new AliRICHTransientDigit(fNch,fDigits),fCounter);
  fHitMap[fNch]->SetHit(padhit->PadX(),padhit->PadY(),fCounter);

  AliRICHTransientDigit* pdigit =
    static_cast<AliRICHTransientDigit*>(fTDList->Last());
  // list of tracks
  Int_t track, charge;
  if (fSignal) {
    track = fTrack;
    charge = padhit->QPad();
  } else {
    track = kBgTag;
    charge = kBgTag;
  }
  pdigit->AddToTrackList(track,charge);
  fCounter++;
}

////////////////////////////////////////////////////////////////////////
Bool_t AliRICHDigitizer::Init()
{
// Initialisation
  fHits     = new TClonesArray("AliRICHHit",1000);
  fSDigits  = new TClonesArray("AliRICHSDigit",1000);
  return kTRUE;
}

////////////////////////////////////////////////////////////////////////
//void AliRICHDigitizer::Digitise(Int_t nev, Int_t flag)
void AliRICHDigitizer::Exec(Option_t* option)
{
  TString optionString = option;
  if (optionString.Data() == "deb") {
    cout<<"AliMUONDigitizer::Exec: called with option deb "<<endl;
    fDebug = 3;
  }

  AliRICHChamber*       iChamber;
  AliSegmentation*  segmentation;

  fTDList = new TObjArray;

  AliRICH *pRICH = (AliRICH *) gAlice->GetDetector("RICH");
  pRICH->MakeBranchInTreeD(fManager->GetTreeD());
  fHitMap= new AliHitMap* [kNCH];

  for (Int_t i =0; i<kNCH; i++) {
    iChamber= &(pRICH->Chamber(i));
    segmentation=iChamber->GetSegmentationModel(1);
    fHitMap[i] = new AliRICHHitMapA1(segmentation, fTDList);
  }

// Loop over files to digitize
  fSignal = kTRUE;
  fCounter = 0;
  for (Int_t inputFile=0; inputFile<fManager->GetNinputs();
       inputFile++) {

// Connect RICH branches

    if (inputFile > 0 ) fSignal = kFALSE;
    TBranch *branchHits = 0;
    TBranch *branchSDigits = 0;
    TTree *treeH = fManager->GetInputTreeH(inputFile);
    if (GetDebug()>2) {
      cerr<<"   inputFile  "<<inputFile<<endl;
      cerr<<"   treeH, fHits "<<treeH<<" "<<fHits<<endl;
    }
    if (treeH && fHits) {
      branchHits = treeH->GetBranch("RICH");
      if (branchHits) {
	fHits->Clear();
	branchHits->SetAddress(&fHits);
      }
      else
	Error("Exec","branch RICH was not found");
    }
    if (GetDebug()>2) cerr<<"   branchHits = "<<branchHits<<endl;

    if (treeH && fSDigits) {
      branchSDigits = treeH->GetBranch("RICHSDigits");
      if (branchSDigits)
	branchSDigits->SetAddress(&fSDigits);
      else
	Error("exec","branch RICHSDigits was not found");
    }
    if (GetDebug()>2) cerr<<"   branchSDigits = "<<branchSDigits<<endl;

    //
    //   Loop over tracks
    //

    Int_t ntracks =(Int_t) treeH->GetEntries();
    for (fTrack=0; fTrack<ntracks; fTrack++) {
      fHits->Clear();
      fSDigits->Clear();
      branchHits->GetEntry(fTrack);
      branchSDigits->GetEntry(fTrack);

      //
      //   Loop over hits
      for(Int_t i = 0; i < fHits->GetEntriesFast(); ++i) {
	AliRICHHit* mHit = static_cast<AliRICHHit*>(fHits->At(i));
	fNch = mHit->Chamber()-1;  // chamber number
	if (fNch >= kNCH) {
	  cerr<<"AliRICHDigitizer: chamber nr. fNch out of range: "<<fNch<<endl;
	  cerr<<"               track: "<<fTrack<<endl;
	  continue;
	}
	iChamber = &(pRICH->Chamber(fNch));

	//
	// Loop over pad hits
	for (AliRICHSDigit* mPad=
	       (AliRICHSDigit*)pRICH->FirstPad(mHit,fSDigits);
	     mPad;
	     mPad=(AliRICHSDigit*)pRICH->NextPad(fSDigits))
	{
	  Int_t iqpad    = mPad->QPad();       // charge per pad
	  fDigits[0]=mPad->PadX();
	  fDigits[1]=mPad->PadY();
	  fDigits[2]=iqpad;
	  fDigits[3]=iqpad;
	  fDigits[4]=mPad->HitNumber();

	  // build the list of fired pads and update the info
	  if (Exists(mPad)) {
	    Update(mPad);
	  } else {
	    CreateNew(mPad);
	  }
	} //end loop over clusters
      } // hit loop
    } // track loop
  } // end file loop
  if (GetDebug()>2) cerr<<"END OF FILE LOOP"<<endl;

  Int_t tracks[kMAXTRACKSPERRICHDIGIT];
  Int_t charges[kMAXTRACKSPERRICHDIGIT];
  Int_t nentries=fTDList->GetEntriesFast();

  for (Int_t nent=0;nent<nentries;nent++) {
    AliRICHTransientDigit *transDigit=(AliRICHTransientDigit*)fTDList->At(nent);
    if (transDigit==0) continue;
    Int_t ich=transDigit->GetChamber();
    Int_t q=transDigit->Signal();
    iChamber=&(pRICH->Chamber(ich));
    AliRICHResponse * response=iChamber->GetResponseModel();
    Int_t adcmax= (Int_t) response->MaxAdc();

    // add white noise and do zero-suppression and signal truncation (new electronics,old electronics gaus 1.2,0.2)
    //printf("Treshold: %d\n",iChamber->fTresh->GetHitIndex(transDigit->PadX(),transDigit->PadY()));

// tmp change
//    Int_t pedestal = iChamber->fTresh->GetHitIndex(transDigit->PadX(),transDigit->PadY());
    Int_t pedestal = 0;

    //printf("Pedestal:%d\n",pedestal);
    //Int_t pedestal=0;
    Float_t treshold = (pedestal + 4*2.2);

    Float_t meanNoise = gRandom->Gaus(2.2, 0.3);
    Float_t noise     = gRandom->Gaus(0, meanNoise);
    q+=(Int_t)(noise + pedestal);
    //q+=(Int_t)(noise);
    //          magic number to be parametrised !!!
    if ( q <= treshold)
    {
      q = q - pedestal;
      continue;
    }
    q = q - pedestal;
    if ( q >= adcmax) q=adcmax;
    fDigits[0]=transDigit->PadX();
    fDigits[1]=transDigit->PadY();
    fDigits[2]=q;
    fDigits[3]=transDigit->Physics();
    fDigits[4]=transDigit->Hit();

    Int_t nptracks = transDigit->GetNTracks();

    // this was changed to accomodate the real number of tracks
    if (nptracks > kMAXTRACKSPERRICHDIGIT) {
      printf("Attention - tracks > 10 %d\n",nptracks);
      nptracks=kMAXTRACKSPERRICHDIGIT;
    }
    if (nptracks > 2) {
      printf("Attention - tracks > 2  %d \n",nptracks);
    }
    for (Int_t tr=0;tr<nptracks;tr++) {
      tracks[tr]=transDigit->GetTrack(tr);
      charges[tr]=transDigit->GetCharge(tr);
    }      //end loop over list of tracks for one pad
    if (nptracks < kMAXTRACKSPERRICHDIGIT ) {
      for (Int_t t=nptracks; t<kMAXTRACKSPERRICHDIGIT; t++) {
	tracks[t]=0;
	charges[t]=0;
      }
    }
    //write file
    //if (ich==2)
    //fprintf(points,"%4d,      %4d,      %4d\n",digits[0],digits[1],digits[2]);

    // fill digits
    pRICH->AddDigits(ich,tracks,charges,fDigits);
  }
  fManager->GetTreeD()->Fill();

  pRICH->ResetDigits();
  fTDList->Delete();    // or fTDList->Clear(); ???
  for(Int_t ii=0;ii<kNCH;++ii) {
    if (fHitMap[ii]) {
      delete fHitMap[ii];
      fHitMap[ii]=0;
    }
  }

  TClonesArray *richDigits;
  for (Int_t k=0;k<kNCH;k++) {
    richDigits = pRICH->DigitsAddress(k);
    Int_t ndigit=richDigits->GetEntriesFast();
    printf ("Chamber %d digits %d \n",k,ndigit);
  }
  pRICH->ResetDigits(); /// ??? should it be here???
  fManager->GetTreeD()->Write(0,TObject::kOverwrite);
  delete [] fHitMap;
  delete fTDList;

  if (fHits)    fHits->Delete();
  if (fSDigits) fSDigits->Delete();

}
<commit_msg>Old style include files needed on HP (aCC)<commit_after>/**************************************************************************
 * Copyright(c) 1998-2000, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/*
   $Log$
   Revision 1.4  2002/05/28 07:53:10  morsch
   Wrong order of arguments in for-statement corrected.

   Revision 1.3  2001/12/05 14:53:34  hristov
   Destructor corrected

   Revision 1.2  2001/11/07 14:50:31  hristov
   Minor correction of the Log part

   Revision 1.1  2001/11/02 15:37:26  hristov
   Digitizer class created. Code cleaning and bug fixes (J.Chudoba)
*/
#include <iostream.h>

#include <TTree.h>
#include <TObjArray.h>
#include <TFile.h>
#include <TDirectory.h>
#include <TParticle.h>

#include "AliRICHDigitizer.h"
#include "AliRICHChamber.h"
#include "AliHitMap.h"
#include "AliRICHHitMapA1.h"
#include "AliRICH.h"
#include "AliRICHHit.h"
#include "AliRICHSDigit.h"
#include "AliRICHDigit.h"
#include "AliRICHTransientDigit.h"
#include "AliRun.h"
#include "AliPDG.h"
#include "AliRunDigitizer.h"

ClassImp(AliRICHDigitizer)

//___________________________________________
  AliRICHDigitizer::AliRICHDigitizer()
{
// Default constructor - don't use it
  fHits = 0;
  fSDigits = 0;
  fHitMap = 0;
  fTDList = 0;
}

////////////////////////////////////////////////////////////////////////
AliRICHDigitizer::AliRICHDigitizer(AliRunDigitizer* manager)
    :AliDigitizer(manager)
{
// ctor which should be used
  fHits = 0;
  fSDigits = 0;
  fHitMap = 0;
  fTDList = 0;
  fDebug   = 0;
  if (GetDebug()>2)
    cerr<<"AliRICHDigitizer::AliRICHDigitizer"
	<<"(AliRunDigitizer* manager) was processed"<<endl;
}

////////////////////////////////////////////////////////////////////////
AliRICHDigitizer::~AliRICHDigitizer()
{
// Destructor
    if (fHits) {
	fHits->Delete();
	delete fHits;
    }
    if (fSDigits) {
	fSDigits->Delete();
	delete fSDigits;
    }
    for (Int_t i=0; i<kNCH; i++ )
	delete fHitMap[i];
    delete [] fHitMap;
    if (fTDList) {
	fTDList->Delete();
	delete fTDList;
  }
}

//------------------------------------------------------------------------
Bool_t AliRICHDigitizer::Exists(const AliRICHSDigit *padhit)
{
  return (fHitMap[fNch]->TestHit(padhit->PadX(),padhit->PadY()));
}

//------------------------------------------------------------------------
void AliRICHDigitizer::Update(AliRICHSDigit *padhit)
{
  AliRICHTransientDigit *pdigit =
    static_cast<AliRICHTransientDigit*>(
      fHitMap[fNch]->GetHit(padhit->PadX(),padhit->PadY()));

  // update charge
  //
  Int_t iqpad    = Int_t(padhit->QPad()); // charge per pad
  pdigit->AddSignal(iqpad);
  pdigit->AddPhysicsSignal(iqpad);

  // update list of tracks
  //
  Int_t track, charge;
  track = fTrack+fMask;
  if (fSignal) {
    charge = iqpad;
  } else {
    charge = kBgTag;
  }
  pdigit->UpdateTrackList(track,charge);
}

//------------------------------------------------------------------------
void AliRICHDigitizer::CreateNew(AliRICHSDigit *padhit)
{
  fTDList->AddAtAndExpand(
    new AliRICHTransientDigit(fNch,fDigits),fCounter);
  fHitMap[fNch]->SetHit(padhit->PadX(),padhit->PadY(),fCounter);

  AliRICHTransientDigit* pdigit =
    static_cast<AliRICHTransientDigit*>(fTDList->Last());
  // list of tracks
  Int_t track, charge;
  if (fSignal) {
    track = fTrack;
    charge = padhit->QPad();
  } else {
    track = kBgTag;
    charge = kBgTag;
  }
  pdigit->AddToTrackList(track,charge);
  fCounter++;
}

////////////////////////////////////////////////////////////////////////
Bool_t AliRICHDigitizer::Init()
{
// Initialisation
  fHits     = new TClonesArray("AliRICHHit",1000);
  fSDigits  = new TClonesArray("AliRICHSDigit",1000);
  return kTRUE;
}

////////////////////////////////////////////////////////////////////////
//void AliRICHDigitizer::Digitise(Int_t nev, Int_t flag)
void AliRICHDigitizer::Exec(Option_t* option)
{
  TString optionString = option;
  if (optionString.Data() == "deb") {
    cout<<"AliMUONDigitizer::Exec: called with option deb "<<endl;
    fDebug = 3;
  }

  AliRICHChamber*       iChamber;
  AliSegmentation*  segmentation;

  fTDList = new TObjArray;

  AliRICH *pRICH = (AliRICH *) gAlice->GetDetector("RICH");
  pRICH->MakeBranchInTreeD(fManager->GetTreeD());
  fHitMap= new AliHitMap* [kNCH];

  for (Int_t i =0; i<kNCH; i++) {
    iChamber= &(pRICH->Chamber(i));
    segmentation=iChamber->GetSegmentationModel(1);
    fHitMap[i] = new AliRICHHitMapA1(segmentation, fTDList);
  }

// Loop over files to digitize
  fSignal = kTRUE;
  fCounter = 0;
  for (Int_t inputFile=0; inputFile<fManager->GetNinputs();
       inputFile++) {

// Connect RICH branches

    if (inputFile > 0 ) fSignal = kFALSE;
    TBranch *branchHits = 0;
    TBranch *branchSDigits = 0;
    TTree *treeH = fManager->GetInputTreeH(inputFile);
    if (GetDebug()>2) {
      cerr<<"   inputFile  "<<inputFile<<endl;
      cerr<<"   treeH, fHits "<<treeH<<" "<<fHits<<endl;
    }
    if (treeH && fHits) {
      branchHits = treeH->GetBranch("RICH");
      if (branchHits) {
	fHits->Clear();
	branchHits->SetAddress(&fHits);
      }
      else
	Error("Exec","branch RICH was not found");
    }
    if (GetDebug()>2) cerr<<"   branchHits = "<<branchHits<<endl;

    if (treeH && fSDigits) {
      branchSDigits = treeH->GetBranch("RICHSDigits");
      if (branchSDigits)
	branchSDigits->SetAddress(&fSDigits);
      else
	Error("exec","branch RICHSDigits was not found");
    }
    if (GetDebug()>2) cerr<<"   branchSDigits = "<<branchSDigits<<endl;

    //
    //   Loop over tracks
    //

    Int_t ntracks =(Int_t) treeH->GetEntries();
    for (fTrack=0; fTrack<ntracks; fTrack++) {
      fHits->Clear();
      fSDigits->Clear();
      branchHits->GetEntry(fTrack);
      branchSDigits->GetEntry(fTrack);

      //
      //   Loop over hits
      for(Int_t i = 0; i < fHits->GetEntriesFast(); ++i) {
	AliRICHHit* mHit = static_cast<AliRICHHit*>(fHits->At(i));
	fNch = mHit->Chamber()-1;  // chamber number
	if (fNch >= kNCH) {
	  cerr<<"AliRICHDigitizer: chamber nr. fNch out of range: "<<fNch<<endl;
	  cerr<<"               track: "<<fTrack<<endl;
	  continue;
	}
	iChamber = &(pRICH->Chamber(fNch));

	//
	// Loop over pad hits
	for (AliRICHSDigit* mPad=
	       (AliRICHSDigit*)pRICH->FirstPad(mHit,fSDigits);
	     mPad;
	     mPad=(AliRICHSDigit*)pRICH->NextPad(fSDigits))
	{
	  Int_t iqpad    = mPad->QPad();       // charge per pad
	  fDigits[0]=mPad->PadX();
	  fDigits[1]=mPad->PadY();
	  fDigits[2]=iqpad;
	  fDigits[3]=iqpad;
	  fDigits[4]=mPad->HitNumber();

	  // build the list of fired pads and update the info
	  if (Exists(mPad)) {
	    Update(mPad);
	  } else {
	    CreateNew(mPad);
	  }
	} //end loop over clusters
      } // hit loop
    } // track loop
  } // end file loop
  if (GetDebug()>2) cerr<<"END OF FILE LOOP"<<endl;

  Int_t tracks[kMAXTRACKSPERRICHDIGIT];
  Int_t charges[kMAXTRACKSPERRICHDIGIT];
  Int_t nentries=fTDList->GetEntriesFast();

  for (Int_t nent=0;nent<nentries;nent++) {
    AliRICHTransientDigit *transDigit=(AliRICHTransientDigit*)fTDList->At(nent);
    if (transDigit==0) continue;
    Int_t ich=transDigit->GetChamber();
    Int_t q=transDigit->Signal();
    iChamber=&(pRICH->Chamber(ich));
    AliRICHResponse * response=iChamber->GetResponseModel();
    Int_t adcmax= (Int_t) response->MaxAdc();

    // add white noise and do zero-suppression and signal truncation (new electronics,old electronics gaus 1.2,0.2)
    //printf("Treshold: %d\n",iChamber->fTresh->GetHitIndex(transDigit->PadX(),transDigit->PadY()));

// tmp change
//    Int_t pedestal = iChamber->fTresh->GetHitIndex(transDigit->PadX(),transDigit->PadY());
    Int_t pedestal = 0;

    //printf("Pedestal:%d\n",pedestal);
    //Int_t pedestal=0;
    Float_t treshold = (pedestal + 4*2.2);

    Float_t meanNoise = gRandom->Gaus(2.2, 0.3);
    Float_t noise     = gRandom->Gaus(0, meanNoise);
    q+=(Int_t)(noise + pedestal);
    //q+=(Int_t)(noise);
    //          magic number to be parametrised !!!
    if ( q <= treshold)
    {
      q = q - pedestal;
      continue;
    }
    q = q - pedestal;
    if ( q >= adcmax) q=adcmax;
    fDigits[0]=transDigit->PadX();
    fDigits[1]=transDigit->PadY();
    fDigits[2]=q;
    fDigits[3]=transDigit->Physics();
    fDigits[4]=transDigit->Hit();

    Int_t nptracks = transDigit->GetNTracks();

    // this was changed to accomodate the real number of tracks
    if (nptracks > kMAXTRACKSPERRICHDIGIT) {
      printf("Attention - tracks > 10 %d\n",nptracks);
      nptracks=kMAXTRACKSPERRICHDIGIT;
    }
    if (nptracks > 2) {
      printf("Attention - tracks > 2  %d \n",nptracks);
    }
    for (Int_t tr=0;tr<nptracks;tr++) {
      tracks[tr]=transDigit->GetTrack(tr);
      charges[tr]=transDigit->GetCharge(tr);
    }      //end loop over list of tracks for one pad
    if (nptracks < kMAXTRACKSPERRICHDIGIT ) {
      for (Int_t t=nptracks; t<kMAXTRACKSPERRICHDIGIT; t++) {
	tracks[t]=0;
	charges[t]=0;
      }
    }
    //write file
    //if (ich==2)
    //fprintf(points,"%4d,      %4d,      %4d\n",digits[0],digits[1],digits[2]);

    // fill digits
    pRICH->AddDigits(ich,tracks,charges,fDigits);
  }
  fManager->GetTreeD()->Fill();

  pRICH->ResetDigits();
  fTDList->Delete();    // or fTDList->Clear(); ???
  for(Int_t ii=0;ii<kNCH;++ii) {
    if (fHitMap[ii]) {
      delete fHitMap[ii];
      fHitMap[ii]=0;
    }
  }

  TClonesArray *richDigits;
  for (Int_t k=0;k<kNCH;k++) {
    richDigits = pRICH->DigitsAddress(k);
    Int_t ndigit=richDigits->GetEntriesFast();
    printf ("Chamber %d digits %d \n",k,ndigit);
  }
  pRICH->ResetDigits(); /// ??? should it be here???
  fManager->GetTreeD()->Write(0,TObject::kOverwrite);
  delete [] fHitMap;
  delete fTDList;

  if (fHits)    fHits->Delete();
  if (fSDigits) fSDigits->Delete();

}
<|endoftext|>


<commit_before>
#include "Primitives.h"
using namespace std;

Sphere::Sphere(vec3 center_, GLfloat radius_)
{
    center = center_;
    radius = radius_;
}

bool Sphere::intersect(const Ray &ray, vec3 *point, GLfloat *t_val)
{
	GLfloat a = dot(ray.direction, ray.direction);
	GLfloat b = 2*dot(ray.direction, -center);
	GLfloat c = dot(-center, -center) - (radius*radius);

	// if discriminant is positive, intersection exists
	GLfloat discriminant = (b*b) - (4*a*c);
	if(discriminant < 0)
	{
		return false;
	}
	GLfloat t1 = (((-1*b) + sqrt(discriminant))/2*a);
	GLfloat t2 = (((-1*b) - sqrt(discriminant))/2*a);
	if(t1 < t2)
	{
		*t_val = t1;
	}
	else
	{
		*t_val = t2;
	}
	*point = (*t_val * ray.direction);

    return true;
}

Triangle::Triangle(vec3 p0_, vec3 p1_, vec3 p2_)
{
	p0 = p0_;
	p1 = p1_;
	p2 = p2_;
}

bool Triangle::intersect(const Ray &ray, vec3 *point, GLfloat *t_val)
{
    vec3 normal = normalize(cross((p1 - p0), (p2 - p0)));

    GLfloat w = dot(-p0, normal);
    GLfloat a = dot(ray.direction, normal);
    *t_val = w/a;
    *point = (*t_val * ray.direction);

    GLfloat xb_xa = p1.x - p0.x;
    GLfloat yb_ya = p1.y - p0.y;
    GLfloat xc_xa = p2.x - p0.x;
    GLfloat yc_ya = p2.y - p0.y;
    GLfloat xp_xa = point->x - p0.x;
    GLfloat yp_ya = point->y - p0.y;

    GLfloat denominator = determinant(mat2(xb_xa, xc_xa, yb_ya, yc_ya));
    GLfloat a1 = determinant(mat2(xp_xa, xc_xa, yp_ya, yc_ya));
    GLfloat a2 = determinant(mat2(xb_xa, xp_xa, yb_ya, yp_ya));

    GLfloat beta = a1/denominator;
    GLfloat sigma = a2/denominator;

    GLfloat alpha = 1 - beta - sigma;

    if(alpha < 0)
    	return false;

    return true;
}
<commit_msg>Added plane intersect equations<commit_after>
#include "Primitives.h"
using namespace std;

Sphere::Sphere(vec3 center_, GLfloat radius_)
{
    center = center_;
    radius = radius_;
}

bool Sphere::intersect(const Ray &ray, vec3 *point, GLfloat *t_val)
{
	GLfloat a = dot(ray.direction, ray.direction);
	GLfloat b = 2*dot(ray.direction, -center);
	GLfloat c = dot(-center, -center) - (radius*radius);

	// if discriminant is positive, intersection exists
	GLfloat discriminant = (b*b) - (4*a*c);
	if(discriminant < 0)
	{
		return false;
	}
	GLfloat t1 = (((-1*b) + sqrt(discriminant))/2*a);
	GLfloat t2 = (((-1*b) - sqrt(discriminant))/2*a);
	if(t1 < t2)
	{
		*t_val = t1;
	}
	else
	{
		*t_val = t2;
	}
	*point = (*t_val * ray.direction);

    return true;
}

Triangle::Triangle(vec3 p0_, vec3 p1_, vec3 p2_)
{
	p0 = p0_;
	p1 = p1_;
	p2 = p2_;
}

bool Triangle::intersect(const Ray &ray, vec3 *point, GLfloat *t_val)
{
    vec3 normal = normalize(cross((p1 - p0), (p2 - p0)));

    GLfloat w = dot(-p0, normal);
    GLfloat a = dot(ray.direction, normal);
	if(a == 0) //TODO handle line contained within plane?
		return false;
    *t_val = w/a;
    *point = (*t_val * ray.direction);

    GLfloat xb_xa = p1.x - p0.x;
    GLfloat yb_ya = p1.y - p0.y;
    GLfloat xc_xa = p2.x - p0.x;
    GLfloat yc_ya = p2.y - p0.y;
    GLfloat xp_xa = point->x - p0.x;
    GLfloat yp_ya = point->y - p0.y;

    GLfloat denominator = determinant(mat2(xb_xa, xc_xa, yb_ya, yc_ya));
    GLfloat a1 = determinant(mat2(xp_xa, xc_xa, yp_ya, yc_ya));
    GLfloat a2 = determinant(mat2(xb_xa, xp_xa, yb_ya, yp_ya));

    GLfloat beta = a1/denominator;
    GLfloat sigma = a2/denominator;

    GLfloat alpha = 1 - beta - sigma;

    if(alpha < 0)
    	return false;

    return true;
}

Plane::Plane(vec3 normal_, vec3 point_)
{
	normal = normal_;
	point = point_;
}

bool Plane::intersect(const Ray &ray, vec3 *point, GLfloat *t_val)
{
    GLfloat w = dot(-point, normal);
    GLfloat a = dot(ray.direction, normal);
	if(a == 0) //TODO handle line contained within plane?
		return false;
    *t_val = w/a;
    *point = (*t_val * ray.direction);

    return true;
}
<|endoftext|>


<commit_before>/*
    This file is part of kdepim.

    Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>
    Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

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

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "kmailchanges.h"

#include <kapplication.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kemailsettings.h>
#include <identitymanager.h>
#include <identity.h>
#include <kdebug.h>
#include <kstringhandler.h>
#include <kwallet.h>
using namespace KWallet;

static const char* s_folderContentsType[] = {
  I18N_NOOP( "Calendar" ),
  I18N_NOOP( "Contacts" ),
  I18N_NOOP( "Notes" ),
  I18N_NOOP( "Tasks" ),
  I18N_NOOP( "Journal" ) };

Wallet* CreateImapAccount::mWallet = 0;

CreateImapAccount::CreateImapAccount( const QString &accountName, const QString &title )
  : KConfigPropagator::Change( title ),
    mAccountName( accountName ), mPort( 993 ), mEnableSieve( false ), mEnableSavePassword( true ),
    mEncryption( None ), mAuthentication( NONE ), mAuthenticationSend( PLAIN ), mSmtpPort( 25 ),
    mExistingAccountId( -1 ), mExistingTransportId( -1 ),
    mCustomWriter( 0 )
{
}

CreateImapAccount::~CreateImapAccount()
{
  delete mCustomWriter;
}

void CreateImapAccount::setServer( const QString &s )
{
  mServer = s;
}

void CreateImapAccount::setUser( const QString &s )
{
  mUser = s;
}

void CreateImapAccount::setPassword( const QString &s )
{
  mPassword = s;
}

void CreateImapAccount::setRealName( const QString &s )
{
  mRealName = s;
}

void CreateImapAccount::setPort( int port )
{
  mPort = port;
}

void CreateImapAccount::setEmail( const QString &s )
{
  mEmail = s;
}

void CreateImapAccount::enableSieve( bool b )
{
  mEnableSieve = b;
}

void CreateImapAccount::setSieveVacationFileName( const QString& f )
{
  mSieveVacationFileName = f;
}

void CreateImapAccount::enableSavePassword( bool b )
{
  mEnableSavePassword = b;
}

void CreateImapAccount::setEncryption(
  CreateImapAccount::Encryption e )
{
  mEncryption = e;
}

void CreateImapAccount::setAuthentication(
  CreateImapAccount::Authentication a )
{
  mAuthentication = a;
}

void CreateImapAccount::setDefaultDomain(const QString &d)
{
  mDefaultDomain = d;
}

void CreateImapAccount::setAuthenticationSend(
  CreateImapAccount::Authentication a )
{
  mAuthenticationSend = a;
}

void CreateImapAccount::setSmtpPort( int port )
{
  mSmtpPort = port;
}

void CreateImapAccount::setExistingAccountId( int id )
{
  mExistingAccountId = id;
}

void CreateImapAccount::setExistingTransportId( int id )
{
  mExistingTransportId = id;
}

void CreateImapAccount::setCustomWriter(
  CreateImapAccount::CustomWriter *writer )
{
  mCustomWriter = writer;
}

CreateDisconnectedImapAccount::CreateDisconnectedImapAccount(const QString & accountName) :
    CreateImapAccount( accountName, i18n("Create Disconnected IMAP Account for KMail") ),
    mLocalSubscription( false ), mGroupwareType( GroupwareKolab )
{
}

void CreateDisconnectedImapAccount::apply()
{
  if ( mEmail.isEmpty() ) mEmail = mUser + "@" + mServer;

  KConfig c( "kmailrc" );
  c.setGroup( "General" );
  c.writeEntry( "Default domain", mDefaultDomain );
  int accountId;
  if ( mExistingAccountId < 0 ) {
    uint accCnt = c.readNumEntry( "accounts", 0 );
    accountId = accCnt + 1;
    c.writeEntry( "accounts", accountId );
  } else {
    accountId = mExistingAccountId;
  }
  int transportId;
  if ( mExistingTransportId < 0 ) {
    uint transCnt = c.readNumEntry( "transports", 0 );
    transportId = transCnt + 1;
    c.writeEntry( "transports", transportId );
  } else {
    transportId = mExistingTransportId;
  }

  c.setGroup( QString("Account %1").arg( accountId ) );
  int uid;
  if ( mExistingAccountId < 0 ) {
    uid = kapp->random();
    c.writeEntry( "Folder", uid );
  } else {
    uid = c.readNumEntry( "Folder" );
  }
  c.writeEntry( "Id", uid );
  c.writeEntry( "Type", "cachedimap");

  switch ( mAuthentication ) {
    case NONE:
      c.writeEntry( "auth", "*" );
      break;
    case PLAIN:
      c.writeEntry( "auth", "PLAIN" );
      break;
    case LOGIN:
      c.writeEntry( "auth", "LOGIN" );
      break;
    case NTLM_SPA:
      c.writeEntry( "auth", "NTLM" );
      break;
    case GSSAPI:
      c.writeEntry( "auth", "GSSAPI" );
      break;
    case DIGEST_MD5:
      c.writeEntry( "auth", "DIGEST-MD5" );
      break;
    case CRAM_MD5:
      c.writeEntry( "auth", "CRAM-MD5" );
      break;
  }

  c.writeEntry( "Name", mAccountName );
  c.writeEntry( "host", mServer );
  c.writeEntry( "port", mPort );

  c.writeEntry( "groupwareType", mGroupwareType );

  // in case the user wants to get rid of some groupware folders
  c.writeEntry( "locally-subscribed-folders", mLocalSubscription );

  c.writeEntry( "login", mUser );

  c.writeEntry( "sieve-support", mEnableSieve ? "true" : "false" );
  if ( !mSieveVacationFileName.isEmpty() )
    c.writeEntry( "sieve-vacation-filename", mSieveVacationFileName );

  if ( mEncryption == SSL ) {
    c.writeEntry( "use-ssl", true );
  } else if ( mEncryption == TLS ) {
    c.writeEntry( "use-tls", true );
  }

  if ( mEnableSavePassword ) {
    if ( !writeToWallet( "account", accountId ) ) {
      c.writeEntry( "pass", KStringHandler::obscure( mPassword ) );
      c.writeEntry( "store-passwd", true );
    }
  }

  c.setGroup( QString("Folder-%1").arg( uid ) );
  c.writeEntry( "isOpen", true );

  c.setGroup(  "AccountWizard"  );
  c.writeEntry(  "ShowOnStartup" , false );

  c.setGroup( QString("Transport %1").arg( transportId ) );
  c.writeEntry( "name", mAccountName );
  c.writeEntry( "host", mServer );
  c.writeEntry( "type", "smtp" );
  c.writeEntry( "port", mSmtpPort );
  if ( mEncryption == SSL ) {
    c.writeEntry( "encryption", "SSL" );
  } else if ( mEncryption == TLS ) {
    c.writeEntry( "encryption", "TLS" );
  }
  c.writeEntry( "auth", true );
  if ( mAuthenticationSend == PLAIN ) {
    c.writeEntry( "authtype", "PLAIN" );
  } else if ( mAuthenticationSend == LOGIN ) {
    c.writeEntry( "authtype", "LOGIN" );
  }
  c.writeEntry( "user", mUser );
  if ( mEnableSavePassword ) {
    if ( !writeToWallet( "transport", transportId ) ) {
      c.writeEntry( "pass", KStringHandler::obscure( mPassword ) );
      c.writeEntry( "storepass", true );
    }
  }

  // Write email in "default kcontrol settings", used by IdentityManager
  // if it has to create a default identity.
  KEMailSettings es;
  es.setSetting( KEMailSettings::RealName, mRealName );
  es.setSetting( KEMailSettings::EmailAddress, mEmail );

  KPIM::IdentityManager identityManager;
  if ( !identityManager.allEmails().contains( mEmail ) ) {
    // Not sure how to name the identity. First one is "Default", next one mAccountName, but then...
    // let's use the server name after that.
    QString accountName = mAccountName;
    const QStringList identities = identityManager.identities();
    if ( identities.find( accountName ) != identities.end() ) {
      accountName = mServer;
      int i = 2;
      // And if there's already one, number them
      while ( identities.find( accountName ) != identities.end() ) {
        accountName = mServer + " " + QString::number( i++ );
      }
    }

    KPIM::Identity& identity = identityManager.newFromScratch( accountName );
    identity.setFullName( mRealName );
    identity.setEmailAddr( mEmail );
    identityManager.commit();
  }

  if ( mCustomWriter ) {
    mCustomWriter->writeFolder( c, uid );
    mCustomWriter->writeIds( accountId, transportId );
  }
}

CreateOnlineImapAccount::CreateOnlineImapAccount(const QString & accountName) :
    CreateImapAccount( accountName, i18n("Create Online IMAP Account for KMail") )
{
}

void CreateOnlineImapAccount::apply()
{
  KConfig c( "kmailrc" );
  c.setGroup( "General" );
  uint accCnt = c.readNumEntry( "accounts", 0 );
  c.writeEntry( "accounts", accCnt+1 );

  c.setGroup( QString("Account %1").arg(accCnt+1) );
  int uid = kapp->random();
  c.writeEntry( "Folder", uid );
  c.writeEntry( "Id", uid );
  c.writeEntry( "Type", "imap" );
  c.writeEntry( "auth", "*" );
  c.writeEntry( "Name", mAccountName );
  c.writeEntry( "host", mServer );

  c.writeEntry( "login", mUser );

  if ( mEnableSavePassword ) {
    if ( !writeToWallet( "account", accCnt+1 ) ) {
      c.writeEntry( "pass", KStringHandler::obscure( mPassword ) );
      c.writeEntry( "store-passwd", true );
    }
  }
  c.writeEntry( "port", "993" );

  if ( mEncryption == SSL ) {
    c.writeEntry( "use-ssl", true );
  } else if ( mEncryption == TLS ) {
    c.writeEntry( "use-tls", true );
  }

  if ( mAuthenticationSend == PLAIN ) {
    c.writeEntry( "authtype", "PLAIN" );
  } else if ( mAuthenticationSend == LOGIN ) {
    c.writeEntry( "authtype", "LOGIN" );
  }

  c.writeEntry( "sieve-support", mEnableSieve );

  // locally unsubscribe the default folders
  c.writeEntry( "locally-subscribed-folders", true );
  QString groupwareFolders = QString("/INBOX/%1/,/INBOX/%2/,/INBOX/%3/,/INBOX/%4/,/INBOX/%5/")
      .arg( i18n(s_folderContentsType[0]) ).arg( i18n(s_folderContentsType[1]) )
      .arg( i18n(s_folderContentsType[2]) ).arg( i18n(s_folderContentsType[3]) )
      .arg( i18n(s_folderContentsType[4]) );
  c.writeEntry( "locallyUnsubscribedFolders", groupwareFolders );

  c.setGroup( QString("Folder-%1").arg( uid ) );
  c.writeEntry( "isOpen", true );

  c.setGroup(  "AccountWizard" );
  c.writeEntry(  "ShowOnStartup" , false );

}

bool CreateImapAccount::writeToWallet(const QString & type, int id)
{
  if ( !Wallet::isEnabled() )
    return false;
  if ( !mWallet || !mWallet->isOpen() ) {
    delete mWallet;
    WId window = 0;
    if ( qApp->activeWindow() )
      window = qApp->activeWindow()->winId();
    mWallet = Wallet::openWallet( Wallet::NetworkWallet(), window );
    if ( !mWallet )
      return false;
    if ( !mWallet->hasFolder( "kmail" ) )
      mWallet->createFolder( "kmail" );
    mWallet->setFolder( "kmail" );
  }
  return mWallet->writePassword( type + "-" + QString::number( id ), mPassword );
}
<commit_msg>Fix part of kolab issue 3492 defined smtp as default transport, otherwise we don't see a default smtp<commit_after>/*
    This file is part of kdepim.

    Copyright (c) 2004 Bo Thorsen <bo@sonofthor.dk>
    Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

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

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "kmailchanges.h"

#include <kapplication.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kemailsettings.h>
#include <identitymanager.h>
#include <identity.h>
#include <kdebug.h>
#include <kstringhandler.h>
#include <kwallet.h>
using namespace KWallet;

static const char* s_folderContentsType[] = {
  I18N_NOOP( "Calendar" ),
  I18N_NOOP( "Contacts" ),
  I18N_NOOP( "Notes" ),
  I18N_NOOP( "Tasks" ),
  I18N_NOOP( "Journal" ) };

Wallet* CreateImapAccount::mWallet = 0;

CreateImapAccount::CreateImapAccount( const QString &accountName, const QString &title )
  : KConfigPropagator::Change( title ),
    mAccountName( accountName ), mPort( 993 ), mEnableSieve( false ), mEnableSavePassword( true ),
    mEncryption( None ), mAuthentication( NONE ), mAuthenticationSend( PLAIN ), mSmtpPort( 25 ),
    mExistingAccountId( -1 ), mExistingTransportId( -1 ),
    mCustomWriter( 0 )
{
}

CreateImapAccount::~CreateImapAccount()
{
  delete mCustomWriter;
}

void CreateImapAccount::setServer( const QString &s )
{
  mServer = s;
}

void CreateImapAccount::setUser( const QString &s )
{
  mUser = s;
}

void CreateImapAccount::setPassword( const QString &s )
{
  mPassword = s;
}

void CreateImapAccount::setRealName( const QString &s )
{
  mRealName = s;
}

void CreateImapAccount::setPort( int port )
{
  mPort = port;
}

void CreateImapAccount::setEmail( const QString &s )
{
  mEmail = s;
}

void CreateImapAccount::enableSieve( bool b )
{
  mEnableSieve = b;
}

void CreateImapAccount::setSieveVacationFileName( const QString& f )
{
  mSieveVacationFileName = f;
}

void CreateImapAccount::enableSavePassword( bool b )
{
  mEnableSavePassword = b;
}

void CreateImapAccount::setEncryption(
  CreateImapAccount::Encryption e )
{
  mEncryption = e;
}

void CreateImapAccount::setAuthentication(
  CreateImapAccount::Authentication a )
{
  mAuthentication = a;
}

void CreateImapAccount::setDefaultDomain(const QString &d)
{
  mDefaultDomain = d;
}

void CreateImapAccount::setAuthenticationSend(
  CreateImapAccount::Authentication a )
{
  mAuthenticationSend = a;
}

void CreateImapAccount::setSmtpPort( int port )
{
  mSmtpPort = port;
}

void CreateImapAccount::setExistingAccountId( int id )
{
  mExistingAccountId = id;
}

void CreateImapAccount::setExistingTransportId( int id )
{
  mExistingTransportId = id;
}

void CreateImapAccount::setCustomWriter(
  CreateImapAccount::CustomWriter *writer )
{
  mCustomWriter = writer;
}

CreateDisconnectedImapAccount::CreateDisconnectedImapAccount(const QString & accountName) :
    CreateImapAccount( accountName, i18n("Create Disconnected IMAP Account for KMail") ),
    mLocalSubscription( false ), mGroupwareType( GroupwareKolab )
{
}

void CreateDisconnectedImapAccount::apply()
{
  if ( mEmail.isEmpty() ) mEmail = mUser + "@" + mServer;

  KConfig c( "kmailrc" );
  c.setGroup( "General" );
  c.writeEntry( "Default domain", mDefaultDomain );
  int accountId;
  if ( mExistingAccountId < 0 ) {
    uint accCnt = c.readNumEntry( "accounts", 0 );
    accountId = accCnt + 1;
    c.writeEntry( "accounts", accountId );
  } else {
    accountId = mExistingAccountId;
  }
  int transportId;
  if ( mExistingTransportId < 0 ) {
    uint transCnt = c.readNumEntry( "transports", 0 );
    transportId = transCnt + 1;
    c.writeEntry( "transports", transportId );
  } else {
    transportId = mExistingTransportId;
  }

  c.setGroup( QString("Account %1").arg( accountId ) );
  int uid;
  if ( mExistingAccountId < 0 ) {
    uid = kapp->random();
    c.writeEntry( "Folder", uid );
  } else {
    uid = c.readNumEntry( "Folder" );
  }
  c.writeEntry( "Id", uid );
  c.writeEntry( "Type", "cachedimap");

  switch ( mAuthentication ) {
    case NONE:
      c.writeEntry( "auth", "*" );
      break;
    case PLAIN:
      c.writeEntry( "auth", "PLAIN" );
      break;
    case LOGIN:
      c.writeEntry( "auth", "LOGIN" );
      break;
    case NTLM_SPA:
      c.writeEntry( "auth", "NTLM" );
      break;
    case GSSAPI:
      c.writeEntry( "auth", "GSSAPI" );
      break;
    case DIGEST_MD5:
      c.writeEntry( "auth", "DIGEST-MD5" );
      break;
    case CRAM_MD5:
      c.writeEntry( "auth", "CRAM-MD5" );
      break;
  }

  c.writeEntry( "Name", mAccountName );
  c.writeEntry( "host", mServer );
  c.writeEntry( "port", mPort );

  c.writeEntry( "groupwareType", mGroupwareType );

  // in case the user wants to get rid of some groupware folders
  c.writeEntry( "locally-subscribed-folders", mLocalSubscription );

  c.writeEntry( "login", mUser );

  c.writeEntry( "sieve-support", mEnableSieve ? "true" : "false" );
  if ( !mSieveVacationFileName.isEmpty() )
    c.writeEntry( "sieve-vacation-filename", mSieveVacationFileName );

  if ( mEncryption == SSL ) {
    c.writeEntry( "use-ssl", true );
  } else if ( mEncryption == TLS ) {
    c.writeEntry( "use-tls", true );
  }

  if ( mEnableSavePassword ) {
    if ( !writeToWallet( "account", accountId ) ) {
      c.writeEntry( "pass", KStringHandler::obscure( mPassword ) );
      c.writeEntry( "store-passwd", true );
    }
  }

  c.setGroup( QString("Folder-%1").arg( uid ) );
  c.writeEntry( "isOpen", true );

  c.setGroup(  "AccountWizard"  );
  c.writeEntry(  "ShowOnStartup" , false );

  c.setGroup( "Composer" );
  c.writeEntry( "default-transport", mAccountName );

  c.setGroup( QString("Transport %1").arg( transportId ) );
  c.writeEntry( "name", mAccountName );
  c.writeEntry( "host", mServer );
  c.writeEntry( "type", "smtp" );
  c.writeEntry( "port", mSmtpPort );
  if ( mEncryption == SSL ) {
    c.writeEntry( "encryption", "SSL" );
  } else if ( mEncryption == TLS ) {
    c.writeEntry( "encryption", "TLS" );
  }
  c.writeEntry( "auth", true );
  if ( mAuthenticationSend == PLAIN ) {
    c.writeEntry( "authtype", "PLAIN" );
  } else if ( mAuthenticationSend == LOGIN ) {
    c.writeEntry( "authtype", "LOGIN" );
  }
  c.writeEntry( "user", mUser );
  if ( mEnableSavePassword ) {
    if ( !writeToWallet( "transport", transportId ) ) {
      c.writeEntry( "pass", KStringHandler::obscure( mPassword ) );
      c.writeEntry( "storepass", true );
    }
  }

  // Write email in "default kcontrol settings", used by IdentityManager
  // if it has to create a default identity.
  KEMailSettings es;
  es.setSetting( KEMailSettings::RealName, mRealName );
  es.setSetting( KEMailSettings::EmailAddress, mEmail );

  KPIM::IdentityManager identityManager;
  if ( !identityManager.allEmails().contains( mEmail ) ) {
    // Not sure how to name the identity. First one is "Default", next one mAccountName, but then...
    // let's use the server name after that.
    QString accountName = mAccountName;
    const QStringList identities = identityManager.identities();
    if ( identities.find( accountName ) != identities.end() ) {
      accountName = mServer;
      int i = 2;
      // And if there's already one, number them
      while ( identities.find( accountName ) != identities.end() ) {
        accountName = mServer + " " + QString::number( i++ );
      }
    }

    KPIM::Identity& identity = identityManager.newFromScratch( accountName );
    identity.setFullName( mRealName );
    identity.setEmailAddr( mEmail );
    identityManager.commit();
  }

  if ( mCustomWriter ) {
    mCustomWriter->writeFolder( c, uid );
    mCustomWriter->writeIds( accountId, transportId );
  }
}

CreateOnlineImapAccount::CreateOnlineImapAccount(const QString & accountName) :
    CreateImapAccount( accountName, i18n("Create Online IMAP Account for KMail") )
{
}

void CreateOnlineImapAccount::apply()
{
  KConfig c( "kmailrc" );
  c.setGroup( "General" );
  uint accCnt = c.readNumEntry( "accounts", 0 );
  c.writeEntry( "accounts", accCnt+1 );

  c.setGroup( QString("Account %1").arg(accCnt+1) );
  int uid = kapp->random();
  c.writeEntry( "Folder", uid );
  c.writeEntry( "Id", uid );
  c.writeEntry( "Type", "imap" );
  c.writeEntry( "auth", "*" );
  c.writeEntry( "Name", mAccountName );
  c.writeEntry( "host", mServer );

  c.writeEntry( "login", mUser );

  if ( mEnableSavePassword ) {
    if ( !writeToWallet( "account", accCnt+1 ) ) {
      c.writeEntry( "pass", KStringHandler::obscure( mPassword ) );
      c.writeEntry( "store-passwd", true );
    }
  }
  c.writeEntry( "port", "993" );

  if ( mEncryption == SSL ) {
    c.writeEntry( "use-ssl", true );
  } else if ( mEncryption == TLS ) {
    c.writeEntry( "use-tls", true );
  }

  if ( mAuthenticationSend == PLAIN ) {
    c.writeEntry( "authtype", "PLAIN" );
  } else if ( mAuthenticationSend == LOGIN ) {
    c.writeEntry( "authtype", "LOGIN" );
  }

  c.writeEntry( "sieve-support", mEnableSieve );

  // locally unsubscribe the default folders
  c.writeEntry( "locally-subscribed-folders", true );
  QString groupwareFolders = QString("/INBOX/%1/,/INBOX/%2/,/INBOX/%3/,/INBOX/%4/,/INBOX/%5/")
      .arg( i18n(s_folderContentsType[0]) ).arg( i18n(s_folderContentsType[1]) )
      .arg( i18n(s_folderContentsType[2]) ).arg( i18n(s_folderContentsType[3]) )
      .arg( i18n(s_folderContentsType[4]) );
  c.writeEntry( "locallyUnsubscribedFolders", groupwareFolders );

  c.setGroup( QString("Folder-%1").arg( uid ) );
  c.writeEntry( "isOpen", true );

  c.setGroup(  "AccountWizard" );
  c.writeEntry(  "ShowOnStartup" , false );

}

bool CreateImapAccount::writeToWallet(const QString & type, int id)
{
  if ( !Wallet::isEnabled() )
    return false;
  if ( !mWallet || !mWallet->isOpen() ) {
    delete mWallet;
    WId window = 0;
    if ( qApp->activeWindow() )
      window = qApp->activeWindow()->winId();
    mWallet = Wallet::openWallet( Wallet::NetworkWallet(), window );
    if ( !mWallet )
      return false;
    if ( !mWallet->hasFolder( "kmail" ) )
      mWallet->createFolder( "kmail" );
    mWallet->setFolder( "kmail" );
  }
  return mWallet->writePassword( type + "-" + QString::number( id ), mPassword );
}
<|endoftext|>


<commit_before>#include "../include/processamento.h"

Processamento::Processamento(std::string inputFile, std::string outputFile)
{
    this->inputFileName =  inputFile;
    this->outputFileName = outputFile;
    this->setInputExtension(".pre");
    this->setOutputExtension (".mcr");
    this->fileText.open(inputFileName);
    this->fileOutput.open(outputFileName);
}

Processamento::~Processamento()
{
    // Sem preocupações com o close
    fileText.close();
    fileOutput.close();
}

std::string Processamento::setOutputExtension(std::string extension)
{
    this->outputFileName = string_ops::setOutputExtension(inputFileName, extension);

    return outputFileName;
}

std::string Processamento::setInputExtension(std::string extension)
{
    this->inputFileName = string_ops::setOutputExtension(inputFileName, extension);

    return inputFileName;
}

//Metodo principal que vai realizar o processamento
bool Processamento::run(std::vector<int> adjusts_vec){
    this->previous_adjusts = adjusts_vec;

    std::string line;
    std::string word;
    this->contador_endereco = 0;        //sera utilizado para determinar o endereco de cada token do programa
    this->contador_de_linhas = 0;       //Controle para saber em qual linha do programa esta algum erro

    //loop linha a linha para analisar o arquivo de entrada
    while (getline(this->fileText, line)){
        std::stringstream lineStream(line);
        this->contador_de_linhas++;

        //loop palavra a palavra para procurar as macros
        while (lineStream >> word){
            //caso ache uma macro, a palavra antes dela eh o seu rotulo
            if (word == "macro"){
                std::string rotulo = this-> getRotulo (line);

                //testa se houve erro na funcao que pega rotulo
                if (rotulo == "erro"){
                    return false;
                }

                //Caso nao houve erro pega o codigo relativo a macro
                std::string codigo = this ->getCode ();

                //testa se houve erro no metodo de pegar o codigo da macro
                if (codigo == "erro"){
                    return false;
                }

                //Se nao houve nenhum erro, cria a Macro
                Macro macro(rotulo, codigo, this->get_address());
                this->macrosList.push_back(macro);
            }
        }
        this->printLineToOutput(line);
    }
    //this-> printMacros();
    return true;
}

//Metodo para pegar o rotulo da macro, considerando que o rotulo tem que ser o primeiro token da linha
std::string Processamento::getRotulo(std::string line){
    std::stringstream lineStream (line);
    std::string word;

    //Pega a primeira palavra da linha
    lineStream >> word;

    //cria um token com a primeira palavra da linha
    Token token(word);

    //caso os dois pontos estejam na string
    if (token.have2points(token.nome)){
        word = string_ops::trunca_nome(word, ':');
        return word;
    }

    //Caso chegue aqui pode ser que o usuario tenha digitado o rotulo, espaco e depois os :
    //Logo, devemos analisar se o segundo token da frase eh :
    lineStream >> word;
    if (word == ":"){
        //se isso ocorreu, entao o nome do Token ja eh o nome da declaracao da macro sem os :
        return token.nome;
    }

    //Se chegar aqui eh pq algum erro ocorreu
    std::cout << "Token invalido para declarar a macro\n";
    return "erro";
}

//Metodo para pegar o codigo relativo a macro, utiliza-se do fileText que ja esta aberto
std::string Processamento::getCode (){
    std::string line;
    std::string word;
    std::string code;

    //como o arquivo ja esta aberto, a linha seguinte eh a linha logo abaixo da macro e sera o comeco do seu codigo
    while(getline(this->fileText,line)){
        std::stringstream lineStream(line);
        this->contador_de_linhas++;

        //pega token a token e vai salvando no code, ate achar end
        while (lineStream >> word){
            if (word == "end"){
                //terminou a macro, imprime-a e retorna
                //this-> fileOutput << code;
                return code;
            }
            //se nao for end, salva em code
            code += word;
            code += ' ';
        }
        //Salta a linha no code
        code += '\n';
    }

    //Se chegar aqui eh pq leu o arquivo todo e nao achou o fim da macro
    std::cout << "ERRO -> Macro inicializada, mas nao finalizada\n";
    return "erro";
}

//Metodo para debug
void Processamento::printMacros(){
    for (size_t i = 0; i < this->macrosList.size(); i++){
        std::cout << "macro name = " << this->macrosList[i].name << std::endl;
        std::cout << "macro code = " << this->macrosList[i].codigo << std::endl;
    }
}

//Metodo para decidir se precisa ou nao imprimir a linha atual no arquivo de saida
void Processamento::printLineToOutput(std::string line){
    std::string word;
    std::stringstream lineStream (line);

    //Pega o primeiro token da linha e joga para a palavra
    lineStream >> word;

    //ve se o primeiro token da linha eh uma chamada de macro
    for (size_t i = 0; i < this->macrosList.size(); i++){
        if (word == this->macrosList[i].name){
            this-> fileOutput << this->macrosList[i].codigo;
            this->update_address_macros(this->macrosList[i]);
            return;
        }
    }

    if(word == "macro"){
        return;
    }

    while (lineStream >> word){
        if(word == "macro"){
            return;
        }
    }

    //Se chegar aqui eh pq essa linha deve ser impressa
    this-> fileOutput << line << std::endl;
    this->contador_endereco++;
    this->update_address_adjusts();
}

int Processamento::get_address()
{
    int address = this->contador_endereco + 1;
    address += this->previous_adjusts[contador_de_linhas];
    return address;
}

void Processamento::update_address_adjusts()
{
    // get processing adjust
    int adjust = contador_endereco - contador_de_linhas;
    // add it to previous adjusts
    // obs: há um elemento em address_adjusts para cada linha
    adjust = adjust + this->previous_adjusts[contador_de_linhas];
    this->address_adjusts.push_back(adjust);
    std::cout << adjust << '\n';
}

void Processamento::update_address_macros(Macro macro)
{
    int numLines = macro.get_numlines();
    int address = macro.get_address();
    // Imprime o endereço de chamada da macro
    for(size_t i = 0; i < numLines; i++)
    {
        this->address_adjusts.push_back(address);
        std::cout << address << '\n';
    }
    // Atualiza o contador de endereço com o número de linhas
    contador_endereco += numLines;
}

std::vector<int> Processamento::get_addresses_adjusts()
{
    return this->address_adjusts;
}
<commit_msg>removidos prints de debug<commit_after>#include "../include/processamento.h"

Processamento::Processamento(std::string inputFile, std::string outputFile)
{
    this->inputFileName =  inputFile;
    this->outputFileName = outputFile;
    this->setInputExtension(".pre");
    this->setOutputExtension (".mcr");
    this->fileText.open(inputFileName);
    this->fileOutput.open(outputFileName);
}

Processamento::~Processamento()
{
    // Sem preocupações com o close
    fileText.close();
    fileOutput.close();
}

std::string Processamento::setOutputExtension(std::string extension)
{
    this->outputFileName = string_ops::setOutputExtension(inputFileName, extension);

    return outputFileName;
}

std::string Processamento::setInputExtension(std::string extension)
{
    this->inputFileName = string_ops::setOutputExtension(inputFileName, extension);

    return inputFileName;
}

//Metodo principal que vai realizar o processamento
bool Processamento::run(std::vector<int> adjusts_vec){
    this->previous_adjusts = adjusts_vec;

    std::string line;
    std::string word;
    this->contador_endereco = 0;        //sera utilizado para determinar o endereco de cada token do programa
    this->contador_de_linhas = 0;       //Controle para saber em qual linha do programa esta algum erro

    //loop linha a linha para analisar o arquivo de entrada
    while (getline(this->fileText, line)){
        std::stringstream lineStream(line);
        this->contador_de_linhas++;

        //loop palavra a palavra para procurar as macros
        while (lineStream >> word){
            //caso ache uma macro, a palavra antes dela eh o seu rotulo
            if (word == "macro"){
                std::string rotulo = this-> getRotulo (line);

                //testa se houve erro na funcao que pega rotulo
                if (rotulo == "erro"){
                    return false;
                }

                //Caso nao houve erro pega o codigo relativo a macro
                std::string codigo = this ->getCode ();

                //testa se houve erro no metodo de pegar o codigo da macro
                if (codigo == "erro"){
                    return false;
                }

                //Se nao houve nenhum erro, cria a Macro
                Macro macro(rotulo, codigo, this->get_address());
                this->macrosList.push_back(macro);
            }
        }
        this->printLineToOutput(line);
    }
    //this-> printMacros();
    return true;
}

//Metodo para pegar o rotulo da macro, considerando que o rotulo tem que ser o primeiro token da linha
std::string Processamento::getRotulo(std::string line){
    std::stringstream lineStream (line);
    std::string word;

    //Pega a primeira palavra da linha
    lineStream >> word;

    //cria um token com a primeira palavra da linha
    Token token(word);

    //caso os dois pontos estejam na string
    if (token.have2points(token.nome)){
        word = string_ops::trunca_nome(word, ':');
        return word;
    }

    //Caso chegue aqui pode ser que o usuario tenha digitado o rotulo, espaco e depois os :
    //Logo, devemos analisar se o segundo token da frase eh :
    lineStream >> word;
    if (word == ":"){
        //se isso ocorreu, entao o nome do Token ja eh o nome da declaracao da macro sem os :
        return token.nome;
    }

    //Se chegar aqui eh pq algum erro ocorreu
    std::cout << "Token invalido para declarar a macro\n";
    return "erro";
}

//Metodo para pegar o codigo relativo a macro, utiliza-se do fileText que ja esta aberto
std::string Processamento::getCode (){
    std::string line;
    std::string word;
    std::string code;

    //como o arquivo ja esta aberto, a linha seguinte eh a linha logo abaixo da macro e sera o comeco do seu codigo
    while(getline(this->fileText,line)){
        std::stringstream lineStream(line);
        this->contador_de_linhas++;

        //pega token a token e vai salvando no code, ate achar end
        while (lineStream >> word){
            if (word == "end"){
                //terminou a macro, imprime-a e retorna
                //this-> fileOutput << code;
                return code;
            }
            //se nao for end, salva em code
            code += word;
            code += ' ';
        }
        //Salta a linha no code
        code += '\n';
    }

    //Se chegar aqui eh pq leu o arquivo todo e nao achou o fim da macro
    std::cout << "ERRO -> Macro inicializada, mas nao finalizada\n";
    return "erro";
}

//Metodo para debug
void Processamento::printMacros(){
    for (size_t i = 0; i < this->macrosList.size(); i++){
        std::cout << "macro name = " << this->macrosList[i].name << std::endl;
        std::cout << "macro code = " << this->macrosList[i].codigo << std::endl;
    }
}

//Metodo para decidir se precisa ou nao imprimir a linha atual no arquivo de saida
void Processamento::printLineToOutput(std::string line){
    std::string word;
    std::stringstream lineStream (line);

    //Pega o primeiro token da linha e joga para a palavra
    lineStream >> word;

    //ve se o primeiro token da linha eh uma chamada de macro
    for (size_t i = 0; i < this->macrosList.size(); i++){
        if (word == this->macrosList[i].name){
            this-> fileOutput << this->macrosList[i].codigo;
            this->update_address_macros(this->macrosList[i]);
            return;
        }
    }

    if(word == "macro"){
        return;
    }

    while (lineStream >> word){
        if(word == "macro"){
            return;
        }
    }

    //Se chegar aqui eh pq essa linha deve ser impressa
    this-> fileOutput << line << std::endl;
    this->contador_endereco++;
    this->update_address_adjusts();
}

int Processamento::get_address()
{
    int address = this->contador_endereco + 1;
    address += this->previous_adjusts[contador_de_linhas];
    return address;
}

void Processamento::update_address_adjusts()
{
    // get processing adjust
    int adjust = contador_endereco - contador_de_linhas;
    // add it to previous adjusts
    // obs: há um elemento em address_adjusts para cada linha
    adjust = adjust + this->previous_adjusts[contador_de_linhas];
    this->address_adjusts.push_back(adjust);
}

void Processamento::update_address_macros(Macro macro)
{
    int numLines = macro.get_numlines();
    int address = macro.get_address();
    // Imprime o endereço de chamada da macro
    for(size_t i = 0; i < numLines; i++)
    {
        this->address_adjusts.push_back(address);
    }
    // Atualiza o contador de endereço com o número de linhas
    contador_endereco += numLines;
}

std::vector<int> Processamento::get_addresses_adjusts()
{
    return this->address_adjusts;
}
<|endoftext|>


<commit_before>/**
 * The Seeks proxy and plugin framework are part of the SEEKS project.
 * Copyright (C) 2009 Emmanuel Benazera, juban@free.fr
 *
 * This library 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.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */

#include "sweeper.h"
#include "mem_utils.h"
#include "seeks_proxy.h"
#include "miscutil.h"
#include "errlog.h"

#include <iostream>

namespace sp
{
  /*- sweepable. -*/
  sweepable::sweepable()
  {
  }

  sweepable::~sweepable()
  {
  }

  /*- sweeper. -*/

  sp_mutex_t sweeper::_mem_dust_mutex;

  void sweeper::register_sweepable(sweepable *spable)
  {
    mutex_lock(&sweeper::_mem_dust_mutex);
    seeks_proxy::_memory_dust.push_back(spable);
    mutex_unlock(&sweeper::_mem_dust_mutex);
  }

  void sweeper::unregister_sweepable(sweepable *spable)
  {
    mutex_lock(&sweeper::_mem_dust_mutex);
    std::vector<sweepable*>::iterator vit
    = seeks_proxy::_memory_dust.begin();
    while (vit!=seeks_proxy::_memory_dust.end())
      {
        if ((*vit) == spable)
          {
            seeks_proxy::_memory_dust.erase(vit);
            mutex_unlock(&sweeper::_mem_dust_mutex);
            return;
          }
        ++vit;
      }
    mutex_unlock(&sweeper::_mem_dust_mutex);
  }

  /*********************************************************************
   * Function    :  sweep
   *
   * Description :  Basically a mark and sweep garbage collector, it is run
   *                (by the parent thread) every once in a while to reclaim
   *                memory.
   *
   * It uses a mark and sweep strategy:
   *   1) mark all files as inactive
   *
   *   2) check with each client:
   *       if it is active,   mark its files as active
   *       if it is inactive, free its resources
   *
   *   3) free the resources.
   *
   * Returns     :  The number of threads that are still active.
   *
   *********************************************************************/
  unsigned int sweeper::sweep()
  {
    client_state *csp, *last_active;
    unsigned int active_threads = 0;

    last_active = &seeks_proxy::_clients;
    csp = seeks_proxy::_clients._next;

    while (NULL != csp)
      {
        if (csp->_flags & CSP_FLAG_ACTIVE)
          {
            active_threads++;

            last_active = csp;
            csp = csp->_next;
          }
        else
          /*
           * This client is not active. Free its resources.
           */
          //TODO: should go into client_state destructor.
          {
            last_active->_next = csp->_next;

            freez(csp->_ip_addr_str);
            freez(csp->_iob._buf);

            if (csp->_action._flags & ACTION_FORWARD_OVERRIDE &&
                NULL != csp->_fwd)
              {
                delete csp->_fwd;
              }

#ifdef FEATURE_STATISTICS
            seeks_proxy::_urls_read++;
            if (csp->_flags & CSP_FLAG_REJECTED)
              {
                seeks_proxy::_urls_rejected++;
              }
#endif /* def FEATURE_STATISTICS */

            delete csp;
            csp = last_active->_next;
          }
      }

    /* sweeps other memory dust grains, as necessary. */

    //debug
    /* std::cerr << "[Debug]:sweeper: cleaning memory dust: "
     << seeks_proxy::_memory_dust.size() << " remaining items\n"; */
    //debug

    mutex_lock(&sweeper::_mem_dust_mutex);
    std::vector<sweepable*>::iterator vit = seeks_proxy::_memory_dust.begin();
    while (vit!=seeks_proxy::_memory_dust.end())
      {
        sweepable *spable = (*vit);
        if (spable->sweep_me())
          {
            delete spable;
            vit = seeks_proxy::_memory_dust.erase(vit);
          }
        else ++vit;
      }
    mutex_unlock(&sweeper::_mem_dust_mutex);

#if defined(PROTOBUF) && defined(TC)
    // user_db sweep.
    seeks_proxy::_user_db->sweep_db();
#endif

    return active_threads;
  }

  unsigned int sweeper::sweep_all_memory_dust()
  {
    unsigned int nm = seeks_proxy::_memory_dust.size();
    std::vector<sweepable*>::iterator vit = seeks_proxy::_memory_dust.begin();
    while (vit!=seeks_proxy::_memory_dust.end())
      {
        sweepable *spable = (*vit);
        vit = seeks_proxy::_memory_dust.erase(vit);
        delete spable;
      }
    errlog::log_error(LOG_LEVEL_INFO, "sweep_all: destroyed %u elements",nm);
    return nm;
  }

  unsigned int sweeper::sweep_all_csps()
  {
    client_state *csp, *last_active;
    unsigned int active_threads = 0;

    last_active = &seeks_proxy::_clients;
    csp = seeks_proxy::_clients._next;

    while (NULL != csp)
      {
        active_threads++;

        /*
         * This client is not active. Free its resources.
         */
        //TODO: should go into client_state destructor.
        {
          last_active->_next = csp->_next;
          freez(csp->_ip_addr_str);
          freez(csp->_iob._buf);

          if (csp->_action._flags & ACTION_FORWARD_OVERRIDE &&
              NULL != csp->_fwd)
            {
              delete csp->_fwd;
            }
          delete csp;
          csp = last_active->_next;
        }
      }
    return active_threads;
  }

  unsigned int sweeper::sweep_all()
  {
    return sweeper::sweep_all_csps() + sweeper::sweep_all_memory_dust();
  }

} /* end of namespace. */
<commit_msg>sweeper: moved iterator removal before object deletion<commit_after>/**
 * The Seeks proxy and plugin framework are part of the SEEKS project.
 * Copyright (C) 2009 Emmanuel Benazera, juban@free.fr
 *
 * This library 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.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */

#include "sweeper.h"
#include "mem_utils.h"
#include "seeks_proxy.h"
#include "miscutil.h"
#include "errlog.h"

#include <iostream>

namespace sp
{
  /*- sweepable. -*/
  sweepable::sweepable()
  {
  }

  sweepable::~sweepable()
  {
  }

  /*- sweeper. -*/

  sp_mutex_t sweeper::_mem_dust_mutex;

  void sweeper::register_sweepable(sweepable *spable)
  {
    mutex_lock(&sweeper::_mem_dust_mutex);
    seeks_proxy::_memory_dust.push_back(spable);
    mutex_unlock(&sweeper::_mem_dust_mutex);
  }

  void sweeper::unregister_sweepable(sweepable *spable)
  {
    mutex_lock(&sweeper::_mem_dust_mutex);
    std::vector<sweepable*>::iterator vit
    = seeks_proxy::_memory_dust.begin();
    while (vit!=seeks_proxy::_memory_dust.end())
      {
        if ((*vit) == spable)
          {
            seeks_proxy::_memory_dust.erase(vit);
            mutex_unlock(&sweeper::_mem_dust_mutex);
            return;
          }
        ++vit;
      }
    mutex_unlock(&sweeper::_mem_dust_mutex);
  }

  /*********************************************************************
   * Function    :  sweep
   *
   * Description :  Basically a mark and sweep garbage collector, it is run
   *                (by the parent thread) every once in a while to reclaim
   *                memory.
   *
   * It uses a mark and sweep strategy:
   *   1) mark all files as inactive
   *
   *   2) check with each client:
   *       if it is active,   mark its files as active
   *       if it is inactive, free its resources
   *
   *   3) free the resources.
   *
   * Returns     :  The number of threads that are still active.
   *
   *********************************************************************/
  unsigned int sweeper::sweep()
  {
    client_state *csp, *last_active;
    unsigned int active_threads = 0;

    last_active = &seeks_proxy::_clients;
    csp = seeks_proxy::_clients._next;

    while (NULL != csp)
      {
        if (csp->_flags & CSP_FLAG_ACTIVE)
          {
            active_threads++;

            last_active = csp;
            csp = csp->_next;
          }
        else
          /*
           * This client is not active. Free its resources.
           */
          //TODO: should go into client_state destructor.
          {
            last_active->_next = csp->_next;

            freez(csp->_ip_addr_str);
            freez(csp->_iob._buf);

            if (csp->_action._flags & ACTION_FORWARD_OVERRIDE &&
                NULL != csp->_fwd)
              {
                delete csp->_fwd;
              }

#ifdef FEATURE_STATISTICS
            seeks_proxy::_urls_read++;
            if (csp->_flags & CSP_FLAG_REJECTED)
              {
                seeks_proxy::_urls_rejected++;
              }
#endif /* def FEATURE_STATISTICS */

            delete csp;
            csp = last_active->_next;
          }
      }

    /* sweeps other memory dust grains, as necessary. */

    //debug
    /* std::cerr << "[Debug]:sweeper: cleaning memory dust: "
     << seeks_proxy::_memory_dust.size() << " remaining items\n"; */
    //debug

    mutex_lock(&sweeper::_mem_dust_mutex);
    std::vector<sweepable*>::iterator vit = seeks_proxy::_memory_dust.begin();
    while (vit!=seeks_proxy::_memory_dust.end())
      {
        sweepable *spable = (*vit);
        if (spable->sweep_me())
          {
            vit = seeks_proxy::_memory_dust.erase(vit);
            delete spable;
          }
        else ++vit;
      }
    mutex_unlock(&sweeper::_mem_dust_mutex);

#if defined(PROTOBUF) && defined(TC)
    // user_db sweep.
    seeks_proxy::_user_db->sweep_db();
#endif

    return active_threads;
  }

  unsigned int sweeper::sweep_all_memory_dust()
  {
    unsigned int nm = seeks_proxy::_memory_dust.size();
    std::vector<sweepable*>::iterator vit = seeks_proxy::_memory_dust.begin();
    while (vit!=seeks_proxy::_memory_dust.end())
      {
        sweepable *spable = (*vit);
        vit = seeks_proxy::_memory_dust.erase(vit);
        delete spable;
      }
    errlog::log_error(LOG_LEVEL_INFO, "sweep_all: destroyed %u elements",nm);
    return nm;
  }

  unsigned int sweeper::sweep_all_csps()
  {
    client_state *csp, *last_active;
    unsigned int active_threads = 0;

    last_active = &seeks_proxy::_clients;
    csp = seeks_proxy::_clients._next;

    while (NULL != csp)
      {
        active_threads++;

        /*
         * This client is not active. Free its resources.
         */
        //TODO: should go into client_state destructor.
        {
          last_active->_next = csp->_next;
          freez(csp->_ip_addr_str);
          freez(csp->_iob._buf);

          if (csp->_action._flags & ACTION_FORWARD_OVERRIDE &&
              NULL != csp->_fwd)
            {
              delete csp->_fwd;
            }
          delete csp;
          csp = last_active->_next;
        }
      }
    return active_threads;
  }

  unsigned int sweeper::sweep_all()
  {
    return sweeper::sweep_all_csps() + sweeper::sweep_all_memory_dust();
  }

} /* end of namespace. */
<|endoftext|>