<commit_before>/*********************************************************************************
- Contact:    Michal Broz     Michal.Broz@cern.ch
- Link:       http
- Raw data test file :
- Reference run number :
- Run Type:   PHYSICS
- DA Type:    MON
- Number of events needed: >=50000
- Input Files:  argument list
- Output Files: FXS file  AD0_SlewingSplines.root (Offline mapping)
- Trigger types used: PHYSICS_EVENT
**********************************************************************************/

/**********************************************************************************
*                                                                                *
* AD Detector Algorithm used for extracting time slewing splines                  *
*                                                                                *
* This program connects to the DAQ data source passed as argument.                *
* It reads calibration parameters, from DAQ_DB "AD0_Pedestals_On.dat"   	  *
* file, Compute 16 TSplines, place it to a root file in TList. 			  *
* File is stored in FXS.                          				  *
* The program exits when being asked to shut down (daqDA_checkshutdown)           *
* or on End of Run event.                                                         *
* Runs in monitoring mode, the splines needs solid statistics, so it asks 	  *
* for rather high number of events to be processed.				  *
*                                                                                *
***********************************************************************************/

// DATE
#include "event.h"
#include "monitor.h"
#include "daqDA.h"

//AliRoot
#include <AliADConst.h>
#include <AliADRawStream.h>
#include <AliRawReaderDate.h>
#include <AliRawReader.h>
#include <AliDAQ.h>

// standard
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <string>

//ROOT
#include "TROOT.h"
#include "TPluginManager.h"
#include <TFile.h>
#include <TString.h>
#include <TH1F.h>
#include <TH1D.h>
#include <TH2F.h>
#include <TSpline.h>
#include <TF1.h>
#include <TList.h>
#include <TMath.h>

/* Main routine --- Arguments: monitoring data source */

