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

  Program:   Visualization Toolkit
  Module:    TestGaussianBlurPass.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
// This test covers the gaussian blur post-processing render pass.
// It renders an actor with a translucent LUT and depth
// peeling using the multi renderpass classes. The mapper uses color
// interpolation (poor quality).
//
// The command line arguments are:
// -I        => run in interactive mode; unless this is used, the program will
//              not allow interaction and exit

#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"

#include "vtkSmartPointer.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderWindow.h"
#include "vtkOpenGLRenderer.h"
#include "vtkActor.h"

#include "vtkImageSinusoidSource.h"
#include "vtkImageData.h"
#include "vtkImageDataGeometryFilter.h"
#include "vtkDataSetSurfaceFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkLookupTable.h"
#include "vtkCamera.h"

#include "vtkCameraPass.h"
#include "vtkLightsPass.h"
#include "vtkSequencePass.h"
#include "vtkOpaquePass.h"
#include "vtkDepthPeelingPass.h"
#include "vtkTranslucentPass.h"
#include "vtkVolumetricPass.h"
#include "vtkOverlayPass.h"
#include "vtkRenderPassCollection.h"
#include "vtkGaussianBlurPass.h"
#include "vtkConeSource.h"

int TestGaussianBlurPass(int argc, char* argv[])
{
  vtkSmartPointer<vtkRenderWindowInteractor> iren=
    vtkSmartPointer<vtkRenderWindowInteractor>::New();
  vtkSmartPointer<vtkRenderWindow> renWin =
    vtkSmartPointer<vtkRenderWindow>::New();
  renWin->SetMultiSamples(0);

  renWin->SetAlphaBitPlanes(1);
  iren->SetRenderWindow(renWin);

  vtkSmartPointer<vtkRenderer> renderer =
    vtkSmartPointer<vtkRenderer>::New();
  renWin->AddRenderer(renderer);

  vtkOpenGLRenderer *glrenderer =
      vtkOpenGLRenderer::SafeDownCast(renderer.GetPointer());

  vtkSmartPointer<vtkCameraPass> cameraP=
    vtkSmartPointer<vtkCameraPass>::New();

  vtkSmartPointer<vtkSequencePass> seq=
    vtkSmartPointer<vtkSequencePass>::New();
  vtkSmartPointer<vtkOpaquePass> opaque=
    vtkSmartPointer<vtkOpaquePass>::New();
//  vtkSmartPointer<vtkDepthPeelingPass> peeling=
//    vtkSmartPointer<vtkDepthPeelingPass>::New();
//  peeling->SetMaximumNumberOfPeels(200);
//  peeling->SetOcclusionRatio(0.1);

  vtkSmartPointer<vtkTranslucentPass> translucent=
    vtkSmartPointer<vtkTranslucentPass>::New();
//  peeling->SetTranslucentPass(translucent);

  vtkSmartPointer<vtkVolumetricPass> volume=
    vtkSmartPointer<vtkVolumetricPass>::New();
  vtkSmartPointer<vtkOverlayPass> overlay=
    vtkSmartPointer<vtkOverlayPass>::New();

  vtkSmartPointer<vtkLightsPass> lights=
    vtkSmartPointer<vtkLightsPass>::New();

  vtkSmartPointer<vtkRenderPassCollection> passes=
    vtkSmartPointer<vtkRenderPassCollection>::New();
  passes->AddItem(lights);
  passes->AddItem(opaque);

//  passes->AddItem(peeling);
  passes->AddItem(translucent);

  passes->AddItem(volume);
  passes->AddItem(overlay);
  seq->SetPasses(passes);
  cameraP->SetDelegatePass(seq);

  vtkSmartPointer<vtkGaussianBlurPass> blurP=
    vtkSmartPointer<vtkGaussianBlurPass>::New();
  blurP->SetDelegatePass(cameraP);

  glrenderer->SetPass(blurP);

//  renderer->SetPass(cameraP);

  vtkSmartPointer<vtkImageSinusoidSource> imageSource=
    vtkSmartPointer<vtkImageSinusoidSource>::New();
  imageSource->SetWholeExtent(0,9,0,9,0,9);
  imageSource->SetPeriod(5);
  imageSource->Update();

  vtkImageData *image=imageSource->GetOutput();
  double range[2];
  image->GetScalarRange(range);

  vtkSmartPointer<vtkDataSetSurfaceFilter> surface=
    vtkSmartPointer<vtkDataSetSurfaceFilter>::New();

  surface->SetInputConnection(imageSource->GetOutputPort());

  vtkSmartPointer<vtkPolyDataMapper> mapper=
    vtkSmartPointer<vtkPolyDataMapper>::New();
  mapper->SetInputConnection(surface->GetOutputPort());

  vtkSmartPointer<vtkLookupTable> lut=
    vtkSmartPointer<vtkLookupTable>::New();
  lut->SetTableRange(range);
  lut->SetAlphaRange(0.5,0.5);
  lut->SetHueRange(0.2,0.7);
  lut->SetNumberOfTableValues(256);
  lut->Build();

  mapper->SetScalarVisibility(1);
  mapper->SetLookupTable(lut);

  vtkSmartPointer<vtkActor> actor=
    vtkSmartPointer<vtkActor>::New();
  renderer->AddActor(actor);
  actor->SetMapper(mapper);
  actor->SetVisibility(1);

  vtkSmartPointer<vtkConeSource> cone=
    vtkSmartPointer<vtkConeSource>::New();
  vtkSmartPointer<vtkPolyDataMapper> coneMapper=
    vtkSmartPointer<vtkPolyDataMapper>::New();
  coneMapper->SetInputConnection(cone->GetOutputPort());
  coneMapper->SetImmediateModeRendering(1);

  vtkSmartPointer<vtkActor> coneActor=
    vtkSmartPointer<vtkActor>::New();
  coneActor->SetMapper(coneMapper);
  coneActor->SetVisibility(1);

  renderer->AddActor(coneActor);

  renderer->SetBackground(0.1,0.3,0.0);
  renWin->SetSize(400,400);

  // empty scene during OpenGL detection.
  actor->SetVisibility(0);
  coneActor->SetVisibility(0);
  renWin->Render();

  int retVal;
  actor->SetVisibility(1);
  coneActor->SetVisibility(1);
  renderer->ResetCamera();
  vtkCamera *camera=renderer->GetActiveCamera();
  camera->Azimuth(-40.0);
  camera->Elevation(20.0);
  renWin->Render();

  if(peeling->GetLastRenderingUsedDepthPeeling())
    {
    cout<<"depth peeling was used"<<endl;
    }
  else
    {
    cout<<"depth peeling was not used (alpha blending instead)"<<endl;
    }

  retVal = vtkRegressionTestImage( renWin );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }
  return !retVal;
}
<commit_msg>Restore file that was accidentally changed<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestGaussianBlurPass.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
// This test covers the gaussian blur post-processing render pass.
// It renders an actor with a translucent LUT and depth
// peeling using the multi renderpass classes. The mapper uses color
// interpolation (poor quality).
//
// The command line arguments are:
// -I        => run in interactive mode; unless this is used, the program will
//              not allow interaction and exit

#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"

#include "vtkSmartPointer.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderWindow.h"
#include "vtkOpenGLRenderer.h"
#include "vtkActor.h"

#include "vtkImageSinusoidSource.h"
#include "vtkImageData.h"
#include "vtkImageDataGeometryFilter.h"
#include "vtkDataSetSurfaceFilter.h"
#include "vtkPolyDataMapper.h"
#include "vtkLookupTable.h"
#include "vtkCamera.h"

#include "vtkCameraPass.h"
#include "vtkLightsPass.h"
#include "vtkSequencePass.h"
#include "vtkOpaquePass.h"
#include "vtkDepthPeelingPass.h"
#include "vtkTranslucentPass.h"
#include "vtkVolumetricPass.h"
#include "vtkOverlayPass.h"
#include "vtkRenderPassCollection.h"
#include "vtkGaussianBlurPass.h"
#include "vtkConeSource.h"

// Make sure to have a valid OpenGL context current on the calling thread
// before calling it. Defined in TestGenericVertexAttributesGLSLAlphaBlending.
bool MesaHasVTKBug8135(vtkRenderWindow *);

int TestGaussianBlurPass(int argc, char* argv[])
{
  vtkSmartPointer<vtkRenderWindowInteractor> iren=
    vtkSmartPointer<vtkRenderWindowInteractor>::New();
  vtkSmartPointer<vtkRenderWindow> renWin =
    vtkSmartPointer<vtkRenderWindow>::New();
  renWin->SetMultiSamples(0);

  renWin->SetAlphaBitPlanes(1);
  iren->SetRenderWindow(renWin);

  vtkSmartPointer<vtkRenderer> renderer =
    vtkSmartPointer<vtkRenderer>::New();
  renWin->AddRenderer(renderer);

  vtkOpenGLRenderer *glrenderer =
      vtkOpenGLRenderer::SafeDownCast(renderer.GetPointer());

  vtkSmartPointer<vtkCameraPass> cameraP=
    vtkSmartPointer<vtkCameraPass>::New();

  vtkSmartPointer<vtkSequencePass> seq=
    vtkSmartPointer<vtkSequencePass>::New();
  vtkSmartPointer<vtkOpaquePass> opaque=
    vtkSmartPointer<vtkOpaquePass>::New();
  vtkSmartPointer<vtkDepthPeelingPass> peeling=
    vtkSmartPointer<vtkDepthPeelingPass>::New();
  peeling->SetMaximumNumberOfPeels(200);
  peeling->SetOcclusionRatio(0.1);

  vtkSmartPointer<vtkTranslucentPass> translucent=
    vtkSmartPointer<vtkTranslucentPass>::New();
  peeling->SetTranslucentPass(translucent);

  vtkSmartPointer<vtkVolumetricPass> volume=
    vtkSmartPointer<vtkVolumetricPass>::New();
  vtkSmartPointer<vtkOverlayPass> overlay=
    vtkSmartPointer<vtkOverlayPass>::New();

  vtkSmartPointer<vtkLightsPass> lights=
    vtkSmartPointer<vtkLightsPass>::New();

  vtkSmartPointer<vtkRenderPassCollection> passes=
    vtkSmartPointer<vtkRenderPassCollection>::New();
  passes->AddItem(lights);
  passes->AddItem(opaque);

  passes->AddItem(peeling);
//  passes->AddItem(translucent);

  passes->AddItem(volume);
  passes->AddItem(overlay);
  seq->SetPasses(passes);
  cameraP->SetDelegatePass(seq);

  vtkSmartPointer<vtkGaussianBlurPass> blurP=
    vtkSmartPointer<vtkGaussianBlurPass>::New();
  blurP->SetDelegatePass(cameraP);

  glrenderer->SetPass(blurP);

//  renderer->SetPass(cameraP);

  vtkSmartPointer<vtkImageSinusoidSource> imageSource=
    vtkSmartPointer<vtkImageSinusoidSource>::New();
  imageSource->SetWholeExtent(0,9,0,9,0,9);
  imageSource->SetPeriod(5);
  imageSource->Update();

  vtkImageData *image=imageSource->GetOutput();
  double range[2];
  image->GetScalarRange(range);

  vtkSmartPointer<vtkDataSetSurfaceFilter> surface=
    vtkSmartPointer<vtkDataSetSurfaceFilter>::New();

  surface->SetInputConnection(imageSource->GetOutputPort());

  vtkSmartPointer<vtkPolyDataMapper> mapper=
    vtkSmartPointer<vtkPolyDataMapper>::New();
  mapper->SetInputConnection(surface->GetOutputPort());

  vtkSmartPointer<vtkLookupTable> lut=
    vtkSmartPointer<vtkLookupTable>::New();
  lut->SetTableRange(range);
  lut->SetAlphaRange(0.5,0.5);
  lut->SetHueRange(0.2,0.7);
  lut->SetNumberOfTableValues(256);
  lut->Build();

  mapper->SetScalarVisibility(1);
  mapper->SetLookupTable(lut);

  vtkSmartPointer<vtkActor> actor=
    vtkSmartPointer<vtkActor>::New();
  renderer->AddActor(actor);
  actor->SetMapper(mapper);
  actor->SetVisibility(1);

  vtkSmartPointer<vtkConeSource> cone=
    vtkSmartPointer<vtkConeSource>::New();
  vtkSmartPointer<vtkPolyDataMapper> coneMapper=
    vtkSmartPointer<vtkPolyDataMapper>::New();
  coneMapper->SetInputConnection(cone->GetOutputPort());
  coneMapper->SetImmediateModeRendering(1);

  vtkSmartPointer<vtkActor> coneActor=
    vtkSmartPointer<vtkActor>::New();
  coneActor->SetMapper(coneMapper);
  coneActor->SetVisibility(1);

  renderer->AddActor(coneActor);

  renderer->SetBackground(0.1,0.3,0.0);
  renWin->SetSize(400,400);

  // empty scene during OpenGL detection.
  actor->SetVisibility(0);
  coneActor->SetVisibility(0);
  renWin->Render();

  int retVal;
  if(MesaHasVTKBug8135(renWin))
    {
    // Mesa will crash if version<7.3
    cout<<"This version of Mesa would crash. Skip the test."<<endl;
    retVal=vtkRegressionTester::PASSED;
    }
  else
    {
    actor->SetVisibility(1);
    coneActor->SetVisibility(1);
    renderer->ResetCamera();
    vtkCamera *camera=renderer->GetActiveCamera();
    camera->Azimuth(-40.0);
    camera->Elevation(20.0);
    renWin->Render();

    if(peeling->GetLastRenderingUsedDepthPeeling())
      {
      cout<<"depth peeling was used"<<endl;
      }
    else
      {
      cout<<"depth peeling was not used (alpha blending instead)"<<endl;
      }

    retVal = vtkRegressionTestImage( renWin );
    if ( retVal == vtkRegressionTester::DO_INTERACTOR)
      {
      iren->Start();
      }
    }
  return !retVal;
}
<|endoftext|>


