<commit_before>//@author A0097630B
#include "stdafx.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/format.hpp>
#include "log.h"

namespace You {
namespace Utils {

Logger Log::debug(LogSeverity::DEBUG);
Logger Log::info(LogSeverity::INFO);
Logger Log::warning(LogSeverity::WARNING);
Logger Log::error(LogSeverity::ERROR);
Logger Log::critical(LogSeverity::CRITICAL);

#ifdef _DEBUG
LogSeverity Log::logLevel = LogSeverity::DEBUG;
#else
LogSeverity Log::logLevel = LogSeverity::WARNING;
#endif
std::shared_ptr<LogSink> Log::sink;

void Log::write(
	LogSeverity severity,
	const std::wstring& category,
	const std::wstring& message) {
	if (severity >= Log::logLevel && sink) {
		sink->onLog(severity, category, message);
	}
}

}  // namespace Utils
}  // namespace You

namespace {

/// The format for debug messages.
const boost::wformat DEBUG_FORMAT(L"[%1%] <%2%>%3% %4%");

/// The format for categories.
const boost::wformat CATEGORY_FORMAT(L"[%1%]");

class DebugLogger : public You::Utils::LogSink {
	void onLog(You::Utils::LogSeverity severity,
		const std::wstring& category,
		const std::wstring& message) override {

		std::wstring categoryString;
		if (!category.empty()) {
			categoryString = (boost::wformat(CATEGORY_FORMAT) % category).str();
		}

		OutputDebugStringW(
			(boost::wformat(DEBUG_FORMAT) %
			boost::posix_time::second_clock::local_time() %
			static_cast<int>(severity) %
			category %
			message).str().c_str());
	}
};

class SetDefaultLogger {
public:
	SetDefaultLogger() {
		You::Utils::Log::setSink(std::make_shared<DebugLogger>());
	}
};

SetDefaultLogger setDefault;

}  // namespace
<commit_msg>Fix lints.<commit_after>//@author A0097630B
#include "stdafx.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/format.hpp>
#include "log.h"

namespace You {
namespace Utils {

Logger Log::debug(LogSeverity::DEBUG);
Logger Log::info(LogSeverity::INFO);
Logger Log::warning(LogSeverity::WARNING);
Logger Log::error(LogSeverity::ERROR);
Logger Log::critical(LogSeverity::CRITICAL);

#ifdef _DEBUG
LogSeverity Log::logLevel = LogSeverity::DEBUG;
#else
LogSeverity Log::logLevel = LogSeverity::WARNING;
#endif
std::shared_ptr<LogSink> Log::sink;

void Log::write(
	LogSeverity severity,
	const std::wstring& category,
	const std::wstring& message) {
	if (severity >= Log::logLevel && sink) {
		sink->onLog(severity, category, message);
	}
}

}  // namespace Utils
}  // namespace You

namespace {

/// The format for debug messages.
const boost::wformat DEBUG_FORMAT(L"[%1%] <%2%>%3% %4%");

/// The format for categories.
const boost::wformat CATEGORY_FORMAT(L"[%1%]");

class DebugLogger : public You::Utils::LogSink {
	void onLog(You::Utils::LogSeverity severity,
		const std::wstring& category,
		const std::wstring& message) override {
		std::wstring categoryString;
		if (!category.empty()) {
			categoryString = (boost::wformat(CATEGORY_FORMAT) % category).str();
		}

		OutputDebugStringW(
			(boost::wformat(DEBUG_FORMAT) %
			boost::posix_time::second_clock::local_time() %
			static_cast<int>(severity) %
			category %
			message).str().c_str());
	}
};

class SetDefaultLogger {
public:
	SetDefaultLogger() {
		You::Utils::Log::setSink(std::make_shared<DebugLogger>());
	}
};

SetDefaultLogger setDefault;

}  // namespace
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, 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.                  *
 **************************************************************************/

// ****************************************************************
//
//	Trigger class for ZDC
//
// ****************************************************************

#include "AliLog.h"
#include "AliRun.h"
#include "AliLoader.h"
#include "AliRunLoader.h"
#include "AliTriggerInput.h"

#include "AliZDC.h"
#include "AliZDCDigit.h"
#include "AliZDCTrigger.h"

//________________________________________________________________
ClassImp(AliZDCTrigger)

//________________________________________________________________
AliZDCTrigger::AliZDCTrigger() : AliTriggerDetector()
{
   // Constructor
   SetName("ZDC");
   CreateInputs();
   //
   SetZDCLeftMinCut(0);
   SetZDCRightMinCut(0);
   SetZEMMinCut(0);
   SetZDCLeftEMDCuts(0,0);
   SetZDCRightEMDCuts(0,0);
   SetZDCLeftMBCut(0);
   SetZDCRightMBCut(0);
   SetZDCLeftCentrCut(0);
   SetZDCRightCentrCut(0);
   SetZDCLeftSemiCentrCut(0);
   SetZDCRightSemiCentrCut(0);
   SetZEMCentrCut(0);

}

//________________________________________________________________
void AliZDCTrigger::CreateInputs()
{
   // Trigger inputs

   // Do not create inputs again!!
   if( fInputs.GetEntriesFast() > 0 ) return;

   fInputs.AddLast(new AliTriggerInput("ZDC_1_L1",   "ZDC Minimum Bias", 0x01));
   fInputs.AddLast(new AliTriggerInput("ZDC_2_L1",   "ZDC Central", 0x02));
   fInputs.AddLast(new AliTriggerInput("ZDC_3_L1",   "ZDC Semi-central", 0x04));
   fInputs.AddLast(new AliTriggerInput("ZDC_EMD_L1", "ZDC EMD events", 0x08));
}

//________________________________________________________________
void AliZDCTrigger::Trigger()
{

   // Trigger selection
   //
   AliRunLoader *runLoader = gAlice->GetRunLoader();

   AliLoader *aZDCLoader = runLoader->GetLoader("ZDCLoader");
   aZDCLoader->LoadDigits("READ");
   AliZDCDigit digit;
   AliZDCDigit* pdigit = &digit;
   TTree* tD = aZDCLoader->TreeD();
   if (!tD) cerr<<"AliZDCTrigger: digits tree not found\n";
   tD->SetBranchAddress("ZDC", &pdigit);
   //
   Float_t signalZNLeft[2], signalZPLeft[2], signalZDCLeftSum[2];
   Float_t signalZNRight[2], signalZPRight[2], signalZDCRightSum[2];
   Float_t signalZEMSum[2];
   for(Int_t iDigit=0; iDigit<tD->GetEntries(); iDigit++){
      tD->GetEntry(iDigit);
      //
      // *** ZDC LEFT
      if(digit.GetSector(0)==1)
         for(Int_t i=0; i<2; i++){ //0=high range; 1=low range
	    signalZNLeft[i] += digit.GetADCValue(i);
	    signalZDCLeftSum[i] += digit.GetADCValue(i);
	  }
      else if(digit.GetSector(0)==2)
         for(Int_t i=0; i<2; i++){
	    signalZPLeft[i] += digit.GetADCValue(i);
	    signalZDCLeftSum[i] += digit.GetADCValue(i);
	  }
      else if(digit.GetSector(0)==3)
         for(Int_t i=0; i<2; i++) signalZEMSum[i] += digit.GetADCValue(i);
      // *** ZDC RIGHT
      else if(digit.GetSector(0)==4)
         for(Int_t i=0; i<2; i++){ //0=high range; 1=low range
	    signalZNRight[i] += digit.GetADCValue(i);
	    signalZDCRightSum[i] += digit.GetADCValue(i);
	  }
      else if(digit.GetSector(0)==5)
         for(Int_t i=0; i<2; i++){
	    signalZPRight[i] += digit.GetADCValue(i);
	    signalZDCRightSum[i] += digit.GetADCValue(i);
	  }
   }
   // *******************************************************************
   if(signalZNLeft[0]>fZDCLeftEMDCuts[0] && signalZNLeft[0]<fZDCLeftEMDCuts[1] &&
      signalZNRight[0]>fZDCRightEMDCuts[0] && signalZNRight[0]<fZDCRightEMDCuts[1] &&
      signalZEMSum[1]<fZEMMinCut){ // *** 1n EMD trigger
        SetInput("ZDC_EMD_L1");
   }
   // *******************************************************************
   if(signalZDCLeftSum[1]>fZDCLeftMBCut && signalZDCRightSum[1]>fZDCRightMBCut)
       // *** ZDC minimum bias trigger
       SetInput("ZDC_1_L1");
   // *******************************************************************
   if(signalZDCLeftSum[1]>fZDCLeftMinCut && signalZDCLeftSum[1]<fZDCLeftCentrCut &&
      signalZDCRightSum[1]>fZDCRightMinCut && signalZDCRightSum[1]<fZDCRightCentrCut &&
      signalZEMSum[1]>fZEMCentrCut)
       // *** ZDC central (0-10%)
       SetInput("ZDC_2_L1");
   // *******************************************************************
   if(signalZDCLeftSum[1]>fZDCLeftCentrCut && signalZDCLeftSum[1]<fZDCLeftSemiCentrCut &&
      signalZDCRightSum[1]>fZDCRightCentrCut && signalZDCRightSum[1]<fZDCRightSemiCentrCut
      && signalZEMSum[1]>fZEMCentrCut)
       // *** ZDC semi-central (10-40%)
       SetInput("ZDC_3_L1");

}

//________________________________________________________________
void AliZDCTrigger::SetZDCLeftMinCut(Float_t ZDCLeftMinCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCLeftMinCut)  fZDCLeftMinCut = ZDCLeftMinCut;
  else  fZDCLeftMinCut = 800.;
}
//________________________________________________________________
void AliZDCTrigger::SetZDCRightMinCut(Float_t ZDCRightMinCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCRightMinCut)  fZDCRightMinCut = ZDCRightMinCut;
  else  fZDCRightMinCut = 800.;
}