int main(int argc, char **argv) {

/* magic line from Cvetan */
  gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo","*","TStreamerInfo","RIO","TStreamerInfo()");

  int status;
  if (argc!=2) {
     printf("Wrong number of arguments\n");
     return -1;
  }

//___________________________________________________
// Get cuts from AD0_Pedestal_DA.config file
  Int_t    kMinEvents; //Minimal number of events requested to make splines
  Int_t    kNPreClocks; //Pre-clocks for charge integration
  Int_t    kNPostClocks; //Post-clocks for charge integration
  Int_t    kNPedSigma; //Cut on pedestal number of sigmas
  Int_t	   kNBinsCharge; //Number of bins in charge distribution

  status = daqDA_DB_getFile("AD0_TimeSlewing_DA.config","AD0_TimeSlewing_DA.config");
  if (status) {
      printf("Failed to get Config file AD0_TimeSlewing_DA.config from DAQ DB, status=%d\n", status);
      printf("Take default values of parameters for pedestal calculation \n");
       kMinEvents = 50000;
       kNPreClocks = 1;
       kNPostClocks = 10;
       kNPedSigma = 3;
       kNBinsCharge = 1000;
  } else {
      /* open the config file and retrieve cuts */
      FILE *fpConfig = fopen("AD0_TimeSlewing_DA.config","r");
      int res = fscanf(fpConfig,"%d %d %d %d %d",&kMinEvents,&kNPreClocks,&kNPostClocks,&kNPedSigma,&kNBinsCharge);
      if(res!=5) {
	    printf("Failed to get values from Config file (AD0_TimeSlewing_DA.config): wrong file format - 4 integers are expected - \n");
       	    kMinEvents = 50000;
            kNPreClocks = 1;
            kNPostClocks = 10;
            kNPedSigma = 3;
	    kNBinsCharge = 1000;
      }
      fclose(fpConfig);
  }
  printf("Minimal number of events requested = %d; Integrating charge in [-%d + %d] LHC clocks around maximum; Number of pedestal sigma cut = %d; Number of bins on charge axis = %d\n",
          kMinEvents, kNPreClocks, kNPostClocks, kNPedSigma, kNBinsCharge);

  // Online pedestals (using FEE channel numbering),
  // from DAQ_DB AD0_Pedestals_On.dat:
  Float_t adcMean[32];
  Float_t adcSigma[32];
  Float_t pedMean[32];
  Float_t pedSigma[32];

  status = daqDA_DB_getFile("AD0_Pedestals_On.dat","AD0_Pedestals_On.dat");
  if (status) {
      printf("Failed to get AD0_Pedestals_On.dat from DAQ DB, status=%d\n", status);
      printf("Take default pedestals \n");
      for(Int_t j=0; j<32; j++) {pedMean[j] = 0; pedSigma[j] = 0.1;}

  } else {
      /* open the pedestal file and retrieve values */
      FILE *fpPedestals = fopen("AD0_Pedestals_On.dat","r");
      for(Int_t j=0; j<32; j++) {
	  Int_t res = fscanf(fpPedestals,"%f %f %f %f",&pedMean[j], &pedSigma[j], &adcMean[j], &adcSigma[j]);
	  if (res != 4) printf("Failed to get values from file: wrong file format - 4 floats are expected - \n");
		}
      fclose(fpPedestals);
  }
  printf("Used pedestals:\n");
  for(Int_t iChannel = 0; iChannel < 16; ++iChannel) {
    	for(Int_t integrator = 0; integrator < 2; ++integrator){
    		if(integrator == 0)printf("ChOn = %d, Int = %d, Pedestal = %.3f, Width = %3f,", iChannel,integrator, pedMean[iChannel+16*integrator],pedSigma[iChannel+16*integrator]);
		else printf(" Int = %d, Pedestal = %.3f, Width = %3f\n", integrator, pedMean[iChannel+16*integrator],pedSigma[iChannel+16*integrator]);
			}
		}

//___________________________________________________
// Book HISTOGRAMS - dynamics of p-p collisions -

  char     TimeVsChargeName[20];
  TH2F     *hTimeVsCharge[16];

  char  texte[20];
  for (Int_t i=0; i<16; i++) {
       	sprintf(TimeVsChargeName,"hTimeVsCharge%d",i);
       	sprintf(texte,"hTimeVsCharge ch%d",i);
       	hTimeVsCharge[i]  = new TH2F(TimeVsChargeName,texte,kNBinsCharge,-4,0,4000,1,4001);
        }

//___________________________________________________

  /* define data source : this is argument 1 */
  status=monitorSetDataSource( argv[1] );
  if (status!=0) {
     printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
     return -1;
  }

  /* declare monitoring program */
  status=monitorDeclareMp( __FILE__ );
  if (status!=0) {
    printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* define wait event timeout - 1s max */
  monitorSetNowait();
  monitorSetNoWaitNetworkTimeout(1000);

  /* init counters on events */
  int neventsPhysics=0;
  int neventsTotal=0;

  /* loop on events (infinite) */
  for(;;) {
      struct eventHeaderStruct *event;
      eventTypeType eventT;

      /* check shutdown condition */
      if (daqDA_checkShutdown()) {break;}

      /* get next event (blocking call until timeout) */
      status=monitorGetEventDynamic((void **)&event);
      if (status==MON_ERR_EOF) {
          printf ("End of File detected\n");
      break; /* end of monitoring file has been reached */
      }

      if (status!=0) {
           printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
      break;
      }

      /* retry if got no event */
      if (event==NULL) continue;

      /* decode event */
      eventT=event->eventType;

      switch (event->eventType){

      case START_OF_RUN:
           break;

      case END_OF_RUN:
           printf("End Of Run detected\n");
           break;

      case PHYSICS_EVENT:
           neventsPhysics++;

	   AliRawReader *rawReader = new AliRawReaderDate((void*)event);

	   AliADRawStream* rawStream  = new AliADRawStream(rawReader);
	   if (rawStream->Next()) {

	   Float_t adc[16], time[16];
           for(Int_t iChannel=0; iChannel<16; iChannel++) {
	   	time[iChannel] = rawStream->GetTime(iChannel);
	   	Float_t maxadc = 0;
      		Int_t imax = -1;
     		Float_t adcPedSub[21];
      		for(Int_t iClock=0; iClock<21; iClock++){
			Bool_t iIntegrator = rawStream->GetIntegratorFlag(iChannel,iClock);
			Int_t k = iChannel+16*iIntegrator;

			adcPedSub[iClock] = rawStream->GetPedestal(iChannel,iClock) - pedMean[k];
			if(adcPedSub[iClock] <= kNPedSigma*pedSigma[k]) {
	  			adcPedSub[iClock] = 0;
	  			continue;
				}
			if(adcPedSub[iClock] > maxadc) {
	 			maxadc = adcPedSub[iClock];
	  			imax   = iClock;
				}
      			}
        	if (imax != -1) {
			Int_t start = imax - kNPreClocks;
			if (start < 0) start = 0;
			Int_t end = imax + kNPostClocks;
			if (end > 20) end = 20;
			for(Int_t iClock = start; iClock <= end; iClock++) adc[iChannel] += adcPedSub[iClock];
			}
		else adc[iChannel] = 0.1;
		hTimeVsCharge[iChannel]->Fill(TMath::Log10(1/adc[iChannel]),time[iChannel]);

    	        } // End loop over channels
	   }   // End : if rawstream
           delete rawStream;
           rawStream = 0x0;
           delete rawReader;
           rawReader = 0x0;
      } // end of switch on event type

      neventsTotal++;
      /* free resources */
      free(event);

      /* exit when last event received, no need to wait for TERM signal */
      if (eventT==END_OF_RUN) {
           printf("End Of Run event detected\n");
      break;
    }
  }  // loop over events

  printf("%d physics events processed\n",neventsPhysics);
  if(neventsPhysics < kMinEvents){
  	printf("Number of events too low to evaluate time slewing splines, exiting\n");
	return status;
  	}
//___________________________________________________________________________
//  Computes mean values, converts FEE channels into Offline AliRoot channels
//  and dumps the ordered values into the output text file for SHUTTLE

  TH1D *hTimeSlice = 0x0;
  TH1F *hMeanTimeVsCharge[16];

  for(Int_t i=0; i<16; i++){
	TString MeanTimeVsChargeName = "hMeanTimeVsCharge";
	MeanTimeVsChargeName += i;
	hMeanTimeVsCharge[i] = new TH1F(MeanTimeVsChargeName.Data(),MeanTimeVsChargeName.Data(),kNBinsCharge,-4,0);
	hMeanTimeVsCharge[i]->GetXaxis()->SetTitle("Log10(1/charge) [ADC counts]");
	hMeanTimeVsCharge[i]->GetYaxis()->SetTitle("Mean leading time [TDC counts]");

	for(Int_t j=0; j<kNBinsCharge;j++){
  		hTimeSlice = hTimeVsCharge[i]->ProjectionY("hTimeSlice",j+1,j+1);
		hMeanTimeVsCharge[i]->SetBinContent(j+1,hTimeSlice->GetMean());
        	if(hTimeSlice->GetEntries()>0)hMeanTimeVsCharge[i]->SetBinError(j+1,1/TMath::Power(hTimeSlice->GetEntries(),2));
  		}
	}

  TSpline3 *fTimeSlewingSpline[16];
  for(Int_t i=0; i<16; i++){
  	Int_t offlineChannel = kOfflineChannel[i];
	TString TimeSlewingSplineName = "hTimeSlewingSpline";
	TimeSlewingSplineName += offlineChannel;
	fTimeSlewingSpline[offlineChannel] = new TSpline3(hMeanTimeVsCharge[i]);
	fTimeSlewingSpline[offlineChannel]->SetName(TimeSlewingSplineName.Data());
	}
  /*/
  TF1 *fTimeSlewingFit[16];
  for(Int_t i=0; i<16; i++){
	TString TimeSlewingFitName = "hTimeSlewingFit";
	TimeSlewingFitName += i;
	fTimeSlewingFit[i] = new TF1(TimeSlewingFitName.Data(),"[0]+[1]*x^[2]+((x<0.04)?0:[3]*(x-0.04)+[4]*(x-0.04)^2+[5]*(x-0.04)^3)",1,4000);
	fTimeSlewingFit[i]->SetParameter(0,650);
	fTimeSlewingFit[i]->SetParameter(1,40);
	fTimeSlewingFit[i]->SetParameter(2,-0.5);
	fTimeSlewingFit[i]->SetLineColor(kMagenta);
	hMeanTimeVsCharge[i]->Fit(TimeSlewingFitName.Data(),"R0");
	}
  /*/

//________________________________________________________________________
// Write root file with splines

  TList *fListSplines = new TList();

  TFile *splineFile = new TFile("AD0_SlewingSplines.root","RECREATE");
  for(Int_t i=0; i<16; i++) fListSplines->Add(fTimeSlewingSpline[i]);
  fListSplines->Write("fListSplines",1);
  splineFile->Close();

//________________________________________________________________________

  /* export result file to FES */
  status=daqDA_FES_storeFile("AD0_SlewingSplines.root","AD0da_slewing");
  if (status)    {
      printf("Failed to export file : %d\n",status);
      return -1; }

  return status;
}

<commit_msg>DA bug fix<commit_after>/*********************************************************************************
- Contact:    Michal Broz     Michal.Broz@cern.ch
- Link:       http
- Raw data test file :
- Reference run number :
- Run Type:   PHYSICS
- DA Type:    MON
- Number of events needed: >=50000
- Input Files:  argument list
- Output Files: FXS file  AD0_SlewingSplines.root (Offline mapping)
- Trigger types used: PHYSICS_EVENT
**********************************************************************************/

/**********************************************************************************
*                                                                                *
* AD Detector Algorithm used for extracting time slewing splines                  *
*                                                                                *
* This program connects to the DAQ data source passed as argument.                *
* It reads calibration parameters, from DAQ_DB "AD0_Pedestals_On.dat"   	  *
* file, Compute 16 TSplines, place it to a root file in TList. 			  *
* File is stored in FXS.                          				  *
* The program exits when being asked to shut down (daqDA_checkshutdown)           *
* or on End of Run event.                                                         *
* Runs in monitoring mode, the splines needs solid statistics, so it asks 	  *
* for rather high number of events to be processed.				  *
*                                                                                *
***********************************************************************************/

// DATE
#include "event.h"
#include "monitor.h"
#include "daqDA.h"

//AliRoot
#include <AliADConst.h>
#include <AliADRawStream.h>
#include <AliRawReaderDate.h>
#include <AliRawReader.h>
#include <AliDAQ.h>

// standard
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <string>

//ROOT
#include "TROOT.h"
#include "TPluginManager.h"
#include <TFile.h>
#include <TString.h>
#include <TH1F.h>
#include <TH1D.h>
#include <TH2F.h>
#include <TSpline.h>
#include <TF1.h>
#include <TList.h>
#include <TMath.h>

/* Main routine --- Arguments: monitoring data source */

int main(int argc, char **argv) {

/* magic line from Cvetan */
  gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo","*","TStreamerInfo","RIO","TStreamerInfo()");

  int status;
  if (argc!=2) {
     printf("Wrong number of arguments\n");
     return -1;
  }

//___________________________________________________
// Get cuts from AD0_Pedestal_DA.config file
  Int_t    kMinEvents; //Minimal number of events requested to make splines
  Int_t    kNPreClocks; //Pre-clocks for charge integration
  Int_t    kNPostClocks; //Post-clocks for charge integration
  Int_t    kNPedSigma; //Cut on pedestal number of sigmas
  Int_t	   kNBinsCharge; //Number of bins in charge distribution

  status = daqDA_DB_getFile("AD0_TimeSlewing_DA.config","AD0_TimeSlewing_DA.config");
  if (status) {
      printf("Failed to get Config file AD0_TimeSlewing_DA.config from DAQ DB, status=%d\n", status);
      printf("Take default values of parameters for pedestal calculation \n");
       kMinEvents = 50000;
       kNPreClocks = 1;
       kNPostClocks = 10;
       kNPedSigma = 3;
       kNBinsCharge = 1000;
  } else {
      /* open the config file and retrieve cuts */
      FILE *fpConfig = fopen("AD0_TimeSlewing_DA.config","r");
      int res = fscanf(fpConfig,"%d %d %d %d %d",&kMinEvents,&kNPreClocks,&kNPostClocks,&kNPedSigma,&kNBinsCharge);
      if(res!=5) {
	    printf("Failed to get values from Config file (AD0_TimeSlewing_DA.config): wrong file format - 4 integers are expected - \n");
       	    kMinEvents = 50000;
            kNPreClocks = 1;
            kNPostClocks = 10;
            kNPedSigma = 3;
	    kNBinsCharge = 1000;
      }
      fclose(fpConfig);
  }
  printf("Minimal number of events requested = %d; Integrating charge in [-%d + %d] LHC clocks around maximum; Number of pedestal sigma cut = %d; Number of bins on charge axis = %d\n",
          kMinEvents, kNPreClocks, kNPostClocks, kNPedSigma, kNBinsCharge);

  // Online pedestals (using FEE channel numbering),
  // from DAQ_DB AD0_Pedestals_On.dat:
  Float_t adcMean[32];
  Float_t adcSigma[32];
  Float_t pedMean[32];
  Float_t pedSigma[32];

  status = daqDA_DB_getFile("AD0_Pedestals_On.dat","AD0_Pedestals_On.dat");
  if (status) {
      printf("Failed to get AD0_Pedestals_On.dat from DAQ DB, status=%d\n", status);
      printf("Take default pedestals \n");
      for(Int_t j=0; j<32; j++) {pedMean[j] = 0; pedSigma[j] = 0.1;}

  } else {
      /* open the pedestal file and retrieve values */
      FILE *fpPedestals = fopen("AD0_Pedestals_On.dat","r");
      for(Int_t j=0; j<32; j++) {
	  Int_t res = fscanf(fpPedestals,"%f %f %f %f",&pedMean[j], &pedSigma[j], &adcMean[j], &adcSigma[j]);
	  if (res != 4) printf("Failed to get values from file: wrong file format - 4 floats are expected - \n");
		}
      fclose(fpPedestals);
  }
  printf("Used pedestals:\n");
  for(Int_t iChannel = 0; iChannel < 16; ++iChannel) {
    	for(Int_t integrator = 0; integrator < 2; ++integrator){
    		if(integrator == 0)printf("ChOn = %d, Int = %d, Pedestal = %.3f, Width = %3f,", iChannel,integrator, pedMean[iChannel+16*integrator],pedSigma[iChannel+16*integrator]);
		else printf(" Int = %d, Pedestal = %.3f, Width = %3f\n", integrator, pedMean[iChannel+16*integrator],pedSigma[iChannel+16*integrator]);
			}
		}

//___________________________________________________
// Book HISTOGRAMS - dynamics of p-p collisions -

  char     TimeVsChargeName[20];
  TH2F     *hTimeVsCharge[16];

  char  texte[20];
  for (Int_t i=0; i<16; i++) {
       	sprintf(TimeVsChargeName,"hTimeVsCharge%d",i);
       	sprintf(texte,"hTimeVsCharge ch%d",i);
       	hTimeVsCharge[i]  = new TH2F(TimeVsChargeName,texte,kNBinsCharge,-4,0,4000,1,4001);
        }

//___________________________________________________

  /* define data source : this is argument 1 */
  status=monitorSetDataSource( argv[1] );
  if (status!=0) {
     printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
     return -1;
  }

  /* declare monitoring program */
  status=monitorDeclareMp( __FILE__ );
  if (status!=0) {
    printf("monitorDeclareMp() failed : %s\n",monitorDecodeError(status));
    return -1;
  }

  /* define wait event timeout - 1s max */
  monitorSetNowait();
  monitorSetNoWaitNetworkTimeout(1000);

  /* init counters on events */
  int neventsPhysics=0;
  int neventsTotal=0;

  /* loop on events (infinite) */
  for(;;) {
      struct eventHeaderStruct *event;
      eventTypeType eventT;

      /* check shutdown condition */
      if (daqDA_checkShutdown()) {break;}

      /* get next event (blocking call until timeout) */
      status=monitorGetEventDynamic((void **)&event);
      if (status==MON_ERR_EOF) {
          printf ("End of File detected\n");
      break; /* end of monitoring file has been reached */
      }

      if (status!=0) {
           printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
      break;
      }

      /* retry if got no event */
      if (event==NULL) continue;

      /* decode event */
      eventT=event->eventType;

      switch (event->eventType){

      case START_OF_RUN:
           break;

      case END_OF_RUN:
           printf("End Of Run detected\n");
           break;

      case PHYSICS_EVENT:
           neventsPhysics++;

	   AliRawReader *rawReader = new AliRawReaderDate((void*)event);

	   AliADRawStream* rawStream  = new AliADRawStream(rawReader);
	   if (rawStream->Next()) {

	   Float_t adc[16], time[16];
           for(Int_t iChannel=0; iChannel<16; iChannel++) {
	   	adc[iChannel] = 0.0;
	   	time[iChannel] = rawStream->GetTime(iChannel);
	   	Float_t maxadc = 0;
      		Int_t imax = -1;
     		Float_t adcPedSub[21];
      		for(Int_t iClock=0; iClock<21; iClock++){
			Bool_t iIntegrator = rawStream->GetIntegratorFlag(iChannel,iClock);
			Int_t k = iChannel+16*iIntegrator;

			adcPedSub[iClock] = rawStream->GetPedestal(iChannel,iClock) - pedMean[k];
			if(adcPedSub[iClock] <= kNPedSigma*pedSigma[k]) {
	  			adcPedSub[iClock] = 0;
	  			continue;
				}
			if(adcPedSub[iClock] > maxadc) {
	 			maxadc = adcPedSub[iClock];
	  			imax   = iClock;
				}
      			}
        	if (imax != -1) {
			Int_t start = imax - kNPreClocks;
			if (start < 0) start = 0;
			Int_t end = imax + kNPostClocks;
			if (end > 20) end = 20;
			for(Int_t iClock = start; iClock <= end; iClock++) adc[iChannel] += adcPedSub[iClock];
			}
		else adc[iChannel] = 0.1;
		hTimeVsCharge[iChannel]->Fill(TMath::Log10(1/adc[iChannel]),time[iChannel]);

    	        } // End loop over channels
	   }   // End : if rawstream
           delete rawStream;
           rawStream = 0x0;
           delete rawReader;
           rawReader = 0x0;
      } // end of switch on event type

      neventsTotal++;
      /* free resources */
      free(event);

      /* exit when last event received, no need to wait for TERM signal */
      if (eventT==END_OF_RUN) {
           printf("End Of Run event detected\n");
      break;
    }
  }  // loop over events

  printf("%d physics events processed\n",neventsPhysics);
  if(neventsPhysics < kMinEvents){
  	printf("Number of events too low to evaluate time slewing splines, exiting\n");
	return status;
  	}
//___________________________________________________________________________
//  Computes mean values, converts FEE channels into Offline AliRoot channels
//  and dumps the ordered values into the output text file for SHUTTLE

  TH1D *hTimeSlice = 0x0;
  TH1F *hMeanTimeVsCharge[16];

  for(Int_t i=0; i<16; i++){
	TString MeanTimeVsChargeName = "hMeanTimeVsCharge";
	MeanTimeVsChargeName += kOfflineChannel[i];
	hMeanTimeVsCharge[i] = new TH1F(MeanTimeVsChargeName.Data(),MeanTimeVsChargeName.Data(),kNBinsCharge,-4,0);
	hMeanTimeVsCharge[i]->GetXaxis()->SetTitle("Log10(1/charge) [ADC counts]");
	hMeanTimeVsCharge[i]->GetYaxis()->SetTitle("Mean leading time [TDC counts]");

	for(Int_t j=0; j<kNBinsCharge;j++){
  		hTimeSlice = hTimeVsCharge[i]->ProjectionY("hTimeSlice",j+1,j+1);
		hMeanTimeVsCharge[i]->SetBinContent(j+1,hTimeSlice->GetMean());
        	if(hTimeSlice->GetEntries()>0)hMeanTimeVsCharge[i]->SetBinError(j+1,1/TMath::Power(hTimeSlice->GetEntries(),2));
  		}
	}

  TSpline3 *fTimeSlewingSpline[16];
  for(Int_t i=0; i<16; i++){
  	Int_t offlineChannel = kOfflineChannel[i];
	TString TimeSlewingSplineName = "hTimeSlewingSpline";
	TimeSlewingSplineName += offlineChannel;
	fTimeSlewingSpline[offlineChannel] = new TSpline3(hMeanTimeVsCharge[i]);
	fTimeSlewingSpline[offlineChannel]->SetName(TimeSlewingSplineName.Data());
	}
  /*/
  TF1 *fTimeSlewingFit[16];
  for(Int_t i=0; i<16; i++){
	TString TimeSlewingFitName = "hTimeSlewingFit";
	TimeSlewingFitName += i;
	fTimeSlewingFit[i] = new TF1(TimeSlewingFitName.Data(),"[0]+[1]*x^[2]+((x<0.04)?0:[3]*(x-0.04)+[4]*(x-0.04)^2+[5]*(x-0.04)^3)",1,4000);
	fTimeSlewingFit[i]->SetParameter(0,650);
	fTimeSlewingFit[i]->SetParameter(1,40);
	fTimeSlewingFit[i]->SetParameter(2,-0.5);
	fTimeSlewingFit[i]->SetLineColor(kMagenta);
	hMeanTimeVsCharge[i]->Fit(TimeSlewingFitName.Data(),"R0");
	}
  /*/

//________________________________________________________________________
// Write root file with splines

  TList *fListSplines = new TList();

  TFile *splineFile = new TFile("AD0_SlewingSplines.root","RECREATE");
  for(Int_t i=0; i<16; i++) fListSplines->Add(fTimeSlewingSpline[i]);
  fListSplines->Write("fListSplines",1);
  splineFile->Close();

//________________________________________________________________________

  /* export result file to FES */
  status=daqDA_FES_storeFile("AD0_SlewingSplines.root","AD0da_slewing");
  if (status)    {
      printf("Failed to export file : %d\n",status);
      return -1; }

  return status;
}

<|endoftext|>


<commit_before>// Copyright 2020 Google LLC
//
// 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 "p4_pdpi/util.h"

#include <google/protobuf/descriptor.h>

#include <algorithm>

#include "absl/algorithm/container.h"
#include "absl/strings/ascii.h"
#include "absl/strings/escaping.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_replace.h"
#include "absl/types/optional.h"

namespace pdpi {

using ::pdpi::ir::Format;
using ::pdpi::ir::IrValue;

absl::Status ReadProtoFromFile(const std::string &filename,
                               google::protobuf::Message *message) {
  // Verifies that the version of the library that we linked against is
  // compatible with the version of the headers we compiled against.
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  int fd = open(filename.c_str(), O_RDONLY);
  if (fd < 0) {
    return InvalidArgumentErrorBuilder()
           << "Error opening the file " << filename << ".";
  }

  google::protobuf::io::FileInputStream file_stream(fd);
  file_stream.SetCloseOnDelete(true);

  if (!google::protobuf::TextFormat::Parse(&file_stream, message)) {
    return InvalidArgumentErrorBuilder()
           << "Failed to parse file " << filename << ".";
  }

  return absl::OkStatus();
}

absl::Status ReadProtoFromString(const std::string &proto_string,
                                 google::protobuf::Message *message) {
  // Verifies that the version of the library that we linked against is
  // compatible with the version of the headers we compiled against.
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  if (!google::protobuf::TextFormat::ParseFromString(proto_string, message)) {
    return InvalidArgumentErrorBuilder()
           << "Failed to parse string " << proto_string << ".";
  }

  return absl::OkStatus();
}

StatusOr<std::string> Normalize(const std::string &pi_byte_string,
                                int expected_bitwidth) {
  std::string stripped_value = pi_byte_string;
  // Remove leading zeros
  stripped_value.erase(0, std::min(stripped_value.find_first_not_of('\x00'),
                                   stripped_value.size() - 1));
  int length = GetBitwidthOfPiByteString(stripped_value);
  if (length > expected_bitwidth) {
    return InvalidArgumentErrorBuilder()
           << "Value of length " << length << " is greater than bitwidth "
           << expected_bitwidth;
  }

  int total_bytes;
  if (expected_bitwidth % 8) {
    total_bytes = expected_bitwidth / 8 + 1;
  } else {
    total_bytes = expected_bitwidth / 8;
  }
  std::string zeros =
      std::string(total_bytes - stripped_value.length(), '\x00');
  return zeros.append(stripped_value);
}

StatusOr<uint64_t> PiByteStringToUint(const std::string &pi_bytes,
                                      int bitwidth) {
  if (bitwidth > 64) {
    return absl::Status(absl::StatusCode::kInternal,
                        absl::StrCat("Cannot convert value with "
                                     "bitwidth ",
                                     bitwidth, " to uint."));
  }
  ASSIGN_OR_RETURN(const auto &stripped_value, Normalize(pi_bytes, bitwidth));
  uint64_t nb_value;  // network byte order
  char value[sizeof(nb_value)];
  int pad = sizeof(nb_value) - stripped_value.size();
  if (pad) {
    memset(value, 0, pad);
  }
  memcpy(value + pad, stripped_value.data(), stripped_value.size());
  memcpy(&nb_value, value, sizeof(nb_value));

  return be64toh(nb_value);
}

std::string PiByteStringToMac(const std::string &normalized_bytes) {
  std::vector<std::string> parts;
  for (const char c : normalized_bytes) {
    parts.push_back(absl::StrCat(absl::Hex(int{c & 0xFF}, absl::kZeroPad2)));
  }
  return absl::StrJoin(parts, ":");
}

std::string PiByteStringToIpv4(const std::string &normalized_bytes) {
  std::vector<std::string> parts;
  for (const char c : normalized_bytes) {
    parts.push_back(absl::StrCat(absl::Hex((int)c)));
  }
  return absl::StrJoin(parts, ".");
}

std::string PiByteStringToIpv6(const std::string &normalized_bytes) {
  // TODO: Find a way to store in shorthand IPv6 notation
  std::vector<std::string> parts;
  for (unsigned int i = 0; i < kNumBytesInIpv6; i += 2) {
    parts.push_back(
        absl::StrCat(absl::Hex((int)normalized_bytes[i], absl::kZeroPad2),
                     absl::Hex((int)normalized_bytes[i + 1], absl::kZeroPad2)));
  }
  return absl::StrJoin(parts, ":");
}

// Based off
// https://github.com/googleapis/gapic-generator-cpp/blob/master/generator/internal/gapic_utils.cc
std::string CamelCaseToSnakeCase(const std::string &input) {
  std::string output;
  for (auto i = 0u; i < input.size(); ++i) {
    if (i + 2 < input.size()) {
      if (std::isupper(input[i + 1]) && std::islower(input[i + 2])) {
        absl::StrAppend(&output, std::string(1, std::tolower(input[i])), "_");
        continue;
      }
    }
    if (i + 1 < input.size()) {
      if ((std::islower(input[i]) || std::isdigit(input[i])) &&
          std::isupper(input[i + 1])) {
        absl::StrAppend(&output, std::string(1, std::tolower(input[i])), "_");
        continue;
      }
    }
    absl::StrAppend(&output, std::string(1, std::tolower(input[i])));
  }
  return output;
}

std::string ProtoFriendlyName(const std::string &p4_name) {
  std::string fieldname = p4_name;
  fieldname.erase(std::remove(fieldname.begin(), fieldname.end(), ']'),
                  fieldname.end());
  absl::c_replace(fieldname, '[', '_');
  absl::c_replace(fieldname, '.', '_');
  return CamelCaseToSnakeCase(fieldname);
}

std::string TableEntryFieldname(const std::string &alias) {
  return absl::StrCat(ProtoFriendlyName(alias), "_entry");
}

std::string ActionFieldname(const std::string &alias) {
  return ProtoFriendlyName(alias);
}

StatusOr<const google::protobuf::FieldDescriptor *> GetFieldDescriptorByName(
    const std::string &fieldname, google::protobuf::Message *parent_message) {
  auto *parent_descriptor = parent_message->GetDescriptor();
  auto *field_descriptor = parent_descriptor->FindFieldByName(fieldname);
  if (field_descriptor == nullptr) {
    return InvalidArgumentErrorBuilder()
           << "Field " << fieldname << " missing in "
           << parent_message->GetTypeName() << ".";
  }
  return field_descriptor;
}

StatusOr<google::protobuf::Message *> GetMessageByFieldname(
    const std::string &fieldname, google::protobuf::Message *parent_message) {
  ASSIGN_OR_RETURN(auto *field_descriptor,
                   GetFieldDescriptorByName(fieldname, parent_message));
  if (field_descriptor == nullptr) {
    return InvalidArgumentErrorBuilder()
           << "Field " << fieldname << " missing in "
           << parent_message->GetTypeName() << ". "
           << kPdProtoAndP4InfoOutOfSync;
  }

  return parent_message->GetReflection()->MutableMessage(parent_message,
                                                         field_descriptor);
}

uint32_t GetBitwidthOfPiByteString(const std::string &input_string) {
  // Use str.length() - 1. MSB will need to be handled separately since it
  // can have leading zeros which should not be counted.
  int length_in_bits = (input_string.length() - 1) * kNumBitsInByte;

  uint8_t msb = input_string[0];
  while (msb) {
    ++length_in_bits;
    msb >>= 1;
  }

  return length_in_bits;
}

StatusOr<Format> GetFormat(const std::vector<std::string> &annotations,
                           const int bitwidth,
                           const absl::optional<std::string> &named_type) {
  Format format = Format::HEX_STRING;
  if (named_type.has_value()) {
    std::string type = named_type.value();
    if (type == "router_interface_id_t" || type == "neighbor_id_t" ||
        type == "nexthop_id_t" || type == "wcmp_group_id_t") {
      format = Format::STRING;
    }
  }
  for (const std::string &annotation : annotations) {
    if (absl::StartsWith(annotation, "@format(")) {
      if (format != Format::HEX_STRING) {
        return InvalidArgumentErrorBuilder()
               << "Found conflicting formatting annotations.";
      }
      if (annotation == "@format(MAC_ADDRESS)") {
        format = Format::MAC;
      }
      if (annotation == "@format(IPV4_ADDRESS)") {
        format = Format::IPV4;
      }
      if (annotation == "@format(IPV6_ADDRESS)") {
        format = Format::IPV6;
      }
    }
  }
  if (format == Format::MAC && bitwidth != kNumBitsInMac) {
    return InvalidArgumentErrorBuilder()
           << "Only 48 bit values can be formatted as a MAC address.";
  }
  if (format == Format::IPV4 && bitwidth != kNumBitsInIpv4) {
    return InvalidArgumentErrorBuilder()
           << "Only 32 bit values can be formatted as an IPv4 address.";
  }
  if (format == Format::IPV6 && bitwidth != kNumBitsInIpv6) {
    return InvalidArgumentErrorBuilder()
           << "Only 128 bit values can be formatted as an IPv6 address.";
  }
  return format;
}

StatusOr<IrValue> FormatByteString(const Format &format, const int bitwidth,
                                   const std::string &pi_value) {
  IrValue result;
  ASSIGN_OR_RETURN(const auto &normalized_bytes, Normalize(pi_value, bitwidth));
  switch (format) {
    case Format::MAC: {
      result.set_mac(PiByteStringToMac(normalized_bytes));
      break;
    }
    case Format::IPV4: {
      result.set_ipv4(PiByteStringToIpv4(normalized_bytes));
      break;
    }
    case Format::IPV6: {
      result.set_ipv6(PiByteStringToIpv6(normalized_bytes));
      break;
    }
    case Format::STRING: {
      ASSIGN_OR_RETURN(uint64_t value, PiByteStringToUint(pi_value, bitwidth));
      result.set_str(absl::StrCat(value));
      break;
    }
    case Format::HEX_STRING: {
      result.set_hex_str(absl::BytesToHexString(normalized_bytes));
      break;
    }
    default:
      return InvalidArgumentErrorBuilder() << "Unexpected format: "
                                           << Format_Name(format);
  }
  return result;
}

std::string EscapeString(const std::string &s) {
  std::string result = absl::CHexEscape(s);
  absl::StrReplaceAll({{"\"", "\\\""}}, &result);
  return result;
}

}  // namespace pdpi
<commit_msg>Truncate integers to 1 byte when translating IPv6 addresses.<commit_after>// Copyright 2020 Google LLC
//
// 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 "p4_pdpi/util.h"

#include <google/protobuf/descriptor.h>

#include <algorithm>

#include "absl/algorithm/container.h"
#include "absl/strings/ascii.h"
#include "absl/strings/escaping.h"
#include "absl/strings/match.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_replace.h"
#include "absl/types/optional.h"

namespace pdpi {

using ::pdpi::ir::Format;
using ::pdpi::ir::IrValue;

absl::Status ReadProtoFromFile(const std::string &filename,
                               google::protobuf::Message *message) {
  // Verifies that the version of the library that we linked against is
  // compatible with the version of the headers we compiled against.
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  int fd = open(filename.c_str(), O_RDONLY);
  if (fd < 0) {
    return InvalidArgumentErrorBuilder()
           << "Error opening the file " << filename << ".";
  }

  google::protobuf::io::FileInputStream file_stream(fd);
  file_stream.SetCloseOnDelete(true);

  if (!google::protobuf::TextFormat::Parse(&file_stream, message)) {
    return InvalidArgumentErrorBuilder()
           << "Failed to parse file " << filename << ".";
  }

  return absl::OkStatus();
}

absl::Status ReadProtoFromString(const std::string &proto_string,
                                 google::protobuf::Message *message) {
  // Verifies that the version of the library that we linked against is
  // compatible with the version of the headers we compiled against.
  GOOGLE_PROTOBUF_VERIFY_VERSION;

  if (!google::protobuf::TextFormat::ParseFromString(proto_string, message)) {
    return InvalidArgumentErrorBuilder()
           << "Failed to parse string " << proto_string << ".";
  }

  return absl::OkStatus();
}

StatusOr<std::string> Normalize(const std::string &pi_byte_string,
                                int expected_bitwidth) {
  std::string stripped_value = pi_byte_string;
  // Remove leading zeros
  stripped_value.erase(0, std::min(stripped_value.find_first_not_of('\x00'),
                                   stripped_value.size() - 1));
  int length = GetBitwidthOfPiByteString(stripped_value);
  if (length > expected_bitwidth) {
    return InvalidArgumentErrorBuilder()
           << "Value of length " << length << " is greater than bitwidth "
           << expected_bitwidth;
  }

  int total_bytes;
  if (expected_bitwidth % 8) {
    total_bytes = expected_bitwidth / 8 + 1;
  } else {
    total_bytes = expected_bitwidth / 8;
  }
  std::string zeros =
      std::string(total_bytes - stripped_value.length(), '\x00');
  return zeros.append(stripped_value);
}

StatusOr<uint64_t> PiByteStringToUint(const std::string &pi_bytes,
                                      int bitwidth) {
  if (bitwidth > 64) {
    return absl::Status(absl::StatusCode::kInternal,
                        absl::StrCat("Cannot convert value with "
                                     "bitwidth ",
                                     bitwidth, " to uint."));
  }
  ASSIGN_OR_RETURN(const auto &stripped_value, Normalize(pi_bytes, bitwidth));
  uint64_t nb_value;  // network byte order
  char value[sizeof(nb_value)];
  int pad = sizeof(nb_value) - stripped_value.size();
  if (pad) {
    memset(value, 0, pad);
  }
  memcpy(value + pad, stripped_value.data(), stripped_value.size());
  memcpy(&nb_value, value, sizeof(nb_value));

  return be64toh(nb_value);
}

std::string PiByteStringToMac(const std::string &normalized_bytes) {
  std::vector<std::string> parts;
  for (const char c : normalized_bytes) {
    parts.push_back(absl::StrCat(absl::Hex(int{c & 0xFF}, absl::kZeroPad2)));
  }
  return absl::StrJoin(parts, ":");
}

std::string PiByteStringToIpv4(const std::string &normalized_bytes) {
  std::vector<std::string> parts;
  for (const char c : normalized_bytes) {
    parts.push_back(absl::StrCat(absl::Hex((int)c)));
  }
  return absl::StrJoin(parts, ".");
}

std::string PiByteStringToIpv6(const std::string &normalized_bytes) {
  // TODO: Find a way to store in shorthand IPv6 notation
  std::vector<std::string> parts;
  for (unsigned int i = 0; i < kNumBytesInIpv6; i += 2) {
    parts.push_back(
        absl::StrCat(absl::Hex(int{normalized_bytes[i] & 0xFF},
                               absl::kZeroPad2),
                     absl::Hex(int{normalized_bytes[i + 1] & 0xFF},
                               absl::kZeroPad2)));
  }
  return absl::StrJoin(parts, ":");
}

// Based off
// https://github.com/googleapis/gapic-generator-cpp/blob/master/generator/internal/gapic_utils.cc
std::string CamelCaseToSnakeCase(const std::string &input) {
  std::string output;
  for (auto i = 0u; i < input.size(); ++i) {
    if (i + 2 < input.size()) {
      if (std::isupper(input[i + 1]) && std::islower(input[i + 2])) {
        absl::StrAppend(&output, std::string(1, std::tolower(input[i])), "_");
        continue;
      }
    }
    if (i + 1 < input.size()) {
      if ((std::islower(input[i]) || std::isdigit(input[i])) &&
          std::isupper(input[i + 1])) {
        absl::StrAppend(&output, std::string(1, std::tolower(input[i])), "_");
        continue;
      }
    }
    absl::StrAppend(&output, std::string(1, std::tolower(input[i])));
  }
  return output;
}

std::string ProtoFriendlyName(const std::string &p4_name) {
  std::string fieldname = p4_name;
  fieldname.erase(std::remove(fieldname.begin(), fieldname.end(), ']'),
                  fieldname.end());
  absl::c_replace(fieldname, '[', '_');
  absl::c_replace(fieldname, '.', '_');
  return CamelCaseToSnakeCase(fieldname);
}

std::string TableEntryFieldname(const std::string &alias) {
  return absl::StrCat(ProtoFriendlyName(alias), "_entry");
}

std::string ActionFieldname(const std::string &alias) {
  return ProtoFriendlyName(alias);
}

StatusOr<const google::protobuf::FieldDescriptor *> GetFieldDescriptorByName(
    const std::string &fieldname, google::protobuf::Message *parent_message) {
  auto *parent_descriptor = parent_message->GetDescriptor();
  auto *field_descriptor = parent_descriptor->FindFieldByName(fieldname);
  if (field_descriptor == nullptr) {
    return InvalidArgumentErrorBuilder()
           << "Field " << fieldname << " missing in "
           << parent_message->GetTypeName() << ".";
  }
  return field_descriptor;
}

StatusOr<google::protobuf::Message *> GetMessageByFieldname(
    const std::string &fieldname, google::protobuf::Message *parent_message) {
  ASSIGN_OR_RETURN(auto *field_descriptor,
                   GetFieldDescriptorByName(fieldname, parent_message));
  if (field_descriptor == nullptr) {
    return InvalidArgumentErrorBuilder()
           << "Field " << fieldname << " missing in "
           << parent_message->GetTypeName() << ". "
           << kPdProtoAndP4InfoOutOfSync;
  }

  return parent_message->GetReflection()->MutableMessage(parent_message,
                                                         field_descriptor);
}

uint32_t GetBitwidthOfPiByteString(const std::string &input_string) {
  // Use str.length() - 1. MSB will need to be handled separately since it
  // can have leading zeros which should not be counted.
  int length_in_bits = (input_string.length() - 1) * kNumBitsInByte;

  uint8_t msb = input_string[0];
  while (msb) {
    ++length_in_bits;
    msb >>= 1;
  }

  return length_in_bits;
}

StatusOr<Format> GetFormat(const std::vector<std::string> &annotations,
                           const int bitwidth,
                           const absl::optional<std::string> &named_type) {
  Format format = Format::HEX_STRING;
  if (named_type.has_value()) {
    std::string type = named_type.value();
    if (type == "router_interface_id_t" || type == "neighbor_id_t" ||
        type == "nexthop_id_t" || type == "wcmp_group_id_t") {
      format = Format::STRING;
    }
  }
  for (const std::string &annotation : annotations) {
    if (absl::StartsWith(annotation, "@format(")) {
      if (format != Format::HEX_STRING) {
        return InvalidArgumentErrorBuilder()
               << "Found conflicting formatting annotations.";
      }
      if (annotation == "@format(MAC_ADDRESS)") {
        format = Format::MAC;
      }
      if (annotation == "@format(IPV4_ADDRESS)") {
        format = Format::IPV4;
      }
      if (annotation == "@format(IPV6_ADDRESS)") {
        format = Format::IPV6;
      }
    }
  }
  if (format == Format::MAC && bitwidth != kNumBitsInMac) {
    return InvalidArgumentErrorBuilder()
           << "Only 48 bit values can be formatted as a MAC address.";
  }
  if (format == Format::IPV4 && bitwidth != kNumBitsInIpv4) {
    return InvalidArgumentErrorBuilder()
           << "Only 32 bit values can be formatted as an IPv4 address.";
  }
  if (format == Format::IPV6 && bitwidth != kNumBitsInIpv6) {
    return InvalidArgumentErrorBuilder()
           << "Only 128 bit values can be formatted as an IPv6 address.";
  }
  return format;
}

StatusOr<IrValue> FormatByteString(const Format &format, const int bitwidth,
                                   const std::string &pi_value) {
  IrValue result;
  ASSIGN_OR_RETURN(const auto &normalized_bytes, Normalize(pi_value, bitwidth));
  switch (format) {
    case Format::MAC: {
      result.set_mac(PiByteStringToMac(normalized_bytes));
      break;
    }
    case Format::IPV4: {
      result.set_ipv4(PiByteStringToIpv4(normalized_bytes));
      break;
    }
    case Format::IPV6: {
      result.set_ipv6(PiByteStringToIpv6(normalized_bytes));
      break;
    }
    case Format::STRING: {
      ASSIGN_OR_RETURN(uint64_t value, PiByteStringToUint(pi_value, bitwidth));
      result.set_str(absl::StrCat(value));
      break;
    }
    case Format::HEX_STRING: {
      result.set_hex_str(absl::BytesToHexString(normalized_bytes));
      break;
    }
    default:
      return InvalidArgumentErrorBuilder() << "Unexpected format: "
                                           << Format_Name(format);
  }
  return result;
}

std::string EscapeString(const std::string &s) {
  std::string result = absl::CHexEscape(s);
  absl::StrReplaceAll({{"\"", "\\\""}}, &result);
  return result;
}

}  // namespace pdpi
<|endoftext|>


<commit_before>#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>

#include "udt.h"
#include "com_udt_udt.h"
#include <android/log.h>

#include <string>

jint JNICALL Java_com_udt_udt_startup(JNIEnv *, jobject)
{
    return UDT::startup();
}

jint JNICALL Java_com_udt_udt_cleanup(JNIEnv *, jobject)
{
    return UDT::cleanup();
}

jint JNICALL Java_com_udt_udt_socket(JNIEnv *, jobject)
{
    struct addrinfo hints, *local;

    memset(&hints, 0, sizeof(struct addrinfo));

    hints.ai_flags = AI_PASSIVE;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;

    int result = 0;
    if ((result = getaddrinfo(NULL, "9000", &hints, &local)) != 0)
    {
        char error[100] = {0};
        sprintf(error, "%s: %d", "incorrect network address", result);
        __android_log_write(ANDROID_LOG_ERROR, "Giggle", error);
        return 0;
    }

    int handle = UDT::socket(local->ai_family, local->ai_socktype, local->ai_protocol);
    freeaddrinfo(local);

    return handle;
}

jint JNICALL Java_com_udt_udt_connect(JNIEnv* env, jobject thiz, jint handle, jstring ip, jint port)
{
    const char *ip_address = env->GetStringUTFChars(ip, NULL);

    struct addrinfo hints, *peer;
    memset(&hints, 0, sizeof(struct addrinfo));

    hints.ai_flags = AI_PASSIVE;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;

    char port_str[100] = {0};
    sprintf(port_str, "%d", port);
    if (0 != getaddrinfo(ip_address, port_str, &hints, &peer))
    {
        __android_log_write(ANDROID_LOG_ERROR, "Giggle", "incorrect server/peer address. ");
        return 0;
    }

    // connect to the server, implict bind
    int connect_result = 0;
    if ((connect_result = UDT::connect(handle, peer->ai_addr, peer->ai_addrlen)) == UDT::ERROR)
    {
        __android_log_write(ANDROID_LOG_ERROR, "Giggle", "connect error");
        return 0;
    }

    freeaddrinfo(peer);
    return connect_result;
}

jint JNICALL Java_com_udt_udt_close(JNIEnv *env, jobject thiz, jint handle)
{
    return UDT::close(handle);
}

jint JNICALL Java_com_udt_udt_send(JNIEnv *env, jobject thiz, jint handle, jbyteArray data, jint flag)
{
    jsize size = env->GetArrayLength(data);

    jboolean is_copy = JNI_FALSE;
    jbyte* data_ptr = env->GetByteArrayElements(data, &is_copy);

    int result = UDT::send(handle, (const char*)data_ptr, size, flag);
    if (result == UDT::ERROR)
    {
        __android_log_write(ANDROID_LOG_ERROR, "Giggle", "send data fail!");
    }

    env->ReleaseByteArrayElements(data, data_ptr, JNI_ABORT);

    return result;
}

jint Java_com_udt_udt_recv(JNIEnv *, jobject, jint, jbyteArray, jint, jint)
{
    return 0;
}

<commit_msg>refine debug message<commit_after>#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>

#include "udt.h"
#include "com_udt_udt.h"
#include <android/log.h>

#include <string>

namespace {

    std::string to_string(int value)
    {
        char buffer[100] = {0};
        sprintf(buffer, "%d", value);

        return std::string(buffer);
    }
}

const char TAG[] = "UDT-JNI";

jint JNICALL Java_com_udt_udt_startup(JNIEnv *, jobject)
{
    return UDT::startup();
}

jint JNICALL Java_com_udt_udt_cleanup(JNIEnv *, jobject)
{
    return UDT::cleanup();
}

jint JNICALL Java_com_udt_udt_socket(JNIEnv *, jobject)
{
    struct addrinfo hints, *local;

    memset(&hints, 0, sizeof(struct addrinfo));

    hints.ai_flags = AI_PASSIVE;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;

    int result = 0;
    if ((result = getaddrinfo(NULL, "9000", &hints, &local)) != 0)
    {
        std::string error = "incorrect network address" + to_string(result);
        __android_log_write(ANDROID_LOG_ERROR, TAG, error.c_str());
        return 0;
    }

    int handle = UDT::socket(local->ai_family, local->ai_socktype, local->ai_protocol);
    freeaddrinfo(local);

    return handle;
}

jint JNICALL Java_com_udt_udt_connect(JNIEnv* env, jobject thiz, jint handle, jstring ip, jint port)
{
    const char *ip_address = env->GetStringUTFChars(ip, NULL);

    struct addrinfo hints, *peer;
    memset(&hints, 0, sizeof(struct addrinfo));

    hints.ai_flags = AI_PASSIVE;
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_STREAM;

    std::string port_str = to_string(port);
    if (0 != getaddrinfo(ip_address, port_str.c_str(), &hints, &peer))
    {
        __android_log_write(ANDROID_LOG_ERROR, TAG, "incorrect server/peer address. ");
        return 0;
    }

    // connect to the server, implict bind
    int connect_result = 0;
    if ((connect_result = UDT::connect(handle, peer->ai_addr, peer->ai_addrlen)) == UDT::ERROR)
    {
        __android_log_write(ANDROID_LOG_ERROR, TAG, "connect error");
        return 0;
    }

    freeaddrinfo(peer);
    return connect_result;
}

jint JNICALL Java_com_udt_udt_close(JNIEnv *env, jobject thiz, jint handle)
{
    return UDT::close(handle);
}

jint JNICALL Java_com_udt_udt_send(JNIEnv *env, jobject thiz, jint handle, jbyteArray data, jint flag)
{
    jsize size = env->GetArrayLength(data);

    jboolean is_copy = JNI_FALSE;
    jbyte* data_ptr = env->GetByteArrayElements(data, &is_copy);

    int result = UDT::send(handle, (const char*)data_ptr, size, flag);
    if (result == UDT::ERROR)
    {
        __android_log_write(ANDROID_LOG_ERROR, TAG, "send data fail!");
    }

    env->ReleaseByteArrayElements(data, data_ptr, JNI_ABORT);

    return result;
}

jint Java_com_udt_udt_recv(JNIEnv *, jobject, jint, jbyteArray, jint, jint)
{
    return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: textcontrolcombo.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 23:35:21 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"

#include "textcontrolcombo.hxx"

TextControlCombo::TextControlCombo( Window* _pParent, const ResId& _rResId,
    Control& _rCtrl, FixedText& _rFTbefore, FixedText& _rFTafter )
    :Window         ( _pParent, _rResId )
    ,mrCtrl         ( _rCtrl )
    ,mrFTbefore     ( _rFTbefore )
    ,mrFTafter      ( _rFTafter )
{
}

TextControlCombo::~TextControlCombo()
{
}

void TextControlCombo::Arrange( FixedText& _rFTcomplete, BOOL bShow )
{
    Point           aBasePos( GetPosPixel() );
    Size            aMetricVals( GetSizePixel() );

    long            nTextHeight = _rFTcomplete.GetSizePixel().Height();
    long            nCtrlHeight = mrCtrl.GetSizePixel().Height();

    // calc y positions / center vertical
    long            nYFT = aBasePos.Y();
    long            nYCtrl = nYFT;
    if( nCtrlHeight > nTextHeight )
        nYFT += aMetricVals.Height();
    else
        nYCtrl += aMetricVals.Height();

    // separate text parts
    const String    aReplStr( RTL_CONSTASCII_STRINGPARAM( "%POSITION_OF_CONTROL" ) );
    String          aTxtBefore( _rFTcomplete.GetText() );
    String          aTxtAfter;
    xub_StrLen      nReplPos = aTxtBefore.Search( aReplStr );
    if( nReplPos != STRING_NOTFOUND )
    {
        xub_StrLen  nStrStartAfter = nReplPos + aReplStr.Len();
        aTxtAfter = String( aTxtBefore, nStrStartAfter, aTxtBefore.Len() - nStrStartAfter );
        aTxtBefore.Erase( nReplPos );
    }

    // arrange and fill Fixed Texts
    long            nX = aBasePos.X();
    long            nWidth = GetTextWidth( aTxtBefore );

    mrFTbefore.SetText( aTxtBefore );
    mrFTbefore.SetPosSizePixel( nX, nYFT, nWidth, nTextHeight );

    nX += nWidth;
    nX += aMetricVals.Width();
    mrCtrl.SetPosPixel( Point( nX, nYCtrl ) );

    nX += mrCtrl.GetSizePixel().Width();
    nX += aMetricVals.Width();
    mrFTafter.SetText( aTxtAfter );
    mrFTafter.SetPosSizePixel( nX, nYFT, GetTextWidth( aTxtAfter ), nTextHeight );

    _rFTcomplete.Hide();

    Show();

    Window::Hide();
}

void TextControlCombo::Show( BOOL _bVisible, USHORT _nFlags )
{
    mrCtrl.Show( _bVisible, _nFlags );
    mrFTbefore.Show( _bVisible, _nFlags );
    mrFTafter.Show( _bVisible, _nFlags );
}

void TextControlCombo::Enable( BOOL _bEnable, BOOL _bChild )
{
    mrCtrl.Enable( _bEnable, _bChild );
    mrFTbefore.Enable( _bEnable, _bChild );
    mrFTafter.Enable( _bEnable, _bChild );
}

<commit_msg>INTEGRATION: CWS swwarnings (1.4.222); FILE MERGED 2007/03/26 12:09:36 tl 1.4.222.1: #i69287# warning-free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: textcontrolcombo.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2007-09-27 12:47:38 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sw.hxx"

#include "textcontrolcombo.hxx"

TextControlCombo::TextControlCombo( Window* _pParent, const ResId& _rResId,
    Control& _rCtrl, FixedText& _rFTbefore, FixedText& _rFTafter )
    :Window         ( _pParent, _rResId )
    ,mrCtrl         ( _rCtrl )
    ,mrFTbefore     ( _rFTbefore )
    ,mrFTafter      ( _rFTafter )
{
}

TextControlCombo::~TextControlCombo()
{
}

void TextControlCombo::Arrange( FixedText& _rFTcomplete, BOOL /*bShow*/ )
{
    Point           aBasePos( GetPosPixel() );
    Size            aMetricVals( GetSizePixel() );

    long            nTextHeight = _rFTcomplete.GetSizePixel().Height();
    long            nCtrlHeight = mrCtrl.GetSizePixel().Height();

    // calc y positions / center vertical
    long            nYFT = aBasePos.Y();
    long            nYCtrl = nYFT;
    if( nCtrlHeight > nTextHeight )
        nYFT += aMetricVals.Height();
    else
        nYCtrl += aMetricVals.Height();

    // separate text parts
    const String    aReplStr( RTL_CONSTASCII_STRINGPARAM( "%POSITION_OF_CONTROL" ) );
    String          aTxtBefore( _rFTcomplete.GetText() );
    String          aTxtAfter;
    xub_StrLen      nReplPos = aTxtBefore.Search( aReplStr );
    if( nReplPos != STRING_NOTFOUND )
    {
        xub_StrLen  nStrStartAfter = nReplPos + aReplStr.Len();
        aTxtAfter = String( aTxtBefore, nStrStartAfter, aTxtBefore.Len() - nStrStartAfter );
        aTxtBefore.Erase( nReplPos );
    }

    // arrange and fill Fixed Texts
    long            nX = aBasePos.X();
    long            nWidth = GetTextWidth( aTxtBefore );

    mrFTbefore.SetText( aTxtBefore );
    mrFTbefore.SetPosSizePixel( nX, nYFT, nWidth, nTextHeight );

    nX += nWidth;
    nX += aMetricVals.Width();
    mrCtrl.SetPosPixel( Point( nX, nYCtrl ) );

    nX += mrCtrl.GetSizePixel().Width();
    nX += aMetricVals.Width();
    mrFTafter.SetText( aTxtAfter );
    mrFTafter.SetPosSizePixel( nX, nYFT, GetTextWidth( aTxtAfter ), nTextHeight );

    _rFTcomplete.Hide();

    Show();

    Window::Hide();
}

void TextControlCombo::Show( BOOL _bVisible, USHORT _nFlags )
{
    mrCtrl.Show( _bVisible, _nFlags );
    mrFTbefore.Show( _bVisible, _nFlags );
    mrFTafter.Show( _bVisible, _nFlags );
}

void TextControlCombo::Enable( BOOL _bEnable, BOOL _bChild )
{
    mrCtrl.Enable( _bEnable, _bChild );
    mrFTbefore.Enable( _bEnable, _bChild );
    mrFTafter.Enable( _bEnable, _bChild );
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: comboboxtoolbarcontroller.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: ihi $ $Date: 2006-08-01 09:38:15 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef __FRAMEWORK_UIELEMENT_COMBOBOXTOOLBARCONTROLLER_HXX
#include "uielement/comboboxtoolbarcontroller.hxx"
#endif

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_TOOLBAR_HXX_
#include "uielement/toolbar.hxx"
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATUS_HPP_
#include <com/sun/star/frame/status/ItemStatus.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATE_HPP_
#include <com/sun/star/frame/status/ItemState.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_VISIBILITY_HPP_
#include <com/sun/star/frame/status/Visibility.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLNOTIFICATIONLISTENER_HPP_
#include <com/sun/star/frame/XControlNotificationListener.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _SVTOOLS_TOOLBOXCONTROLLER_HXX
#include <svtools/toolboxcontroller.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _VCL_MNEMONIC_HXX_
#include <vcl/mnemonic.hxx>
#endif
#include <vcl/toolbox.hxx>
#include <vcl/combobox.hxx>
#include <tools/urlobj.hxx>

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::frame::status;
using namespace ::com::sun::star::util;

namespace framework
{

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

// Wrapper class to notify controller about events from combobox.
// Unfortunaltly the events are notifed through virtual methods instead
// of Listeners.

class ComboBoxControl : public ComboBox
{
    public:
        ComboBoxControl( Window* pParent, WinBits nStyle, IComboBoxListener* pComboBoxListener );
        virtual ~ComboBoxControl();

        virtual void Select();
        virtual void DoubleClick();
        virtual void Modify();
        virtual void KeyInput( const ::KeyEvent& rKEvt );
        virtual void GetFocus();
        virtual void LoseFocus();
        virtual long PreNotify( NotifyEvent& rNEvt );

    private:
        IComboBoxListener* m_pComboBoxListener;
};

ComboBoxControl::ComboBoxControl( Window* pParent, WinBits nStyle, IComboBoxListener* pComboBoxListener ) :
    ComboBox( pParent, nStyle )
    , m_pComboBoxListener( pComboBoxListener )
{
}

ComboBoxControl::~ComboBoxControl()
{
    m_pComboBoxListener = 0;
}

void ComboBoxControl::Select()
{
    ComboBox::Select();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->Select();
}

void ComboBoxControl::DoubleClick()
{
    ComboBox::DoubleClick();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->DoubleClick();
}

void ComboBoxControl::Modify()
{
    ComboBox::Modify();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->Modify();
}

void ComboBoxControl::KeyInput( const ::KeyEvent& rKEvt )
{
    ComboBox::KeyInput( rKEvt );
    if ( m_pComboBoxListener )
        m_pComboBoxListener->KeyInput( rKEvt );
}

void ComboBoxControl::GetFocus()
{
    ComboBox::GetFocus();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->GetFocus();
}

void ComboBoxControl::LoseFocus()
{
    ComboBox::LoseFocus();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->LoseFocus();
}

long ComboBoxControl::PreNotify( NotifyEvent& rNEvt )
{
    long nRet( 0 );
    if ( m_pComboBoxListener )
        nRet = m_pComboBoxListener->PreNotify( rNEvt );
    if ( nRet == 0 )
        nRet = ComboBox::PreNotify( rNEvt );

    return nRet;
}

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

ComboboxToolbarController::ComboboxToolbarController(
    const Reference< XMultiServiceFactory >& rServiceManager,
    const Reference< XFrame >&               rFrame,
    ToolBar*                                 pToolbar,
    USHORT                                   nID,
    sal_Int32                                nWidth,
    const OUString&                          aCommand ) :
    ComplexToolbarController( rServiceManager, rFrame, pToolbar, nID, aCommand )
    ,   m_pComboBox( 0 )
{
    m_pComboBox = new ComboBoxControl( m_pToolbar, WB_DROPDOWN, this );
    if ( nWidth == 0 )
        nWidth = 100;

    // default dropdown size
    ::Size aLogicalSize( 8, 160 );
    ::Size aPixelSize = m_pComboBox->LogicToPixel( aLogicalSize, MAP_APPFONT );

    m_pComboBox->SetSizePixel( ::Size( nWidth, aPixelSize.Height() ));
    m_pToolbar->SetItemWindow( m_nID, m_pComboBox );
    m_pComboBox->SetDropDownLineCount( 5 );
}

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

ComboboxToolbarController::~ComboboxToolbarController()
{
}

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

void SAL_CALL ComboboxToolbarController::dispose()
throw ( RuntimeException )
{
    vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );

    m_pToolbar->SetItemWindow( m_nID, 0 );
    delete m_pComboBox;

    ComplexToolbarController::dispose();

    m_pComboBox = 0;
}

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

void SAL_CALL ComboboxToolbarController::execute( sal_Int16 KeyModifier )
throw ( RuntimeException )
{
    Reference< XDispatch >       xDispatch;
    Reference< XURLTransformer > xURLTransformer;
    OUString                     aCommandURL;
    OUString                     aSelectedText;
    ::com::sun::star::util::URL  aTargetURL;

    {
        vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );

        if ( m_bDisposed )
            throw DisposedException();

        if ( m_bInitialized &&
             m_xFrame.is() &&
             m_xServiceManager.is() &&
             m_aCommandURL.getLength() )
        {
            xURLTransformer = m_xURLTransformer;
            xDispatch = getDispatchFromCommand( m_aCommandURL );
            aCommandURL = m_aCommandURL;
            aTargetURL = getInitializedURL();
            aSelectedText = m_pComboBox->GetText();
        }
    }

    if ( xDispatch.is() && aTargetURL.Complete.getLength() > 0 )
    {
        Sequence<PropertyValue>   aArgs( 2 );

        // Add key modifier to argument list
        aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "KeyModifier" ));
        aArgs[0].Value <<= KeyModifier;
        aArgs[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Text" ));
        aArgs[1].Value <<= aSelectedText;

        // Execute dispatch asynchronously
        ExecuteInfo* pExecuteInfo = new ExecuteInfo;
        pExecuteInfo->xDispatch     = xDispatch;
        pExecuteInfo->aTargetURL    = aTargetURL;
        pExecuteInfo->aArgs         = aArgs;
        Application::PostUserEvent( STATIC_LINK(0, ComplexToolbarController , ExecuteHdl_Impl), pExecuteInfo );
    }
}

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

void ComboboxToolbarController::Select()
{
    if ( m_pComboBox->GetEntryCount() > 0 )
    {
        Window::PointerState aState = m_pComboBox->GetPointerState();

        sal_uInt16 nKeyModifier = sal_uInt16( aState.mnState & KEY_MODTYPE );
        execute( nKeyModifier );
    }
}

void ComboboxToolbarController::DoubleClick()
{
}

void ComboboxToolbarController::Modify()
{
    notifyTextChanged( m_pComboBox->GetText() );
}

void ComboboxToolbarController::KeyInput( const ::KeyEvent& )
{
}

void ComboboxToolbarController::GetFocus()
{
    notifyFocusGet();
}

void ComboboxToolbarController::LoseFocus()
{
    notifyFocusLost();
}

long ComboboxToolbarController::PreNotify( NotifyEvent& rNEvt )
{
    if( rNEvt.GetType() == EVENT_KEYINPUT )
    {
        const ::KeyEvent* pKeyEvent = rNEvt.GetKeyEvent();
        const KeyCode& rKeyCode = pKeyEvent->GetKeyCode();
        if(( rKeyCode.GetModifier() | rKeyCode.GetCode()) == KEY_RETURN )
        {
            // Call execute only with non-empty text
            if ( m_pComboBox->GetText().Len() > 0 )
                execute( rKeyCode.GetModifier() );
            return 1;
        }
    }

    return 0;
}

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

void ComboboxToolbarController::executeControlCommand( const ::com::sun::star::frame::ControlCommand& rControlCommand )
{
    if ( rControlCommand.Command.equalsAsciiL( "SetText", 7 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
            {
                rtl::OUString aText;
                rControlCommand.Arguments[i].Value >>= aText;
                m_pComboBox->SetText( aText );

                // send notification
                notifyTextChanged( aText );
                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "SetList", 7 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "List", 4 ))
            {
                Sequence< OUString > aList;
                m_pComboBox->Clear();

                rControlCommand.Arguments[i].Value >>= aList;
                for ( sal_Int32 j = 0; j < aList.getLength(); j++ )
                    m_pComboBox->InsertEntry( aList[j] );

                // send notification
                uno::Sequence< beans::NamedValue > aInfo( 1 );
                aInfo[0].Name  = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "List" ));
                aInfo[0].Value <<= aList;
                addNotifyInfo( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ListChanged" )),
                               getDispatchFromCommand( m_aCommandURL ),
                               aInfo );

                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "AddEntry", 8 ))
    {
        sal_uInt16      nPos( COMBOBOX_APPEND );
        rtl::OUString   aText;
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
            {
                if ( rControlCommand.Arguments[i].Value >>= aText )
                    m_pComboBox->InsertEntry( aText, nPos );
                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "InsertEntry", 11 ))
    {
        sal_uInt16      nPos( COMBOBOX_APPEND );
        rtl::OUString   aText;
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Pos", 3 ))
            {
                sal_Int32 nTmpPos;
                if ( rControlCommand.Arguments[i].Value >>= nTmpPos )
                {
                    if (( nTmpPos >= 0 ) &&
                        ( nTmpPos < sal_Int32( m_pComboBox->GetEntryCount() )))
                        nPos = sal_uInt16( nTmpPos );
                }
            }
            else if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
                rControlCommand.Arguments[i].Value >>= aText;
        }

        m_pComboBox->InsertEntry( aText, nPos );
    }
    else if ( rControlCommand.Command.equalsAsciiL( "RemoveEntryPos", 14 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Pos", 3 ))
            {
                sal_Int32 nPos( -1 );
                if ( rControlCommand.Arguments[i].Value >>= nPos )
                {
                    if ( nPos < sal_Int32( m_pComboBox->GetEntryCount() ))
                        m_pComboBox->RemoveEntry( sal_uInt16( nPos ));
                }
                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "RemoveEntryText", 15 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
            {
                rtl::OUString aText;
                if ( rControlCommand.Arguments[i].Value >>= aText )
                    m_pComboBox->RemoveEntry( aText );
                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "SetDropDownLines", 16 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Lines", 5 ))
            {
                sal_Int32 nValue( 5 );
                rControlCommand.Arguments[i].Value >>= nValue;
                m_pComboBox->SetDropDownLineCount( sal_uInt16( nValue ));
                break;
            }
        }
    }
}

} // namespace
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.16); FILE MERGED 2006/09/01 17:29:25 kaib 1.5.16.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: comboboxtoolbarcontroller.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 14:17:57 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"