<commit_before>#include <TimingAnalysis.h>
#include <timingAlgorithm.h>

#include <TFileCollection.h>

int main (int argc, char** argv)
{
  std::string filename("");
  std::string outputdir("./Results");
  int firstchannel=0;
  int secondchannel=1;
  float cfd_threshold=0.4;
  float threshold_MCP=0.01;
  float threshold=-0.1;
  float lowpass=0;

  // Additional parameters
  float hysteresis=1e-3;
  float min_amplitude_MCP=0;
  float max_amplitude_MCP=0.034;
  float min_amplitude_ch2=0;
  float max_amplitude_ch2=0.2;
  float baseline_p=0.1; //Use first 10% of the samples to compute baseline

  for (int i=1; i<argc; ++i)
  {
    if (argv[i][0] == '-') {
      // Option found
      std::string option(argv[i]);
      if ( option == "-h" || option == "--help" ) {
        std::cout << "List of options: " << std::endl;
        std::cout << "-h [ --help ]                         produce help message" << std::endl;
        std::cout << "-f [ --channel ] arg (=0)             channel to analyze" << std::endl;
        std::cout << "-c [ --cfd_threshold ] arg (=0.4)     CFD fraction" << std::endl;
        std::cout << "-t [ --threshold ] arg (=-0.1)        Threshold, negative for" << std::endl;
        std::cout << "                                      negative signals (V)" << std::endl;
        std::cout << "-p [ --lowpass ] arg (=0)             Lowpass filter frequency (Hz)" << std::endl;
        std::cout << "-o [ --outputdir ] arg (=./Results)   output directory" << std::endl;
        std::cout << "-i [ --filename ] arg                 input file" << std::endl;
        return 0;
      }
      std::string value(argv[++i]);

      if ( option == "-f" || option == "--channel" )
        secondchannel = std::stoi(value);
      if ( option == "-i" || option == "--filename" )
        filename = value;
      if ( option == "-c" || option == "--cfd_threshold" )
        cfd_threshold = std::stof(value);
      if ( option == "-t" || option == "--threshold" )
        threshold = std::stof(value);
      if ( option == "-p" || option == "--lowpass" )
        lowpass = std::stof(value);
      if ( option == "-o" || option == "--outputdir" )
        outputdir = value;
      if ( option == "-i" || option == "--filename" )
        filename = value;
    }
  }

  if (filename == "") {
    std::cout << "Input file required! For help use:" << std::endl;
    std::cout << argv[0] << " --help" << std::endl;
    return 0;
  }

  // Creating the analysis object from data TTree
  TFileCollection * fc_example = new TFileCollection();
  TChain * c_example = new TChain("pulse");
  fc_example->Add(filename.c_str());
  c_example->AddFileInfoList((TCollection*)fc_example->GetList());

  TimingAnalysis example_analyzeData(c_example);

  // Output file
  TString filenameTail("_result_MCP_");
  filenameTail+=secondchannel;
  filename.insert(filename.size()-5,filenameTail.Data());
  filename.erase(0,filename.find_last_of('/',filename.size()));
  filename.insert(0,outputdir);
  TFile * f_root = new TFile (filename.c_str(),"RECREATE");

  std::cout<<"Filling "<<filename<<" with "<<filename<<std::endl;

  if (cfd_threshold > 0) {
    AlgorithmParameters par(0.5, cfd_threshold, threshold_MCP,threshold,lowpass,hysteresis,min_amplitude_MCP, max_amplitude_MCP, min_amplitude_ch2, max_amplitude_ch2,baseline_p);
    double timeres_ps = example_analyzeData.executeTimeDifference<AlgorithmParameters>(f_root, ComputeExactTimeCFD, par, firstchannel, secondchannel)*1e12;
    std::cout << "\t\t\tTime difference: " << timeres_ps << " ps" << std::endl;
  }
  else {
    TDirectory* cfd_dir = f_root->mkdir("cfd_scan");
    TGraph cfd_graph;
    cfd_graph.SetName("cfd_scan");
    int cfd_counter=0;
    for (float cfd_th=std::abs(cfd_threshold); cfd_th<1; cfd_th+=std::abs(cfd_threshold)) {
      std::cout<< "############ CFD fraction " << cfd_th << " ############" <<std::endl;
      TString cfd_tmpdir_name("cfd_");
      cfd_tmpdir_name += (int) (100*cfd_th);
      cfd_tmpdir_name += "_percent";
      TDirectory* cfd_tmpdir = f_root->mkdir(cfd_tmpdir_name);
      cfd_tmpdir->cd();
      AlgorithmParameters par( 0.5, cfd_th, threshold_MCP,threshold,lowpass,hysteresis,min_amplitude_MCP, max_amplitude_MCP, min_amplitude_ch2, max_amplitude_ch2,baseline_p);  //Fixed cfd_threshold for ch0
      double timeres_ps = example_analyzeData.executeTimeDifference<AlgorithmParameters>(f_root, ComputeExactTimeCFD, par, firstchannel, secondchannel)*1e12;
      std::cout << "\t\t\tTime difference: " << timeres_ps << " ps" << std::endl;
      cfd_graph.SetPoint(cfd_counter++, cfd_th, timeres_ps);
    }
    cfd_dir->cd();
    cfd_graph.Write();
  }

  f_root->Close();
  return 0;
}
<commit_msg>Better help<commit_after>#include <TimingAnalysis.h>
#include <timingAlgorithm.h>

#include <TFileCollection.h>