//________________________________________________________________
void AliZDCTrigger::SetZEMMinCut(Float_t ZEMMinCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZEMMinCut)  fZEMMinCut = ZEMMinCut;
  else  fZEMMinCut = 80.;
}
//________________________________________________________________
void AliZDCTrigger::SetZDCLeftEMDCuts(Float_t* ZDCLeftEMDCuts)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCLeftEMDCuts) for(int j=0; j<2; j++) fZDCLeftEMDCuts[j] = ZDCLeftEMDCuts[j];
  else{
    fZDCLeftEMDCuts[0] = 600.;
    fZDCLeftEMDCuts[1] = 1000.;
  }
}
//________________________________________________________________
void AliZDCTrigger::SetZDCLeftEMDCuts(Float_t ZDCLeftEMDCutInf,
	Float_t ZDCLeftEMDCutSup)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCLeftEMDCutInf && ZDCLeftEMDCutSup){
    fZDCLeftEMDCuts[0]=ZDCLeftEMDCutInf;
    fZDCLeftEMDCuts[1]=ZDCLeftEMDCutSup;
  }
  else{
    fZDCLeftEMDCuts[0] = 600.;
    fZDCLeftEMDCuts[1] = 1000.;
  }
}
//________________________________________________________________
void AliZDCTrigger::SetZDCRightEMDCuts(Float_t* ZDCRightEMDCuts)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCRightEMDCuts) for(int j=0; j<2; j++) fZDCRightEMDCuts[j] = ZDCRightEMDCuts[j];
  else{
    fZDCRightEMDCuts[0] = 600.;
    fZDCRightEMDCuts[1] = 1000.;
  }
}
//________________________________________________________________
void AliZDCTrigger::SetZDCRightEMDCuts(Float_t ZDCRightEMDCutInf,
	Float_t ZDCRightEMDCutSup)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCRightEMDCutInf && ZDCRightEMDCutSup){
    fZDCRightEMDCuts[0]=ZDCRightEMDCutInf;
    fZDCRightEMDCuts[1]=ZDCRightEMDCutSup;
  }
  else{
    fZDCRightEMDCuts[0] = 600.;
    fZDCRightEMDCuts[1] = 1000.;
  }
}
//________________________________________________________________
void AliZDCTrigger::SetZDCLeftMBCut(Float_t ZDCLeftMBCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCLeftMBCut) fZDCLeftMBCut = ZDCLeftMBCut;
  else fZDCLeftMBCut = 800.;
}
//________________________________________________________________
void AliZDCTrigger::SetZDCRightMBCut(Float_t ZDCRightMBCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCRightMBCut) fZDCRightMBCut = ZDCRightMBCut;
  else fZDCRightMBCut = 800.;
}
//________________________________________________________________
void AliZDCTrigger::SetZDCLeftCentrCut(Float_t ZDCLeftCentrCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCLeftCentrCut) fZDCLeftCentrCut = ZDCLeftCentrCut;
  else fZDCLeftCentrCut = 10000.;
}
//________________________________________________________________
void AliZDCTrigger::SetZDCRightCentrCut(Float_t ZDCRightCentrCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCRightCentrCut) fZDCRightCentrCut = ZDCRightCentrCut;
  else fZDCRightCentrCut = 10000.;
}
//________________________________________________________________
void AliZDCTrigger::SetZDCLeftSemiCentrCut(Float_t ZDCLeftSemiCentrCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCLeftSemiCentrCut) fZDCLeftSemiCentrCut = ZDCLeftSemiCentrCut;
  else fZDCLeftSemiCentrCut = 18500.;
}
//________________________________________________________________
void AliZDCTrigger::SetZDCRightSemiCentrCut(Float_t ZDCRightSemiCentrCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCRightSemiCentrCut) fZDCRightSemiCentrCut = ZDCRightSemiCentrCut;
  else fZDCRightSemiCentrCut = 18500.;
}
//________________________________________________________________
void AliZDCTrigger::SetZEMCentrCut(Float_t ZEMCentrCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZEMCentrCut) fZEMCentrCut = ZEMCentrCut;
  else fZEMCentrCut = 210.;
}
<commit_msg>Corrected input definition of the ZDC trigger (Chiara)<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, 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.                  *
 **************************************************************************/

// ****************************************************************
//
//	Trigger class for ZDC
//
// ****************************************************************

#include "AliLog.h"
#include "AliRun.h"
#include "AliLoader.h"
#include "AliRunLoader.h"
#include "AliTriggerInput.h"

#include "AliZDC.h"
#include "AliZDCDigit.h"
#include "AliZDCTrigger.h"

//________________________________________________________________
ClassImp(AliZDCTrigger)

//________________________________________________________________
AliZDCTrigger::AliZDCTrigger() : AliTriggerDetector()
{
   // Constructor
   SetName("ZDC");
   CreateInputs();
   //
   SetZDCLeftMinCut(0);
   SetZDCRightMinCut(0);
   SetZEMMinCut(0);
   SetZDCLeftEMDCuts(0,0);
   SetZDCRightEMDCuts(0,0);
   SetZDCLeftMBCut(0);
   SetZDCRightMBCut(0);
   SetZDCLeftCentrCut(0);
   SetZDCRightCentrCut(0);
   SetZDCLeftSemiCentrCut(0);
   SetZDCRightSemiCentrCut(0);
   SetZEMCentrCut(0);

}

//________________________________________________________________
void AliZDCTrigger::CreateInputs()
{
   // Trigger inputs

   // Do not create inputs again!!
   if( fInputs.GetEntriesFast() > 0 ) return;

   fInputs.AddLast(new AliTriggerInput("ZDC_1_L1",   "ZDC Minimum Bias", 0x01));
   fInputs.AddLast(new AliTriggerInput("ZDC_2_L1",   "ZDC Semi-central", 0x02));
   fInputs.AddLast(new AliTriggerInput("ZDC_3_L1",   "ZDC Central", 0x04));
   fInputs.AddLast(new AliTriggerInput("ZDC_EMD_L1", "ZDC EMD events", 0x08));
}

//________________________________________________________________
void AliZDCTrigger::Trigger()
{

   // Trigger selection
   //
   AliRunLoader *runLoader = gAlice->GetRunLoader();

   AliLoader *aZDCLoader = runLoader->GetLoader("ZDCLoader");
   aZDCLoader->LoadDigits("READ");
   AliZDCDigit digit;
   AliZDCDigit* pdigit = &digit;
   TTree* tD = aZDCLoader->TreeD();
   if (!tD) cerr<<"AliZDCTrigger: digits tree not found\n";
   tD->SetBranchAddress("ZDC", &pdigit);
   //
   Float_t signalZNLeft[2], signalZPLeft[2], signalZDCLeftSum[2];
   Float_t signalZNRight[2], signalZPRight[2], signalZDCRightSum[2];
   Float_t signalZEMSum[2];
   for(Int_t iDigit=0; iDigit<tD->GetEntries(); iDigit++){
      tD->GetEntry(iDigit);
      //
      // *** ZDC LEFT
      if(digit.GetSector(0)==1)
         for(Int_t i=0; i<2; i++){ //0=high range; 1=low range
	    signalZNLeft[i] += digit.GetADCValue(i);
	    signalZDCLeftSum[i] += digit.GetADCValue(i);
	  }
      else if(digit.GetSector(0)==2)
         for(Int_t i=0; i<2; i++){
	    signalZPLeft[i] += digit.GetADCValue(i);
	    signalZDCLeftSum[i] += digit.GetADCValue(i);
	  }
      else if(digit.GetSector(0)==3)
         for(Int_t i=0; i<2; i++) signalZEMSum[i] += digit.GetADCValue(i);
      // *** ZDC RIGHT
      else if(digit.GetSector(0)==4)
         for(Int_t i=0; i<2; i++){ //0=high range; 1=low range
	    signalZNRight[i] += digit.GetADCValue(i);
	    signalZDCRightSum[i] += digit.GetADCValue(i);
	  }
      else if(digit.GetSector(0)==5)
         for(Int_t i=0; i<2; i++){
	    signalZPRight[i] += digit.GetADCValue(i);
	    signalZDCRightSum[i] += digit.GetADCValue(i);
	  }
   }
   // *******************************************************************
   if(signalZDCLeftSum[1]>fZDCLeftMBCut && signalZDCRightSum[1]>fZDCRightMBCut)
       // *** ZDC minimum bias trigger
       SetInput("ZDC_1_L1");
   // *******************************************************************
   if(signalZDCLeftSum[1]>fZDCLeftCentrCut && signalZDCLeftSum[1]<fZDCLeftSemiCentrCut &&
      signalZDCRightSum[1]>fZDCRightCentrCut && signalZDCRightSum[1]<fZDCRightSemiCentrCut
      && signalZEMSum[1]>fZEMCentrCut)
       // *** ZDC semi-central (10-40%)
       SetInput("ZDC_2_L1");
   // *******************************************************************
   if(signalZDCLeftSum[1]>fZDCLeftMinCut && signalZDCLeftSum[1]<fZDCLeftCentrCut &&
      signalZDCRightSum[1]>fZDCRightMinCut && signalZDCRightSum[1]<fZDCRightCentrCut &&
      signalZEMSum[1]>fZEMCentrCut)
       // *** ZDC central (0-10%)
       SetInput("ZDC_3_L1");
   // *******************************************************************
   if(signalZNLeft[0]>fZDCLeftEMDCuts[0] && signalZNLeft[0]<fZDCLeftEMDCuts[1] &&
      signalZNRight[0]>fZDCRightEMDCuts[0] && signalZNRight[0]<fZDCRightEMDCuts[1] &&
      signalZEMSum[1]<fZEMMinCut){ // *** 1n EMD trigger
        SetInput("ZDC_EMD_L1");
   }

}

//________________________________________________________________
void AliZDCTrigger::SetZDCLeftMinCut(Float_t ZDCLeftMinCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCLeftMinCut)  fZDCLeftMinCut = ZDCLeftMinCut;
  else  fZDCLeftMinCut = 800.;
}
//________________________________________________________________
void AliZDCTrigger::SetZDCRightMinCut(Float_t ZDCRightMinCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCRightMinCut)  fZDCRightMinCut = ZDCRightMinCut;
  else  fZDCRightMinCut = 800.;
}

//________________________________________________________________
void AliZDCTrigger::SetZEMMinCut(Float_t ZEMMinCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZEMMinCut)  fZEMMinCut = ZEMMinCut;
  else  fZEMMinCut = 80.;
}
//________________________________________________________________
void AliZDCTrigger::SetZDCLeftEMDCuts(Float_t* ZDCLeftEMDCuts)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCLeftEMDCuts) for(int j=0; j<2; j++) fZDCLeftEMDCuts[j] = ZDCLeftEMDCuts[j];
  else{
    fZDCLeftEMDCuts[0] = 600.;
    fZDCLeftEMDCuts[1] = 1000.;
  }
}
//________________________________________________________________
void AliZDCTrigger::SetZDCLeftEMDCuts(Float_t ZDCLeftEMDCutInf,
	Float_t ZDCLeftEMDCutSup)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCLeftEMDCutInf && ZDCLeftEMDCutSup){
    fZDCLeftEMDCuts[0]=ZDCLeftEMDCutInf;
    fZDCLeftEMDCuts[1]=ZDCLeftEMDCutSup;
  }
  else{
    fZDCLeftEMDCuts[0] = 600.;
    fZDCLeftEMDCuts[1] = 1000.;
  }
}
//________________________________________________________________
void AliZDCTrigger::SetZDCRightEMDCuts(Float_t* ZDCRightEMDCuts)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCRightEMDCuts) for(int j=0; j<2; j++) fZDCRightEMDCuts[j] = ZDCRightEMDCuts[j];
  else{
    fZDCRightEMDCuts[0] = 600.;
    fZDCRightEMDCuts[1] = 1000.;
  }
}
//________________________________________________________________
void AliZDCTrigger::SetZDCRightEMDCuts(Float_t ZDCRightEMDCutInf,
	Float_t ZDCRightEMDCutSup)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCRightEMDCutInf && ZDCRightEMDCutSup){
    fZDCRightEMDCuts[0]=ZDCRightEMDCutInf;
    fZDCRightEMDCuts[1]=ZDCRightEMDCutSup;
  }
  else{
    fZDCRightEMDCuts[0] = 600.;
    fZDCRightEMDCuts[1] = 1000.;
  }
}
//________________________________________________________________
void AliZDCTrigger::SetZDCLeftMBCut(Float_t ZDCLeftMBCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCLeftMBCut) fZDCLeftMBCut = ZDCLeftMBCut;
  else fZDCLeftMBCut = 800.;
}
//________________________________________________________________
void AliZDCTrigger::SetZDCRightMBCut(Float_t ZDCRightMBCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCRightMBCut) fZDCRightMBCut = ZDCRightMBCut;
  else fZDCRightMBCut = 800.;
}
//________________________________________________________________
void AliZDCTrigger::SetZDCLeftCentrCut(Float_t ZDCLeftCentrCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCLeftCentrCut) fZDCLeftCentrCut = ZDCLeftCentrCut;
  else fZDCLeftCentrCut = 10000.;
}
//________________________________________________________________
void AliZDCTrigger::SetZDCRightCentrCut(Float_t ZDCRightCentrCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCRightCentrCut) fZDCRightCentrCut = ZDCRightCentrCut;
  else fZDCRightCentrCut = 10000.;
}
//________________________________________________________________
void AliZDCTrigger::SetZDCLeftSemiCentrCut(Float_t ZDCLeftSemiCentrCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCLeftSemiCentrCut) fZDCLeftSemiCentrCut = ZDCLeftSemiCentrCut;
  else fZDCLeftSemiCentrCut = 18500.;
}
//________________________________________________________________
void AliZDCTrigger::SetZDCRightSemiCentrCut(Float_t ZDCRightSemiCentrCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZDCRightSemiCentrCut) fZDCRightSemiCentrCut = ZDCRightSemiCentrCut;
  else fZDCRightSemiCentrCut = 18500.;
}
//________________________________________________________________
void AliZDCTrigger::SetZEMCentrCut(Float_t ZEMCentrCut)
{
  // Set default cut values for ZDC trigger
  //
  if(ZEMCentrCut) fZEMCentrCut = ZEMCentrCut;
  else fZEMCentrCut = 210.;
}
<|endoftext|>