#ifndef __FRAMEWORK_UIELEMENT_COMBOBOXTOOLBARCONTROLLER_HXX
#include "uielement/comboboxtoolbarcontroller.hxx"
#endif

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_TOOLBAR_HXX_
#include "uielement/toolbar.hxx"
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_
#include <com/sun/star/util/XURLTransformer.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATUS_HPP_
#include <com/sun/star/frame/status/ItemStatus.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_ITEMSTATE_HPP_
#include <com/sun/star/frame/status/ItemState.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_STATUS_VISIBILITY_HPP_
#include <com/sun/star/frame/status/Visibility.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XCONTROLNOTIFICATIONLISTENER_HPP_
#include <com/sun/star/frame/XControlNotificationListener.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _SVTOOLS_TOOLBOXCONTROLLER_HXX
#include <svtools/toolboxcontroller.hxx>
#endif
#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
#ifndef _VCL_MNEMONIC_HXX_
#include <vcl/mnemonic.hxx>
#endif
#include <vcl/toolbox.hxx>
#include <vcl/combobox.hxx>
#include <tools/urlobj.hxx>

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::frame::status;
using namespace ::com::sun::star::util;

namespace framework
{

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

// Wrapper class to notify controller about events from combobox.
// Unfortunaltly the events are notifed through virtual methods instead
// of Listeners.

class ComboBoxControl : public ComboBox
{
    public:
        ComboBoxControl( Window* pParent, WinBits nStyle, IComboBoxListener* pComboBoxListener );
        virtual ~ComboBoxControl();