int main (int argc, char** argv)
{
  std::string filename("");
  std::string outputdir("./Results");
  int firstchannel=0;
  int secondchannel=1;
  float cfd_threshold=0.4;
  float threshold_MCP=0.01;
  float threshold=-0.1;
  float lowpass=0;

  // Additional parameters
  float hysteresis=1e-3;
  float min_amplitude_MCP=0;
  float max_amplitude_MCP=0.034;
  float min_amplitude_ch2=0;
  float max_amplitude_ch2=0.2;
  float baseline_p=0.1; //Use first 10% of the samples to compute baseline

  for (int i=1; i<argc; ++i)
  {
    if (argv[i][0] == '-') {
      // Option found
      std::string option(argv[i]);
      if ( option == "-h" || option == "--help" ) {
        std::cout << "List of options: " << std::endl;
        std::cout << "-h [ --help ]                         produce help message" << std::endl;
        std::cout << "-f [ --channel ] arg (=0)             channel to analyze" << std::endl;
        std::cout << "-c [ --cfd_threshold ] arg (=0.4)     CFD fraction" << std::endl;
        std::cout << "                                      a negative value will start a scan with" << std::endl;
        std::cout << "                                      a step equal to |cfd_threshold|" << std::endl;
        std::cout << "-t [ --threshold ] arg (=-0.1)        Threshold, negative for" << std::endl;
        std::cout << "                                      negative signals (V)" << std::endl;
        std::cout << "-p [ --lowpass ] arg (=0)             Lowpass filter frequency (Hz)" << std::endl;
        std::cout << "-o [ --outputdir ] arg (=./Results)   output directory" << std::endl;
        std::cout << "-i [ --filename ] arg                 input file" << std::endl;
        return 0;
      }
      std::string value(argv[++i]);

      if ( option == "-f" || option == "--channel" )
        secondchannel = std::stoi(value);
      if ( option == "-i" || option == "--filename" )
        filename = value;
      if ( option == "-c" || option == "--cfd_threshold" )
        cfd_threshold = std::stof(value);
      if ( option == "-t" || option == "--threshold" )
        threshold = std::stof(value);
      if ( option == "-p" || option == "--lowpass" )
        lowpass = std::stof(value);
      if ( option == "-o" || option == "--outputdir" )
        outputdir = value;
      if ( option == "-i" || option == "--filename" )
        filename = value;
    }
  }

  if (filename == "") {
    std::cout << "Input file required! For help use:" << std::endl;
    std::cout << argv[0] << " --help" << std::endl;
    return 0;
  }

  // Creating the analysis object from data TTree
  TFileCollection * fc_example = new TFileCollection();
  TChain * c_example = new TChain("pulse");
  fc_example->Add(filename.c_str());
  c_example->AddFileInfoList((TCollection*)fc_example->GetList());

  TimingAnalysis example_analyzeData(c_example);

  // Output file
  TString filenameTail("_result_MCP_");
  filenameTail+=secondchannel;
  filename.insert(filename.size()-5,filenameTail.Data());
  filename.erase(0,filename.find_last_of('/',filename.size()));
  filename.insert(0,outputdir);
  TFile * f_root = new TFile (filename.c_str(),"RECREATE");

  std::cout<<"Filling "<<filename<<" with "<<filename<<std::endl;

  if (cfd_threshold > 0) {
    AlgorithmParameters par(0.5, cfd_threshold, threshold_MCP,threshold,lowpass,hysteresis,min_amplitude_MCP, max_amplitude_MCP, min_amplitude_ch2, max_amplitude_ch2,baseline_p);
    double timeres_ps = example_analyzeData.executeTimeDifference<AlgorithmParameters>(f_root, ComputeExactTimeCFD, par, firstchannel, secondchannel)*1e12;
    std::cout << "\t\t\tTime difference: " << timeres_ps << " ps" << std::endl;
  }
  else {
    TDirectory* cfd_dir = f_root->mkdir("cfd_scan");
    TGraph cfd_graph;
    cfd_graph.SetName("cfd_scan");
    int cfd_counter=0;
    for (float cfd_th=std::abs(cfd_threshold); cfd_th<1; cfd_th+=std::abs(cfd_threshold)) {
      std::cout<< "############ CFD fraction " << cfd_th << " ############" <<std::endl;
      TString cfd_tmpdir_name("cfd_");
      cfd_tmpdir_name += (int) (100*cfd_th);
      cfd_tmpdir_name += "_percent";
      TDirectory* cfd_tmpdir = f_root->mkdir(cfd_tmpdir_name);
      cfd_tmpdir->cd();
      AlgorithmParameters par( 0.5, cfd_th, threshold_MCP,threshold,lowpass,hysteresis,min_amplitude_MCP, max_amplitude_MCP, min_amplitude_ch2, max_amplitude_ch2,baseline_p);  //Fixed cfd_threshold for ch0
      double timeres_ps = example_analyzeData.executeTimeDifference<AlgorithmParameters>(f_root, ComputeExactTimeCFD, par, firstchannel, secondchannel)*1e12;
      std::cout << "\t\t\tTime difference: " << timeres_ps << " ps" << std::endl;
      cfd_graph.SetPoint(cfd_counter++, cfd_th, timeres_ps);
    }
    cfd_dir->cd();
    cfd_graph.Write();
  }

  f_root->Close();
  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: segmentedname.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2007-12-12 14:56:07 $
 *
 *  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 ARY_SEGMENTEDNAME_HXX
#define ARY_SEGMENTEDNAME_HXX

// USED SERVICES
    // BASE CLASSES
    // OTHER

namespace ary
{
namespace sn    // segmented name
{

/** One segment in a name like "::global::abc<hello,xy>::def".
    A segment being the part between "::"s.

    @collab implements ->SegmentedName
*/
class NameSegment
{
  public:
    explicit            NameSegment(
                            const char *        i_name );
    explicit            NameSegment(
                            const String &      i_name );
                        NameSegment(
                            const NameSegment & i_segment );
                        ~NameSegment();
    // OPERATORS
    NameSegment &       operator=(
                            const NameSegment & i_other );
    bool                operator<(
                            const NameSegment & i_other ) const;
    // OPERATIONS
    String &            Make_Template();

    // INQUIRY
    const String  &     Name() const;
    const String *      TemplateArguments() const;

    void                Get_Text(
                            StreamStr &         o_out ) const;
  private:
    // DATA
    String              sName;
    Dyn<String>         pTemplateArguments;
};

typedef std::vector<NameSegment>        NameChain;

}   // namespace sn

/** A name of the form "::global::abc<hello,xy>::def".
*/
class SegmentedName
{
  public:
    explicit            SegmentedName(
                            const char *        i_text );
    explicit            SegmentedName(
                            const String &      i_text );
                        ~SegmentedName();
    // OPERATIONS
    bool                operator<(
                            const SegmentedName &
                                                i_other ) const;

    // INQUIRY
    bool                IsAbsolute() const;
    const sn::NameChain &
                        Sequence() const;

    void                Get_Text(
                            StreamStr &         o_out ) const;
  private:
    void                Interpret_Text(
                            const char *        i_text ); /// [valid C++ or IDL name].

    // DATA
    sn::NameChain       aSegments;
    bool                bIsAbsolute;
};

// IMPLEMENTATION
namespace sn
{

inline const String  &
NameSegment::Name() const
{
    return sName;
}

inline const String *
NameSegment::TemplateArguments() const
{
    return pTemplateArguments.Ptr();
}

}   // namespace sn

inline bool
SegmentedName::IsAbsolute() const
{
    return bIsAbsolute;
}

inline const sn::NameChain &
SegmentedName::Sequence() const
{
    return aSegments;
}

}   // namespace ary
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.14); FILE MERGED 2008/03/28 16:00:58 rt 1.3.14.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: segmentedname.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef ARY_SEGMENTEDNAME_HXX
#define ARY_SEGMENTEDNAME_HXX

// USED SERVICES
    // BASE CLASSES
    // OTHER

namespace ary
{
namespace sn    // segmented name
{

/** One segment in a name like "::global::abc<hello,xy>::def".
    A segment being the part between "::"s.

    @collab implements ->SegmentedName
*/
class NameSegment
{
  public:
    explicit            NameSegment(
                            const char *        i_name );
    explicit            NameSegment(
                            const String &      i_name );
                        NameSegment(
                            const NameSegment & i_segment );
                        ~NameSegment();
    // OPERATORS
    NameSegment &       operator=(
                            const NameSegment & i_other );
    bool                operator<(
                            const NameSegment & i_other ) const;
    // OPERATIONS
    String &            Make_Template();

    // INQUIRY
    const String  &     Name() const;
    const String *      TemplateArguments() const;

    void                Get_Text(
                            StreamStr &         o_out ) const;
  private:
    // DATA
    String              sName;
    Dyn<String>         pTemplateArguments;
};

typedef std::vector<NameSegment>        NameChain;

}   // namespace sn

/** A name of the form "::global::abc<hello,xy>::def".
*/
class SegmentedName
{
  public:
    explicit            SegmentedName(
                            const char *        i_text );
    explicit            SegmentedName(
                            const String &      i_text );
                        ~SegmentedName();
    // OPERATIONS
    bool                operator<(
                            const SegmentedName &
                                                i_other ) const;

    // INQUIRY
    bool                IsAbsolute() const;
    const sn::NameChain &
                        Sequence() const;

    void                Get_Text(
                            StreamStr &         o_out ) const;
  private:
    void                Interpret_Text(
                            const char *        i_text ); /// [valid C++ or IDL name].

    // DATA
    sn::NameChain       aSegments;
    bool                bIsAbsolute;
};

// IMPLEMENTATION
namespace sn
{

inline const String  &
NameSegment::Name() const
{
    return sName;
}

inline const String *
NameSegment::TemplateArguments() const
{
    return pTemplateArguments.Ptr();
}

}   // namespace sn

inline bool
SegmentedName::IsAbsolute() const
{
    return bIsAbsolute;
}

inline const sn::NameChain &
SegmentedName::Sequence() const
{
    return aSegments;
}

}   // namespace ary
#endif
<|endoftext|>


<commit_before>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * 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 "system/globalenv.h"
#include "common/shared_types.h"
#include <zorbatypes/xerces_xmlcharray.h>
#include "store/api/item_factory.h"
#include "store/api/pul.h"

#include "types/casting.h"
#include "types/delegating_typemanager.h"
#include "types/typeimpl.h"
#include "types/schema/schema.h"
#include "types/schema/SchemaValidator.h"
#include "types/schema/StrX.h"

#include "context/static_context.h"
#include "context/collation_cache.h"
#include "context/namespace_context.h"
#include "compiler/parser/query_loc.h"
//#include "zorbaerrors/error_manager.h"
#include "zorbaerrors/error_messages.h"
#include "zorbaerrors/errors.h"

using namespace std;