<commit_before>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2019 visualfc. All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
** Lesser General Public License for more details.
**
** In addition, as a special exception,  that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: tooldockwidget.cpp
// Creator: visualfc <visualfc@gmail.com>

#include "tooldockwidget.h"
#include "liteapi/liteapi.h"
#include <QAction>
#include <QIcon>
#include <QLabel>
#include <QHBoxLayout>
#include <QVariant>
#include <QMenu>
#include <QToolButton>
#include <QDebug>
//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) &&  defined(_DEBUG)
     #define _CRTDBG_MAP_ALLOC
     #include <stdlib.h>
     #include <crtdbg.h>
     #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
     #define new DEBUG_NEW
#endif
//lite_memory_check_end

BaseDockWidget::BaseDockWidget(QSize iconSize, QWidget *parent) :
    QDockWidget(parent), current(0)
{
    m_comboBox = new QComboBox;
    m_comboBox->setMinimumContentsLength(4);
    //m_comboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
    m_comboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);

    m_toolBar = new QToolBar(this);
    m_toolBar->setContentsMargins(0, 0, 0, 0);
    m_toolBar->setIconSize(iconSize);
    //m_toolBar->setFixedHeight(24);
    m_titleLabel = new QLabel;
    m_titleLabel->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Minimum);
    m_comboBoxAct = m_toolBar->addWidget(m_comboBox);
    m_titleLabelAct = m_toolBar->addWidget(m_titleLabel);
    m_titleLabelAct->setChecked(false);

    QWidget *spacer = new QWidget;
    spacer->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
    m_toolBar->addSeparator();
    m_spacerAct = m_toolBar->addWidget(spacer);

    m_closeAct = new QAction(tr("Hide"), m_toolBar);
    m_closeAct->setToolTip(tr("Hide Tool Window"));
    m_closeAct->setIcon(QIcon("icon:images/closetool.png"));
    m_toolBar->addAction(m_closeAct);

    connect(m_closeAct,SIGNAL(triggered()),this,SLOT(close()));
    connect(m_comboBox,SIGNAL(activated(int)),this,SLOT(activeComboBoxIndex(int)));

    this->setTitleBarWidget(m_toolBar);

    m_floatAct = new QAction(tr("Floating Window"),this);
    m_floatAct->setCheckable(true);
    connect(m_floatAct,SIGNAL(triggered(bool)),this,SLOT(setFloatingWindow(bool)));
    connect(this,SIGNAL(topLevelChanged(bool)),this,SLOT(topLevelChanged(bool)));
    /*
    m_toolBar->setStyleSheet("QToolBar {border: 1px ; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #eeeeee, stop: 1 #ababab); }"\
                             "QToolBar QToolButton { border:1px ; border-radius: 1px; }"\
                             "QToolBar QToolButton::hover { background-color: #ababab;}"\
                             "QToolBar::separator {width:2px; margin-left:2px; margin-right:2px; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #dedede, stop: 1 #a0a0a0);}");
*/
}

void BaseDockWidget::setWindowTitle(const QString &text)
{
    QDockWidget::setWindowTitle(text);
}

QAction *BaseDockWidget::addWidget(QWidget *widget)
{
   return m_toolBar->insertWidget(m_closeAct,widget);
}

void BaseDockWidget::setToolMenu(QMenu *menu)
{
    QToolButton *btn = new QToolButton;
    btn->setPopupMode(QToolButton::InstantPopup);
    btn->setMenu(menu);
    btn->setStyleSheet("QToolButton::menu-indicator{image:none;}");

    m_toolBar->insertWidget(m_closeAct,btn);
}

void BaseDockWidget::setWidgetActions(QList<QAction*> actions)
{
    foreach(QAction *action, m_widgetActions) {
        m_toolBar->removeAction(action);
    }
    m_widgetActions = actions;
    m_spacerAct->setVisible(!m_widgetActions.isEmpty());
    foreach(QAction *action, m_widgetActions) {
        m_toolBar->insertAction(m_spacerAct,action);
        if (action->menu() != 0) {
            QWidget *w = m_toolBar->widgetForAction(action);
            QToolButton *btn = qobject_cast<QToolButton*>(w);
            if (btn) {
                btn->setPopupMode(QToolButton::InstantPopup);
                btn->setStyleSheet("QToolButton::menu-indicator{image:none;}");
            }
        }
    }
}

QList<QAction *> BaseDockWidget::actions() const
{
    return m_actions;
}

void BaseDockWidget::removeAction(QAction *action)
{
    if (m_actions.removeAll(action)) {
        if (action == current)
            current = 0;
        int index = m_comboBox->findData(action->objectName());
        if (index >= 0) {
            m_comboBox->removeItem(index);
        }
        QObject::disconnect(action, SIGNAL(changed()), this, SLOT(actionChanged()));
    }
}

QAction * BaseDockWidget::checkedAction () const
{
    return current;
}

void BaseDockWidget::actionChanged()
{
    QAction *action = qobject_cast<QAction*>(sender());
    Q_ASSERT_X(action != 0, "ActionGroup::actionChanged", "internal error");
    if (action->isChecked()) {
        if (action != current) {
            if(current)
                current->setChecked(false);
            current = action;
            int index = m_comboBox->findData(action->objectName());
            if (index >= 0) {
                m_comboBox->setCurrentIndex(index);
            }
        }
    } else if (action == current) {
        current = 0;
    }
}

void BaseDockWidget::activeComboBoxIndex(int index)
{
    if (index < 0 || index >= m_comboBox->count()) {
        return;
    }
    QString objName = m_comboBox->itemData(index).toString();
    foreach(QAction *act, m_actions) {
        if (act->objectName() == objName) {
            if (!act->isChecked()) {
                act->setChecked(true);
            }
            break;
        }
    }
}

void BaseDockWidget::topLevelChanged(bool b)
{
    m_comboBoxAct->setVisible(!b);
    m_titleLabel->setText(m_comboBox->currentText());
    m_titleLabelAct->setVisible(b);
    DockWidgetFeatures flags = this->features();
    if (b) {
        flags |= QDockWidget::DockWidgetFloatable;
    } else {
        flags &= (~QDockWidget::DockWidgetFloatable);
    }
    this->setFeatures(flags);
    m_floatAct->setChecked(b);
}

void BaseDockWidget::setFloatingWindow(bool b)
{
    if (this->isFloating() != b) {
        DockWidgetFeatures flags = this->features();
        if (b) {
            flags |= QDockWidget::DockWidgetFloatable;
        } else {
            flags &= (~QDockWidget::DockWidgetFloatable);
        }
        this->setFeatures(flags);
        this->setFloating(b);
    }
    if (m_floatAct->isChecked() != b) {
        m_floatAct->setChecked(b);
    }
}

void BaseDockWidget::addAction(QAction *action, const QString &title)
{
    if(!m_actions.contains(action)) {
        m_actions.append(action);
        m_comboBox->addItem(title,action->objectName());
        QObject::connect(action, SIGNAL(changed()), this, SLOT(actionChanged()));
    }
    if (current && current->isChecked()) {
        current->setChecked(false);
    }
    if (action->isChecked()) {
        current = action;
    }
}

SplitDockWidget::SplitDockWidget(QSize iconSize, QWidget *parent) :
    BaseDockWidget(iconSize,parent)
{
}

void SplitDockWidget::createMenu(Qt::DockWidgetArea area, bool split)
{
    m_area = area;
    QMenu *moveMenu = new QMenu(tr("Move To"),this);
    if (area != Qt::TopDockWidgetArea) {
        QAction *act = new QAction(tr("Top"),this);
        act->setData(Qt::TopDockWidgetArea);
        moveMenu->addAction(act);
        connect(act,SIGNAL(triggered()),this,SLOT(moveAction()));
        QAction *act1 = new QAction(tr("Top (Split)"),this);
        act1->setData(Qt::TopDockWidgetArea);
        moveMenu->addAction(act1);
        connect(act1,SIGNAL(triggered()),this,SLOT(moveActionSplit()));
    }
    if (area != Qt::BottomDockWidgetArea) {
        QAction *act = new QAction(tr("Bottom"),this);
        act->setData(Qt::BottomDockWidgetArea);
        moveMenu->addAction(act);
        connect(act,SIGNAL(triggered()),this,SLOT(moveAction()));
        QAction *act1 = new QAction(tr("Bottom (Split)"),this);
        act1->setData(Qt::BottomDockWidgetArea);
        moveMenu->addAction(act1);
        connect(act1,SIGNAL(triggered()),this,SLOT(moveActionSplit()));
    }
    if (area != Qt::LeftDockWidgetArea) {
        QAction *act = new QAction(tr("Left"),this);
        act->setData(Qt::LeftDockWidgetArea);
        moveMenu->addAction(act);
        connect(act,SIGNAL(triggered()),this,SLOT(moveAction()));
        QAction *act1 = new QAction(tr("Left (Split)"),this);
        act1->setData(Qt::LeftDockWidgetArea);
        moveMenu->addAction(act1);
        connect(act1,SIGNAL(triggered()),this,SLOT(moveActionSplit()));
    }
    if (area != Qt::RightDockWidgetArea) {
        QAction *act = new QAction(tr("Right"),this);
        act->setData(Qt::RightDockWidgetArea);
        moveMenu->addAction(act);
        connect(act,SIGNAL(triggered()),this,SLOT(moveAction()));
        QAction *act1 = new QAction(tr("Right (Split)"),this);
        act1->setData(Qt::RightDockWidgetArea);
        moveMenu->addAction(act1);
        connect(act1,SIGNAL(triggered()),this,SLOT(moveActionSplit()));
    }

    QMenu *menu = new QMenu(this);
    menu->addAction(m_floatAct);
    if (split) {
        QAction *unsplitAct = new QAction(tr("Unsplit"),this);
        unsplitAct->setData(area);
        connect(unsplitAct,SIGNAL(triggered()),this,SLOT(unsplitAction()));
        menu->addAction(unsplitAct);
    } else {
        QAction *splitAct = new QAction(tr("Split"),this);
        splitAct->setData(area);
        connect(splitAct,SIGNAL(triggered()),this,SLOT(splitAction()));
        menu->addAction(splitAct);
    }
    menu->addAction(moveMenu->menuAction());

    if (area == Qt::BottomDockWidgetArea || area == Qt::TopDockWidgetArea) {
        m_comboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
        m_comboBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
        QWidget *spacer = new QWidget;
        spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
        m_toolBar->insertWidget(m_closeAct,spacer);
    }

    QToolButton *btn = new QToolButton(m_toolBar);
    btn->setPopupMode(QToolButton::InstantPopup);
    btn->setIcon(QIcon("icon:images/movemenu.png"));
    btn->setMenu(menu);
    btn->setText(tr("Move To"));
    btn->setToolTip(tr("Move To"));
    btn->setStyleSheet("QToolButton::menu-indicator {image: none;}");
    m_toolBar->insertWidget(m_closeAct,btn);
}