        virtual void Select();
        virtual void DoubleClick();
        virtual void Modify();
        virtual void KeyInput( const ::KeyEvent& rKEvt );
        virtual void GetFocus();
        virtual void LoseFocus();
        virtual long PreNotify( NotifyEvent& rNEvt );

    private:
        IComboBoxListener* m_pComboBoxListener;
};

ComboBoxControl::ComboBoxControl( Window* pParent, WinBits nStyle, IComboBoxListener* pComboBoxListener ) :
    ComboBox( pParent, nStyle )
    , m_pComboBoxListener( pComboBoxListener )
{
}

ComboBoxControl::~ComboBoxControl()
{
    m_pComboBoxListener = 0;
}

void ComboBoxControl::Select()
{
    ComboBox::Select();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->Select();
}

void ComboBoxControl::DoubleClick()
{
    ComboBox::DoubleClick();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->DoubleClick();
}

void ComboBoxControl::Modify()
{
    ComboBox::Modify();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->Modify();
}

void ComboBoxControl::KeyInput( const ::KeyEvent& rKEvt )
{
    ComboBox::KeyInput( rKEvt );
    if ( m_pComboBoxListener )
        m_pComboBoxListener->KeyInput( rKEvt );
}

void ComboBoxControl::GetFocus()
{
    ComboBox::GetFocus();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->GetFocus();
}

void ComboBoxControl::LoseFocus()
{
    ComboBox::LoseFocus();
    if ( m_pComboBoxListener )
        m_pComboBoxListener->LoseFocus();
}

long ComboBoxControl::PreNotify( NotifyEvent& rNEvt )
{
    long nRet( 0 );
    if ( m_pComboBoxListener )
        nRet = m_pComboBoxListener->PreNotify( rNEvt );
    if ( nRet == 0 )
        nRet = ComboBox::PreNotify( rNEvt );

    return nRet;
}

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

ComboboxToolbarController::ComboboxToolbarController(
    const Reference< XMultiServiceFactory >& rServiceManager,
    const Reference< XFrame >&               rFrame,
    ToolBar*                                 pToolbar,
    USHORT                                   nID,
    sal_Int32                                nWidth,
    const OUString&                          aCommand ) :
    ComplexToolbarController( rServiceManager, rFrame, pToolbar, nID, aCommand )
    ,   m_pComboBox( 0 )
{
    m_pComboBox = new ComboBoxControl( m_pToolbar, WB_DROPDOWN, this );
    if ( nWidth == 0 )
        nWidth = 100;

    // default dropdown size
    ::Size aLogicalSize( 8, 160 );
    ::Size aPixelSize = m_pComboBox->LogicToPixel( aLogicalSize, MAP_APPFONT );

    m_pComboBox->SetSizePixel( ::Size( nWidth, aPixelSize.Height() ));
    m_pToolbar->SetItemWindow( m_nID, m_pComboBox );
    m_pComboBox->SetDropDownLineCount( 5 );
}

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

ComboboxToolbarController::~ComboboxToolbarController()
{
}

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

void SAL_CALL ComboboxToolbarController::dispose()
throw ( RuntimeException )
{
    vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );

    m_pToolbar->SetItemWindow( m_nID, 0 );
    delete m_pComboBox;

    ComplexToolbarController::dispose();

    m_pComboBox = 0;
}

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

void SAL_CALL ComboboxToolbarController::execute( sal_Int16 KeyModifier )
throw ( RuntimeException )
{
    Reference< XDispatch >       xDispatch;
    Reference< XURLTransformer > xURLTransformer;
    OUString                     aCommandURL;
    OUString                     aSelectedText;
    ::com::sun::star::util::URL  aTargetURL;

    {
        vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );

        if ( m_bDisposed )
            throw DisposedException();

        if ( m_bInitialized &&
             m_xFrame.is() &&
             m_xServiceManager.is() &&
             m_aCommandURL.getLength() )
        {
            xURLTransformer = m_xURLTransformer;
            xDispatch = getDispatchFromCommand( m_aCommandURL );
            aCommandURL = m_aCommandURL;
            aTargetURL = getInitializedURL();
            aSelectedText = m_pComboBox->GetText();
        }
    }

    if ( xDispatch.is() && aTargetURL.Complete.getLength() > 0 )
    {
        Sequence<PropertyValue>   aArgs( 2 );

        // Add key modifier to argument list
        aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "KeyModifier" ));
        aArgs[0].Value <<= KeyModifier;
        aArgs[1].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Text" ));
        aArgs[1].Value <<= aSelectedText;

        // Execute dispatch asynchronously
        ExecuteInfo* pExecuteInfo = new ExecuteInfo;
        pExecuteInfo->xDispatch     = xDispatch;
        pExecuteInfo->aTargetURL    = aTargetURL;
        pExecuteInfo->aArgs         = aArgs;
        Application::PostUserEvent( STATIC_LINK(0, ComplexToolbarController , ExecuteHdl_Impl), pExecuteInfo );
    }
}

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