namespace zorba
{

void validateAfterUpdate(zorba::store::Item* item, zorba::store::Item_t& pul,
    DelegatingTypeManager* delegatingTypeManager, static_context* staticContext,
    const QueryLoc& loc, bool isLax);

void processElement( store::Item_t& pul, static_context* staticContext,
    DelegatingTypeManager* delegatingTypeManager, SchemaValidator& schemaValidator,
    store::Item_t element);

void validateAttributes( SchemaValidator& schemaValidator, store::Iterator_t attributes);

void processAttributes( store::Item_t& pul, namespace_context& nsCtx,
    DelegatingTypeManager* delegatingTypeManager, SchemaValidator& schemaValidator,
    const store::Item* parent, store::Iterator_t attributes);

void processChildren( store::Item_t& pul, static_context* staticContext,
    namespace_context& nsCtx, DelegatingTypeManager* delegatingTypeManager,
    SchemaValidator& schemaValidator, store::Iterator_t children);

void processNamespaces ( SchemaValidator& schemaValidator, const store::Item *item);

void processTextValue (store::Item_t& pul, DelegatingTypeManager* delegatingTypeManager,
    namespace_context &nsCtx, store::Item_t typeQName, xqpStringStore_t& textValue,
    std::vector<store::Item_t> &resultList);

store::Item_t findAttributeItem(const store::Item *parent, store::Item_t &attQName);

/**
 *   Given a vector of root nodes, this method validates all of them and
 *   fills out pul with a list of changes that will be applied later, if
 *   the validation succeds. This should be called after an update.
 */
void validateAfterUpdate(const vector<zorba::store::Item*>& nodes, zorba::store::Item_t& pul,
    DelegatingTypeManager* delegatingTypeManager, static_context* staticContext,
    const QueryLoc& loc, bool isLax)
{
    for ( unsigned int i = 0; i<nodes.size() ; i++)
    {
        validateAfterUpdate(nodes[i], pul, delegatingTypeManager, staticContext, loc, isLax);
    }
}

void validateAfterUpdate(store::Item* item, zorba::store::Item_t& pul,
    DelegatingTypeManager* delegatingTypeManager, static_context* staticContext,
    const QueryLoc& loc, bool isLax)
{
    ZORBA_ASSERT(item->isNode());

    Schema* schema = delegatingTypeManager->getSchema();
    if ( !schema )
    {
        // no schema available no change to pul
        return;
    }

    //xqpStringStore_t baseUri = planState.theRuntimeCB->theStaticContext->
    //    final_baseuri().getStore();

    SchemaValidator schemaValidator = SchemaValidator(delegatingTypeManager,
        schema->getGrammarPool(), isLax, loc);

    switch ( item->getNodeKind() )
    {
    case store::StoreConsts::documentNode:
    {
        //std::cout << "Validate document" << "\n"; std::cout.flush();

        schemaValidator.startDoc();

        store::NsBindings bindings;
        item->getNamespaceBindings(bindings);
        namespace_context nsCtx = namespace_context(staticContext, bindings);

        processChildren( pul, staticContext, nsCtx, delegatingTypeManager, schemaValidator,
            item->getChildren() );

        schemaValidator.endDoc();

        //std::cout << "End Validate doc" << "\n"; std::cout.flush();
        return;
    }
    case store::StoreConsts::elementNode:
    {
        //std::cout << "Validate element" << "\n"; std::cout.flush();

        schemaValidator.startDoc();

        processElement(pul, staticContext, delegatingTypeManager, schemaValidator, item);

        schemaValidator.endDoc();

        //std::cout << "End Validate elem" << "\n"; std::cout.flush();
        return;
    }
    default:
        ZORBA_ERROR_LOC_DESC( XQDY0061, loc,
            "Argument in validate expression not a document or element node.");
        return;
    }
}

void processElement( store::Item_t& pul, static_context* staticContext,
    DelegatingTypeManager* delegatingTypeManager, SchemaValidator& schemaValidator,
    store::Item_t element)
{
    ZORBA_ASSERT(element->isNode());
    ZORBA_ASSERT(element->getNodeKind() == store::StoreConsts::elementNode);

    store::Item_t nodeName = element->getNodeName();
    xqpStringStore_t baseUri = element->getBaseURI();

    schemaValidator.startElem(nodeName);

    // namespace declarations must go first
    processNamespaces( schemaValidator, element);

    // since the type of an element is determined only after the validator receives all
    // of it's attributes, and an attribute node needs it's parent when created
    // we need to go through the attributes twice: once for validation and once for creation
    validateAttributes(schemaValidator, element->getAttributes());

    store::Item_t typeName = schemaValidator.getTypeQName();

    // check if type has changed
    //if ( typeName != element->getType() )
    {
        vector<store::Item_t> typedValues;
        bool hasTypedValue = true;
        bool hasEmptyValue = false;
        store::PUL *p = static_cast<store::PUL *>(pul.getp());
        p->addSetElementType(element, typeName, (vector<store::Item_t>&)typedValues, hasTypedValue, hasEmptyValue, element->isId(), element->isIdRefs());
    }

    store::NsBindings bindings;
    element->getNamespaceBindings(bindings);
    namespace_context nsCtx = namespace_context(staticContext, bindings);

    processAttributes( pul, nsCtx, delegatingTypeManager, schemaValidator, element, element->getAttributes());

    processChildren( pul, staticContext, nsCtx, delegatingTypeManager, schemaValidator, element->getChildren());

    schemaValidator.endElem(nodeName);
}

void validateAttributes( SchemaValidator& schemaValidator, store::Iterator_t attributes)
{
    store::Item_t attribute;

    while ( attributes->next(attribute) )
    {
        ZORBA_ASSERT(attribute->isNode());
        ZORBA_ASSERT(attribute->getNodeKind() == store::StoreConsts::attributeNode);

        //std::cout << " v    - attr: " << attribute->getNodeName()->getLocalName()->c_str() << "\n"; std::cout.flush();

        store::Item_t attName = attribute->getNodeName();
        schemaValidator.attr(attName, attribute->getStringValue());
    }
}

void processAttributes( store::Item_t& pul, namespace_context& nsCtx,
    DelegatingTypeManager* delegatingTypeManager, SchemaValidator& schemaValidator,
    const store::Item* parent, store::Iterator_t attributes)
{
    std::list<AttributeValidationInfo*>* attList = schemaValidator.getAttributeList();
    std::list<AttributeValidationInfo*>::iterator curAtt;

    for( curAtt = attList->begin() ; curAtt != attList->end(); ++curAtt )
    {
        AttributeValidationInfo* att = *curAtt;
        //std::cout << " v    proccessATT2: " << att->_localName << " T: " << att->_typeName << "\n";

        store::Item_t attQName;
        GENV_ITEMFACTORY->createQName( attQName, att->_uri, att->_prefix, att->_localName);

        store::Item_t attrib = findAttributeItem(parent, attQName);

        std::string typePrefix;
        if ( std::strcmp(Schema::XSD_NAMESPACE, att->_typeURI->c_str() )==0 ) // hack around typeManager bug for comparing QNames
            typePrefix = "xs";
        else
            typePrefix = "";

        store::Item_t typeQName;
        GENV_ITEMFACTORY->createQName(typeQName, att->_typeURI, new xqpStringStore(typePrefix), att->_typeName);

        std::vector<store::Item_t> typedValues;
        processTextValue(pul, delegatingTypeManager, nsCtx, typeQName, att->_value, typedValues);

        //todo check in attributes if the type is different
        {
            store::PUL *p = static_cast<store::PUL *>(pul.getp());
            if ( typedValues.size()==1 )        // optimize when only one item is available
                p->addSetAttributeType( attrib, typeQName, (store::Item_t&)(typedValues[0]), attrib->isId(), attrib->isIdRefs() );
            else
                p->addSetAttributeType( attrib, typeQName, typedValues, attrib->isId(), attrib->isIdRefs() );
        }
    }
}

void processChildren( store::Item_t& pul, static_context* staticContext, namespace_context& nsCtx, DelegatingTypeManager* delegatingTypeManager,
    SchemaValidator& schemaValidator, store::Iterator_t children)
{
    store::Item_t child;

    store::Item_t typeName;

    while ( children->next(child) )
    {
        if ( child->isNode() )
        {
            //std::cout << "  > child: " << child->getNodeKind() << " " << child->getType()->getLocalName()->c_str() << "\n";
            //std::cout.flush();

            switch ( child->getNodeKind() )
            {
            case store::StoreConsts::elementNode:
                processElement( pul, staticContext, delegatingTypeManager, schemaValidator, child);
                break;

            case store::StoreConsts::attributeNode:
                ZORBA_ASSERT(false);
                break;

            case store::StoreConsts::documentNode:
                ZORBA_ASSERT(false);
                break;

            case store::StoreConsts::textNode:
                {
                    //std::cout << "     - text: " << child->getStringValue() << "\n"; std::cout.flush();
                    xqpStringStore_t childStringValue = child->getStringValue();
                    schemaValidator.text(childStringValue);

                    store::Item_t type = schemaValidator.getTypeQName();

                    std::vector<store::Item_t> typedValues;
                    processTextValue(pul, delegatingTypeManager, nsCtx, type, childStringValue, typedValues );

                    //todo check in attributes if the type is different
                    {
                        bool hasTypedValue = true;
                        bool hasEmptyValue = false;
                        store::PUL *p = static_cast<store::PUL *>(pul.getp());

                        if ( typedValues.size()==1 ) // hack around serialization bug
                            p->addSetElementType(child, type, typedValues[0], hasTypedValue, hasEmptyValue, child->isId(), child->isIdRefs());
                        else
                            p->addSetElementType(child, type, typedValues, hasTypedValue, hasEmptyValue, child->isId(), child->isIdRefs());
                    }
                }
                break;

            case store::StoreConsts::piNode:
                {
                    //std::cout << "     - pi: " << child->getStringValue() << "\n"; std::cout.flush();
                    // do nothing
                }
                break;

            case store::StoreConsts::commentNode:
                {
                    //std::cout << "     - comment: " << child->getStringValue() << "\n"; std::cout.flush();
                    // do nothing
                }
                break;

            case store::StoreConsts::anyNode:
                //std::cout << "     - any: " << child->getStringValue() << "\n"; std::cout.flush();
                ZORBA_ASSERT(false);
                break;

            default:
                ZORBA_ASSERT(false);
            }
        }
    }
}

void processNamespaces ( SchemaValidator& schemaValidator, const store::Item *item)
{
    store::NsBindings bindings;
    item->getNamespaceBindings(bindings, store::StoreConsts::ONLY_LOCAL_NAMESPACES);

    for (unsigned long i = 0; i < bindings.size(); i++)
    {
        schemaValidator.ns( bindings[i].first.getStore(), bindings[i].second.getStore() );
    }
}

void processTextValue (store::Item_t& pul, DelegatingTypeManager* delegatingTypeManager,
    namespace_context &nsCtx, store::Item_t typeQName, xqpStringStore_t& textValue,
    std::vector<store::Item_t> &resultList)
{
    xqtref_t type = delegatingTypeManager->create_named_atomic_type(typeQName, TypeConstants::QUANT_ONE);
    //std::cout << "     - processTextValue: " << typeQName->getPrefix()->str() << ":" << typeQName->getLocalName()->str() << "@" <<
    //    typeQName->getNamespace()->str() ; std::cout.flush();
    //std::cout << " type: " << ( type==NULL ? "NULL" : type->toString()) << "\n"; std::cout.flush();

    store::Item_t result;
    if (type!=NULL)
    {
        bool listOrUnion = false;
        if ( type->type_kind() == XQType::USER_DEFINED_KIND )
        {
            const UserDefinedXQType udXQType = static_cast<const UserDefinedXQType&>(*type);
            if ( udXQType.isList() || udXQType.isUnion() )
            {
                listOrUnion = true;
            }
        }

        if ( listOrUnion )
        {
            xqp_string str(textValue);
            delegatingTypeManager->getSchema()->
                parseUserSimpleTypes(str, type, resultList);
        }
        else
        {
            bool isResult = GenericCast::instance()->castToAtomic(result, textValue, type.getp(), &nsCtx);
            if ( isResult )
                resultList.push_back(result);
        }
    }
    else
    {
        if ( GENV_ITEMFACTORY->createUntypedAtomic( result, textValue) )
            resultList.push_back(result);
    }
}

store::Item_t findAttributeItem(const store::Item *parent, store::Item_t &attQName)
{
    store::Iterator_t attributes = parent->getAttributes();

    store::Item_t attribute;

    while ( attributes->next(attribute) )
    {
        ZORBA_ASSERT(attribute->isNode());
        ZORBA_ASSERT(attribute->getNodeKind() == store::StoreConsts::attributeNode);

        store::Item_t currentAttName = attribute->getNodeName();

        if ( attQName->getLocalName()->
                compare(currentAttName->getLocalName())==0 &&
             attQName->getNamespace()->
                compare(currentAttName->getNamespace())==0 )
        {
            return attribute.getp();
        }
    }
    ZORBA_ASSERT(false);
    return NULL;
}

}// namespace zorba
<commit_msg>Fix build with ZORBA_NO_XMLSCHEMA flag.<commit_after>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * 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 "system/globalenv.h"
#include "common/shared_types.h"
#include <zorbatypes/xerces_xmlcharray.h>
#include "store/api/item_factory.h"
#include "store/api/pul.h"

#include "types/casting.h"
#include "types/delegating_typemanager.h"
#include "types/typeimpl.h"
#include "types/schema/schema.h"
#include "types/schema/SchemaValidator.h"
#include "types/schema/StrX.h"

#include "context/static_context.h"
#include "context/collation_cache.h"
#include "context/namespace_context.h"
#include "compiler/parser/query_loc.h"
//#include "zorbaerrors/error_manager.h"
#include "zorbaerrors/error_messages.h"
#include "zorbaerrors/errors.h"

using namespace std;