void SplitDockWidget::moveAction()
{
    QAction *action = static_cast<QAction*>(sender());
    if (!action) {
        return;
    }
    Qt::DockWidgetArea area = (Qt::DockWidgetArea)action->data().toInt();
    emit moveActionTo(m_area,area,current,false);
}

void SplitDockWidget::moveActionSplit()
{
    QAction *action = static_cast<QAction*>(sender());
    if (!action) {
        return;
    }
    Qt::DockWidgetArea area = (Qt::DockWidgetArea)action->data().toInt();
    emit moveActionTo(m_area,area,current,true);
}

void SplitDockWidget::splitAction()
{
    QAction *action = static_cast<QAction*>(sender());
    if (!action) {
        return;
    }
    Qt::DockWidgetArea area = (Qt::DockWidgetArea)action->data().toInt();
    emit moveActionTo(m_area,area,current,true);
}

void SplitDockWidget::unsplitAction()
{
    QAction *action = static_cast<QAction*>(sender());
    if (!action) {
        return;
    }
    Qt::DockWidgetArea area = (Qt::DockWidgetArea)action->data().toInt();
    emit moveActionTo(m_area,area,current,false);
}

OutputDockWidget::OutputDockWidget(QSize iconSize, QWidget *parent) :
    BaseDockWidget(iconSize,parent)
{
    m_comboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
    m_comboBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
    QWidget *spacer = new QWidget;
    spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
    m_toolBar->insertWidget(m_closeAct,spacer);
}

void OutputDockWidget::createMenu(Qt::DockWidgetArea area)
{
    this->setAllowedAreas(area);
    QMenu *moveMenu = new QMenu(tr("Move To"),this);

    QAction *leftAct = new QAction(tr("LeftSideBar"),this);
    QAction *rightAct = new QAction(tr("RightSideBar"),this);

    leftAct->setData(Qt::LeftDockWidgetArea);
    rightAct->setData(Qt::RightDockWidgetArea);

    moveMenu->addAction(leftAct);
    moveMenu->addAction(rightAct);

    connect(leftAct,SIGNAL(triggered()),this,SLOT(moveAction()));
    connect(rightAct,SIGNAL(triggered()),this,SLOT(moveAction()));

    QMenu *menu = new QMenu(this);
    menu->addAction(m_floatAct);
    menu->addAction(moveMenu->menuAction());

    m_comboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
    m_comboBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
    QWidget *spacer = new QWidget;
    spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
    m_toolBar->insertWidget(m_closeAct,spacer);

    QToolButton *btn = new QToolButton(m_toolBar);
    btn->setPopupMode(QToolButton::InstantPopup);
    btn->setIcon(QIcon("icon:images/movemenu.png"));
    btn->setMenu(menu);
    btn->setText(tr("Move To"));
    btn->setToolTip(tr("Move To"));
    btn->setStyleSheet("QToolButton::menu-indicator {image: none;}");
    m_toolBar->insertWidget(m_closeAct,btn);
}

void OutputDockWidget::moveAction()
{
    QAction *action = static_cast<QAction*>(sender());
    if (!action) {
        return;
    }
    this->setFloatingWindow(false);
    Qt::DockWidgetArea area = (Qt::DockWidgetArea)action->data().toInt();
    emit moveActionTo(Qt::BottomDockWidgetArea,area,current);
}
<commit_msg>tooldock widget fix title label<commit_after>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2019 visualfc. All rights reserved.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
** Lesser General Public License for more details.
**
** In addition, as a special exception,  that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: tooldockwidget.cpp
// Creator: visualfc <visualfc@gmail.com>

#include "tooldockwidget.h"
#include "liteapi/liteapi.h"
#include <QAction>
#include <QIcon>
#include <QLabel>
#include <QHBoxLayout>
#include <QVariant>
#include <QMenu>
#include <QToolButton>
#include <QDebug>
//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) &&  defined(_DEBUG)
     #define _CRTDBG_MAP_ALLOC
     #include <stdlib.h>
     #include <crtdbg.h>
     #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
     #define new DEBUG_NEW
#endif
//lite_memory_check_end

BaseDockWidget::BaseDockWidget(QSize iconSize, QWidget *parent) :
    QDockWidget(parent), current(0)
{
    m_comboBox = new QComboBox;
    m_comboBox->setMinimumContentsLength(4);
    //m_comboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
    m_comboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);

    m_toolBar = new QToolBar(this);
    m_toolBar->setContentsMargins(0, 0, 0, 0);
    m_toolBar->setIconSize(iconSize);
    //m_toolBar->setFixedHeight(24);
    m_titleLabel = new QLabel;
    m_titleLabel->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Minimum);
    m_comboBoxAct = m_toolBar->addWidget(m_comboBox);
    m_titleLabelAct = m_toolBar->addWidget(m_titleLabel);
    m_titleLabelAct->setChecked(false);

    QWidget *spacer = new QWidget;
    spacer->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
    m_toolBar->addSeparator();
    m_spacerAct = m_toolBar->addWidget(spacer);

    m_closeAct = new QAction(tr("Hide"), m_toolBar);
    m_closeAct->setToolTip(tr("Hide Tool Window"));
    m_closeAct->setIcon(QIcon("icon:images/closetool.png"));
    m_toolBar->addAction(m_closeAct);

    connect(m_closeAct,SIGNAL(triggered()),this,SLOT(close()));
    connect(m_comboBox,SIGNAL(activated(int)),this,SLOT(activeComboBoxIndex(int)));

    this->setTitleBarWidget(m_toolBar);

    m_floatAct = new QAction(tr("Floating Window"),this);
    m_floatAct->setCheckable(true);
    connect(m_floatAct,SIGNAL(triggered(bool)),this,SLOT(setFloatingWindow(bool)));
    connect(this,SIGNAL(topLevelChanged(bool)),this,SLOT(topLevelChanged(bool)));
    /*
    m_toolBar->setStyleSheet("QToolBar {border: 1px ; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #eeeeee, stop: 1 #ababab); }"\
                             "QToolBar QToolButton { border:1px ; border-radius: 1px; }"\
                             "QToolBar QToolButton::hover { background-color: #ababab;}"\
                             "QToolBar::separator {width:2px; margin-left:2px; margin-right:2px; background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,stop: 0 #dedede, stop: 1 #a0a0a0);}");
*/
}

void BaseDockWidget::setWindowTitle(const QString &text)
{
    QDockWidget::setWindowTitle(text);
}

QAction *BaseDockWidget::addWidget(QWidget *widget)
{
   return m_toolBar->insertWidget(m_closeAct,widget);
}

void BaseDockWidget::setToolMenu(QMenu *menu)
{
    QToolButton *btn = new QToolButton;
    btn->setPopupMode(QToolButton::InstantPopup);
    btn->setMenu(menu);
    btn->setStyleSheet("QToolButton::menu-indicator{image:none;}");

    m_toolBar->insertWidget(m_closeAct,btn);
}

void BaseDockWidget::setWidgetActions(QList<QAction*> actions)
{
    foreach(QAction *action, m_widgetActions) {
        m_toolBar->removeAction(action);
    }
    m_widgetActions = actions;
    m_spacerAct->setVisible(!m_widgetActions.isEmpty());
    foreach(QAction *action, m_widgetActions) {
        m_toolBar->insertAction(m_spacerAct,action);
        if (action->menu() != 0) {
            QWidget *w = m_toolBar->widgetForAction(action);
            QToolButton *btn = qobject_cast<QToolButton*>(w);
            if (btn) {
                btn->setPopupMode(QToolButton::InstantPopup);
                btn->setStyleSheet("QToolButton::menu-indicator{image:none;}");
            }
        }
    }
}

QList<QAction *> BaseDockWidget::actions() const
{
    return m_actions;
}

void BaseDockWidget::removeAction(QAction *action)
{
    if (m_actions.removeAll(action)) {
        if (action == current)
            current = 0;
        int index = m_comboBox->findData(action->objectName());
        if (index >= 0) {
            m_comboBox->removeItem(index);
        }
        QObject::disconnect(action, SIGNAL(changed()), this, SLOT(actionChanged()));
    }
}

QAction * BaseDockWidget::checkedAction () const
{
    return current;
}

void BaseDockWidget::actionChanged()
{
    QAction *action = qobject_cast<QAction*>(sender());
    Q_ASSERT_X(action != 0, "ActionGroup::actionChanged", "internal error");
    if (action->isChecked()) {
        if (action != current) {
            if(current)
                current->setChecked(false);
            current = action;
            int index = m_comboBox->findData(action->objectName());
            if (index >= 0) {
                m_comboBox->setCurrentIndex(index);
                m_titleLabel->setText(m_comboBox->currentText());
            }
        }
    } else if (action == current) {
        current = 0;
    }
}

void BaseDockWidget::activeComboBoxIndex(int index)
{
    if (index < 0 || index >= m_comboBox->count()) {
        return;
    }
    QString objName = m_comboBox->itemData(index).toString();
    foreach(QAction *act, m_actions) {
        if (act->objectName() == objName) {
            if (!act->isChecked()) {
                act->setChecked(true);
            }
            break;
        }
    }
}

void BaseDockWidget::topLevelChanged(bool b)
{
    m_comboBoxAct->setVisible(!b);
    m_titleLabel->setText(m_comboBox->currentText());
    m_titleLabelAct->setVisible(b);
    DockWidgetFeatures flags = this->features();
    if (b) {
        flags |= QDockWidget::DockWidgetFloatable;
    } else {
        flags &= (~QDockWidget::DockWidgetFloatable);
    }
    this->setFeatures(flags);
    m_floatAct->setChecked(b);
}