void ComboboxToolbarController::Select()
{
    if ( m_pComboBox->GetEntryCount() > 0 )
    {
        Window::PointerState aState = m_pComboBox->GetPointerState();

        sal_uInt16 nKeyModifier = sal_uInt16( aState.mnState & KEY_MODTYPE );
        execute( nKeyModifier );
    }
}

void ComboboxToolbarController::DoubleClick()
{
}

void ComboboxToolbarController::Modify()
{
    notifyTextChanged( m_pComboBox->GetText() );
}

void ComboboxToolbarController::KeyInput( const ::KeyEvent& )
{
}

void ComboboxToolbarController::GetFocus()
{
    notifyFocusGet();
}

void ComboboxToolbarController::LoseFocus()
{
    notifyFocusLost();
}

long ComboboxToolbarController::PreNotify( NotifyEvent& rNEvt )
{
    if( rNEvt.GetType() == EVENT_KEYINPUT )
    {
        const ::KeyEvent* pKeyEvent = rNEvt.GetKeyEvent();
        const KeyCode& rKeyCode = pKeyEvent->GetKeyCode();
        if(( rKeyCode.GetModifier() | rKeyCode.GetCode()) == KEY_RETURN )
        {
            // Call execute only with non-empty text
            if ( m_pComboBox->GetText().Len() > 0 )
                execute( rKeyCode.GetModifier() );
            return 1;
        }
    }

    return 0;
}

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