namespace zorba
{

void validateAfterUpdate(zorba::store::Item* item, zorba::store::Item_t& pul,
    DelegatingTypeManager* delegatingTypeManager, static_context* staticContext,
    const QueryLoc& loc, bool isLax);

void processElement( store::Item_t& pul, static_context* staticContext,
    DelegatingTypeManager* delegatingTypeManager, SchemaValidator& schemaValidator,
    store::Item_t element);

void validateAttributes( SchemaValidator& schemaValidator, store::Iterator_t attributes);

void processAttributes( store::Item_t& pul, namespace_context& nsCtx,
    DelegatingTypeManager* delegatingTypeManager, SchemaValidator& schemaValidator,
    const store::Item* parent, store::Iterator_t attributes);

void processChildren( store::Item_t& pul, static_context* staticContext,
    namespace_context& nsCtx, DelegatingTypeManager* delegatingTypeManager,
    SchemaValidator& schemaValidator, store::Iterator_t children);

void processNamespaces ( SchemaValidator& schemaValidator, const store::Item *item);

void processTextValue (store::Item_t& pul, DelegatingTypeManager* delegatingTypeManager,
    namespace_context &nsCtx, store::Item_t typeQName, xqpStringStore_t& textValue,
    std::vector<store::Item_t> &resultList);

store::Item_t findAttributeItem(const store::Item *parent, store::Item_t &attQName);

/**
 *   Given a vector of root nodes, this method validates all of them and
 *   fills out pul with a list of changes that will be applied later, if
 *   the validation succeds. This should be called after an update.
 */
void validateAfterUpdate(const vector<zorba::store::Item*>& nodes, zorba::store::Item_t& pul,
    DelegatingTypeManager* delegatingTypeManager, static_context* staticContext,
    const QueryLoc& loc, bool isLax)
{
#ifndef ZORBA_NO_XMLSCHEMA
    for ( unsigned int i = 0; i<nodes.size() ; i++)
    {
        validateAfterUpdate(nodes[i], pul, delegatingTypeManager, staticContext, loc, isLax);
    }
#endif //ZORBA_NO_XMLSCHEMA
}

#ifndef ZORBA_NO_XMLSCHEMA
void validateAfterUpdate(store::Item* item, zorba::store::Item_t& pul,
    DelegatingTypeManager* delegatingTypeManager, static_context* staticContext,
    const QueryLoc& loc, bool isLax)
{
    ZORBA_ASSERT(item->isNode());

    Schema* schema = delegatingTypeManager->getSchema();
    if ( !schema )
    {
        // no schema available no change to pul
        return;
    }

    //xqpStringStore_t baseUri = planState.theRuntimeCB->theStaticContext->
    //    final_baseuri().getStore();

    SchemaValidator schemaValidator = SchemaValidator(delegatingTypeManager,
        schema->getGrammarPool(), isLax, loc);

    switch ( item->getNodeKind() )
    {
    case store::StoreConsts::documentNode:
    {
        //std::cout << "Validate document" << "\n"; std::cout.flush();

        schemaValidator.startDoc();

        store::NsBindings bindings;
        item->getNamespaceBindings(bindings);
        namespace_context nsCtx = namespace_context(staticContext, bindings);

        processChildren( pul, staticContext, nsCtx, delegatingTypeManager, schemaValidator,
            item->getChildren() );

        schemaValidator.endDoc();

        //std::cout << "End Validate doc" << "\n"; std::cout.flush();
        return;
    }
    case store::StoreConsts::elementNode:
    {
        //std::cout << "Validate element" << "\n"; std::cout.flush();

        schemaValidator.startDoc();

        processElement(pul, staticContext, delegatingTypeManager, schemaValidator, item);

        schemaValidator.endDoc();

        //std::cout << "End Validate elem" << "\n"; std::cout.flush();
        return;
    }
    default:
        ZORBA_ERROR_LOC_DESC( XQDY0061, loc,
            "Argument in validate expression not a document or element node.");
        return;
    }
}

void processElement( store::Item_t& pul, static_context* staticContext,
    DelegatingTypeManager* delegatingTypeManager, SchemaValidator& schemaValidator,
    store::Item_t element)
{
    ZORBA_ASSERT(element->isNode());
    ZORBA_ASSERT(element->getNodeKind() == store::StoreConsts::elementNode);

    store::Item_t nodeName = element->getNodeName();
    xqpStringStore_t baseUri = element->getBaseURI();

    schemaValidator.startElem(nodeName);

    // namespace declarations must go first
    processNamespaces( schemaValidator, element);

    // since the type of an element is determined only after the validator receives all
    // of it's attributes, and an attribute node needs it's parent when created
    // we need to go through the attributes twice: once for validation and once for creation
    validateAttributes(schemaValidator, element->getAttributes());

    store::Item_t typeName = schemaValidator.getTypeQName();

    // check if type has changed
    //if ( typeName != element->getType() )
    {
        vector<store::Item_t> typedValues;
        bool hasTypedValue = true;
        bool hasEmptyValue = false;
        store::PUL *p = static_cast<store::PUL *>(pul.getp());
        p->addSetElementType(element, typeName, (vector<store::Item_t>&)typedValues, hasTypedValue, hasEmptyValue, element->isId(), element->isIdRefs());
    }

    store::NsBindings bindings;
    element->getNamespaceBindings(bindings);
    namespace_context nsCtx = namespace_context(staticContext, bindings);

    processAttributes( pul, nsCtx, delegatingTypeManager, schemaValidator, element, element->getAttributes());

    processChildren( pul, staticContext, nsCtx, delegatingTypeManager, schemaValidator, element->getChildren());

    schemaValidator.endElem(nodeName);
}

void validateAttributes( SchemaValidator& schemaValidator, store::Iterator_t attributes)
{
    store::Item_t attribute;

    while ( attributes->next(attribute) )
    {
        ZORBA_ASSERT(attribute->isNode());
        ZORBA_ASSERT(attribute->getNodeKind() == store::StoreConsts::attributeNode);

        //std::cout << " v    - attr: " << attribute->getNodeName()->getLocalName()->c_str() << "\n"; std::cout.flush();

        store::Item_t attName = attribute->getNodeName();
        schemaValidator.attr(attName, attribute->getStringValue());
    }
}

void processAttributes( store::Item_t& pul, namespace_context& nsCtx,
    DelegatingTypeManager* delegatingTypeManager, SchemaValidator& schemaValidator,
    const store::Item* parent, store::Iterator_t attributes)
{
    std::list<AttributeValidationInfo*>* attList = schemaValidator.getAttributeList();
    std::list<AttributeValidationInfo*>::iterator curAtt;

    for( curAtt = attList->begin() ; curAtt != attList->end(); ++curAtt )
    {
        AttributeValidationInfo* att = *curAtt;
        //std::cout << " v    proccessATT2: " << att->_localName << " T: " << att->_typeName << "\n";

        store::Item_t attQName;
        GENV_ITEMFACTORY->createQName( attQName, att->_uri, att->_prefix, att->_localName);

        store::Item_t attrib = findAttributeItem(parent, attQName);

        std::string typePrefix;
        if ( std::strcmp(Schema::XSD_NAMESPACE, att->_typeURI->c_str() )==0 ) // hack around typeManager bug for comparing QNames
            typePrefix = "xs";
        else
            typePrefix = "";

        store::Item_t typeQName;
        GENV_ITEMFACTORY->createQName(typeQName, att->_typeURI, new xqpStringStore(typePrefix), att->_typeName);

        std::vector<store::Item_t> typedValues;
        processTextValue(pul, delegatingTypeManager, nsCtx, typeQName, att->_value, typedValues);

        //todo check in attributes if the type is different
        {
            store::PUL *p = static_cast<store::PUL *>(pul.getp());
            if ( typedValues.size()==1 )        // optimize when only one item is available
                p->addSetAttributeType( attrib, typeQName, (store::Item_t&)(typedValues[0]), attrib->isId(), attrib->isIdRefs() );
            else
                p->addSetAttributeType( attrib, typeQName, typedValues, attrib->isId(), attrib->isIdRefs() );
        }
    }
}

void processChildren( store::Item_t& pul, static_context* staticContext, namespace_context& nsCtx, DelegatingTypeManager* delegatingTypeManager,
    SchemaValidator& schemaValidator, store::Iterator_t children)
{
    store::Item_t child;

    store::Item_t typeName;

    while ( children->next(child) )
    {
        if ( child->isNode() )
        {
            //std::cout << "  > child: " << child->getNodeKind() << " " << child->getType()->getLocalName()->c_str() << "\n";
            //std::cout.flush();

            switch ( child->getNodeKind() )
            {
            case store::StoreConsts::elementNode:
                processElement( pul, staticContext, delegatingTypeManager, schemaValidator, child);
                break;

            case store::StoreConsts::attributeNode:
                ZORBA_ASSERT(false);
                break;

            case store::StoreConsts::documentNode:
                ZORBA_ASSERT(false);
                break;

            case store::StoreConsts::textNode:
                {
                    //std::cout << "     - text: " << child->getStringValue() << "\n"; std::cout.flush();
                    xqpStringStore_t childStringValue = child->getStringValue();
                    schemaValidator.text(childStringValue);

                    store::Item_t type = schemaValidator.getTypeQName();

                    std::vector<store::Item_t> typedValues;
                    processTextValue(pul, delegatingTypeManager, nsCtx, type, childStringValue, typedValues );

                    //todo check in attributes if the type is different
                    {
                        bool hasTypedValue = true;
                        bool hasEmptyValue = false;
                        store::PUL *p = static_cast<store::PUL *>(pul.getp());

                        if ( typedValues.size()==1 ) // hack around serialization bug
                            p->addSetElementType(child, type, typedValues[0], hasTypedValue, hasEmptyValue, child->isId(), child->isIdRefs());
                        else
                            p->addSetElementType(child, type, typedValues, hasTypedValue, hasEmptyValue, child->isId(), child->isIdRefs());
                    }
                }
                break;

            case store::StoreConsts::piNode:
                {
                    //std::cout << "     - pi: " << child->getStringValue() << "\n"; std::cout.flush();
                    // do nothing
                }
                break;

            case store::StoreConsts::commentNode:
                {
                    //std::cout << "     - comment: " << child->getStringValue() << "\n"; std::cout.flush();
                    // do nothing
                }
                break;

            case store::StoreConsts::anyNode:
                //std::cout << "     - any: " << child->getStringValue() << "\n"; std::cout.flush();
                ZORBA_ASSERT(false);
                break;

            default:
                ZORBA_ASSERT(false);
            }
        }
    }
}

void processNamespaces ( SchemaValidator& schemaValidator, const store::Item *item)
{
    store::NsBindings bindings;
    item->getNamespaceBindings(bindings, store::StoreConsts::ONLY_LOCAL_NAMESPACES);

    for (unsigned long i = 0; i < bindings.size(); i++)
    {
        schemaValidator.ns( bindings[i].first.getStore(), bindings[i].second.getStore() );
    }
}

void processTextValue (store::Item_t& pul, DelegatingTypeManager* delegatingTypeManager,
    namespace_context &nsCtx, store::Item_t typeQName, xqpStringStore_t& textValue,
    std::vector<store::Item_t> &resultList)
{
    xqtref_t type = delegatingTypeManager->create_named_atomic_type(typeQName, TypeConstants::QUANT_ONE);
    //std::cout << "     - processTextValue: " << typeQName->getPrefix()->str() << ":" << typeQName->getLocalName()->str() << "@" <<
    //    typeQName->getNamespace()->str() ; std::cout.flush();
    //std::cout << " type: " << ( type==NULL ? "NULL" : type->toString()) << "\n"; std::cout.flush();

    store::Item_t result;
    if (type!=NULL)
    {
        bool listOrUnion = false;
        if ( type->type_kind() == XQType::USER_DEFINED_KIND )
        {
            const UserDefinedXQType udXQType = static_cast<const UserDefinedXQType&>(*type);
            if ( udXQType.isList() || udXQType.isUnion() )
            {
                listOrUnion = true;
            }
        }

        if ( listOrUnion )
        {
            xqp_string str(textValue);
            delegatingTypeManager->getSchema()->
                parseUserSimpleTypes(str, type, resultList);
        }
        else
        {
            bool isResult = GenericCast::instance()->castToAtomic(result, textValue, type.getp(), &nsCtx);
            if ( isResult )
                resultList.push_back(result);
        }
    }
    else
    {
        if ( GENV_ITEMFACTORY->createUntypedAtomic( result, textValue) )
            resultList.push_back(result);
    }
}

store::Item_t findAttributeItem(const store::Item *parent, store::Item_t &attQName)
{
    store::Iterator_t attributes = parent->getAttributes();

    store::Item_t attribute;

    while ( attributes->next(attribute) )
    {
        ZORBA_ASSERT(attribute->isNode());
        ZORBA_ASSERT(attribute->getNodeKind() == store::StoreConsts::attributeNode);

        store::Item_t currentAttName = attribute->getNodeName();

        if ( attQName->getLocalName()->
                compare(currentAttName->getLocalName())==0 &&
             attQName->getNamespace()->
                compare(currentAttName->getNamespace())==0 )
        {
            return attribute.getp();
        }
    }
    ZORBA_ASSERT(false);
    return NULL;
}
#endif //ZORBA_NO_XMLSCHEMA

}// namespace zorba
<|endoftext|>