void BaseDockWidget::setFloatingWindow(bool b)
{
    if (this->isFloating() != b) {
        DockWidgetFeatures flags = this->features();
        if (b) {
            flags |= QDockWidget::DockWidgetFloatable;
        } else {
            flags &= (~QDockWidget::DockWidgetFloatable);
        }
        this->setFeatures(flags);
        this->setFloating(b);
    }
    if (m_floatAct->isChecked() != b) {
        m_floatAct->setChecked(b);
    }
}

void BaseDockWidget::addAction(QAction *action, const QString &title)
{
    if(!m_actions.contains(action)) {
        m_actions.append(action);
        m_comboBox->addItem(title,action->objectName());
        QObject::connect(action, SIGNAL(changed()), this, SLOT(actionChanged()));
    }
    if (current && current->isChecked()) {
        current->setChecked(false);
    }
    if (action->isChecked()) {
        current = action;
    }
}

SplitDockWidget::SplitDockWidget(QSize iconSize, QWidget *parent) :
    BaseDockWidget(iconSize,parent)
{
}

void SplitDockWidget::createMenu(Qt::DockWidgetArea area, bool split)
{
    m_area = area;
    QMenu *moveMenu = new QMenu(tr("Move To"),this);
    if (area != Qt::TopDockWidgetArea) {
        QAction *act = new QAction(tr("Top"),this);
        act->setData(Qt::TopDockWidgetArea);
        moveMenu->addAction(act);
        connect(act,SIGNAL(triggered()),this,SLOT(moveAction()));
        QAction *act1 = new QAction(tr("Top (Split)"),this);
        act1->setData(Qt::TopDockWidgetArea);
        moveMenu->addAction(act1);
        connect(act1,SIGNAL(triggered()),this,SLOT(moveActionSplit()));
    }
    if (area != Qt::BottomDockWidgetArea) {
        QAction *act = new QAction(tr("Bottom"),this);
        act->setData(Qt::BottomDockWidgetArea);
        moveMenu->addAction(act);
        connect(act,SIGNAL(triggered()),this,SLOT(moveAction()));
        QAction *act1 = new QAction(tr("Bottom (Split)"),this);
        act1->setData(Qt::BottomDockWidgetArea);
        moveMenu->addAction(act1);
        connect(act1,SIGNAL(triggered()),this,SLOT(moveActionSplit()));
    }
    if (area != Qt::LeftDockWidgetArea) {
        QAction *act = new QAction(tr("Left"),this);
        act->setData(Qt::LeftDockWidgetArea);
        moveMenu->addAction(act);
        connect(act,SIGNAL(triggered()),this,SLOT(moveAction()));
        QAction *act1 = new QAction(tr("Left (Split)"),this);
        act1->setData(Qt::LeftDockWidgetArea);
        moveMenu->addAction(act1);
        connect(act1,SIGNAL(triggered()),this,SLOT(moveActionSplit()));
    }
    if (area != Qt::RightDockWidgetArea) {
        QAction *act = new QAction(tr("Right"),this);
        act->setData(Qt::RightDockWidgetArea);
        moveMenu->addAction(act);
        connect(act,SIGNAL(triggered()),this,SLOT(moveAction()));
        QAction *act1 = new QAction(tr("Right (Split)"),this);
        act1->setData(Qt::RightDockWidgetArea);
        moveMenu->addAction(act1);
        connect(act1,SIGNAL(triggered()),this,SLOT(moveActionSplit()));
    }

    QMenu *menu = new QMenu(this);
    menu->addAction(m_floatAct);
    if (split) {
        QAction *unsplitAct = new QAction(tr("Unsplit"),this);
        unsplitAct->setData(area);
        connect(unsplitAct,SIGNAL(triggered()),this,SLOT(unsplitAction()));
        menu->addAction(unsplitAct);
    } else {
        QAction *splitAct = new QAction(tr("Split"),this);
        splitAct->setData(area);
        connect(splitAct,SIGNAL(triggered()),this,SLOT(splitAction()));
        menu->addAction(splitAct);
    }
    menu->addAction(moveMenu->menuAction());

    if (area == Qt::BottomDockWidgetArea || area == Qt::TopDockWidgetArea) {
        m_comboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
        m_comboBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
        QWidget *spacer = new QWidget;
        spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
        m_toolBar->insertWidget(m_closeAct,spacer);
    }

    QToolButton *btn = new QToolButton(m_toolBar);
    btn->setPopupMode(QToolButton::InstantPopup);
    btn->setIcon(QIcon("icon:images/movemenu.png"));
    btn->setMenu(menu);
    btn->setText(tr("Move To"));
    btn->setToolTip(tr("Move To"));
    btn->setStyleSheet("QToolButton::menu-indicator {image: none;}");
    m_toolBar->insertWidget(m_closeAct,btn);
}

void SplitDockWidget::moveAction()
{
    QAction *action = static_cast<QAction*>(sender());
    if (!action) {
        return;
    }
    Qt::DockWidgetArea area = (Qt::DockWidgetArea)action->data().toInt();
    emit moveActionTo(m_area,area,current,false);
}

void SplitDockWidget::moveActionSplit()
{
    QAction *action = static_cast<QAction*>(sender());
    if (!action) {
        return;
    }
    Qt::DockWidgetArea area = (Qt::DockWidgetArea)action->data().toInt();
    emit moveActionTo(m_area,area,current,true);
}

void SplitDockWidget::splitAction()
{
    QAction *action = static_cast<QAction*>(sender());
    if (!action) {
        return;
    }
    Qt::DockWidgetArea area = (Qt::DockWidgetArea)action->data().toInt();
    emit moveActionTo(m_area,area,current,true);
}

void SplitDockWidget::unsplitAction()
{
    QAction *action = static_cast<QAction*>(sender());
    if (!action) {
        return;
    }
    Qt::DockWidgetArea area = (Qt::DockWidgetArea)action->data().toInt();
    emit moveActionTo(m_area,area,current,false);
}

OutputDockWidget::OutputDockWidget(QSize iconSize, QWidget *parent) :
    BaseDockWidget(iconSize,parent)
{
    m_comboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
    m_comboBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
    QWidget *spacer = new QWidget;
    spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
    m_toolBar->insertWidget(m_closeAct,spacer);
}

void OutputDockWidget::createMenu(Qt::DockWidgetArea area)
{
    this->setAllowedAreas(area);
    QMenu *moveMenu = new QMenu(tr("Move To"),this);

    QAction *leftAct = new QAction(tr("LeftSideBar"),this);
    QAction *rightAct = new QAction(tr("RightSideBar"),this);

    leftAct->setData(Qt::LeftDockWidgetArea);
    rightAct->setData(Qt::RightDockWidgetArea);

    moveMenu->addAction(leftAct);
    moveMenu->addAction(rightAct);

    connect(leftAct,SIGNAL(triggered()),this,SLOT(moveAction()));
    connect(rightAct,SIGNAL(triggered()),this,SLOT(moveAction()));

    QMenu *menu = new QMenu(this);
    menu->addAction(m_floatAct);
    menu->addAction(moveMenu->menuAction());

    m_comboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
    m_comboBox->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum);
    QWidget *spacer = new QWidget;
    spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
    m_toolBar->insertWidget(m_closeAct,spacer);

    QToolButton *btn = new QToolButton(m_toolBar);
    btn->setPopupMode(QToolButton::InstantPopup);
    btn->setIcon(QIcon("icon:images/movemenu.png"));
    btn->setMenu(menu);
    btn->setText(tr("Move To"));
    btn->setToolTip(tr("Move To"));
    btn->setStyleSheet("QToolButton::menu-indicator {image: none;}");
    m_toolBar->insertWidget(m_closeAct,btn);
}

void OutputDockWidget::moveAction()
{
    QAction *action = static_cast<QAction*>(sender());
    if (!action) {
        return;
    }
    this->setFloatingWindow(false);
    Qt::DockWidgetArea area = (Qt::DockWidgetArea)action->data().toInt();
    emit moveActionTo(Qt::BottomDockWidgetArea,area,current);
}
<|endoftext|>


<commit_before>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"

#include "DebugOperatorNew.h"

#include "UICanvas.h"
#include "Profiler.h"

#ifndef Q_WS_WIN
#include <QX11Info>
#endif

#include <QCoreApplication>
#include <QPicture>
#include <QGraphicsSceneEvent>
#include <QUuid>
#include <QWidget>
#include <QGraphicsProxyWidget>
#include <QDebug>
#include <Ogre.h>

#include <OgreHardwarePixelBuffer.h>
#include <OgreTexture.h>
#include <OgreMaterial.h>
#include <OgreTextAreaOverlayElement.h>
#include <OgreFontManager.h>
#include <OgrePanelOverlayElement.h>
#include <OgreTextureUnitState.h>

#include "MemoryLeakCheck.h"