void ComboboxToolbarController::executeControlCommand( const ::com::sun::star::frame::ControlCommand& rControlCommand )
{
    if ( rControlCommand.Command.equalsAsciiL( "SetText", 7 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
            {
                rtl::OUString aText;
                rControlCommand.Arguments[i].Value >>= aText;
                m_pComboBox->SetText( aText );

                // send notification
                notifyTextChanged( aText );
                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "SetList", 7 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "List", 4 ))
            {
                Sequence< OUString > aList;
                m_pComboBox->Clear();

                rControlCommand.Arguments[i].Value >>= aList;
                for ( sal_Int32 j = 0; j < aList.getLength(); j++ )
                    m_pComboBox->InsertEntry( aList[j] );

                // send notification
                uno::Sequence< beans::NamedValue > aInfo( 1 );
                aInfo[0].Name  = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "List" ));
                aInfo[0].Value <<= aList;
                addNotifyInfo( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ListChanged" )),
                               getDispatchFromCommand( m_aCommandURL ),
                               aInfo );

                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "AddEntry", 8 ))
    {
        sal_uInt16      nPos( COMBOBOX_APPEND );
        rtl::OUString   aText;
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
            {
                if ( rControlCommand.Arguments[i].Value >>= aText )
                    m_pComboBox->InsertEntry( aText, nPos );
                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "InsertEntry", 11 ))
    {
        sal_uInt16      nPos( COMBOBOX_APPEND );
        rtl::OUString   aText;
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Pos", 3 ))
            {
                sal_Int32 nTmpPos;
                if ( rControlCommand.Arguments[i].Value >>= nTmpPos )
                {
                    if (( nTmpPos >= 0 ) &&
                        ( nTmpPos < sal_Int32( m_pComboBox->GetEntryCount() )))
                        nPos = sal_uInt16( nTmpPos );
                }
            }
            else if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
                rControlCommand.Arguments[i].Value >>= aText;
        }

        m_pComboBox->InsertEntry( aText, nPos );
    }
    else if ( rControlCommand.Command.equalsAsciiL( "RemoveEntryPos", 14 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Pos", 3 ))
            {
                sal_Int32 nPos( -1 );
                if ( rControlCommand.Arguments[i].Value >>= nPos )
                {
                    if ( nPos < sal_Int32( m_pComboBox->GetEntryCount() ))
                        m_pComboBox->RemoveEntry( sal_uInt16( nPos ));
                }
                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "RemoveEntryText", 15 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Text", 4 ))
            {
                rtl::OUString aText;
                if ( rControlCommand.Arguments[i].Value >>= aText )
                    m_pComboBox->RemoveEntry( aText );
                break;
            }
        }
    }
    else if ( rControlCommand.Command.equalsAsciiL( "SetDropDownLines", 16 ))
    {
        for ( sal_Int32 i = 0; i < rControlCommand.Arguments.getLength(); i++ )
        {
            if ( rControlCommand.Arguments[i].Name.equalsAsciiL( "Lines", 5 ))
            {
                sal_Int32 nValue( 5 );
                rControlCommand.Arguments[i].Value >>= nValue;
                m_pComboBox->SetDropDownLineCount( sal_uInt16( nValue ));
                break;
            }
        }
    }
}

} // namespace
<|endoftext|>