<commit_before><commit_msg>add ttree for local efficiency<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 2016 Patrizio Bekerle -- http://www.bekerle.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * QTextEdit markdown highlighter
 */

#include <QTimer>
#include "markdownhighlighter.h"

/**
 * Markdown syntax highlighting
 *
 * markdown syntax:
 * http://daringfireball.net/projects/markdown/syntax
 *
 * @param parent
 * @return
 */
MarkdownHighlighter::MarkdownHighlighter(QTextDocument *parent)
        : QSyntaxHighlighter(parent) {
    _dirtyBlockTimer = new QTimer(this);
    QObject::connect(_dirtyBlockTimer, SIGNAL(timeout()),
                     this, SLOT(reHighlightDirtyBlocks()));
    _dirtyBlockTimer->start(1000);

    // initialize the highlighting rules
    initHighlightingRules();

    // initialize the text formats
    initTextFormats();
}

/**
 * Re-highlights all dirty blocks
 */
void MarkdownHighlighter::reHighlightDirtyBlocks() {
    while (_dirtyTextBlocks.count() > 0) {
        QTextBlock block = _dirtyTextBlocks.at(0);
        rehighlightBlock(block);
        _dirtyTextBlocks.removeFirst();
    }
}

/**
 * Adds a dirty block to the list if it doesn't already exist
 *
 * @param block
 */
void MarkdownHighlighter::addDirtyBlock(QTextBlock block) {
    if (!_dirtyTextBlocks.contains(block)) {
        _dirtyTextBlocks.append(block);
    }
}

/**
 * Initializes the highlighting rules
 *
 * regexp tester:
 * https://regex101.com
 */
void MarkdownHighlighter::initHighlightingRules() {
    HighlightingRule rule;

    // highlight bold
    rule.pattern = QRegularExpression("\\B\\*{2}.+?\\*{2}\\B");
    rule.state = HighlighterState::Bold;
    _highlightingRulesAfter.append(rule);
    rule.pattern = QRegularExpression("(^|\\s)__.+?__($|\\s)");
    _highlightingRulesAfter.append(rule);

    // highlight italic
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("(^|\\s)\\*[^\\*]+\\*($|\\s)");
    rule.state = HighlighterState::Italic;
    _highlightingRulesAfter.append(rule);
    rule.pattern = QRegularExpression("(^|\\s)_[^_]+_($|\\s)");
    _highlightingRulesAfter.append(rule);

    // highlight urls
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("<.+?:\\/\\/.+?>");
    rule.state = HighlighterState::Link;
    _highlightingRulesAfter.append(rule);

    // highlight urls without any other markup
    rule.pattern = QRegularExpression("\\b\\w+?:\\/\\/[^\\s]+");
    _highlightingRulesAfter.append(rule);

    // highlight urls with title
    rule.pattern = QRegularExpression("\\[.+?\\]\\(.+?://.+?\\)");
    _highlightingRulesAfter.append(rule);

    // highlight email links
    rule.pattern = QRegularExpression("<.+?@.+?>");
    _highlightingRulesAfter.append(rule);

    // highlight reference links
    rule.pattern = QRegularExpression("\\[.+?\\]\\[\\d+\\]");
    _highlightingRulesAfter.append(rule);

    // highlight the reference of reference links
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("^\\[\\d+?\\]: .+://.+$");
    rule.state = HighlighterState::Comment;
    _highlightingRulesPre.append(rule);

    // highlight unordered lists
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("^\\s*[-*+]\\s");
    rule.state = HighlighterState::List;
    rule.useStateAsCurrentBlockState = true;
    _highlightingRulesPre.append(rule);

    // highlight ordered lists
    rule.pattern = QRegularExpression("^\\s*\\d\\.\\s");
    _highlightingRulesPre.append(rule);

    // highlight inline code
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("`.+?`");
    rule.state = HighlighterState::InlineCodeBlock;
    _highlightingRulesPre.append(rule);

    // highlight code blocks with four spaces or tabs in front of them
    // and no list character after that
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("^((\\t)|( {4,})).+$");
    rule.state = HighlighterState::CodeBlock;
    rule.disableIfCurrentStateIsSet = true;
    _highlightingRulesPre.append(rule);

    // highlight images
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("!\\[.*?\\]\\(.+?\\)");
    rule.state = HighlighterState::Image;
    _highlightingRulesPre.append(rule);

    // highlight block quotes
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("^> ");
    rule.state = HighlighterState::BlockQuote;
    _highlightingRulesPre.append(rule);

    // highlight inline comments
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("<!\\-\\-.+?\\-\\->");
    rule.state = HighlighterState::Comment;
    _highlightingRulesPre.append(rule);

    // highlight horizontal rulers
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("^([*\\-_]\\s?){3,}$");
    rule.state = HighlighterState::HorizontalRuler;
    _highlightingRulesPre.append(rule);

    // highlight tables
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("^\\|.+?\\|$");
    rule.state = HighlighterState::Table;
    _highlightingRulesPre.append(rule);
    rule.pattern = QRegularExpression("^.+? \\| .+? \\| .+$");
    _highlightingRulesPre.append(rule);
}

/**
 * Initializes the text formats
 *
 * @param defaultFontSize
 */
void MarkdownHighlighter::initTextFormats(int defaultFontSize) {
    QTextCharFormat format;

    // set character formats for headlines
    format = QTextCharFormat();
    format.setForeground(QBrush(QColor(0, 49, 110)));
    format.setBackground(QBrush(QColor(230, 230, 240)));
    format.setFontWeight(QFont::Bold);
    format.setFontPointSize(defaultFontSize * 1.2);
    _formats[H1] = format;
    format.setFontPointSize(defaultFontSize * 1.1);
    _formats[H2] = format;
    format.setFontPointSize(defaultFontSize);
    _formats[H3] = format;
    _formats[H4] = format;
    _formats[H5] = format;
    _formats[H6] = format;

    // set character format for horizontal rulers
    format = QTextCharFormat();
    format.setForeground(QBrush(Qt::darkGray));
    format.setBackground(QBrush(Qt::lightGray));
    _formats[HorizontalRuler] = format;

    // set character format for lists
    format = QTextCharFormat();
    format.setForeground(QBrush(QColor(163, 0, 123)));
    _formats[List] = format;

    // set character format for links
    format = QTextCharFormat();
    format.setForeground(QBrush(QColor(255, 128, 0)));
    format.setBackground(QBrush(QColor(255, 233, 211)));
    _formats[Link] = format;

    // set character format for images
    format = QTextCharFormat();
    format.setForeground(QBrush(QColor(0, 191, 0)));
    format.setBackground(QBrush(QColor(228, 255, 228)));
    _formats[Image] = format;

    // set character format for code blocks
    format = QTextCharFormat();
    format.setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
    format.setForeground(QBrush(Qt::darkGreen));
    format.setBackground(QBrush(QColor(217, 231, 217)));
    _formats[CodeBlock] = format;
    _formats[InlineCodeBlock] = format;

    // set character format for italic
    format = QTextCharFormat();
    format.setFontWeight(QFont::StyleItalic);
    format.setForeground(QBrush(QColor(0, 87, 174)));
    _formats[Italic] = format;

    // set character format for bold
    format = QTextCharFormat();
    format.setFontWeight(QFont::Bold);
    format.setForeground(QBrush(QColor(0, 66, 138)));
    _formats[Bold] = format;

    // set character format for comments
    format = QTextCharFormat();
    format.setForeground(QBrush(Qt::gray));
    _formats[Comment] = format;

    // set character format for tables
    format = QTextCharFormat();
    format.setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
    format.setForeground(QBrush(QColor("#649449")));
    _formats[Table] = format;

    // set character format for block quotes
    format = QTextCharFormat();
    format.setForeground(QBrush(QColor(Qt::darkRed)));
    _formats[BlockQuote] = format;
}

/**
 * Sets the text formats
 *
 * @param formats
 */
void MarkdownHighlighter::setTextFormats(
        QHash<HighlighterState, QTextCharFormat> formats) {
    _formats = formats;
}

/**
 * Sets a text format
 *
 * @param formats
 */
void MarkdownHighlighter::setTextFormat(HighlighterState state,
                                        QTextCharFormat format) {
    _formats[state] = format;
}

/**
 * Does the markdown highlighting
 *
 * @param text
 */
void MarkdownHighlighter::highlightBlock(const QString &text) {
    setCurrentBlockState(HighlighterState::NoState);
    currentBlock().setUserState(HighlighterState::NoState);
    highlightMarkdown(text);
    emit(highlightingFinished());
}

void MarkdownHighlighter::highlightMarkdown(QString text) {
    if (!text.isEmpty()) {
        highlightAdditionalRules(_highlightingRulesPre, text);

        // needs to be called after the horizontal ruler highlighting
        highlightHeadline(text);

        highlightAdditionalRules(_highlightingRulesAfter, text);
    }

    highlightCommentBlock(text);
    highlightCodeBlock(text);
}

/**
 * Highlight headlines
 *
 * @param text
 */
void MarkdownHighlighter::highlightHeadline(QString text) {
    QRegularExpression re("^(#+) .+?$");
    QRegularExpressionMatch match = re.match(text);

    // check for headline blocks with # in front of them
    if (match.hasMatch()) {
        int count = match.captured(1).count();

        // we just have H1 to H6
        count = qMin(count, 6);

        HighlighterState state = HighlighterState(
                HighlighterState::H1 + count - 1);

        setFormat(match.capturedStart(), match.capturedLength(),
                  _formats[state]);
        setCurrentBlockState(state);
        currentBlock().setUserState(state);
        return;
    }

    // take care of ==== and ---- headlines
    QRegularExpression patternH1 = QRegularExpression("^=+$");
    QRegularExpression patternH2 = QRegularExpression("^-+$");
    QTextBlock previousBlock = currentBlock().previous();
    QString previousText = previousBlock.text();
    previousText.trimmed().remove(QRegularExpression("[=-]"));

    // check for ===== after a headline text and highlight as H1
    if (patternH1.match(text).hasMatch()) {
        if (((previousBlockState() == HighlighterState::H1) ||
                (previousBlockState() == HighlighterState::NoState)) &&
                (previousText.length() > 0)) {
            setFormat(0, text.length(), _formats[HighlighterState::H1]);
            setCurrentBlockState(HighlighterState::HeadlineEnd);
            previousBlock.setUserState(HighlighterState::H1);

            // we want to re-highlight the previous block
            // this must not done directly, but with a queue, otherwise it
            // will crash
            // setting the character format of the previous text, because this
            // causes text to be formatted the same way when writing after
            // the text
            addDirtyBlock(previousBlock);
        }

        return;
    }

    // check for ----- after a headline text and highlight as H2
    if (patternH2.match(text).hasMatch()) {
        if (((previousBlockState() == HighlighterState::H2) ||
             (previousBlockState() == HighlighterState::NoState)) &&
            (previousText.length() > 0)) {
            setFormat(0, text.length(), _formats[HighlighterState::H2]);
            setCurrentBlockState(HighlighterState::HeadlineEnd);
            previousBlock.setUserState(HighlighterState::H2);

            // we want to re-highlight the previous block
            addDirtyBlock(previousBlock);
        }

        return;
    }

    QTextBlock nextBlock = currentBlock().next();
    QString nextBlockText = nextBlock.text();

    // highlight as H1 if next block is =====
    if (patternH1.match(nextBlockText).hasMatch() ||
            patternH2.match(nextBlockText).hasMatch()) {
        setFormat(0, text.length(), _formats[HighlighterState::H1]);
        setCurrentBlockState(HighlighterState::H1);
        currentBlock().setUserState(HighlighterState::H1);
    }

    // highlight as H2 if next block is -----
    if (patternH2.match(nextBlockText).hasMatch()) {
        setFormat(0, text.length(), _formats[HighlighterState::H2]);
        setCurrentBlockState(HighlighterState::H2);
        currentBlock().setUserState(HighlighterState::H2);
    }
}