namespace QtUI
{

UICanvas::UICanvas(): overlay_(0),
                      container_(0),
                      dirty_(true),
                      surfaceName_(""),
                      mode_(External),
                      id_(QUuid::createUuid().toString()),
                      widgets_(0),
                      locked_(false)

{

    setScene(new QGraphicsScene);
    setViewportUpdateMode(QGraphicsView::FullViewportUpdate);

    QObject::connect(this->scene(),SIGNAL(changed(const QList<QRectF>&)),this,SLOT(Dirty()));
}

UICanvas::UICanvas(Mode mode, const QSize& parentWindowSize): overlay_(0),
                               container_(0),
                               dirty_(true),
                               renderWindowSize_(parentWindowSize),
                               mode_(mode),
                               id_(QUuid::createUuid().toString()),
                               widgets_(0),
                               locked_(false)

{
 setScene(new QGraphicsScene);

 if (mode_ == External)
 {
    // Deal canvas as normal QWidget.
    // Currently do nothing

 }
 else if (mode_ == Internal)
 {
    setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
    QSize size = this->size();

    CreateOgreResources(size.width(), size.height());
    QObject::connect(this->scene(),SIGNAL(changed(const QList<QRectF>&)),this,SLOT(Dirty()));
 }

}

UICanvas::~UICanvas()
{

    for (int i = scene_widgets_.size(); i--;)
    {
        QGraphicsProxyWidget* widget = scene_widgets_.takeAt(i);
        delete widget;

    }

    if (mode_ != External)
    {

      Ogre::TextureManager::getSingleton().remove(surfaceName_.toStdString().c_str());
      QString surfaceMaterial = QString("mat") + id_;
      Ogre::MaterialManager::getSingleton().remove(surfaceMaterial.toStdString().c_str());

      QString containerName = QString("con") + id_;
      Ogre::OverlayManager::getSingleton().destroyOverlayElement(containerName.toStdString().c_str());

      QString overlayName = QString("over") + id_;
      Ogre::OverlayManager::getSingleton().destroy(overlayName.toStdString().c_str());

    }
    container_ = 0;
    overlay_ = 0;

    QGraphicsScene* scene = this->scene();
    delete scene;
    scene = 0;

}

void UICanvas::AddWidget(QWidget* widget)
{

    switch(mode_)
    {
        case Internal:
            {
                  QGraphicsScene* scene = this->scene();
                  scene_widgets_.append(scene->addWidget(widget));
                  ++widgets_;
                  break;
            }
        case External:
            {
              ///todo Here lies a desing flaw do it better, this does not work.
              if ( widgets_ != 0)
               {
                   // Possible memory LEAK !!!
                    QGraphicsScene* scene = this->scene();
                    if(widgets_ == 1)
                    {
                        QWidget* viewport = this->viewport();
                        scene_widgets_.append(scene->addWidget(viewport));
                        scene_widgets_.append(scene->addWidget(widget));
                        setViewport(new QWidget);
                    }
                    else
                        scene_widgets_.append(scene->addWidget(widget));

               }
               else
                   setViewport(widget);

               ++widgets_;

               break;
            }

        default:
            break;
    }
}

void UICanvas::SetPosition(int x, int y)
{
    switch (mode_)
    {
    case External:
        {
            move(x,y);
            break;
        }
    case Internal:
        {
            float relX = x/double(renderWindowSize_.width()), relY = y/double(renderWindowSize_.height());
            container_->setPosition(relX, relY);

            emit RequestArrange();
            dirty_ = true;
            break;
        }

    default:
        break;

    }

}

QPoint UICanvas::MapToCanvas(int x, int y)
{
    if ( mode_ != External)
    {
        x -= container_->getLeft() * renderWindowSize_.width();
        y -= container_->getTop() * renderWindowSize_.height();
    }
     return QPoint(x,y);
}

QPointF UICanvas::GetPosition() const
{
    QPointF position;

    switch(mode_)
    {
        case External:
            {
                position = pos();
                break;
            }
        case Internal:
            {
                double width = container_->getLeft();
                double height = container_->getTop();

                // Calculate position in render window coordinate frame.
                position.rx() = width * renderWindowSize_.width();
                position.ry() = height * renderWindowSize_.height();
                break;

            }

        default:
            break;

    }

    return position;
}

void UICanvas::SetCanvasSize(int width, int height)
{
    //move(0, 0);
    resize(width, height);

    if ( mode_ != External)
    {
        CreateOgreResources(width, height);
        Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(surfaceName_.toStdString().c_str());
        float relWidth = (float)texture->getWidth()/double(renderWindowSize_.width());
        float relHeight = (float)texture->getHeight()/double(renderWindowSize_.height());
        container_->setDimensions(relWidth, relHeight);

    }

    // Repaint canvas.
    dirty_ = true;
    RenderSceneToOgreSurface();
}

void UICanvas::SetRenderWindowSize(const QSize& size)
{

    renderWindowSize_ = size;
    Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(surfaceName_.toStdString().c_str());
    float relWidth = (float)texture->getWidth()/double(renderWindowSize_.width());
    float relHeight = (float)texture->getHeight()/double(renderWindowSize_.height());
    container_->setDimensions(relWidth, relHeight);
    dirty_ = true;
}

void UICanvas::ResizeOgreTexture(int width, int height)
{
    Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(surfaceName_.toStdString().c_str());
    texture->freeInternalResources();
    texture->setWidth(width);
    texture->setHeight(height);
    texture->createInternalResources();
}

void UICanvas::CreateOgreResources(int width, int height)
{
    // If we've already created the resources, just resize the texture to a new size.

    if ( surfaceName_ != "")
    {
        Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(surfaceName_.toStdString().c_str());
        if (width == texture->getWidth() && height == texture->getHeight())
            return;
        ResizeOgreTexture(width, height);
        assert(overlay_);
        assert(container_);
        return;

    }

    QString overlayName = QString("over") + id_;
    overlay_ = Ogre::OverlayManager::getSingleton().create(overlayName.toStdString().c_str());

    QString containerName = QString("con") + id_;
    container_ = static_cast<Ogre::OverlayContainer*>(Ogre::OverlayManager::getSingleton()
                                     .createOverlayElement("Panel", containerName.toStdString().c_str()));

    // This is not done so currently -- tuoki
    // Make the overlay cover 100% of the render window. Note that the UI surface will be
    // rendered pixel perfect without stretching only if the GraphicsView surface dimension
    // matches the render window size.
    //container_->setDimensions(1.0,1.0);

    container_->setPosition(0,0);

    // Add container in default overlay
    overlay_->add2D(container_);

    ///\todo Tell Ogre not to generate a mipmap chain. This texture only needs to have only one
    /// mip level.

    surfaceName_ = QString("tex") + id_;

    Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual(surfaceName_.toStdString().c_str(),
						        Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
						        Ogre::TEX_TYPE_2D, width, height, 0,
						        Ogre::PF_A8R8G8B8, Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);

    QString surfaceMaterial = QString("mat") + id_;
    Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create(surfaceMaterial.toStdString().c_str(),
						        Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

    Ogre::TextureUnitState *state = material->getTechnique(0)->getPass(0)->createTextureUnitState();
    material->getTechnique(0)->getPass(0)->setSceneBlending(Ogre::SBF_SOURCE_ALPHA, Ogre::SBF_ONE_MINUS_SOURCE_ALPHA);
    state->setTextureName(surfaceName_.toStdString().c_str());

    // Generate pixel perfect texture.

    float relWidth = (float)texture->getWidth()/double(renderWindowSize_.width());
    float relHeight = (float)texture->getHeight()/double(renderWindowSize_.height());
    container_->setDimensions(relWidth, relHeight);

    container_->setMaterialName(surfaceMaterial .toStdString().c_str());
    container_->show();
    container_->setEnabled(true);
    container_->setColour(Ogre::ColourValue(1,1,1,1));

    overlay_->show();
}

void UICanvas::Show()
{

    if ( mode_ != External)
    {
        QList<QGraphicsProxyWidget* >::iterator iter = scene_widgets_.begin();
        for (; iter != scene_widgets_.end(); ++iter)
            (*iter)->show();

        container_->show();
        overlay_->show();

        dirty_ = true;
        RenderSceneToOgreSurface();
    }
    else
        show();

}

void UICanvas::Hide()
{

    if ( mode_ != External)
        {
            QList<QGraphicsProxyWidget* >::iterator iter = scene_widgets_.begin();
            for (; iter != scene_widgets_.end(); ++iter)
                (*iter)->hide();

            container_->hide();
            overlay_->hide();
            dirty_ = true;
            RenderSceneToOgreSurface();
        }
    else
        hide();

}

void UICanvas::drawBackground(QPainter *painter, const QRectF &rect)
{
    QBrush black(Qt::transparent);
    painter->fillRect(rect, black);
}

void UICanvas::RenderSceneToOgreSurface()
{

	// Render if and only if scene is dirty.
	if (!dirty_ || mode_ == External)
		return;

    PROFILE(RenderSceneToOgre);

    // We draw the GraphicsView area to an offscreen QPixmap and blit that onto the Ogre GPU surface.
    QPixmap pixmap(this->size());
    {
        PROFILE(FillEmpty);
        pixmap.fill(Qt::transparent);
    }
    assert(pixmap.hasAlphaChannel());
    QImage img = pixmap.toImage();

    QPainter painter(&img);
    QRectF destRect(0, 0, pixmap.width(), pixmap.height());
    QRect sourceRect(0, 0, pixmap.width(), pixmap.height());
    {
        PROFILE(RenderUI);
        this->render(&painter, destRect, sourceRect);
    }
    assert(img.hasAlphaChannel());

    ///\todo Can optimize an extra blit away if we paint directly onto the GPU surface.

    Ogre::Box dimensions(0,0, img.rect().width(), img.rect().height());
    Ogre::PixelBox pixel_box(dimensions, Ogre::PF_A8R8G8B8, (void*)img.bits());
    {
        PROFILE(UIToOgreBlit);
        Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(surfaceName_.toStdString().c_str());
        texture->getBuffer()->blitFromMemory(pixel_box);
    }

    dirty_ = false;
}

void UICanvas::Render()
{
    RenderSceneToOgreSurface();
}

}
<commit_msg>Fixes a crash if render window size is changed in case if there exist  external window. <commit_after>// For conditions of distribution and use, see copyright notice in license.txt

#include "StableHeaders.h"

#include "DebugOperatorNew.h"

#include "UICanvas.h"
#include "Profiler.h"

#ifndef Q_WS_WIN
#include <QX11Info>
#endif

#include <QCoreApplication>
#include <QPicture>
#include <QGraphicsSceneEvent>
#include <QUuid>
#include <QWidget>
#include <QGraphicsProxyWidget>
#include <QDebug>
#include <Ogre.h>

#include <OgreHardwarePixelBuffer.h>
#include <OgreTexture.h>
#include <OgreMaterial.h>
#include <OgreTextAreaOverlayElement.h>
#include <OgreFontManager.h>
#include <OgrePanelOverlayElement.h>
#include <OgreTextureUnitState.h>

#include "MemoryLeakCheck.h"

namespace QtUI
{

UICanvas::UICanvas(): overlay_(0),
                      container_(0),
                      dirty_(true),
                      surfaceName_(""),
                      mode_(External),
                      id_(QUuid::createUuid().toString()),
                      widgets_(0),
                      locked_(false)

{

    setScene(new QGraphicsScene);
    setViewportUpdateMode(QGraphicsView::FullViewportUpdate);

    QObject::connect(this->scene(),SIGNAL(changed(const QList<QRectF>&)),this,SLOT(Dirty()));
}

UICanvas::UICanvas(Mode mode, const QSize& parentWindowSize): overlay_(0),
                               container_(0),
                               dirty_(true),
                               renderWindowSize_(parentWindowSize),
                               mode_(mode),
                               id_(QUuid::createUuid().toString()),
                               widgets_(0),
                               locked_(false)

{
 setScene(new QGraphicsScene);

 if (mode_ == External)
 {
    // Deal canvas as normal QWidget.
    // Currently do nothing

 }
 else if (mode_ == Internal)
 {
    setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
    QSize size = this->size();

    CreateOgreResources(size.width(), size.height());
    QObject::connect(this->scene(),SIGNAL(changed(const QList<QRectF>&)),this,SLOT(Dirty()));
 }

}

UICanvas::~UICanvas()
{

    for (int i = scene_widgets_.size(); i--;)
    {
        QGraphicsProxyWidget* widget = scene_widgets_.takeAt(i);
        delete widget;

    }

    if (mode_ != External)
    {

      Ogre::TextureManager::getSingleton().remove(surfaceName_.toStdString().c_str());
      QString surfaceMaterial = QString("mat") + id_;
      Ogre::MaterialManager::getSingleton().remove(surfaceMaterial.toStdString().c_str());

      QString containerName = QString("con") + id_;
      Ogre::OverlayManager::getSingleton().destroyOverlayElement(containerName.toStdString().c_str());

      QString overlayName = QString("over") + id_;
      Ogre::OverlayManager::getSingleton().destroy(overlayName.toStdString().c_str());

    }
    container_ = 0;
    overlay_ = 0;

    QGraphicsScene* scene = this->scene();
    delete scene;
    scene = 0;

}

void UICanvas::AddWidget(QWidget* widget)
{

    switch(mode_)
    {
        case Internal:
            {
                  QGraphicsScene* scene = this->scene();
                  scene_widgets_.append(scene->addWidget(widget));
                  ++widgets_;
                  break;
            }
        case External:
            {
              ///todo Here lies a desing flaw do it better, this does not work.
              if ( widgets_ != 0)
               {
                   // Possible memory LEAK !!!
                    QGraphicsScene* scene = this->scene();
                    if(widgets_ == 1)
                    {
                        QWidget* viewport = this->viewport();
                        scene_widgets_.append(scene->addWidget(viewport));
                        scene_widgets_.append(scene->addWidget(widget));
                        setViewport(new QWidget);
                    }
                    else
                        scene_widgets_.append(scene->addWidget(widget));

               }
               else
                   setViewport(widget);

               ++widgets_;

               break;
            }

        default:
            break;
    }
}

void UICanvas::SetPosition(int x, int y)
{
    switch (mode_)
    {
    case External:
        {
            move(x,y);
            break;
        }
    case Internal:
        {
            float relX = x/double(renderWindowSize_.width()), relY = y/double(renderWindowSize_.height());
            container_->setPosition(relX, relY);

            emit RequestArrange();
            dirty_ = true;
            break;
        }

    default:
        break;

    }

}

QPoint UICanvas::MapToCanvas(int x, int y)
{
    if ( mode_ != External)
    {
        x -= container_->getLeft() * renderWindowSize_.width();
        y -= container_->getTop() * renderWindowSize_.height();
    }
     return QPoint(x,y);
}

QPointF UICanvas::GetPosition() const
{
    QPointF position;

    switch(mode_)
    {
        case External:
            {
                position = pos();
                break;
            }
        case Internal:
            {
                double width = container_->getLeft();
                double height = container_->getTop();

                // Calculate position in render window coordinate frame.
                position.rx() = width * renderWindowSize_.width();
                position.ry() = height * renderWindowSize_.height();
                break;

            }

        default:
            break;

    }

    return position;
}

void UICanvas::SetCanvasSize(int width, int height)
{
    //move(0, 0);
    resize(width, height);

    if ( mode_ != External)
    {
        CreateOgreResources(width, height);
        Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(surfaceName_.toStdString().c_str());
        float relWidth = (float)texture->getWidth()/double(renderWindowSize_.width());
        float relHeight = (float)texture->getHeight()/double(renderWindowSize_.height());
        container_->setDimensions(relWidth, relHeight);

    }

    // Repaint canvas.
    dirty_ = true;
    RenderSceneToOgreSurface();
}

void UICanvas::SetRenderWindowSize(const QSize& size)
{

    renderWindowSize_ = size;
    if ( mode_ != External)
    {
        Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(surfaceName_.toStdString().c_str());
        float relWidth = (float)texture->getWidth()/double(renderWindowSize_.width());
        float relHeight = (float)texture->getHeight()/double(renderWindowSize_.height());
        container_->setDimensions(relWidth, relHeight);
        dirty_ = true;
    }
}

void UICanvas::ResizeOgreTexture(int width, int height)
{
    Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(surfaceName_.toStdString().c_str());
    texture->freeInternalResources();
    texture->setWidth(width);
    texture->setHeight(height);
    texture->createInternalResources();
}

void UICanvas::CreateOgreResources(int width, int height)
{
    // If we've already created the resources, just resize the texture to a new size.

    if ( surfaceName_ != "")
    {
        Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(surfaceName_.toStdString().c_str());
        if (width == texture->getWidth() && height == texture->getHeight())
            return;
        ResizeOgreTexture(width, height);
        assert(overlay_);
        assert(container_);
        return;

    }

    QString overlayName = QString("over") + id_;
    overlay_ = Ogre::OverlayManager::getSingleton().create(overlayName.toStdString().c_str());

    QString containerName = QString("con") + id_;
    container_ = static_cast<Ogre::OverlayContainer*>(Ogre::OverlayManager::getSingleton()
                                     .createOverlayElement("Panel", containerName.toStdString().c_str()));

    // This is not done so currently -- tuoki
    // Make the overlay cover 100% of the render window. Note that the UI surface will be
    // rendered pixel perfect without stretching only if the GraphicsView surface dimension
    // matches the render window size.
    //container_->setDimensions(1.0,1.0);

    container_->setPosition(0,0);

    // Add container in default overlay
    overlay_->add2D(container_);

    ///\todo Tell Ogre not to generate a mipmap chain. This texture only needs to have only one
    /// mip level.

    surfaceName_ = QString("tex") + id_;

    Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual(surfaceName_.toStdString().c_str(),
						        Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
						        Ogre::TEX_TYPE_2D, width, height, 0,
						        Ogre::PF_A8R8G8B8, Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE);

    QString surfaceMaterial = QString("mat") + id_;
    Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create(surfaceMaterial.toStdString().c_str(),
						        Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME);

    Ogre::TextureUnitState *state = material->getTechnique(0)->getPass(0)->createTextureUnitState();
    material->getTechnique(0)->getPass(0)->setSceneBlending(Ogre::SBF_SOURCE_ALPHA, Ogre::SBF_ONE_MINUS_SOURCE_ALPHA);
    state->setTextureName(surfaceName_.toStdString().c_str());

    // Generate pixel perfect texture.

    float relWidth = (float)texture->getWidth()/double(renderWindowSize_.width());
    float relHeight = (float)texture->getHeight()/double(renderWindowSize_.height());
    container_->setDimensions(relWidth, relHeight);

    container_->setMaterialName(surfaceMaterial .toStdString().c_str());
    container_->show();
    container_->setEnabled(true);
    container_->setColour(Ogre::ColourValue(1,1,1,1));

    overlay_->show();
}

void UICanvas::Show()
{

    if ( mode_ != External)
    {
        QList<QGraphicsProxyWidget* >::iterator iter = scene_widgets_.begin();
        for (; iter != scene_widgets_.end(); ++iter)
            (*iter)->show();

        container_->show();
        overlay_->show();

        dirty_ = true;
        RenderSceneToOgreSurface();
    }
    else
        show();

}

void UICanvas::Hide()
{

    if ( mode_ != External)
        {
            QList<QGraphicsProxyWidget* >::iterator iter = scene_widgets_.begin();
            for (; iter != scene_widgets_.end(); ++iter)
                (*iter)->hide();

            container_->hide();
            overlay_->hide();
            dirty_ = true;
            RenderSceneToOgreSurface();
        }
    else
        hide();

}

void UICanvas::drawBackground(QPainter *painter, const QRectF &rect)
{
    QBrush black(Qt::transparent);
    painter->fillRect(rect, black);
}

void UICanvas::RenderSceneToOgreSurface()
{

	// Render if and only if scene is dirty.
	if (!dirty_ || mode_ == External)
		return;

    PROFILE(RenderSceneToOgre);

    // We draw the GraphicsView area to an offscreen QPixmap and blit that onto the Ogre GPU surface.
    QPixmap pixmap(this->size());
    {
        PROFILE(FillEmpty);
        pixmap.fill(Qt::transparent);
    }
    assert(pixmap.hasAlphaChannel());
    QImage img = pixmap.toImage();

    QPainter painter(&img);
    QRectF destRect(0, 0, pixmap.width(), pixmap.height());
    QRect sourceRect(0, 0, pixmap.width(), pixmap.height());
    {
        PROFILE(RenderUI);
        this->render(&painter, destRect, sourceRect);
    }
    assert(img.hasAlphaChannel());

    ///\todo Can optimize an extra blit away if we paint directly onto the GPU surface.

    Ogre::Box dimensions(0,0, img.rect().width(), img.rect().height());
    Ogre::PixelBox pixel_box(dimensions, Ogre::PF_A8R8G8B8, (void*)img.bits());
    {
        PROFILE(UIToOgreBlit);
        Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().getByName(surfaceName_.toStdString().c_str());
        texture->getBuffer()->blitFromMemory(pixel_box);
    }

    dirty_ = false;
}

void UICanvas::Render()
{
    RenderSceneToOgreSurface();
}

}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "rPlayer.h"

rPlayer::rPlayer()
{

}

rPlayer::~rPlayer()
{

}

void rPlayer::Frame()
{
	// ((currenttick / endtick) X current_value / end_result
	// Thanks portie

	rEntity::Frame();
}

bool rPlayer::Move(int x, int y)
{
	targetCameraOffsetX += x * 32;
	targetCameraOffsetY += y * 32;
	return rEntity::Move(x,y);
}
<commit_msg>again<commit_after>#include "stdafx.h"
#include "rPlayer.h"

rPlayer::rPlayer()
{

}

rPlayer::~rPlayer()
{

}

void rPlayer::Frame()
{
	// ((currenttick / endtick) X current_value / end_result
	// Thanks portie

	rEntity::Frame();
}

bool rPlayer::Move(int x, int y)
{
	if (rEntity::Move(x, y))
	{
		targetCameraOffsetX += x * 32;
		targetCameraOffsetY += y * 32;
		return true;
	}
	return false;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2010 Couchbase, Inc
 *
 *   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 "config.h"

#include <map>
#include <string>
#include <fcntl.h>

#include "common.h"
#include "couch-kvstore/couch-kvstore.h"
#include "forest-kvstore/forest-kvstore.h"
#include "kvstore.h"
#include "vbucket.h"
#include <platform/dirutils.h>
#include <sys/types.h>
#include <sys/stat.h>

using namespace CouchbaseDirectoryUtilities;

KVStoreConfig::KVStoreConfig(Configuration& config, uint16_t shardid)
    : maxVBuckets(config.getMaxVbuckets()), maxShards(config.getMaxNumShards()),
      dbname(config.getDbname()), backend(config.getBackend()), shardId(shardid) {

}
KVStoreConfig::KVStoreConfig(uint16_t _maxVBuckets, uint16_t _maxShards,
                             std::string& _dbname, std::string& _backend,
                             uint16_t _shardId)
    : maxVBuckets(_maxVBuckets), maxShards(_maxShards), dbname(_dbname),
      backend(_backend), shardId(_shardId) {

}

KVStore *KVStoreFactory::create(KVStoreConfig &config, bool read_only) {
    KVStore *ret = NULL;
    std::string backend = config.getBackend();
    if (backend.compare("couchdb") == 0) {
        ret = new CouchKVStore(config, read_only);
    } else if (backend.compare("forestdb") == 0) {
        ret = new ForestKVStore(config);
    } else {
        LOG(EXTENSION_LOG_WARNING, "Unknown backend: [%s]", backend.c_str());
    }

    return ret;
}

void KVStore::createDataDir(const std::string& dbname) {
    if (!mkdirp(dbname.c_str())) {
        if (errno != EEXIST) {
            std::stringstream ss;
            ss << "Failed to create data directory ["
               << dbname << "]: " << strerror(errno);
            throw std::runtime_error(ss.str());
        }
    }
}

std::string KVStore::updateCachedVBState(uint16_t vbid, const vbucket_state& newState) {

    std::string output;
    vbucket_state *vbState = cachedVBStates[vbid];

    if (vbState != nullptr) {
        //Check if the cached state requires any update
        if (*vbState == newState) {
            return output;
        }

        vbState->state = newState.state;
        vbState->checkpointId = newState.checkpointId;
        vbState->failovers = newState.failovers;

        if (newState.maxDeletedSeqno > 0 &&
                vbState->maxDeletedSeqno < newState.maxDeletedSeqno) {
            vbState->maxDeletedSeqno = newState.maxDeletedSeqno;
        }

        vbState->highSeqno = newState.highSeqno;
        vbState->lastSnapStart = newState.lastSnapStart;
        vbState->lastSnapEnd = newState.lastSnapEnd;
        vbState->maxCas = std::max(vbState->maxCas, newState.maxCas);
        vbState->driftCounter = newState.driftCounter;
    } else {
        cachedVBStates[vbid] = new vbucket_state(newState);
    }

    return newState.toJSON();
}

bool KVStore::snapshotStats(const std::map<std::string,
                            std::string> &stats) {
    if (isReadOnly()) {
        throw std::logic_error("KVStore::snapshotStats: Cannot perform "
                        "on a read-only instance.");
    }

    size_t count = 0;
    size_t size = stats.size();
    std::stringstream stats_buf;
    stats_buf << "{";
    std::map<std::string, std::string>::const_iterator it = stats.begin();
    for (; it != stats.end(); ++it) {
        stats_buf << "\"" << it->first << "\": \"" << it->second << "\"";
        ++count;
        if (count < size) {
            stats_buf << ", ";
        }
    }
    stats_buf << "}";
    std::string dbname = configuration.getDBName();
    std::string next_fname = dbname + "/stats.json.new";

    FILE *new_stats = fopen(next_fname.c_str(), "w");
    if (new_stats == nullptr) {
        LOG(EXTENSION_LOG_NOTICE, "Failed to log the engine stats to "
                "file \"%s\" due to an error \"%s\"; Not critical because new "
                "stats will be dumped later, please ignore.",
            next_fname.c_str(), strerror(errno));
        return false;
    }

    bool rv = true;
    if (fprintf(new_stats, "%s\n", stats_buf.str().c_str()) < 0) {
        LOG(EXTENSION_LOG_NOTICE, "Failed to log the engine stats to "
                "file \"%s\" due to an error \"%s\"; Not critical because new "
                "stats will be dumped later, please ignore.",
            next_fname.c_str(), strerror(errno));
        rv = false;
    }
    fclose(new_stats);

    if (rv) {
        std::string old_fname = dbname + "/stats.json.old";
        std::string stats_fname = dbname + "/stats.json";
        if (access(old_fname.c_str(), F_OK) == 0 && remove(old_fname.c_str()) != 0) {
            LOG(EXTENSION_LOG_WARNING, "Failed to remove '%s': %s",
                old_fname.c_str(), strerror(errno));
            remove(next_fname.c_str());
            rv = false;
        } else if (access(stats_fname.c_str(), F_OK) == 0 &&
                   rename(stats_fname.c_str(), old_fname.c_str()) != 0) {
            LOG(EXTENSION_LOG_WARNING,
                "Failed to rename '%s' to '%s': %s",
                stats_fname.c_str(), old_fname.c_str(), strerror(errno));
            remove(next_fname.c_str());
            rv = false;
        } else if (rename(next_fname.c_str(), stats_fname.c_str()) != 0) {
            LOG(EXTENSION_LOG_WARNING,
                "Failed to rename '%s' to '%s': %s",
                next_fname.c_str(), stats_fname.c_str(), strerror(errno));
            remove(next_fname.c_str());
            rv = false;
        }
    }

    return rv;
}

std::string vbucket_state::toJSON() const {
    std::stringstream jsonState;
    jsonState << "{\"state\": \"" << VBucket::toString(state) << "\""
              << ",\"checkpoint_id\": \"" << checkpointId << "\""
              << ",\"max_deleted_seqno\": \"" << maxDeletedSeqno << "\""
              << ",\"failover_table\": " << failovers
              << ",\"snap_start\": \"" << lastSnapStart << "\""
              << ",\"snap_end\": \"" << lastSnapEnd << "\""
              << ",\"max_cas\": \"" << maxCas << "\""
              << ",\"drift_counter\": \"" << driftCounter << "\""
              << "}";

    return jsonState.str();
}

IORequest::IORequest(uint16_t vbId, MutationRequestCallback &cb , bool del,
                     const std::string &itmKey)
    : vbucketId(vbId), deleteItem(del), key(itmKey) {

    if (del) {
        callback.delCb = cb.delCb;
    } else {
        callback.setCb = cb.setCb;
    }

    start = gethrtime();
}
<commit_msg>Return empty string when necessary, remove otherwise unused variable<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2010 Couchbase, Inc
 *
 *   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 "config.h"

#include <map>
#include <string>
#include <fcntl.h>

#include "common.h"
#include "couch-kvstore/couch-kvstore.h"
#include "forest-kvstore/forest-kvstore.h"
#include "kvstore.h"
#include "vbucket.h"
#include <platform/dirutils.h>
#include <sys/types.h>
#include <sys/stat.h>

using namespace CouchbaseDirectoryUtilities;

KVStoreConfig::KVStoreConfig(Configuration& config, uint16_t shardid)
    : maxVBuckets(config.getMaxVbuckets()), maxShards(config.getMaxNumShards()),
      dbname(config.getDbname()), backend(config.getBackend()), shardId(shardid) {

}
KVStoreConfig::KVStoreConfig(uint16_t _maxVBuckets, uint16_t _maxShards,
                             std::string& _dbname, std::string& _backend,
                             uint16_t _shardId)
    : maxVBuckets(_maxVBuckets), maxShards(_maxShards), dbname(_dbname),
      backend(_backend), shardId(_shardId) {

}

KVStore *KVStoreFactory::create(KVStoreConfig &config, bool read_only) {
    KVStore *ret = NULL;
    std::string backend = config.getBackend();
    if (backend.compare("couchdb") == 0) {
        ret = new CouchKVStore(config, read_only);
    } else if (backend.compare("forestdb") == 0) {
        ret = new ForestKVStore(config);
    } else {
        LOG(EXTENSION_LOG_WARNING, "Unknown backend: [%s]", backend.c_str());
    }

    return ret;
}

void KVStore::createDataDir(const std::string& dbname) {
    if (!mkdirp(dbname.c_str())) {
        if (errno != EEXIST) {
            std::stringstream ss;
            ss << "Failed to create data directory ["
               << dbname << "]: " << strerror(errno);
            throw std::runtime_error(ss.str());
        }
    }
}

std::string KVStore::updateCachedVBState(uint16_t vbid, const vbucket_state& newState) {

    vbucket_state *vbState = cachedVBStates[vbid];

    if (vbState != nullptr) {
        //Check if the cached state requires any update
        if (*vbState == newState) {
            return std::string();
        }

        vbState->state = newState.state;
        vbState->checkpointId = newState.checkpointId;
        vbState->failovers = newState.failovers;

        if (newState.maxDeletedSeqno > 0 &&
                vbState->maxDeletedSeqno < newState.maxDeletedSeqno) {
            vbState->maxDeletedSeqno = newState.maxDeletedSeqno;
        }

        vbState->highSeqno = newState.highSeqno;
        vbState->lastSnapStart = newState.lastSnapStart;
        vbState->lastSnapEnd = newState.lastSnapEnd;
        vbState->maxCas = std::max(vbState->maxCas, newState.maxCas);
        vbState->driftCounter = newState.driftCounter;
    } else {
        cachedVBStates[vbid] = new vbucket_state(newState);
    }

    return newState.toJSON();
}

bool KVStore::snapshotStats(const std::map<std::string,
                            std::string> &stats) {
    if (isReadOnly()) {
        throw std::logic_error("KVStore::snapshotStats: Cannot perform "
                        "on a read-only instance.");
    }

    size_t count = 0;
    size_t size = stats.size();
    std::stringstream stats_buf;
    stats_buf << "{";
    std::map<std::string, std::string>::const_iterator it = stats.begin();
    for (; it != stats.end(); ++it) {
        stats_buf << "\"" << it->first << "\": \"" << it->second << "\"";
        ++count;
        if (count < size) {
            stats_buf << ", ";
        }
    }
    stats_buf << "}";
    std::string dbname = configuration.getDBName();
    std::string next_fname = dbname + "/stats.json.new";

    FILE *new_stats = fopen(next_fname.c_str(), "w");
    if (new_stats == nullptr) {
        LOG(EXTENSION_LOG_NOTICE, "Failed to log the engine stats to "
                "file \"%s\" due to an error \"%s\"; Not critical because new "
                "stats will be dumped later, please ignore.",
            next_fname.c_str(), strerror(errno));
        return false;
    }

    bool rv = true;
    if (fprintf(new_stats, "%s\n", stats_buf.str().c_str()) < 0) {
        LOG(EXTENSION_LOG_NOTICE, "Failed to log the engine stats to "
                "file \"%s\" due to an error \"%s\"; Not critical because new "
                "stats will be dumped later, please ignore.",
            next_fname.c_str(), strerror(errno));
        rv = false;
    }
    fclose(new_stats);

    if (rv) {
        std::string old_fname = dbname + "/stats.json.old";
        std::string stats_fname = dbname + "/stats.json";
        if (access(old_fname.c_str(), F_OK) == 0 && remove(old_fname.c_str()) != 0) {
            LOG(EXTENSION_LOG_WARNING, "Failed to remove '%s': %s",
                old_fname.c_str(), strerror(errno));
            remove(next_fname.c_str());
            rv = false;
        } else if (access(stats_fname.c_str(), F_OK) == 0 &&
                   rename(stats_fname.c_str(), old_fname.c_str()) != 0) {
            LOG(EXTENSION_LOG_WARNING,
                "Failed to rename '%s' to '%s': %s",
                stats_fname.c_str(), old_fname.c_str(), strerror(errno));
            remove(next_fname.c_str());
            rv = false;
        } else if (rename(next_fname.c_str(), stats_fname.c_str()) != 0) {
            LOG(EXTENSION_LOG_WARNING,
                "Failed to rename '%s' to '%s': %s",
                next_fname.c_str(), stats_fname.c_str(), strerror(errno));
            remove(next_fname.c_str());
            rv = false;
        }
    }

    return rv;
}

std::string vbucket_state::toJSON() const {
    std::stringstream jsonState;
    jsonState << "{\"state\": \"" << VBucket::toString(state) << "\""
              << ",\"checkpoint_id\": \"" << checkpointId << "\""
              << ",\"max_deleted_seqno\": \"" << maxDeletedSeqno << "\""
              << ",\"failover_table\": " << failovers
              << ",\"snap_start\": \"" << lastSnapStart << "\""
              << ",\"snap_end\": \"" << lastSnapEnd << "\""
              << ",\"max_cas\": \"" << maxCas << "\""
              << ",\"drift_counter\": \"" << driftCounter << "\""
              << "}";

    return jsonState.str();
}

IORequest::IORequest(uint16_t vbId, MutationRequestCallback &cb , bool del,
                     const std::string &itmKey)
    : vbucketId(vbId), deleteItem(del), key(itmKey) {

    if (del) {
        callback.delCb = cb.delCb;
    } else {
        callback.setCb = cb.setCb;
    }

    start = gethrtime();
}
<|endoftext|>