/**
 * Highlight multiline code blocks
 *
 * @param text
 */
void MarkdownHighlighter::highlightCodeBlock(QString text) {
    bool highlight = false;

    QRegularExpression re("^```\\w*?$");
    QRegularExpressionMatch match = re.match(text);

    if (match.hasMatch()) {
        setCurrentBlockState(
                previousBlockState() == HighlighterState::CodeBlock ?
                HighlighterState::CodeBlockEnd : HighlighterState::CodeBlock);
        highlight = true;
    } else if (previousBlockState() == HighlighterState::CodeBlock) {
        setCurrentBlockState(HighlighterState::CodeBlock);
        highlight = true;
    }

    if (highlight) {
        setFormat(0, text.length(), _formats[HighlighterState::CodeBlock]);
    }
}

/**
 * Highlight multiline comments
 *
 * @param text
 */
void MarkdownHighlighter::highlightCommentBlock(QString text) {
    bool highlight = false;
    text.trimmed();
    QString startText = "<!--";
    QString endText = "-->";

    if ((text.startsWith(startText)) ||
            ((!text.endsWith(endText)) &&
                    ((previousBlockState() == HighlighterState::Comment)))) {
        setCurrentBlockState(HighlighterState::Comment);
        highlight = true;
    } else if (text.endsWith(endText)) {
        highlight = true;
    }

    if (highlight) {
        setFormat(0, text.length(), _formats[HighlighterState::Comment]);
    }
}

/**
 * Highlights the rules from the _highlightingRules list
 *
 * @param text
 */
void MarkdownHighlighter::highlightAdditionalRules(
        QVector<HighlightingRule> &rules, QString text) {
    foreach(const HighlightingRule &rule, rules) {
            // continue if an other current block state was already set if
            // disableIfCurrentStateIsSet is set
            if (rule.disableIfCurrentStateIsSet &&
                    (currentBlockState() != HighlighterState::NoState)) {
                continue;
            }

            QRegularExpression expression(rule.pattern);
            QRegularExpressionMatchIterator i = expression.globalMatch(text);

            // store the current block state if useStateAsCurrentBlockState
            // is set
            if (i.hasNext() && rule.useStateAsCurrentBlockState) {
                setCurrentBlockState(rule.state);
            }

            // find and format all occurrences
            while (i.hasNext()) {
                QRegularExpressionMatch match = i.next();
                setFormat(match.capturedStart(), match.capturedLength(),
                          _formats[rule.state]);
            }
        }
}
<commit_msg>fixed a highlighting issue with images and tables<commit_after>/*
 * Copyright (C) 2016 Patrizio Bekerle -- http://www.bekerle.com
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * QTextEdit markdown highlighter
 */

#include <QTimer>
#include "markdownhighlighter.h"

/**
 * Markdown syntax highlighting
 *
 * markdown syntax:
 * http://daringfireball.net/projects/markdown/syntax
 *
 * @param parent
 * @return
 */
MarkdownHighlighter::MarkdownHighlighter(QTextDocument *parent)
        : QSyntaxHighlighter(parent) {
    _dirtyBlockTimer = new QTimer(this);
    QObject::connect(_dirtyBlockTimer, SIGNAL(timeout()),
                     this, SLOT(reHighlightDirtyBlocks()));
    _dirtyBlockTimer->start(1000);

    // initialize the highlighting rules
    initHighlightingRules();

    // initialize the text formats
    initTextFormats();
}

/**
 * Re-highlights all dirty blocks
 */
void MarkdownHighlighter::reHighlightDirtyBlocks() {
    while (_dirtyTextBlocks.count() > 0) {
        QTextBlock block = _dirtyTextBlocks.at(0);
        rehighlightBlock(block);
        _dirtyTextBlocks.removeFirst();
    }
}

/**
 * Adds a dirty block to the list if it doesn't already exist
 *
 * @param block
 */
void MarkdownHighlighter::addDirtyBlock(QTextBlock block) {
    if (!_dirtyTextBlocks.contains(block)) {
        _dirtyTextBlocks.append(block);
    }
}

/**
 * Initializes the highlighting rules
 *
 * regexp tester:
 * https://regex101.com
 */
void MarkdownHighlighter::initHighlightingRules() {
    HighlightingRule rule;

    // highlight the reference of reference links
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("^\\[\\d+?\\]: .+://.+$");
    rule.state = HighlighterState::Comment;
    _highlightingRulesPre.append(rule);

    // highlight unordered lists
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("^\\s*[-*+]\\s");
    rule.state = HighlighterState::List;
    rule.useStateAsCurrentBlockState = true;
    _highlightingRulesPre.append(rule);

    // highlight ordered lists
    rule.pattern = QRegularExpression("^\\s*\\d\\.\\s");
    _highlightingRulesPre.append(rule);

    // highlight inline code
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("`.+?`");
    rule.state = HighlighterState::InlineCodeBlock;
    _highlightingRulesPre.append(rule);

    // highlight code blocks with four spaces or tabs in front of them
    // and no list character after that
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("^((\\t)|( {4,})).+$");
    rule.state = HighlighterState::CodeBlock;
    rule.disableIfCurrentStateIsSet = true;
    _highlightingRulesPre.append(rule);

    // highlight block quotes
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("^> ");
    rule.state = HighlighterState::BlockQuote;
    _highlightingRulesPre.append(rule);

    // highlight inline comments
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("<!\\-\\-.+?\\-\\->");
    rule.state = HighlighterState::Comment;
    _highlightingRulesPre.append(rule);

    // highlight horizontal rulers
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("^([*\\-_]\\s?){3,}$");
    rule.state = HighlighterState::HorizontalRuler;
    _highlightingRulesPre.append(rule);

    // highlight tables without starting |
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("^.+? \\| .+? \\| .+$");
    rule.state = HighlighterState::Table;
    _highlightingRulesPre.append(rule);

    // highlight bold
    rule.pattern = QRegularExpression("\\B\\*{2}.+?\\*{2}\\B");
    rule.state = HighlighterState::Bold;
    _highlightingRulesAfter.append(rule);
    rule.pattern = QRegularExpression("(^|\\s)__.+?__($|\\s)");
    _highlightingRulesAfter.append(rule);

    // highlight italic
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("(^|\\s)\\*[^\\*]+\\*($|\\s)");
    rule.state = HighlighterState::Italic;
    _highlightingRulesAfter.append(rule);
    rule.pattern = QRegularExpression("(^|\\s)_[^_]+_($|\\s)");
    _highlightingRulesAfter.append(rule);

    // highlight urls
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("<.+?:\\/\\/.+?>");
    rule.state = HighlighterState::Link;
    _highlightingRulesAfter.append(rule);

    // highlight urls without any other markup
    rule.pattern = QRegularExpression("\\b\\w+?:\\/\\/[^\\s]+");
    _highlightingRulesAfter.append(rule);

    // highlight urls with title
    rule.pattern = QRegularExpression("\\[.+?\\]\\(.+?://.+?\\)");
    _highlightingRulesAfter.append(rule);

    // highlight email links
    rule.pattern = QRegularExpression("<.+?@.+?>");
    _highlightingRulesAfter.append(rule);

    // highlight reference links
    rule.pattern = QRegularExpression("\\[.+?\\]\\[\\d+\\]");
    _highlightingRulesAfter.append(rule);

    // highlight images
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("!\\[.*?\\]\\(.+?\\)");
    rule.state = HighlighterState::Image;
    _highlightingRulesAfter.append(rule);

    // highlight tables with starting |
    rule = HighlightingRule();
    rule.pattern = QRegularExpression("^\\|.+?\\|$");
    rule.state = HighlighterState::Table;
    _highlightingRulesAfter.append(rule);
}

/**
 * Initializes the text formats
 *
 * @param defaultFontSize
 */
void MarkdownHighlighter::initTextFormats(int defaultFontSize) {
    QTextCharFormat format;

    // set character formats for headlines
    format = QTextCharFormat();
    format.setForeground(QBrush(QColor(0, 49, 110)));
    format.setBackground(QBrush(QColor(230, 230, 240)));
    format.setFontWeight(QFont::Bold);
    format.setFontPointSize(defaultFontSize * 1.2);
    _formats[H1] = format;
    format.setFontPointSize(defaultFontSize * 1.1);
    _formats[H2] = format;
    format.setFontPointSize(defaultFontSize);
    _formats[H3] = format;
    _formats[H4] = format;
    _formats[H5] = format;
    _formats[H6] = format;

    // set character format for horizontal rulers
    format = QTextCharFormat();
    format.setForeground(QBrush(Qt::darkGray));
    format.setBackground(QBrush(Qt::lightGray));
    _formats[HorizontalRuler] = format;

    // set character format for lists
    format = QTextCharFormat();
    format.setForeground(QBrush(QColor(163, 0, 123)));
    _formats[List] = format;

    // set character format for links
    format = QTextCharFormat();
    format.setForeground(QBrush(QColor(255, 128, 0)));
    format.setBackground(QBrush(QColor(255, 233, 211)));
    _formats[Link] = format;

    // set character format for images
    format = QTextCharFormat();
    format.setForeground(QBrush(QColor(0, 191, 0)));
    format.setBackground(QBrush(QColor(228, 255, 228)));
    _formats[Image] = format;

    // set character format for code blocks
    format = QTextCharFormat();
    format.setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
    format.setForeground(QBrush(Qt::darkGreen));
    format.setBackground(QBrush(QColor(217, 231, 217)));
    _formats[CodeBlock] = format;
    _formats[InlineCodeBlock] = format;

    // set character format for italic
    format = QTextCharFormat();
    format.setFontWeight(QFont::StyleItalic);
    format.setForeground(QBrush(QColor(0, 87, 174)));
    _formats[Italic] = format;

    // set character format for bold
    format = QTextCharFormat();
    format.setFontWeight(QFont::Bold);
    format.setForeground(QBrush(QColor(0, 66, 138)));
    _formats[Bold] = format;

    // set character format for comments
    format = QTextCharFormat();
    format.setForeground(QBrush(Qt::gray));
    _formats[Comment] = format;

    // set character format for tables
    format = QTextCharFormat();
    format.setFont(QFontDatabase::systemFont(QFontDatabase::FixedFont));
    format.setForeground(QBrush(QColor("#649449")));
    _formats[Table] = format;

    // set character format for block quotes
    format = QTextCharFormat();
    format.setForeground(QBrush(QColor(Qt::darkRed)));
    _formats[BlockQuote] = format;
}

/**
 * Sets the text formats
 *
 * @param formats
 */
void MarkdownHighlighter::setTextFormats(
        QHash<HighlighterState, QTextCharFormat> formats) {
    _formats = formats;
}

/**
 * Sets a text format
 *
 * @param formats
 */
void MarkdownHighlighter::setTextFormat(HighlighterState state,
                                        QTextCharFormat format) {
    _formats[state] = format;
}

/**
 * Does the markdown highlighting
 *
 * @param text
 */
void MarkdownHighlighter::highlightBlock(const QString &text) {
    setCurrentBlockState(HighlighterState::NoState);
    currentBlock().setUserState(HighlighterState::NoState);
    highlightMarkdown(text);
    emit(highlightingFinished());
}

void MarkdownHighlighter::highlightMarkdown(QString text) {
    if (!text.isEmpty()) {
        highlightAdditionalRules(_highlightingRulesPre, text);

        // needs to be called after the horizontal ruler highlighting
        highlightHeadline(text);

        highlightAdditionalRules(_highlightingRulesAfter, text);
    }

    highlightCommentBlock(text);
    highlightCodeBlock(text);
}

/**
 * Highlight headlines
 *
 * @param text
 */
void MarkdownHighlighter::highlightHeadline(QString text) {
    QRegularExpression re("^(#+) .+?$");
    QRegularExpressionMatch match = re.match(text);

    // check for headline blocks with # in front of them
    if (match.hasMatch()) {
        int count = match.captured(1).count();

        // we just have H1 to H6
        count = qMin(count, 6);

        HighlighterState state = HighlighterState(
                HighlighterState::H1 + count - 1);

        setFormat(match.capturedStart(), match.capturedLength(),
                  _formats[state]);
        setCurrentBlockState(state);
        currentBlock().setUserState(state);
        return;
    }

    // take care of ==== and ---- headlines
    QRegularExpression patternH1 = QRegularExpression("^=+$");
    QRegularExpression patternH2 = QRegularExpression("^-+$");
    QTextBlock previousBlock = currentBlock().previous();
    QString previousText = previousBlock.text();
    previousText.trimmed().remove(QRegularExpression("[=-]"));

    // check for ===== after a headline text and highlight as H1
    if (patternH1.match(text).hasMatch()) {
        if (((previousBlockState() == HighlighterState::H1) ||
                (previousBlockState() == HighlighterState::NoState)) &&
                (previousText.length() > 0)) {
            setFormat(0, text.length(), _formats[HighlighterState::H1]);
            setCurrentBlockState(HighlighterState::HeadlineEnd);
            previousBlock.setUserState(HighlighterState::H1);

            // we want to re-highlight the previous block
            // this must not done directly, but with a queue, otherwise it
            // will crash
            // setting the character format of the previous text, because this
            // causes text to be formatted the same way when writing after
            // the text
            addDirtyBlock(previousBlock);
        }

        return;
    }

    // check for ----- after a headline text and highlight as H2
    if (patternH2.match(text).hasMatch()) {
        if (((previousBlockState() == HighlighterState::H2) ||
             (previousBlockState() == HighlighterState::NoState)) &&
            (previousText.length() > 0)) {
            setFormat(0, text.length(), _formats[HighlighterState::H2]);
            setCurrentBlockState(HighlighterState::HeadlineEnd);
            previousBlock.setUserState(HighlighterState::H2);

            // we want to re-highlight the previous block
            addDirtyBlock(previousBlock);
        }

        return;
    }

    QTextBlock nextBlock = currentBlock().next();
    QString nextBlockText = nextBlock.text();

    // highlight as H1 if next block is =====
    if (patternH1.match(nextBlockText).hasMatch() ||
            patternH2.match(nextBlockText).hasMatch()) {
        setFormat(0, text.length(), _formats[HighlighterState::H1]);
        setCurrentBlockState(HighlighterState::H1);
        currentBlock().setUserState(HighlighterState::H1);
    }

    // highlight as H2 if next block is -----
    if (patternH2.match(nextBlockText).hasMatch()) {
        setFormat(0, text.length(), _formats[HighlighterState::H2]);
        setCurrentBlockState(HighlighterState::H2);
        currentBlock().setUserState(HighlighterState::H2);
    }
}

/**
 * Highlight multiline code blocks
 *
 * @param text
 */
void MarkdownHighlighter::highlightCodeBlock(QString text) {
    bool highlight = false;

    QRegularExpression re("^```\\w*?$");
    QRegularExpressionMatch match = re.match(text);

    if (match.hasMatch()) {
        setCurrentBlockState(
                previousBlockState() == HighlighterState::CodeBlock ?
                HighlighterState::CodeBlockEnd : HighlighterState::CodeBlock);
        highlight = true;
    } else if (previousBlockState() == HighlighterState::CodeBlock) {
        setCurrentBlockState(HighlighterState::CodeBlock);
        highlight = true;
    }

    if (highlight) {
        setFormat(0, text.length(), _formats[HighlighterState::CodeBlock]);
    }
}

/**
 * Highlight multiline comments
 *
 * @param text
 */
void MarkdownHighlighter::highlightCommentBlock(QString text) {
    bool highlight = false;
    text.trimmed();
    QString startText = "<!--";
    QString endText = "-->";

    if ((text.startsWith(startText)) ||
            ((!text.endsWith(endText)) &&
                    ((previousBlockState() == HighlighterState::Comment)))) {
        setCurrentBlockState(HighlighterState::Comment);
        highlight = true;
    } else if (text.endsWith(endText)) {
        highlight = true;
    }

    if (highlight) {
        setFormat(0, text.length(), _formats[HighlighterState::Comment]);
    }
}

/**
 * Highlights the rules from the _highlightingRules list
 *
 * @param text
 */
void MarkdownHighlighter::highlightAdditionalRules(
        QVector<HighlightingRule> &rules, QString text) {
    foreach(const HighlightingRule &rule, rules) {
            // continue if an other current block state was already set if
            // disableIfCurrentStateIsSet is set
            if (rule.disableIfCurrentStateIsSet &&
                    (currentBlockState() != HighlighterState::NoState)) {
                continue;
            }

            QRegularExpression expression(rule.pattern);
            QRegularExpressionMatchIterator i = expression.globalMatch(text);

            // store the current block state if useStateAsCurrentBlockState
            // is set
            if (i.hasNext() && rule.useStateAsCurrentBlockState) {
                setCurrentBlockState(rule.state);
            }

            // find and format all occurrences
            while (i.hasNext()) {
                QRegularExpressionMatch match = i.next();
                setFormat(match.capturedStart(), match.capturedLength(),
                          _formats[rule.state]);
            }
        }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: tbxctl.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-07-06 12:19:41 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _BASIDE_TBXCTL_HXX
#define _BASIDE_TBXCTL_HXX

#ifndef _SFXTBXCTRL_HXX //autogen
#include <sfx2/tbxctrl.hxx>
#endif

#ifndef _SFXTBXMGR_HXX
#include <sfx2/tbxmgr.hxx>
#endif
/*
#ifdef _BASIDE_POPUPWINDOWTBX

// class PopupWindowTbx --------------------------------------------------

class PopupWindowTbx : public SfxPopupWindow
{
private:
    SfxToolBoxManager   aTbx;
    Link                aSelectLink;

    DECL_LINK( SelectHdl, void* );

public:
    PopupWindowTbx( USHORT nId, WindowAlign eAlign,
                    ResId aRIdWin, ResId aRIdTbx, SfxBindings& rBind );
    ~PopupWindowTbx();

    void                    StartSelection()
                                { aTbx.GetToolBox().StartSelection(); }
    void                    Update();

    virtual SfxPopupWindow* Clone() const;
    virtual void            PopupModeEnd();
};
#endif
*/
//-------------------
// class TbxControls
//-------------------
class TbxControls : public SfxToolBoxControl
{
    USHORT                  nLastSlot;

protected:
    virtual void            StateChanged( USHORT nSID, SfxItemState eState,
                                          const SfxPoolItem* pState );
public:
    SFX_DECL_TOOLBOX_CONTROL();

    TbxControls(USHORT nSlotId, USHORT nId, ToolBox& rTbx );
    ~TbxControls() {}

    virtual SfxPopupWindowType  GetPopupWindowType() const;
    virtual SfxPopupWindow*     CreatePopupWindow();

    void                        Select( USHORT nModifier );
};

#endif // _BASIDE_TBXCTL_HXX

<commit_msg>INTEGRATION: CWS tbe13 (1.3.52); FILE MERGED 2004/11/03 17:03:34 tbe 1.3.52.1: #i36073# Insert Controls Toolbar disappears if Properties Window has been opened<commit_after>/*************************************************************************
 *
 *  $RCSfile: tbxctl.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2004-11-15 13:41:45 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _BASIDE_TBXCTL_HXX
#define _BASIDE_TBXCTL_HXX

#ifndef _SFXTBXCTRL_HXX //autogen
#include <sfx2/tbxctrl.hxx>
#endif
#ifndef _SFXTBXMGR_HXX
#include <sfx2/tbxmgr.hxx>
#endif

#ifndef _DRAFTS_COM_SUN_STAR_FRAME_XLAYOUTMANAGER_HPP_
#include <drafts/com/sun/star/frame/XLayoutManager.hpp>
#endif

/*
#ifdef _BASIDE_POPUPWINDOWTBX

// class PopupWindowTbx --------------------------------------------------

class PopupWindowTbx : public SfxPopupWindow
{
private:
    SfxToolBoxManager   aTbx;
    Link                aSelectLink;

    DECL_LINK( SelectHdl, void* );

public:
    PopupWindowTbx( USHORT nId, WindowAlign eAlign,
                    ResId aRIdWin, ResId aRIdTbx, SfxBindings& rBind );
    ~PopupWindowTbx();

    void                    StartSelection()
                                { aTbx.GetToolBox().StartSelection(); }
    void                    Update();

    virtual SfxPopupWindow* Clone() const;
    virtual void            PopupModeEnd();
};
#endif
*/
//-------------------
// class TbxControls
//-------------------
class TbxControls : public SfxToolBoxControl
{
private:

    struct StateChangedInfo
    {
        ::com::sun::star::uno::Reference< ::drafts::com::sun::star::frame::XLayoutManager > xLayoutManager;
        bool bDisabled;
    };

    USHORT                  nLastSlot;

    DECL_STATIC_LINK( TbxControls, StateChangedHdl_Impl, StateChangedInfo* );

protected:
    virtual void            StateChanged( USHORT nSID, SfxItemState eState,
                                          const SfxPoolItem* pState );
public:
    SFX_DECL_TOOLBOX_CONTROL();

    TbxControls(USHORT nSlotId, USHORT nId, ToolBox& rTbx );
    ~TbxControls() {}

    virtual SfxPopupWindowType  GetPopupWindowType() const;
    virtual SfxPopupWindow*     CreatePopupWindow();

    void                        Select( USHORT nModifier );
};

#endif // _BASIDE_TBXCTL_HXX

<|endoftext|>