<commit_before>/**************************************************************************\
**
**       TODDLER: Slimmed-down version of CHILD without Vegetation,
**                Stream Meandering, or mesh densification.
**
**                            C H I L D
**
**       CHANNEL-HILLSLOPE INTEGRATED LANDSCAPE DEVELOPMENT MODEL
**
**                      VERSION 2.1.2, JUNE 2000
**
**  Designed and created by Gregory E. Tucker, Stephen T. Lancaster,
**      Nicole M. Gasparini, and Rafael L. Bras, Department of Civil
**      and Environmental Engineering, Massachusetts Institute of
**      Technology, Cambridge, MA, USA.
**
**  MAIN.CPP -- This file contains the main() routine that handles
**              top-level initialization and implements the main
**              time-loop.
**
**  NOTE: This source code is copyrighted material. It is distributed
**        solely for noncommercial research and educational purposes
**        only. Use in whole or in part for commercial purposes without
**        a written license from the copyright holder(s) is expressly
**        prohibited. Copies of this source code or any of its components
**        may not be transferred to any other individuals or organizations
**        without written consent. Copyright (C) Massachusetts Institute
**        of Technology, 1997-2000. All rights reserved.
**
**  For information regarding this program, please contact Greg Tucker at:
**
**       School of Geography and the Environment
**       University of Oxford
**       Mansfield Road
**       Oxford OX1 3TB United Kingdom
**
**  $Id: toddlermain.cpp,v 1.3 2000-12-07 11:50:05 gtucker Exp $
\**************************************************************************/

#include "Inclusions.h"
#include "tFloodplain/tFloodplain.h"
#include "tEolian/tEolian.h"

Predicates predicate;

main( int argc, char **argv )
{
   int silent_mode,       // Option for silent mode (no time output to stdout)
       optDetachLim,      // Option for detachment-limited erosion only
       optFloodplainDep,  // Option for floodplain (overbank) deposition
       optLoessDep,       // Option for eolian deposition
       optDiffuseDepo;    // Option for deposition / no deposition by diff'n
   tFloodplain *floodplain;  // -> floodplain object
   tEolian *loess;           // -> eolian deposition object

   /****************** INITIALIZATION *************************************\
   **  ALGORITHM
   **    Get command-line arguments (name of input file + any other opts)
   **    Set silent_mode flag
   **    Open main input file
   **    Create and initialize objects for...
   **      Mesh
   **      Output files
   **      Storm
   **      Stream network
   **      Erosion
   **      Uplift (or baselevel change)
   **      Run timer
   **    Write output for initial state
   **    Get options for erosion type, meandering, etc.
   \**********************************************************************/

   // Check command-line arguments
   if( argc<2 )
   {
      cerr << "Usage: " << argv[0] << " <input file>" << endl;
      ReportFatalError( "You need to give the name of an input file." );
   }

   // Check whether we're in silent mode
   silent_mode = ( argc>2 && argv[2][1]=='s' );

   // Say hello
   cout << "\nThis is TODDLER, version " << VERSION << endl << endl;

   // Open main input file
   tInputFile inputFile( argv[1] );

   // Create and initialize objects:
   cout << "Creating mesh...\n";
   tMesh<tLNode> mesh( inputFile );
   cout << "Creating output files...\n";
   tLOutput<tLNode> output( &mesh, inputFile );
   tStorm storm( inputFile );
   cout << "Creating stream network...\n";
   tStreamNet strmNet( mesh, storm, inputFile );
   tErosion erosion( &mesh, inputFile );
   tUplift uplift( inputFile );
   cout << "Writing data for time zero...\n";
   tRunTimer time( inputFile, !silent_mode );
   output.WriteOutput( 0 );
   cout << "Initialization done.\n";

   // Get various options
   optDetachLim = inputFile.ReadItem( optDetachLim, "OPTDETACHLIM" );
   optDiffuseDepo = inputFile.ReadItem( optDiffuseDepo, "OPTDIFFDEP" );
   optFloodplainDep = inputFile.ReadItem( optFloodplainDep, "OPTFLOODPLAIN" );
   optLoessDep = inputFile.ReadItem( optLoessDep, "OPTLOESSDEP" );

   // If applicable, create floodplain object
   if( optFloodplainDep )
       floodplain = new tFloodplain( inputFile, &mesh );

   // If applicable, create eolian deposition object
   if( optLoessDep )
       loess = new tEolian( inputFile );

   // Temporary -- for canyon range stuff
   cout << "Densifying around fold strike ...\n";
   int optFoldDens = inputFile.ReadItem( optFoldDens, "OPTFOLDDENS" );
   if( optFoldDens )
     {
       double foldDensYmin = inputFile.ReadItem( foldDensYmin, "FOLDDENSYMIN" );
       double foldDensYmax = inputFile.ReadItem( foldDensYmax, "FOLDDENSYMAX" );
       for( int i=1; i<=optFoldDens; i++ )
	 {
	   tPtrList<tLNode> foldPoints;
	   tMeshListIter<tLNode> ni( mesh.getNodeList() );
	   tLNode *cn;
	   for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() )
	     if( cn->getY()>=foldDensYmin && cn->getY()<=foldDensYmax )
	       foldPoints.insertAtBack( cn );
	   tPtrListIter<tLNode> fpi( foldPoints );
	   for( cn=fpi.FirstP(); !(fpi.AtEnd()); cn=fpi.NextP() )
	     mesh.AddNodesAround( cn, 0.0 );
	   foldPoints.Flush();
	 }
     }

   /**************** MAIN LOOP ******************************************\
   **  ALGORITHM
   **    Generate storm
   **    Do storm...
   **      Update network (flow directions, drainage area, runoff)
   **      Water erosion/deposition (vertical)
   **      Meandering (if applicable)
   **      Floodplain deposition (if applicable)
   **    Do interstorm...
   **      Hillslope transport
   **      Vegetation (if applicable)
   **      Exposure history
   **      Mesh densification (if applicable)
   **      Eolian (loess) deposition (if applicable)
   **      Uplift (or baselevel change)
   **********************************************************************/
   while( !time.IsFinished() )
   {
      time.ReportTimeStatus();

      // Do storm...
      storm.GenerateStorm( time.getCurrentTime(),
                           strmNet.getInfilt(), strmNet.getSoilStore() );
      cout << storm.getRainrate() << " " << storm.getStormDuration() << " "
           << storm.interstormDur() << endl;

      strmNet.UpdateNet( time.getCurrentTime(), storm );

      if( optDetachLim )
          erosion.ErodeDetachLim( storm.getStormDuration() );
      else
          erosion.DetachErode( storm.getStormDuration(), &strmNet,
                               time.getCurrentTime() );

      if( optFloodplainDep )
          floodplain->DepositOverbank( storm.getRainrate(),
                                       storm.getStormDuration(),
                                       time.getCurrentTime() );

      // Do interstorm...
      erosion.Diffuse( storm.getStormDuration() + storm.interstormDur(),
      optDiffuseDepo );

      erosion.UpdateExposureTime( storm.getStormDuration() +
                                      storm.interstormDur() );

      if( optLoessDep )
          loess->DepositLoess( &mesh,
                               storm.getStormDuration()+storm.interstormDur(),
                               time.getCurrentTime() );

      if( time.getCurrentTime() < uplift.getDuration() )
          uplift.DoUplift( &mesh,
                           storm.getStormDuration() + storm.interstormDur() );

      time.Advance( storm.getStormDuration() + storm.interstormDur() );

      if( time.CheckOutputTime() )
          output.WriteOutput( time.getCurrentTime() );

   } // end of main loop

}

<commit_msg>just debugging, no chgs<commit_after>/**************************************************************************\
**
**       TODDLER: Slimmed-down version of CHILD without Vegetation,
**                Stream Meandering, or mesh densification.
**
**                            C H I L D
**
**       CHANNEL-HILLSLOPE INTEGRATED LANDSCAPE DEVELOPMENT MODEL
**
**                      VERSION 2.1.2, JUNE 2000
**
**  Designed and created by Gregory E. Tucker, Stephen T. Lancaster,
**      Nicole M. Gasparini, and Rafael L. Bras, Department of Civil
**      and Environmental Engineering, Massachusetts Institute of
**      Technology, Cambridge, MA, USA.
**
**  MAIN.CPP -- This file contains the main() routine that handles
**              top-level initialization and implements the main
**              time-loop.
**
**  NOTE: This source code is copyrighted material. It is distributed
**        solely for noncommercial research and educational purposes
**        only. Use in whole or in part for commercial purposes without
**        a written license from the copyright holder(s) is expressly
**        prohibited. Copies of this source code or any of its components
**        may not be transferred to any other individuals or organizations
**        without written consent. Copyright (C) Massachusetts Institute
**        of Technology, 1997-2000. All rights reserved.
**
**  For information regarding this program, please contact Greg Tucker at:
**
**       School of Geography and the Environment
**       University of Oxford
**       Mansfield Road
**       Oxford OX1 3TB United Kingdom
**
**  $Id: toddlermain.cpp,v 1.4 2002-02-11 09:22:15 gtucker Exp $
\**************************************************************************/

#include "Inclusions.h"
#include "tFloodplain/tFloodplain.h"
#include "tEolian/tEolian.h"

Predicates predicate;

main( int argc, char **argv )
{
   int silent_mode,       // Option for silent mode (no time output to stdout)
       optDetachLim,      // Option for detachment-limited erosion only
       optFloodplainDep,  // Option for floodplain (overbank) deposition
       optLoessDep,       // Option for eolian deposition
       optVegetation,     // Option for dynamic vegetation cover
       optDiffuseDepo;    // Option for deposition / no deposition by diff'n
   tVegetation *vegetation;  // -> vegetation object
   tFloodplain *floodplain;  // -> floodplain object
   tEolian *loess;           // -> eolian deposition object

   /****************** INITIALIZATION *************************************\
   **  ALGORITHM
   **    Get command-line arguments (name of input file + any other opts)
   **    Set silent_mode flag
   **    Open main input file
   **    Create and initialize objects for...
   **      Mesh
   **      Output files
   **      Storm
   **      Stream network
   **      Erosion
   **      Uplift (or baselevel change)
   **      Run timer
   **    Write output for initial state
   **    Get options for erosion type, meandering, etc.
   \**********************************************************************/

   // Check command-line arguments
   if( argc<2 )
   {
      cerr << "Usage: " << argv[0] << " <input file>" << endl;
      ReportFatalError( "You need to give the name of an input file." );
   }

   // Check whether we're in silent mode
   silent_mode = ( argc>2 && argv[2][1]=='s' );

   // Say hello
   cout << "\nThis is TODDLER, version " << VERSION << endl << endl;

   // Open main input file
   tInputFile inputFile( argv[1] );

   // Create and initialize objects:
   cout << "Creating mesh...\n";
   tMesh<tLNode> mesh( inputFile );
   cout << "Creating output files...\n";
   tLOutput<tLNode> output( &mesh, inputFile );
   tStorm storm( inputFile );
   cout << "Creating stream network...\n";
   tStreamNet strmNet( mesh, storm, inputFile );
   tErosion erosion( &mesh, inputFile );
   tUplift uplift( inputFile );
   cout << "Writing data for time zero...\n";
   tRunTimer time( inputFile, !silent_mode );
   output.WriteOutput( 0 );
   cout << "Initialization done.\n";

   // Get various options
   optDetachLim = inputFile.ReadItem( optDetachLim, "OPTDETACHLIM" );
   optDiffuseDepo = inputFile.ReadItem( optDiffuseDepo, "OPTDIFFDEP" );
   optVegetation = inputFile.ReadItem( optVegetation, "OPTVEG" );
   optFloodplainDep = inputFile.ReadItem( optFloodplainDep, "OPTFLOODPLAIN" );
   optLoessDep = inputFile.ReadItem( optLoessDep, "OPTLOESSDEP" );

   // If applicable, create Vegetation object
   if( optVegetation )
       vegetation = new tVegetation( &mesh, inputFile );

   // If applicable, create floodplain object
   if( optFloodplainDep )
       floodplain = new tFloodplain( inputFile, &mesh );

   // If applicable, create eolian deposition object
   if( optLoessDep )
       loess = new tEolian( inputFile );

   // Option for time series output (IN PROGRESS)
   /*   switch( optTSOutput ){
   case 1:   // Volume output each N years.
     if( time.CheckTSOutputTime() )
       output.WriteVolOutput();
     break;
   case 2:   // Volume and vegetation cover output each N years.
     cout << "here" << endl;
     if( time.CheckTSOutputTime() ){
       cout << "there" << endl;
       output.WriteVolVegOutput();}
     break;
   case 3:   // All data at each storm.
     output.WriteTSOutput();
     break;
   case 0:   // No additional timeseries output.
     break;
   default:  // Invalid option.
     ReportFatalError( "The input file contains an invalid value for
OptTSOutput." );
   }   */

   // Temporary -- for canyon range stuff
   /*cout << "Densifying around fold strike ...\n";
   int optFoldDens = inputFile.ReadItem( optFoldDens, "OPTFOLDDENS" );
   if( optFoldDens )
     {
       double foldDensYmin = inputFile.ReadItem( foldDensYmin, "FOLDDENSYMIN" );
       double foldDensYmax = inputFile.ReadItem( foldDensYmax, "FOLDDENSYMAX" );
       double fault = inputFile.ReadItem( fault, "FAULTPOS" );
       for( int i=1; i<=optFoldDens; i++ )
	 {
	   tPtrList<tLNode> foldPoints;
	   tMeshListIter<tLNode> ni( mesh.getNodeList() );
	   tLNode *cn;
	   for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() )
	     {
	     if( cn->getY()>=foldDensYmin && cn->getY()<=foldDensYmax &&
		 cn->getX()>=7500 && cn->getX()<=92500 )
	       foldPoints.insertAtBack( cn );
	     if( cn->getY()<fault )
	       cn->setAlluvThickness( 100000 );
	     }
	   tPtrListIter<tLNode> fpi( foldPoints );
	   for( cn=fpi.FirstP(); !(fpi.AtEnd()); cn=fpi.NextP() )
	     mesh.AddNodesAround( cn, 0.0 );
	   foldPoints.Flush();
	 }
	 }*/

   /**************** MAIN LOOP ******************************************\
   **  ALGORITHM
   **    Generate storm
   **    Do storm...
   **      Update network (flow directions, drainage area, runoff)
   **      Water erosion/deposition (vertical)
   **      Meandering (if applicable)
   **      Floodplain deposition (if applicable)
   **    Do interstorm...
   **      Hillslope transport
   **      Vegetation (if applicable)
   **      Exposure history
   **      Mesh densification (if applicable)
   **      Eolian (loess) deposition (if applicable)
   **      Uplift (or baselevel change)
   **********************************************************************/
   while( !time.IsFinished() )
   {
      time.ReportTimeStatus();

      // Do storm...
      storm.GenerateStorm( time.getCurrentTime(),
                           strmNet.getInfilt(), strmNet.getSoilStore() );
      cout << storm.getRainrate() << " " << storm.getStormDuration() << " "
           << storm.interstormDur() << endl;

      strmNet.UpdateNet( time.getCurrentTime(), storm );

      if( optDetachLim )
          erosion.ErodeDetachLim( storm.getStormDuration(), &strmNet );
      else
          erosion.DetachErode( storm.getStormDuration(), &strmNet,
                               time.getCurrentTime() );

      if( optVegetation )
	  vegetation->UpdateVegetation( &mesh, storm.getStormDuration(),
					storm.interstormDur() );

      if( optFloodplainDep )
          floodplain->DepositOverbank( storm.getRainrate(),
                                       storm.getStormDuration(),
                                       time.getCurrentTime() );

      // Do interstorm...
      erosion.Diffuse( storm.getStormDuration() + storm.interstormDur(),
      optDiffuseDepo );

      erosion.UpdateExposureTime( storm.getStormDuration() +
                                      storm.interstormDur() );

      if( optLoessDep )
          loess->DepositLoess( &mesh,
                               storm.getStormDuration()+storm.interstormDur(),
                               time.getCurrentTime() );

      if( time.getCurrentTime() < uplift.getDuration() )
          uplift.DoUplift( &mesh,
                           storm.getStormDuration() + storm.interstormDur() );

      time.Advance( storm.getStormDuration() + storm.interstormDur() );

      if( time.CheckOutputTime() )
          output.WriteOutput( time.getCurrentTime() );

      if( output.OptTSOutput() ) output.WriteTSOutput();

      /* IN PROGRESS
      switch( optTSOutput ){
      case 1:   // Volume output each N years.
        if( time.CheckTSOutputTime() )
  output.WriteVolOutput();
break;
      case 2:   // Volume and vegetation cover output each N years.
if( time.CheckTSOutputTime() )
  output.WriteVolVegOutput();
break;
      case 3:   // All data at each storm.
output.WriteTSOutput();
break;
      case 0:   // No additional timeseries output.
break;
      default:  // Invalid option.
ReportFatalError( "The input file contains an invalid value for OptTSOutput."
*/

     /*tMeshListIter<tLNode> ni( mesh.getNodeList() );
      tLNode *cn;
      for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() )
	{
	  if( cn->getY()<25 && cn->getX()>250 && cn->getDrArea()>1000 )
	    cn->TellAll();
	}*/

   } // end of main loop

}

<|endoftext|>


<commit_before>#include <iostream>
#include <random>
#include <numeric>

#include <OpenMS/FORMAT/FASTAFile.h>
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/CHEMISTRY/ElementDB.h>
#include <OpenMS/CHEMISTRY/Residue.h>
#include <OpenMS/CHEMISTRY/EnzymaticDigestion.h>
#include <OpenMS/CHEMISTRY/IsotopeDistribution.h>
#include <OpenMS/MATH/STATISTICS/StatisticFunctions.h>

#include "Stats.h"

using namespace OpenMS;

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(0, 1);

std::vector<double> sampleDecoy(int length)
{
    std::vector<double> probabilities;
    double sum = 0;
    for (int i = 0; i < length; ++i)
    {
        probabilities.push_back(dis(gen));
        sum+= probabilities[i];
    }
    for (int i = 0; i < length; ++i)
    {
        probabilities[i] /= sum;
    }

    return probabilities;
}

std::vector<double> sampleFromDistribution(std::vector<double>& probabilities)
{
    static int SAMPLE_SIZE = 1e3;

    std::vector<double> prefix_sum(probabilities.size());
    std::partial_sum(probabilities.begin(), probabilities.end(), prefix_sum.begin());

    std::vector<double> sample(probabilities.size(),0);

    for (int i = 0; i < SAMPLE_SIZE; ++i)
    {
        double ran = dis(gen);
        int index = std::upper_bound(prefix_sum.begin(), prefix_sum.end(), ran) - prefix_sum.begin();
        sample[index] += 1.0/SAMPLE_SIZE;
    }
    return sample;
}

std::vector<double> fillProbabilities(IsotopeDistribution& dist, UInt length)
{
    std::vector<double> probabilities;
    for (Size i = 0; i < dist.size(); ++i)
    {
        probabilities.push_back(dist.getContainer()[i].second);
    }

    for (Size i = dist.size(); i < length; ++i) {
        probabilities.push_back(0);
    }

    return probabilities;
}

std::vector<double> calculateScores(std::vector<double>& l, std::vector<double>& r)
{
    std::vector<double> result;
    result.push_back(Math::pearsonCorrelationCoefficient(l.begin(), l.end(), r.begin(), r.end()));
    result.push_back(Stats::totalVariationDistance(l.begin(), l.end(), r.begin(), r.end()));
    result.push_back(Stats::chiSquared(l.begin(), l.end(), r.begin(), r.end()));
    return result;
}

void testTheoreticalIon(AASequence& pep, AASequence& frag, EmpiricalFormula& precursor, EmpiricalFormula& fragment)
{
    static Size MAX_ISOTOPE = 3;
    static Size LENGTH = MAX_ISOTOPE+1;
    static Size num_processed = 0;

    int num_s = fragment.getNumberOf(ElementDB::getInstance()->getElement("Sulfur"));
    int num_cs = precursor.getNumberOf(ElementDB::getInstance()->getElement("Sulfur")) - num_s;

    std::vector<UInt> isolated_precursor_isotopes(1,0);
    for (UInt i = 1; i <= MAX_ISOTOPE; ++i) {
        isolated_precursor_isotopes.push_back(i);
        IsotopeDistribution frag_dist = fragment.getConditionalFragmentIsotopeDist(precursor, isolated_precursor_isotopes);

        IsotopeDistribution dist_averagine_precursor(i+1);
        dist_averagine_precursor.estimateFromPeptideWeight(fragment.getAverageWeight());
        dist_averagine_precursor.renormalize();
        IsotopeDistribution dist_exact_precursor = fragment.getIsotopeDistribution(i+1);

        std::vector<double> prob_averagine_precursor = fillProbabilities(dist_averagine_precursor, i+1);
        std::vector<double> prob_exact_precursor = fillProbabilities(dist_averagine_precursor, i+1);
        std::vector<double> prob_decoy = sampleDecoy(i+1);
        std::vector<double> prob_exact_fragment =  fillProbabilities(frag_dist, i+1);
        std::vector<double> prob_sampled_exact_fragment = sampleFromDistribution(prob_exact_fragment);

        std::vector<double> scores;

        scores = calculateScores(prob_averagine_precursor, prob_exact_fragment);

        //std::cout << scores[0] << "\t" << scores[1] << "\t" << scores[2] << "\t" << pep_mass << "\t"
        //          << frag_mass << "\t" << i << "\t" << num_s << "\t" << num_cs << "\t" << 0 << std::endl;

        scores = calculateScores(prob_exact_precursor, prob_exact_fragment);

        //std::cout << scores[0] << "\t" << scores[1] << "\t" << scores[2] << "\t" << pep_mass << "\t"
        //          << frag_mass << "\t" << i << "\t" << num_s << "\t" << num_cs << "\t" << 0 << std::endl;

        scores = calculateScores(prob_decoy, prob_exact_fragment);

        //std::cout << scores[0] << "\t" << scores[1] << "\t" << scores[2] << "\t" << pep_mass << "\t"
        //          << frag_mass << "\t" << i << "\t" << num_s << "\t" << num_cs << "\t" << 1 << std::endl;

        scores = calculateScores(prob_sampled_exact_fragment, prob_exact_fragment);

        //std::cout << scores[0] << "\t" << scores[1] << "\t" << scores[2] << "\t" << pep_mass << "\t"
        //          << frag_mass << "\t" << i << "\t" << num_s << "\t" << num_cs << "\t" << 0 << std::endl;
    }

    num_processed++;
    if (num_processed % 10000 == 0) {
        std::cout << num_processed << std::endl;
    }
}

void testTheoreticalPeptide(AASequence& pep)
{
    EmpiricalFormula precursor = pep.getFormula();
    EmpiricalFormula fragment;
    for (Size i = 1; i < pep.size(); i++)
    {
        AASequence frag = pep.getPrefix(i);

        fragment = frag.getFormula(Residue::ResidueType::BIon);
        testTheoreticalIon(pep, frag, precursor, fragment);

        fragment = pep.getPrefix(i).getFormula(Residue::ResidueType::YIon);
        testTheoreticalIon(pep, frag, precursor, fragment);
    }
}

void testTheoreticalProtein(FASTAFile::FASTAEntry& protein, EnzymaticDigestion& digestor)
{
    static Size MIN_PEPTIDE_LENGTH = 5;
    static Size MAX_PEPTIDE_LENGTH = 80;

    std::vector<AASequence> peptides;
    digestor.digest(AASequence::fromString(protein.sequence), peptides);
    for (Size j = 0; j < peptides.size(); ++j)
    {
        if (peptides[j].size() >= MIN_PEPTIDE_LENGTH && peptides[j].size() <= MAX_PEPTIDE_LENGTH)
        {
            testTheoreticalPeptide(peptides[j]);
        }
    }
}

void testTheoreticalPeptides(std::string fasta_path)
{
    std::vector<FASTAFile::FASTAEntry> proteins;
    FASTAFile().load(fasta_path, proteins);

    EnzymaticDigestion digestor; // default parameters are fully tryptic with 0 missed cleavages

    for (Size i = 0; i < proteins.size(); ++i)
    {
        testTheoreticalProtein(proteins[i], digestor);
    }
}

int main(int argc, char * argv[])
{
    testTheoreticalPeptides(argv[1]);
    return 0;
}<commit_msg>Evaluation of approx precursor, approx fragment, approx fragment_S, and exact precursor in comparison to exact fragment<commit_after>#include <iostream>
#include <random>
#include <numeric>

#include <OpenMS/FORMAT/FASTAFile.h>
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/CHEMISTRY/ElementDB.h>
#include <OpenMS/CHEMISTRY/Residue.h>
#include <OpenMS/CHEMISTRY/EnzymaticDigestion.h>
#include <OpenMS/CHEMISTRY/IsotopeDistribution.h>
#include <OpenMS/MATH/STATISTICS/StatisticFunctions.h>

#include "Stats.h"

using namespace OpenMS;

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(0, 1);

std::vector<double> sampleDecoy(int length)
{
    std::vector<double> probabilities;
    double sum = 0;
    for (int i = 0; i < length; ++i)
    {
        probabilities.push_back(dis(gen));
        sum+= probabilities[i];
    }
    for (int i = 0; i < length; ++i)
    {
        probabilities[i] /= sum;
    }

    return probabilities;
}

std::vector<double> sampleFromDistribution(std::vector<double>& probabilities)
{
    static int SAMPLE_SIZE = 1e3;

    std::vector<double> prefix_sum(probabilities.size());
    std::partial_sum(probabilities.begin(), probabilities.end(), prefix_sum.begin());

    std::vector<double> sample(probabilities.size(),0);

    for (int i = 0; i < SAMPLE_SIZE; ++i)
    {
        double ran = dis(gen);
        int index = std::upper_bound(prefix_sum.begin(), prefix_sum.end(), ran) - prefix_sum.begin();
        sample[index] += 1.0/SAMPLE_SIZE;
    }
    return sample;
}

std::vector<double> fillProbabilities(IsotopeDistribution& dist, UInt length)
{
    std::vector<double> probabilities;
    for (Size i = 0; i < dist.size(); ++i)
    {
        probabilities.push_back(dist.getContainer()[i].second);
    }

    for (Size i = dist.size(); i < length; ++i) {
        probabilities.push_back(0);
    }

    return probabilities;
}

std::vector<double> calculateScores(std::vector<double>& l, std::vector<double>& r)
{
    std::vector<double> result;
    result.push_back(Math::pearsonCorrelationCoefficient(l.begin(), l.end(), r.begin(), r.end()));
    result.push_back(Stats::totalVariationDistance(l.begin(), l.end(), r.begin(), r.end()));
    result.push_back(Stats::chiSquared(l.begin(), l.end(), r.begin(), r.end()));
    return result;
}

void testTheoreticalIon(AASequence& pep, AASequence& frag, EmpiricalFormula& precursor, EmpiricalFormula& fragment)
{
    static Size MAX_ISOTOPE = 10;
    static Size LENGTH = MAX_ISOTOPE+1;

    int num_s = fragment.getNumberOf(ElementDB::getInstance()->getElement("Sulfur"));
    int num_cs = precursor.getNumberOf(ElementDB::getInstance()->getElement("Sulfur")) - num_s;

    double pep_mass = precursor.getAverageWeight();
    double frag_mass = fragment.getAverageWeight();

    std::vector<UInt> isolated_precursor_isotopes(1,0);
    for (UInt i = 1; i <= MAX_ISOTOPE; ++i) {
        //isolated_precursor_isotopes.clear();
        isolated_precursor_isotopes.push_back(i);

        IsotopeDistribution exact_fragment_dist = fragment.getConditionalFragmentIsotopeDist(precursor, isolated_precursor_isotopes);
        IsotopeDistribution exact_precursor_dist = fragment.getIsotopeDistribution(i+1);

        IsotopeDistribution approx_precursor_dist(i+1);
        approx_precursor_dist.estimateFromPeptideWeight(fragment.getAverageWeight());
        approx_precursor_dist.renormalize();

        IsotopeDistribution approx_fragment_dist(i+1);
        approx_fragment_dist.estimateForFragmentFromPeptideWeight(precursor.getAverageWeight(), fragment.getAverageWeight(), isolated_precursor_isotopes);
        approx_fragment_dist.renormalize();

        IsotopeDistribution approx_fragment_S_dist(i+1);
        approx_fragment_S_dist.estimateForFragmentFromPeptideWeightAndS(precursor.getAverageWeight(), num_s+num_cs, fragment.getAverageWeight(), num_s, isolated_precursor_isotopes);
        approx_fragment_S_dist.renormalize();

        std::vector<double> exact_fragment_prob =  fillProbabilities(exact_fragment_dist, i+1);
        std::vector<double> exact_precursor_prob = fillProbabilities(exact_precursor_dist, i+1);
        std::vector<double> approx_precursor_prob = fillProbabilities(approx_precursor_dist, i+1);
        std::vector<double> approx_fragment_prob = fillProbabilities(approx_fragment_dist, i+1);
        std::vector<double> approx_fragment_S_prob = fillProbabilities(approx_fragment_S_dist, i+1);

        //std::vector<double> decoy_prob = sampleDecoy(i+1);
        //std::vector<double> sampled_exact_fragment_prob = sampleFromDistribution(exact_fragment_prob);

        std::vector<double> scores;

        scores = calculateScores(exact_fragment_prob, exact_precursor_prob);

        std::cout << scores[0] << "\t" << scores[1] << "\t" << scores[2] << "\t" << pep_mass << "\t"
                  << frag_mass << "\t" << i << "\t" << num_s << "\t" << num_cs << "\t" << "exact_precursor" << std::endl;

        scores = calculateScores(exact_fragment_prob, approx_precursor_prob);

        std::cout << scores[0] << "\t" << scores[1] << "\t" << scores[2] << "\t" << pep_mass << "\t"
                  << frag_mass << "\t" << i << "\t" << num_s << "\t" << num_cs << "\t" << "approx_precursor" << std::endl;

        scores = calculateScores(exact_fragment_prob, approx_fragment_prob);

        std::cout << scores[0] << "\t" << scores[1] << "\t" << scores[2] << "\t" << pep_mass << "\t"
                  << frag_mass << "\t" << i << "\t" << num_s << "\t" << num_cs << "\t" << "approx_fragment" << std::endl;

        scores = calculateScores(exact_fragment_prob, approx_fragment_S_prob);

        std::cout << scores[0] << "\t" << scores[1] << "\t" << scores[2] << "\t" << pep_mass << "\t"
                  << frag_mass << "\t" << i << "\t" << num_s << "\t" << num_cs << "\t" << "approx_fragment_S" << std::endl;
    }
}

void testTheoreticalPeptide(AASequence& pep)
{
    EmpiricalFormula precursor = pep.getFormula();
    EmpiricalFormula fragment;
    for (Size i = 1; i < pep.size(); i++)
    {
        AASequence frag = pep.getPrefix(i);

        fragment = frag.getFormula(Residue::ResidueType::BIon);
        testTheoreticalIon(pep, frag, precursor, fragment);

        fragment = pep.getPrefix(i).getFormula(Residue::ResidueType::YIon);
        testTheoreticalIon(pep, frag, precursor, fragment);
    }
}

void testTheoreticalProtein(FASTAFile::FASTAEntry& protein, EnzymaticDigestion& digestor)
{
    static Size MIN_PEPTIDE_LENGTH = 5;
    static Size MAX_PEPTIDE_LENGTH = 80;

    std::vector<AASequence> peptides;
    digestor.digest(AASequence::fromString(protein.sequence), peptides);
    for (Size j = 0; j < peptides.size(); ++j)
    {
        if (peptides[j].size() >= MIN_PEPTIDE_LENGTH && peptides[j].size() <= MAX_PEPTIDE_LENGTH)
        {
            testTheoreticalPeptide(peptides[j]);
        }
    }
}

void testTheoreticalPeptides(std::string fasta_path, int job_id, int num_jobs)
{
    std::vector<FASTAFile::FASTAEntry> proteins;
    FASTAFile().load(fasta_path, proteins);

    EnzymaticDigestion digestor; // default parameters are fully tryptic with 0 missed cleavages

    for (Size i = job_id; i < proteins.size(); i+=num_jobs)
    {
        testTheoreticalProtein(proteins[i], digestor);
    }
}

int main(int argc, char * argv[])
{
    testTheoreticalPeptides(argv[1], atoi(argv[2])-1, atoi(argv[3]));
    return 0;
}<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <AnyValue.h>
#include <Serialize/Serializable.h>
#include <Bundle.h>
#include <DynamicObjectHelper.h>

using namespace EasyCpp;

namespace EasyCppTest
{
	TEST(AnyValue, Int)
	{
		int val = 10;
		AnyValue any(val);
		ASSERT_TRUE(any.isType<int>());
		ASSERT_TRUE(any.isConvertibleTo<int>());
		ASSERT_EQ(val, any.as<int>());
	}

	TEST(AnyValue, Default)
	{
		AnyValue any;
		ASSERT_TRUE(any.isType<nullptr_t>());
	}

	TEST(AnyValue, Convert)
	{
		AnyValue any(true);
		ASSERT_TRUE(any.isType<bool>());
		ASSERT_TRUE(any.isConvertibleTo<std::string>());
		ASSERT_EQ(std::string("true"), any.as<std::string>());
	}

	TEST(AnyValue, isSerializable)
	{
		class SimpleSerializable : public Serialize::Serializable
		{
		public:
			virtual AnyValue toAnyValue() const override
			{
				return AnyValue();
			}
			virtual void fromAnyValue(const AnyValue& any) override
			{}
		};

		SimpleSerializable t;
		AnyValue any(t);
		ASSERT_TRUE(any.isType<SimpleSerializable>());
		ASSERT_TRUE(any.isSerializable());

		AnyValue any2(true);
		ASSERT_TRUE(any2.isType<bool>());
		ASSERT_FALSE(any2.isSerializable());
	}

	TEST(AnyValue, CastOperator)
	{
		AnyValue a = std::string("20");

		std::string s = a;
		ASSERT_EQ(std::string("20"), s);
		int i = a;
		ASSERT_EQ(20, i);
	}

	TEST(AnyValue, NullNotNullptr)
	{
		AnyValue a((void*)0x00);
		ASSERT_FALSE(a.isType<nullptr_t>());
	}

	class SimpleSample
	{
	public:
		SimpleSample()
		{
			setText("Hello");
		}

		std::string getText()
		{
			return _text;
		}

		void setText(const std::string& text)
		{
			_text = text;
		}

	private:
		std::string _text;
	};
}

template<>
struct EasyCpp::TypeCheck<EasyCppTest::SimpleSample*>
{
	typedef EasyCppTest::SimpleSample Type;
	static bool IsSerializable()
	{
		return false;
	}

	static bool IsDynamicObject()
	{
		return true;
	}

	static const Serialize::Serializable& AsSerializable(const EasyCppTest::SimpleSample* value)
	{
		throw std::runtime_error("This Anyvalue does not implement Serializable");
	}

	static std::shared_ptr<DynamicObject> AsDynamicObject(EasyCppTest::SimpleSample* value)
	{
		class DynamicWrapper : public DynamicObjectHelper
		{
		public:
			DynamicWrapper(EasyCppTest::SimpleSample* value)
				:_value(value)
			{
				this->addFunction("setText", AnyFunction::fromDynamicFunction([this](const AnyArray& params) {
					this->_value->setText(params[0].as<std::string>());
					return AnyValue();
				}));
			}
		private:
			EasyCppTest::SimpleSample* _value;
		};
		return std::make_shared<DynamicWrapper>(value);
	}
};

template<>
struct EasyCpp::TypeCheck<EasyCppTest::SimpleSample>
{
	typedef EasyCppTest::SimpleSample Type;
	static bool IsSerializable()
	{
		return TypeCheck<EasyCppTest::SimpleSample*>::IsSerializable();
	}

	static bool IsDynamicObject()
	{
		return TypeCheck<EasyCppTest::SimpleSample*>::IsDynamicObject();
	}

	static const Serialize::Serializable& AsSerializable(const EasyCppTest::SimpleSample& value)
	{
		return TypeCheck<EasyCppTest::SimpleSample*>::AsSerializable(&value);
	}

	static std::shared_ptr<DynamicObject> AsDynamicObject(EasyCppTest::SimpleSample& value)
	{
		return TypeCheck<EasyCppTest::SimpleSample*>::AsDynamicObject(&value);
	}
};

namespace EasyCppTest
{
	TEST(AnyValue, ExternalTypeCheck)
	{
		SimpleSample sample;
		AnyValue val(&sample);

		ASSERT_TRUE(val.isDynamicObject());
		auto& obj = val.asDynamicObject();
		obj.callFunction("setText", { std::string("test_value") });

		ASSERT_EQ("test_value", sample.getText());
	}
}<commit_msg>Linux Buildfix<commit_after>#include <gtest/gtest.h>
#include <AnyValue.h>
#include <Serialize/Serializable.h>
#include <Bundle.h>
#include <DynamicObjectHelper.h>

using namespace EasyCpp;

namespace EasyCppTest
{
	TEST(AnyValue, Int)
	{
		int val = 10;
		AnyValue any(val);
		ASSERT_TRUE(any.isType<int>());
		ASSERT_TRUE(any.isConvertibleTo<int>());
		ASSERT_EQ(val, any.as<int>());
	}

	TEST(AnyValue, Default)
	{
		AnyValue any;
		ASSERT_TRUE(any.isType<nullptr_t>());
	}

	TEST(AnyValue, Convert)
	{
		AnyValue any(true);
		ASSERT_TRUE(any.isType<bool>());
		ASSERT_TRUE(any.isConvertibleTo<std::string>());
		ASSERT_EQ(std::string("true"), any.as<std::string>());
	}

	TEST(AnyValue, isSerializable)
	{
		class SimpleSerializable : public Serialize::Serializable
		{
		public:
			virtual AnyValue toAnyValue() const override
			{
				return AnyValue();
			}
			virtual void fromAnyValue(const AnyValue& any) override
			{}
		};

		SimpleSerializable t;
		AnyValue any(t);
		ASSERT_TRUE(any.isType<SimpleSerializable>());
		ASSERT_TRUE(any.isSerializable());

		AnyValue any2(true);
		ASSERT_TRUE(any2.isType<bool>());
		ASSERT_FALSE(any2.isSerializable());
	}

	TEST(AnyValue, CastOperator)
	{
		AnyValue a = std::string("20");

		std::string s = a;
		ASSERT_EQ(std::string("20"), s);
		int i = a;
		ASSERT_EQ(20, i);
	}

	TEST(AnyValue, NullNotNullptr)
	{
		AnyValue a((void*)0x00);
		ASSERT_FALSE(a.isType<nullptr_t>());
	}

	class SimpleSample
	{
	public:
		SimpleSample()
		{
			setText("Hello");
		}

		std::string getText()
		{
			return _text;
		}

		void setText(const std::string& text)
		{
			_text = text;
		}

	private:
		std::string _text;
	};
}

namespace EasyCpp
{
	template<>
	struct TypeCheck<EasyCppTest::SimpleSample*>
	{
		typedef EasyCppTest::SimpleSample Type;
		static bool IsSerializable()
		{
			return false;
		}

		static bool IsDynamicObject()
		{
			return true;
		}

		static const Serialize::Serializable& AsSerializable(const EasyCppTest::SimpleSample* value)
		{
			throw std::runtime_error("This Anyvalue does not implement Serializable");
		}

		static std::shared_ptr<DynamicObject> AsDynamicObject(EasyCppTest::SimpleSample* value)
		{
			class DynamicWrapper : public DynamicObjectHelper
			{
			public:
				DynamicWrapper(EasyCppTest::SimpleSample* value)
					:_value(value)
				{
					this->addFunction("setText", AnyFunction::fromDynamicFunction([this](const AnyArray& params) {
						this->_value->setText(params[0].as<std::string>());
						return AnyValue();
					}));
				}
			private:
				EasyCppTest::SimpleSample* _value;
			};
			return std::make_shared<DynamicWrapper>(value);
		}
	};

	template<>
	struct TypeCheck<EasyCppTest::SimpleSample>
	{
		typedef EasyCppTest::SimpleSample Type;
		static bool IsSerializable()
		{
			return TypeCheck<EasyCppTest::SimpleSample*>::IsSerializable();
		}

		static bool IsDynamicObject()
		{
			return TypeCheck<EasyCppTest::SimpleSample*>::IsDynamicObject();
		}

		static const Serialize::Serializable& AsSerializable(const EasyCppTest::SimpleSample& value)
		{
			return TypeCheck<EasyCppTest::SimpleSample*>::AsSerializable(&value);
		}

		static std::shared_ptr<DynamicObject> AsDynamicObject(EasyCppTest::SimpleSample& value)
		{
			return TypeCheck<EasyCppTest::SimpleSample*>::AsDynamicObject(&value);
		}
	};
}
namespace EasyCppTest
{
	TEST(AnyValue, ExternalTypeCheck)
	{
		SimpleSample sample;
		AnyValue val(&sample);

		ASSERT_TRUE(val.isDynamicObject());
		auto& obj = val.asDynamicObject();
		obj.callFunction("setText", { std::string("test_value") });

		ASSERT_EQ("test_value", sample.getText());
	}
}<|endoftext|>


<commit_before>#ifndef FAST_MOVIE_STREAMER_HPP_
#define FAST_MOVIE_STREAMER_HPP_

#include "FAST/Streamers/Streamer.hpp"
#include <QObject>

class QMediaPlayer;
class QThread;

namespace fast {

class Image;

class MovieStreamerWorker;

class FAST_EXPORT MovieStreamer : public Streamer {
    FAST_OBJECT(MovieStreamer)
    public:
        void setFilename(std::string filename);
        std::string getFilename() const;
        bool hasReachedEnd();
        void addNewImageFrame(const uchar* data, int width, int height);
        void setGrayscale(bool grayscale);
        bool getGrayscale() const;
        void setFinished(bool finished);
        int getFramesAdded() const;
        ~MovieStreamer();
        void loadAttributes() override;
        void addLastFrame();
    private:
        MovieStreamer();
        void execute();
        void generateStream() override {};

        std::string mFilename;
        bool mGrayscale = true;
        bool m_finished = false;
        int64_t m_framesAdded = 0;
        std::chrono::high_resolution_clock::time_point m_startTime;
        QThread* thread;
        MovieStreamerWorker* worker;
        std::shared_ptr<Image> m_currentImage;

};

class VideoSurface;

class MovieStreamerWorker : public QObject {
    Q_OBJECT
    public:
        MovieStreamerWorker(MovieStreamer* streamer);
        ~MovieStreamerWorker();
    public Q_SLOTS:
        void run();
    Q_SIGNALS:
        void finished();
        void error(QString err);
    private:
        MovieStreamer* mStreamer;
        std::unique_ptr<QMediaPlayer> m_player;
        std::unique_ptr<VideoSurface> m_myVideoSurface;
};

}

#endif
<commit_msg>Fixed windows build issue with movie streamer worker<commit_after>#pragma once

#include "FAST/Streamers/Streamer.hpp"
#include <QObject>

class QMediaPlayer;
class QThread;

namespace fast {

class Image;

class MovieStreamerWorker;

class FAST_EXPORT MovieStreamer : public Streamer {
    FAST_OBJECT(MovieStreamer)
    public:
        void setFilename(std::string filename);
        std::string getFilename() const;
        bool hasReachedEnd();
        void addNewImageFrame(const uchar* data, int width, int height);
        void setGrayscale(bool grayscale);
        bool getGrayscale() const;
        void setFinished(bool finished);
        int getFramesAdded() const;
        ~MovieStreamer();
        void loadAttributes() override;
        void addLastFrame();
    private:
        MovieStreamer();
        void execute();
        void generateStream() override {};

        std::string mFilename;
        bool mGrayscale = true;
        bool m_finished = false;
        int64_t m_framesAdded = 0;
        std::chrono::high_resolution_clock::time_point m_startTime;
        QThread* thread;
        MovieStreamerWorker* worker;
        std::shared_ptr<Image> m_currentImage;

};

class VideoSurface;

class FAST_EXPORT MovieStreamerWorker : public QObject {
    Q_OBJECT
    public:
        MovieStreamerWorker(MovieStreamer* streamer);
        ~MovieStreamerWorker();
    public Q_SLOTS:
        void run();
    Q_SIGNALS:
        void finished();
        void error(QString err);
    private:
        MovieStreamer* mStreamer;
        std::unique_ptr<QMediaPlayer> m_player;
        std::unique_ptr<VideoSurface> m_myVideoSurface;
};

}

<|endoftext|>


<commit_before>//===-- ThreadPlanStepInRange.cpp -------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Target/ThreadPlanStepInRange.h"

// C Includes
// C++ Includes
// Other libraries and framework includes
// Project includes

#include "lldb/lldb-private-log.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/Stream.h"
#include "lldb/Symbol/Symbol.h"
#include "lldb/Symbol/Function.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Target/ThreadPlanStepOut.h"
#include "lldb/Target/ThreadPlanStepThrough.h"
#include "lldb/Core/RegularExpression.h"

using namespace lldb;
using namespace lldb_private;

uint32_t ThreadPlanStepInRange::s_default_flag_values = ThreadPlanShouldStopHere::eAvoidNoDebug;

//----------------------------------------------------------------------
// ThreadPlanStepInRange: Step through a stack range, either stepping over or into
// based on the value of \a type.
//----------------------------------------------------------------------

ThreadPlanStepInRange::ThreadPlanStepInRange
(
    Thread &thread,
    const AddressRange &range,
    const SymbolContext &addr_context,
    lldb::RunMode stop_others
) :
    ThreadPlanStepRange (ThreadPlan::eKindStepInRange, "Step Range stepping in", thread, range, addr_context, stop_others),
    ThreadPlanShouldStopHere (this, ThreadPlanStepInRange::DefaultShouldStopHereCallback, NULL),
    m_step_past_prologue (true),
    m_virtual_step (false)
{
    SetFlagsToDefault ();
}

ThreadPlanStepInRange::ThreadPlanStepInRange
(
    Thread &thread,
    const AddressRange &range,
    const SymbolContext &addr_context,
    const char *step_into_target,
    lldb::RunMode stop_others
) :
    ThreadPlanStepRange (ThreadPlan::eKindStepInRange, "Step Range stepping in", thread, range, addr_context, stop_others),
    ThreadPlanShouldStopHere (this, ThreadPlanStepInRange::DefaultShouldStopHereCallback, NULL),
    m_step_past_prologue (true),
    m_virtual_step (false),
    m_step_into_target (step_into_target)
{
    SetFlagsToDefault ();
}

ThreadPlanStepInRange::~ThreadPlanStepInRange ()
{
}

void
ThreadPlanStepInRange::GetDescription (Stream *s, lldb::DescriptionLevel level)
{
    if (level == lldb::eDescriptionLevelBrief)
        s->Printf("step in");
    else
    {
        s->Printf ("Stepping through range (stepping into functions): ");
        DumpRanges(s);
        s->Printf ("targeting %s.", m_step_into_target.AsCString());
    }
}

bool
ThreadPlanStepInRange::ShouldStop (Event *event_ptr)
{
    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
    m_no_more_plans = false;

    if (log)
    {
        StreamString s;
        s.Address (m_thread.GetRegisterContext()->GetPC(),
                   m_thread.CalculateTarget()->GetArchitecture().GetAddressByteSize());
        log->Printf("ThreadPlanStepInRange reached %s.", s.GetData());
    }

    if (IsPlanComplete())
        return true;

    ThreadPlan* new_plan = NULL;

    if (m_virtual_step)
    {
        // If we've just completed a virtual step, all we need to do is check for a ShouldStopHere plan, and otherwise
        // we're done.
        new_plan = InvokeShouldStopHereCallback();
    }
    else
    {
        // Stepping through should be done running other threads in general, since we're setting a breakpoint and
        // continuing.  So only stop others if we are explicitly told to do so.

        bool stop_others;
        if (m_stop_others == lldb::eOnlyThisThread)
            stop_others = false;
        else
            stop_others = true;

        FrameComparison frame_order = CompareCurrentFrameToStartFrame();

        if (frame_order == eFrameCompareOlder)
        {
            // If we're in an older frame then we should stop.
            //
            // A caveat to this is if we think the frame is older but we're actually in a trampoline.
            // I'm going to make the assumption that you wouldn't RETURN to a trampoline.  So if we are
            // in a trampoline we think the frame is older because the trampoline confused the backtracer.
            new_plan = m_thread.QueueThreadPlanForStepThrough (m_stack_id, false, stop_others);
            if (new_plan == NULL)
                return true;
            else if (log)
            {
                log->Printf("Thought I stepped out, but in fact arrived at a trampoline.");
            }

        }
        else if (frame_order == eFrameCompareEqual && InSymbol())
        {
            // If we are not in a place we should step through, we're done.
            // One tricky bit here is that some stubs don't push a frame, so we have to check
            // both the case of a frame that is younger, or the same as this frame.
            // However, if the frame is the same, and we are still in the symbol we started
            // in, the we don't need to do this.  This first check isn't strictly necessary,
            // but it is more efficient.

            // If we're still in the range, keep going, either by running to the next branch breakpoint, or by
            // stepping.
            if (InRange())
            {
                SetNextBranchBreakpoint();
                return false;
            }

            SetPlanComplete();
            m_no_more_plans = true;
            return true;
        }

        // If we get to this point, we're not going to use a previously set "next branch" breakpoint, so delete it:
        ClearNextBranchBreakpoint();

        // We may have set the plan up above in the FrameIsOlder section:

        if (new_plan == NULL)
            new_plan = m_thread.QueueThreadPlanForStepThrough (m_stack_id, false, stop_others);

        if (log)
        {
            if (new_plan != NULL)
                log->Printf ("Found a step through plan: %s", new_plan->GetName());
            else
                log->Printf ("No step through plan found.");
        }

        // If not, give the "should_stop" callback a chance to push a plan to get us out of here.
        // But only do that if we actually have stepped in.
        if (!new_plan && frame_order == eFrameCompareYounger)
            new_plan = InvokeShouldStopHereCallback();

        // If we've stepped in and we are going to stop here, check to see if we were asked to
        // run past the prologue, and if so do that.

        if (new_plan == NULL && frame_order == eFrameCompareYounger && m_step_past_prologue)
        {
            lldb::StackFrameSP curr_frame = m_thread.GetStackFrameAtIndex(0);
            if (curr_frame)
            {
                size_t bytes_to_skip = 0;
                lldb::addr_t curr_addr = m_thread.GetRegisterContext()->GetPC();
                Address func_start_address;

                SymbolContext sc = curr_frame->GetSymbolContext (eSymbolContextFunction | eSymbolContextSymbol);

                if (sc.function)
                {
                    func_start_address = sc.function->GetAddressRange().GetBaseAddress();
                    if (curr_addr == func_start_address.GetLoadAddress(m_thread.CalculateTarget().get()))
                        bytes_to_skip = sc.function->GetPrologueByteSize();
                }
                else if (sc.symbol)
                {
                    func_start_address = sc.symbol->GetAddress();
                    if (curr_addr == func_start_address.GetLoadAddress(m_thread.CalculateTarget().get()))
                        bytes_to_skip = sc.symbol->GetPrologueByteSize();
                }

                if (bytes_to_skip != 0)
                {
                    func_start_address.Slide (bytes_to_skip);
                    log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP);
                    if (log)
                        log->Printf ("Pushing past prologue ");

                    new_plan = m_thread.QueueThreadPlanForRunToAddress(false, func_start_address,true);
                }
            }
        }
     }

     if (new_plan == NULL)
     {
        m_no_more_plans = true;
        SetPlanComplete();
        return true;
    }
    else
    {
        m_no_more_plans = false;
        return false;
    }
}

void
ThreadPlanStepInRange::SetFlagsToDefault ()
{
    GetFlags().Set(ThreadPlanStepInRange::s_default_flag_values);
}

void
ThreadPlanStepInRange::SetAvoidRegexp(const char *name)
{
    if (m_avoid_regexp_ap.get() == NULL)
        m_avoid_regexp_ap.reset (new RegularExpression(name));

    m_avoid_regexp_ap->Compile (name);
}

void
ThreadPlanStepInRange::SetDefaultFlagValue (uint32_t new_value)
{
    // TODO: Should we test this for sanity?
    ThreadPlanStepInRange::s_default_flag_values = new_value;
}

bool
ThreadPlanStepInRange::FrameMatchesAvoidRegexp ()
{
    StackFrame *frame = GetThread().GetStackFrameAtIndex(0).get();

    const RegularExpression *avoid_regexp_to_use = m_avoid_regexp_ap.get();
    if (avoid_regexp_to_use == NULL)
        avoid_regexp_to_use = GetThread().GetSymbolsToAvoidRegexp();

    if (avoid_regexp_to_use != NULL)
    {
        SymbolContext sc = frame->GetSymbolContext(eSymbolContextFunction|eSymbolContextBlock|eSymbolContextSymbol);
        if (sc.symbol != NULL)
        {
            const char *frame_function_name = sc.GetFunctionName().GetCString();
            if (frame_function_name)
               return avoid_regexp_to_use->Execute(frame_function_name);
        }
    }
    return false;
}

ThreadPlan *
ThreadPlanStepInRange::DefaultShouldStopHereCallback (ThreadPlan *current_plan, Flags &flags, void *baton)
{
    bool should_step_out = false;
    StackFrame *frame = current_plan->GetThread().GetStackFrameAtIndex(0).get();

    if (flags.Test(eAvoidNoDebug))
    {
        if (!frame->HasDebugInformation())
        {
            LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
            if (log)
                log->Printf ("Stepping out of frame with no debug info");

            should_step_out = true;
        }
    }

    if (current_plan->GetKind() == eKindStepInRange)
    {
        ThreadPlanStepInRange *step_in_range_plan = static_cast<ThreadPlanStepInRange *> (current_plan);
        if (step_in_range_plan->m_step_into_target)
        {
            SymbolContext sc = frame->GetSymbolContext(eSymbolContextFunction|eSymbolContextBlock|eSymbolContextSymbol);
            if (sc.symbol != NULL)
            {
                // First try an exact match, since that's cheap with ConstStrings.  Then do a strstr compare.
                if (step_in_range_plan->m_step_into_target == sc.GetFunctionName())
                {
                    should_step_out = false;
                }
                else
                {
                    const char *target_name = step_in_range_plan->m_step_into_target.AsCString();
                    const char *function_name = sc.GetFunctionName().AsCString();

                    if (function_name == NULL)
                        should_step_out = true;
                    else if (strstr (function_name, target_name) == NULL)
                        should_step_out = true;
                }
            }
        }

        if (!should_step_out)
        {
                ThreadPlanStepInRange *step_in_range_plan = static_cast<ThreadPlanStepInRange *> (current_plan);
                should_step_out = step_in_range_plan->FrameMatchesAvoidRegexp ();
        }
    }

    if (should_step_out)
    {
        // FIXME: Make sure the ThreadPlanForStepOut does the right thing with inlined functions.
        // We really should have all plans take the tri-state for "stop others" so we can do the right
        // thing.  For now let's be safe and always run others when we are likely to run arbitrary code.
        const bool stop_others = false;
        return current_plan->GetThread().QueueThreadPlanForStepOut (false,
                                                                    NULL,
                                                                    true,
                                                                    stop_others,
                                                                    eVoteNo,
                                                                    eVoteNoOpinion,
                                                                    0); // Frame index
    }

    return NULL;
}

bool
ThreadPlanStepInRange::PlanExplainsStop (Event *event_ptr)
{
    // We always explain a stop.  Either we've just done a single step, in which
    // case we'll do our ordinary processing, or we stopped for some
    // reason that isn't handled by our sub-plans, in which case we want to just stop right
    // away.
    // In general, we don't want to mark the plan as complete for unexplained stops.
    // For instance, if you step in to some code with no debug info, so you step out
    // and in the course of that hit a breakpoint, then you want to stop & show the user
    // the breakpoint, but not unship the step in plan, since you still may want to complete that
    // plan when you continue.  This is particularly true when doing "step in to target function."
    // stepping.
    //
    // The only variation is that if we are doing "step by running to next branch" in which case
    // if we hit our branch breakpoint we don't set the plan to complete.

    if (m_virtual_step)
        return true;

    StopInfoSP stop_info_sp = GetPrivateStopReason();
    if (stop_info_sp)
    {
        StopReason reason = stop_info_sp->GetStopReason();

        switch (reason)
        {
        case eStopReasonBreakpoint:
            if (NextRangeBreakpointExplainsStop(stop_info_sp))
                return true;
        case eStopReasonWatchpoint:
        case eStopReasonSignal:
        case eStopReasonException:
        case eStopReasonExec:
        case eStopReasonThreadExiting:
            {
                LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
                if (log)
                    log->PutCString ("ThreadPlanStepInRange got asked if it explains the stop for some reason other than step.");
            }
            return false;
            break;
        default:
            break;
        }
    }
    return true;
}

bool
ThreadPlanStepInRange::WillResume (lldb::StateType resume_state, bool current_plan)
{
    if (resume_state == eStateStepping && current_plan)
    {
        // See if we are about to step over a virtual inlined call.
        bool step_without_resume = m_thread.DecrementCurrentInlinedDepth();
        if (step_without_resume)
        {
            LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
            if (log)
                log->Printf ("ThreadPlanStepInRange::WillResume: returning false, inline_depth: %d",
                             m_thread.GetCurrentInlinedDepth());
            SetStopInfo(StopInfo::CreateStopReasonToTrace(m_thread));

            // FIXME: Maybe it would be better to create a InlineStep stop reason, but then
            // the whole rest of the world would have to handle that stop reason.
            m_virtual_step = true;
        }
        return !step_without_resume;
    }
    else
        return ThreadPlan::WillResume(resume_state, current_plan);

}
<commit_msg>Add some logging to track cases where “step-in” steps out due to the avoid-regexp and the step-in target.<commit_after>//===-- ThreadPlanStepInRange.cpp -------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Target/ThreadPlanStepInRange.h"

// C Includes
// C++ Includes
// Other libraries and framework includes
// Project includes

#include "lldb/lldb-private-log.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/Stream.h"
#include "lldb/Symbol/Symbol.h"
#include "lldb/Symbol/Function.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/RegisterContext.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Target/ThreadPlanStepOut.h"
#include "lldb/Target/ThreadPlanStepThrough.h"
#include "lldb/Core/RegularExpression.h"

using namespace lldb;
using namespace lldb_private;

uint32_t ThreadPlanStepInRange::s_default_flag_values = ThreadPlanShouldStopHere::eAvoidNoDebug;

//----------------------------------------------------------------------
// ThreadPlanStepInRange: Step through a stack range, either stepping over or into
// based on the value of \a type.
//----------------------------------------------------------------------

ThreadPlanStepInRange::ThreadPlanStepInRange
(
    Thread &thread,
    const AddressRange &range,
    const SymbolContext &addr_context,
    lldb::RunMode stop_others
) :
    ThreadPlanStepRange (ThreadPlan::eKindStepInRange, "Step Range stepping in", thread, range, addr_context, stop_others),
    ThreadPlanShouldStopHere (this, ThreadPlanStepInRange::DefaultShouldStopHereCallback, NULL),
    m_step_past_prologue (true),
    m_virtual_step (false)
{
    SetFlagsToDefault ();
}

ThreadPlanStepInRange::ThreadPlanStepInRange
(
    Thread &thread,
    const AddressRange &range,
    const SymbolContext &addr_context,
    const char *step_into_target,
    lldb::RunMode stop_others
) :
    ThreadPlanStepRange (ThreadPlan::eKindStepInRange, "Step Range stepping in", thread, range, addr_context, stop_others),
    ThreadPlanShouldStopHere (this, ThreadPlanStepInRange::DefaultShouldStopHereCallback, NULL),
    m_step_past_prologue (true),
    m_virtual_step (false),
    m_step_into_target (step_into_target)
{
    SetFlagsToDefault ();
}

ThreadPlanStepInRange::~ThreadPlanStepInRange ()
{
}

void
ThreadPlanStepInRange::GetDescription (Stream *s, lldb::DescriptionLevel level)
{
    if (level == lldb::eDescriptionLevelBrief)
        s->Printf("step in");
    else
    {
        s->Printf ("Stepping through range (stepping into functions): ");
        DumpRanges(s);
        s->Printf ("targeting %s.", m_step_into_target.AsCString());
    }
}

bool
ThreadPlanStepInRange::ShouldStop (Event *event_ptr)
{
    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
    m_no_more_plans = false;

    if (log)
    {
        StreamString s;
        s.Address (m_thread.GetRegisterContext()->GetPC(),
                   m_thread.CalculateTarget()->GetArchitecture().GetAddressByteSize());
        log->Printf("ThreadPlanStepInRange reached %s.", s.GetData());
    }

    if (IsPlanComplete())
        return true;

    ThreadPlan* new_plan = NULL;

    if (m_virtual_step)
    {
        // If we've just completed a virtual step, all we need to do is check for a ShouldStopHere plan, and otherwise
        // we're done.
        new_plan = InvokeShouldStopHereCallback();
    }
    else
    {
        // Stepping through should be done running other threads in general, since we're setting a breakpoint and
        // continuing.  So only stop others if we are explicitly told to do so.

        bool stop_others;
        if (m_stop_others == lldb::eOnlyThisThread)
            stop_others = false;
        else
            stop_others = true;

        FrameComparison frame_order = CompareCurrentFrameToStartFrame();

        if (frame_order == eFrameCompareOlder)
        {
            // If we're in an older frame then we should stop.
            //
            // A caveat to this is if we think the frame is older but we're actually in a trampoline.
            // I'm going to make the assumption that you wouldn't RETURN to a trampoline.  So if we are
            // in a trampoline we think the frame is older because the trampoline confused the backtracer.
            new_plan = m_thread.QueueThreadPlanForStepThrough (m_stack_id, false, stop_others);
            if (new_plan == NULL)
                return true;
            else if (log)
            {
                log->Printf("Thought I stepped out, but in fact arrived at a trampoline.");
            }

        }
        else if (frame_order == eFrameCompareEqual && InSymbol())
        {
            // If we are not in a place we should step through, we're done.
            // One tricky bit here is that some stubs don't push a frame, so we have to check
            // both the case of a frame that is younger, or the same as this frame.
            // However, if the frame is the same, and we are still in the symbol we started
            // in, the we don't need to do this.  This first check isn't strictly necessary,
            // but it is more efficient.

            // If we're still in the range, keep going, either by running to the next branch breakpoint, or by
            // stepping.
            if (InRange())
            {
                SetNextBranchBreakpoint();
                return false;
            }

            SetPlanComplete();
            m_no_more_plans = true;
            return true;
        }

        // If we get to this point, we're not going to use a previously set "next branch" breakpoint, so delete it:
        ClearNextBranchBreakpoint();

        // We may have set the plan up above in the FrameIsOlder section:

        if (new_plan == NULL)
            new_plan = m_thread.QueueThreadPlanForStepThrough (m_stack_id, false, stop_others);

        if (log)
        {
            if (new_plan != NULL)
                log->Printf ("Found a step through plan: %s", new_plan->GetName());
            else
                log->Printf ("No step through plan found.");
        }

        // If not, give the "should_stop" callback a chance to push a plan to get us out of here.
        // But only do that if we actually have stepped in.
        if (!new_plan && frame_order == eFrameCompareYounger)
            new_plan = InvokeShouldStopHereCallback();

        // If we've stepped in and we are going to stop here, check to see if we were asked to
        // run past the prologue, and if so do that.

        if (new_plan == NULL && frame_order == eFrameCompareYounger && m_step_past_prologue)
        {
            lldb::StackFrameSP curr_frame = m_thread.GetStackFrameAtIndex(0);
            if (curr_frame)
            {
                size_t bytes_to_skip = 0;
                lldb::addr_t curr_addr = m_thread.GetRegisterContext()->GetPC();
                Address func_start_address;

                SymbolContext sc = curr_frame->GetSymbolContext (eSymbolContextFunction | eSymbolContextSymbol);

                if (sc.function)
                {
                    func_start_address = sc.function->GetAddressRange().GetBaseAddress();
                    if (curr_addr == func_start_address.GetLoadAddress(m_thread.CalculateTarget().get()))
                        bytes_to_skip = sc.function->GetPrologueByteSize();
                }
                else if (sc.symbol)
                {
                    func_start_address = sc.symbol->GetAddress();
                    if (curr_addr == func_start_address.GetLoadAddress(m_thread.CalculateTarget().get()))
                        bytes_to_skip = sc.symbol->GetPrologueByteSize();
                }

                if (bytes_to_skip != 0)
                {
                    func_start_address.Slide (bytes_to_skip);
                    log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP);
                    if (log)
                        log->Printf ("Pushing past prologue ");

                    new_plan = m_thread.QueueThreadPlanForRunToAddress(false, func_start_address,true);
                }
            }
        }
     }

     if (new_plan == NULL)
     {
        m_no_more_plans = true;
        SetPlanComplete();
        return true;
    }
    else
    {
        m_no_more_plans = false;
        return false;
    }
}

void
ThreadPlanStepInRange::SetFlagsToDefault ()
{
    GetFlags().Set(ThreadPlanStepInRange::s_default_flag_values);
}

void
ThreadPlanStepInRange::SetAvoidRegexp(const char *name)
{
    if (m_avoid_regexp_ap.get() == NULL)
        m_avoid_regexp_ap.reset (new RegularExpression(name));

    m_avoid_regexp_ap->Compile (name);
}

void
ThreadPlanStepInRange::SetDefaultFlagValue (uint32_t new_value)
{
    // TODO: Should we test this for sanity?
    ThreadPlanStepInRange::s_default_flag_values = new_value;
}

bool
ThreadPlanStepInRange::FrameMatchesAvoidRegexp ()
{
    StackFrame *frame = GetThread().GetStackFrameAtIndex(0).get();

    const RegularExpression *avoid_regexp_to_use = m_avoid_regexp_ap.get();
    if (avoid_regexp_to_use == NULL)
        avoid_regexp_to_use = GetThread().GetSymbolsToAvoidRegexp();

    if (avoid_regexp_to_use != NULL)
    {
        SymbolContext sc = frame->GetSymbolContext(eSymbolContextFunction|eSymbolContextBlock|eSymbolContextSymbol);
        if (sc.symbol != NULL)
        {
            const char *frame_function_name = sc.GetFunctionName().GetCString();
            if (frame_function_name)
            {
                bool return_value = avoid_regexp_to_use->Execute(frame_function_name);
                if (return_value)
                {
                    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
                    if (log)
                        log->Printf ("Stepping out of function %s because it matches the avoid regexp \"%s\".",
                                     frame_function_name,
                                     avoid_regexp_to_use->GetText());

                }
                return return_value;
            }
        }
    }
    return false;
}

ThreadPlan *
ThreadPlanStepInRange::DefaultShouldStopHereCallback (ThreadPlan *current_plan, Flags &flags, void *baton)
{
    bool should_step_out = false;
    StackFrame *frame = current_plan->GetThread().GetStackFrameAtIndex(0).get();
    LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));

    if (flags.Test(eAvoidNoDebug))
    {
        if (!frame->HasDebugInformation())
        {
            if (log)
                log->Printf ("Stepping out of frame with no debug info");

            should_step_out = true;
        }
    }

    if (current_plan->GetKind() == eKindStepInRange)
    {
        ThreadPlanStepInRange *step_in_range_plan = static_cast<ThreadPlanStepInRange *> (current_plan);
        if (step_in_range_plan->m_step_into_target)
        {
            SymbolContext sc = frame->GetSymbolContext(eSymbolContextFunction|eSymbolContextBlock|eSymbolContextSymbol);
            if (sc.symbol != NULL)
            {
                // First try an exact match, since that's cheap with ConstStrings.  Then do a strstr compare.
                if (step_in_range_plan->m_step_into_target == sc.GetFunctionName())
                {
                    should_step_out = false;
                }
                else
                {
                    const char *target_name = step_in_range_plan->m_step_into_target.AsCString();
                    const char *function_name = sc.GetFunctionName().AsCString();

                    if (function_name == NULL)
                        should_step_out = true;
                    else if (strstr (function_name, target_name) == NULL)
                        should_step_out = true;
                }
                if (log && should_step_out)
                    log->Printf("Stepping out of frame %s which did not match step into target %s.",
                                sc.GetFunctionName().AsCString(),
                                step_in_range_plan->m_step_into_target.AsCString());
            }
        }

        if (!should_step_out)
        {
            ThreadPlanStepInRange *step_in_range_plan = static_cast<ThreadPlanStepInRange *> (current_plan);
            // Don't log the should_step_out here, it's easier to do it in FrameMatchesAvoidRegexp.
            should_step_out = step_in_range_plan->FrameMatchesAvoidRegexp ();
        }
    }

    if (should_step_out)
    {
        // FIXME: Make sure the ThreadPlanForStepOut does the right thing with inlined functions.
        // We really should have all plans take the tri-state for "stop others" so we can do the right
        // thing.  For now let's be safe and always run others when we are likely to run arbitrary code.
        const bool stop_others = false;
        return current_plan->GetThread().QueueThreadPlanForStepOut (false,
                                                                    NULL,
                                                                    true,
                                                                    stop_others,
                                                                    eVoteNo,
                                                                    eVoteNoOpinion,
                                                                    0); // Frame index
    }

    return NULL;
}

bool
ThreadPlanStepInRange::PlanExplainsStop (Event *event_ptr)
{
    // We always explain a stop.  Either we've just done a single step, in which
    // case we'll do our ordinary processing, or we stopped for some
    // reason that isn't handled by our sub-plans, in which case we want to just stop right
    // away.
    // In general, we don't want to mark the plan as complete for unexplained stops.
    // For instance, if you step in to some code with no debug info, so you step out
    // and in the course of that hit a breakpoint, then you want to stop & show the user
    // the breakpoint, but not unship the step in plan, since you still may want to complete that
    // plan when you continue.  This is particularly true when doing "step in to target function."
    // stepping.
    //
    // The only variation is that if we are doing "step by running to next branch" in which case
    // if we hit our branch breakpoint we don't set the plan to complete.

    if (m_virtual_step)
        return true;

    StopInfoSP stop_info_sp = GetPrivateStopReason();
    if (stop_info_sp)
    {
        StopReason reason = stop_info_sp->GetStopReason();

        switch (reason)
        {
        case eStopReasonBreakpoint:
            if (NextRangeBreakpointExplainsStop(stop_info_sp))
                return true;
        case eStopReasonWatchpoint:
        case eStopReasonSignal:
        case eStopReasonException:
        case eStopReasonExec:
        case eStopReasonThreadExiting:
            {
                LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
                if (log)
                    log->PutCString ("ThreadPlanStepInRange got asked if it explains the stop for some reason other than step.");
            }
            return false;
            break;
        default:
            break;
        }
    }
    return true;
}

bool
ThreadPlanStepInRange::WillResume (lldb::StateType resume_state, bool current_plan)
{
    if (resume_state == eStateStepping && current_plan)
    {
        // See if we are about to step over a virtual inlined call.
        bool step_without_resume = m_thread.DecrementCurrentInlinedDepth();
        if (step_without_resume)
        {
            LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
            if (log)
                log->Printf ("ThreadPlanStepInRange::WillResume: returning false, inline_depth: %d",
                             m_thread.GetCurrentInlinedDepth());
            SetStopInfo(StopInfo::CreateStopReasonToTrace(m_thread));

            // FIXME: Maybe it would be better to create a InlineStep stop reason, but then
            // the whole rest of the world would have to handle that stop reason.
            m_virtual_step = true;
        }
        return !step_without_resume;
    }
    else
        return ThreadPlan::WillResume(resume_state, current_plan);

}
<|endoftext|>


<commit_before>//
// PROJECT:         Aspia Remote Desktop
// FILE:            client/file_transfer_uploader.cc
// LICENSE:         Mozilla Public License Version 2.0
// PROGRAMMERS:     Dmitry Chapyshev (dmitry@aspia.ru)
//

#include "client/file_transfer_uploader.h"
#include "base/logging.h"

namespace aspia {

namespace fs = std::experimental::filesystem;

FileTransferUploader::FileTransferUploader(
    std::shared_ptr<FileRequestSenderProxy> sender,
    Delegate* delegate)
    : FileTransfer(std::move(sender), delegate)
{
    // Nothing
}

uint64_t FileTransferUploader::BuildTaskListForDirectoryContent(
    const FilePath& source_path,
    const FilePath& target_path)
{
    std::error_code code;
    uint64_t size = 0;

    for (const auto& entry : fs::directory_iterator(source_path, code))
    {
        FilePath target_object_path;

        target_object_path.assign(target_path);
        target_object_path.append(entry.path().filename());

        if (fs::is_directory(entry.status()))
        {
            task_queue_.push(Task(entry.path(), target_object_path, true));

            size += BuildTaskListForDirectoryContent(entry.path(),
                                                     target_object_path);
        }
        else
        {
            task_queue_.push(Task(entry.path(), target_object_path, false));

            size += fs::file_size(entry.path(), code);
        }
    }

    return size;
}

void FileTransferUploader::Start(const FilePath& source_path,
                                 const FilePath& target_path,
                                 const FileList& file_list)
{
    uint64_t total_size = 0;
    std::error_code code;

    for (const auto& file : file_list)
    {
        FilePath source_object_path;

        source_object_path.assign(source_path);
        source_object_path.append(fs::u8path(file.name()));

        FilePath target_object_path;

        target_object_path.assign(target_path);
        target_object_path.append(fs::u8path(file.name()));

        if (file.is_directory())
        {
            task_queue_.push(Task(source_object_path, target_object_path, true));

            total_size += BuildTaskListForDirectoryContent(source_object_path,
                                                           target_object_path);
        }
        else
        {
            task_queue_.push(Task(source_object_path, target_object_path, false));

            uintmax_t file_size = fs::file_size(source_object_path, code);

            if (file_size != static_cast<uintmax_t>(-1))
                total_size += file_size;
        }
    }

    delegate_->OnObjectSizeNotify(total_size);

    // Run first task.
    RunTask(task_queue_.front());
}

void FileTransferUploader::RunTask(const Task& task)
{
    if (task.IsDirectory())
    {
        sender_->SendCreateDirectoryRequest(This(), task.TargetPath());
    }
    else
    {
        // TODO: Start file uploading.
    }
}

void FileTransferUploader::RunNextTask()
{
    // Delete the task only after confirmation of its successful execution.
    if (!task_queue_.empty())
        task_queue_.pop();

    if (task_queue_.empty())
    {
        delegate_->OnTransferCompletionNotify();
        return;
    }

    const Task& task = task_queue_.front();

    delegate_->OnObjectTransferNotify(task.SourcePath(), task.TargetPath());

    // Run next task.
    RunTask(task);
}

void FileTransferUploader::OnDriveListRequestReply(
    std::unique_ptr<proto::DriveList> drive_list)
{
    DLOG(FATAL) << "Unexpectedly received a list of drives";
}

void FileTransferUploader::OnDriveListRequestFailure(
    proto::RequestStatus status)
{
    // TODO
}

void FileTransferUploader::OnFileListRequestReply(
    const FilePath& path,
    std::unique_ptr<proto::FileList> file_list)
{
    DLOG(FATAL) << "Unexpectedly received a list of file";
}

void FileTransferUploader::OnFileListRequestFailure(
    const FilePath& path,
    proto::RequestStatus status)
{
    DLOG(FATAL) << "Unexpectedly received a list of files";
}

void FileTransferUploader::OnDirectorySizeRequestReply(
    const FilePath& path,
    uint64_t size)
{
    // TODO
}

void FileTransferUploader::OnDirectorySizeRequestFailure(
    const FilePath& path,
    proto::RequestStatus status)
{
    // TODO
}

void FileTransferUploader::OnCreateDirectoryRequestReply(
    const FilePath& path,
    proto::RequestStatus status)
{
    RunNextTask();
}

void FileTransferUploader::OnRemoveRequestReply(
    const FilePath& path,
    proto::RequestStatus status)
{
    // TODO
}

void FileTransferUploader::OnRenameRequestReply(
    const FilePath& old_name,
    const FilePath& new_name,
    proto::RequestStatus status)
{
    // TODO
}

} // namespace aspia
<commit_msg>Added check of the returned value<commit_after>//
// PROJECT:         Aspia Remote Desktop
// FILE:            client/file_transfer_uploader.cc
// LICENSE:         Mozilla Public License Version 2.0
// PROGRAMMERS:     Dmitry Chapyshev (dmitry@aspia.ru)
//

#include "client/file_transfer_uploader.h"
#include "base/logging.h"

namespace aspia {

namespace fs = std::experimental::filesystem;

FileTransferUploader::FileTransferUploader(
    std::shared_ptr<FileRequestSenderProxy> sender,
    Delegate* delegate)
    : FileTransfer(std::move(sender), delegate)
{
    // Nothing
}

uint64_t FileTransferUploader::BuildTaskListForDirectoryContent(
    const FilePath& source_path,
    const FilePath& target_path)
{
    std::error_code code;
    uint64_t size = 0;

    for (const auto& entry : fs::directory_iterator(source_path, code))
    {
        FilePath target_object_path;

        target_object_path.assign(target_path);
        target_object_path.append(entry.path().filename());

        if (fs::is_directory(entry.status()))
        {
            task_queue_.push(Task(entry.path(), target_object_path, true));

            size += BuildTaskListForDirectoryContent(entry.path(),
                                                     target_object_path);
        }
        else
        {
            task_queue_.push(Task(entry.path(), target_object_path, false));

            uintmax_t file_size = fs::file_size(entry.path(), code);

            if (file_size != static_cast<uintmax_t>(-1))
                size += file_size;
        }
    }

    return size;
}

void FileTransferUploader::Start(const FilePath& source_path,
                                 const FilePath& target_path,
                                 const FileList& file_list)
{
    uint64_t total_size = 0;
    std::error_code code;

    for (const auto& file : file_list)
    {
        FilePath source_object_path;

        source_object_path.assign(source_path);
        source_object_path.append(fs::u8path(file.name()));

        FilePath target_object_path;

        target_object_path.assign(target_path);
        target_object_path.append(fs::u8path(file.name()));

        if (file.is_directory())
        {
            task_queue_.push(Task(source_object_path, target_object_path, true));

            total_size += BuildTaskListForDirectoryContent(source_object_path,
                                                           target_object_path);
        }
        else
        {
            task_queue_.push(Task(source_object_path, target_object_path, false));

            uintmax_t file_size = fs::file_size(source_object_path, code);

            if (file_size != static_cast<uintmax_t>(-1))
                total_size += file_size;
        }
    }

    delegate_->OnObjectSizeNotify(total_size);

    // Run first task.
    RunTask(task_queue_.front());
}

void FileTransferUploader::RunTask(const Task& task)
{
    if (task.IsDirectory())
    {
        sender_->SendCreateDirectoryRequest(This(), task.TargetPath());
    }
    else
    {
        // TODO: Start file uploading.
    }
}

void FileTransferUploader::RunNextTask()
{
    // Delete the task only after confirmation of its successful execution.
    if (!task_queue_.empty())
        task_queue_.pop();

    if (task_queue_.empty())
    {
        delegate_->OnTransferCompletionNotify();
        return;
    }

    const Task& task = task_queue_.front();

    delegate_->OnObjectTransferNotify(task.SourcePath(), task.TargetPath());

    // Run next task.
    RunTask(task);
}

void FileTransferUploader::OnDriveListRequestReply(
    std::unique_ptr<proto::DriveList> drive_list)
{
    DLOG(FATAL) << "Unexpectedly received a list of drives";
}

void FileTransferUploader::OnDriveListRequestFailure(
    proto::RequestStatus status)
{
    // TODO
}

void FileTransferUploader::OnFileListRequestReply(
    const FilePath& path,
    std::unique_ptr<proto::FileList> file_list)
{
    DLOG(FATAL) << "Unexpectedly received a list of file";
}

void FileTransferUploader::OnFileListRequestFailure(
    const FilePath& path,
    proto::RequestStatus status)
{
    DLOG(FATAL) << "Unexpectedly received a list of files";
}

void FileTransferUploader::OnDirectorySizeRequestReply(
    const FilePath& path,
    uint64_t size)
{
    // TODO
}

void FileTransferUploader::OnDirectorySizeRequestFailure(
    const FilePath& path,
    proto::RequestStatus status)
{
    // TODO
}

void FileTransferUploader::OnCreateDirectoryRequestReply(
    const FilePath& path,
    proto::RequestStatus status)
{
    RunNextTask();
}

void FileTransferUploader::OnRemoveRequestReply(
    const FilePath& path,
    proto::RequestStatus status)
{
    // TODO
}

void FileTransferUploader::OnRenameRequestReply(
    const FilePath& old_name,
    const FilePath& new_name,
    proto::RequestStatus status)
{
    // TODO
}

} // namespace aspia
<|endoftext|>


<commit_before>// __BEGIN_LICENSE__
//  Copyright (c) 2006-2012, United States Government as represented by the
//  Administrator of the National Aeronautics and Space Administration. All
//  rights reserved.
//
//  The NASA Vision Workbench is 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.
// __END_LICENSE__

#ifdef _MSC_VER
#pragma warning(disable:4244)
#pragma warning(disable:4267)
#pragma warning(disable:4996)
#endif

#include <vw/FileIO/DiskImageView.h>
#include <vw/Stereo/DisparityMap.h>

using namespace vw;
using namespace std;

// Average the rows in a given disparity image. Save them to disk as
// two text files (x and y values), with as many entries as there
// were columns in the disparity.

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

  // TODO: Use Boost program options.

  // TODO: No need for outdx.txt and outdy.txt, just save with with same prefix.
  if (argc <= 3) {
    vw_out() << "Usage: disp_avg disp.tif outdx.txt outdy.txt [row_start] [num_rows] [col_start] [num_cols]\n";
    return 1;
  }

  std::string in_file = argv[1], outx = argv[2], outy = argv[3];

  std::cout << "Reading: " << in_file << std::endl;
  DiskImageView < PixelMask<Vector2f> > D(in_file);

  int cols = D.cols(), rows = D.rows();
  std::cout << "Number of cols and rows is " << cols << ' ' << rows << std::endl;

  // Handle optional row ROI arguments.
  // - No col ROI since we want the entire column range.
  int row_start = 0;
  int row_stop  = rows;
  int col_start = 0;
  int col_stop  = cols;
  if (argc > 4) row_start = atoi(argv[4]);
  if (argc > 5) row_stop  = row_start + atoi(argv[5]);
  if (argc > 6) col_start = atoi(argv[6]);
  if (argc > 7) col_stop  = col_start + atoi(argv[7]);

  // TODO: Add a progress bar.
  vector<double> Dx(cols, 0), Dy(cols, 0); // Always full sized, even if crop is used.
  for (int col = col_start; col < col_stop; col++){
    if (col%100 == 0){
      std::cout << "column " << col << std::endl;
    }
    vector<double> px, py;
    for (int row = row_start; row < row_stop; row++){
      PixelMask<Vector2f> p = D(col, row);
      if (! is_valid(p)) continue;
      px.push_back(p.child()[0]);
      py.push_back(p.child()[1]);
    }
    std::sort(px.begin(), px.end());
    std::sort(py.begin(), py.end());
    int len = px.size();
    int num_valid = 0;
    Dx[col] = 0;
    Dy[col] = 0;
    for (int k = 0; k < len; k++){
      num_valid++;
      Dx[col] += px[k];
      Dy[col] += py[k];
    }

    if (num_valid > 0){
      Dx[col] /= num_valid;
      Dy[col] /= num_valid;
    }
  }

  // Write dx file
  ofstream dx(outx.c_str());
  dx.precision(16);
  std::cout << "Writing: " << outx << std::endl;
  dx << col_start << std::endl << col_stop << std::endl; // Column crop on header lines
  for (int col = 0; col < cols; col++)
    dx << Dx[col] << std::endl;

  // Write dy file
  ofstream dy(outy.c_str());
  dy.precision(16);
  std::cout << "Writing: " << outy << std::endl;
  dy << col_start << std::endl << col_stop << std::endl; // Column crop on header lines
  for (int col = 0; col < cols; col++)
    dy << Dy[col] << std::endl;

  return 0;
}
<commit_msg>disp_avg: Ability to filter outliers. Commented out by default<commit_after>// __BEGIN_LICENSE__
//  Copyright (c) 2006-2012, United States Government as represented by the
//  Administrator of the National Aeronautics and Space Administration. All
//  rights reserved.
//
//  The NASA Vision Workbench is 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.
// __END_LICENSE__

#ifdef _MSC_VER
#pragma warning(disable:4244)
#pragma warning(disable:4267)
#pragma warning(disable:4996)
#endif

#include <vw/FileIO/DiskImageView.h>
#include <vw/Stereo/DisparityMap.h>

#include <asp/Core/Macros.h>
#include <asp/Core/Common.h>
#include <vw/Image/Statistics.h>

using namespace vw;

// Average the rows in a given disparity image. Save them to disk as
// two text files (x and y values), with as many entries as there
// were columns in the disparity.

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

  // TODO: Use Boost program options.

  // TODO: No need for outdx.txt and outdy.txt, just save with with same prefix.
  if (argc <= 3) {
    vw_out() << "Usage: disp_avg disp.tif outdx.txt outdy.txt [row_start] [num_rows] [col_start] [num_cols]\n";
    return 1;
  }

  std::string in_file = argv[1], outx = argv[2], outy = argv[3];

  std::cout << "Reading: " << in_file << std::endl;
  DiskImageView < PixelMask<Vector2f> > D(in_file);

  int cols = D.cols(), rows = D.rows();
  std::cout << "Number of cols and rows is " << cols << ' ' << rows << std::endl;

  // Handle optional row ROI arguments.
  // - No col ROI since we want the entire column range.
  int row_start = 0;
  int row_stop  = rows;
  int col_start = 0;
  int col_stop  = cols;
  if (argc > 4) row_start = atoi(argv[4]);
  if (argc > 5) row_stop  = row_start + atoi(argv[5]);
  if (argc > 6) col_start = atoi(argv[6]);
  if (argc > 7) col_stop  = col_start + atoi(argv[7]);

  TerminalProgressCallback disp_progress("asp", "\tAveraging:   ");
  double disp_progress_mult = 1.0/double(std::max(col_stop - col_start, 1));

  std::vector<double> Dx(cols, 0), Dy(cols, 0); // Always full-sized, even if crop is used.
  for (int col = col_start; col < col_stop; col++){
    disp_progress.report_progress((col - col_start) * disp_progress_mult);

    std::vector<double> px, py;
    for (int row = row_start; row < row_stop; row++){
      PixelMask<Vector2f> p = D(col, row);
      if (! is_valid(p)) continue;
      px.push_back(p.child()[0]);
      py.push_back(p.child()[1]);
    }
    std::sort(px.begin(), px.end());
    std::sort(py.begin(), py.end());

    double pct_factor     = 0.75;
    double outlier_factor = 3.0;
    double bx, ex;
    if (!vw::math::find_outlier_brackets(px, pct_factor, outlier_factor, bx, ex))
      continue;
    double by, ey;
    if (!vw::math::find_outlier_brackets(py, pct_factor, outlier_factor, by, ey))
      continue;

    int len = px.size();
    int num_valid = 0;
    Dx[col] = 0;
    Dy[col] = 0;
    for (int k = 0; k < len; k++){

      // TODO(oalexan1): This was tested only with WV3 pan to color disparity.
      // if (px[k] < bx || px[k] > ex || py[k] < by || py[k] > ey) continue;

      num_valid++;
      Dx[col] += px[k];
      Dy[col] += py[k];
    }

    if (num_valid > 0){
      Dx[col] /= num_valid;
      Dy[col] /= num_valid;
    }
  }

  disp_progress.report_finished();

  // Write dx file
  std::ofstream dx(outx.c_str());
  dx.precision(16);
  std::cout << "Writing: " << outx << std::endl;
  dx << col_start << std::endl << col_stop << std::endl; // Column crop on header lines
  for (int col = 0; col < cols; col++)
    dx << Dx[col] << std::endl;
  dx.close();

  // Write dy file
  std::ofstream dy(outy.c_str());
  dy.precision(16);
  std::cout << "Writing: " << outy << std::endl;
  dy << col_start << std::endl << col_stop << std::endl; // Column crop on header lines
  for (int col = 0; col < cols; col++)
    dy << Dy[col] << std::endl;
  dy.close();

  return 0;
}
<|endoftext|>


<commit_before><commit_msg>sal_Bool->bool<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlwrap.hxx,v $
 *
 *  $Revision: 1.15 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 18:04:52 $
 *
 *  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 SC_XMLWRAP_HXX
#define SC_XMLWRAP_HXX

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

class ScDocument;
class SfxMedium;
class ScMySharedData;

#include <tools/errcode.hxx>

namespace com { namespace sun { namespace star {
    namespace beans { struct PropertyValue; }
    namespace frame { class XModel; }
    namespace task { class XStatusIndicator; }
    namespace lang { class XMultiServiceFactory; }
    namespace uno { class XInterface; }
    namespace embed { class XStorage; }
    namespace xml {
        namespace sax { struct InputSource; } }
} } }

class ScXMLImportWrapper
{
    ScDocument&     rDoc;
    SfxMedium*      pMedium;
    ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > xStorage;

    com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator> GetStatusIndicator(
        com::sun::star::uno::Reference< com::sun::star::frame::XModel >& rModel);
    com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator> GetStatusIndicator();

    sal_uInt32 ImportFromComponent(com::sun::star::uno::Reference<com::sun::star::lang::XMultiServiceFactory>& xServiceFactory,
        com::sun::star::uno::Reference<com::sun::star::frame::XModel>& xModel,
        com::sun::star::uno::Reference<com::sun::star::uno::XInterface>& xXMLParser,
        com::sun::star::xml::sax::InputSource& aParserInput,
        const rtl::OUString& sComponentName, const rtl::OUString& sDocName, const rtl::OUString& sOldDocName,
        com::sun::star::uno::Sequence<com::sun::star::uno::Any>& aArgs,
        sal_Bool bMustBeSuccessfull);

    sal_Bool ExportToComponent(com::sun::star::uno::Reference<com::sun::star::lang::XMultiServiceFactory>& xServiceFactory,
        com::sun::star::uno::Reference<com::sun::star::frame::XModel>& xModel,
        com::sun::star::uno::Reference<com::sun::star::uno::XInterface>& xWriter,
        com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aDescriptor,
        const rtl::OUString& sName, const rtl::OUString& sMediaType, const rtl::OUString& sComponentName,
        const sal_Bool bPlainText, com::sun::star::uno::Sequence<com::sun::star::uno::Any>& aArgs,
        ScMySharedData*& pSharedData);

public:
    ScXMLImportWrapper(ScDocument& rD, SfxMedium* pM, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >&);
    BOOL Import(sal_Bool bStylesOnly, ErrCode& );
    BOOL Export(sal_Bool bStylesOnly);
};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.15.700); FILE MERGED 2008/04/01 15:29:47 thb 1.15.700.2: #i85898# Stripping all external header guards 2008/03/31 17:13:36 rt 1.15.700.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: xmlwrap.hxx,v $
 * $Revision: 1.16 $
 *
 * 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 SC_XMLWRAP_HXX
#define SC_XMLWRAP_HXX

#include <tools/solar.h>
#include <com/sun/star/uno/Reference.hxx>
#include <com/sun/star/uno/Sequence.hxx>

class ScDocument;
class SfxMedium;
class ScMySharedData;

#include <tools/errcode.hxx>

namespace com { namespace sun { namespace star {
    namespace beans { struct PropertyValue; }
    namespace frame { class XModel; }
    namespace task { class XStatusIndicator; }
    namespace lang { class XMultiServiceFactory; }
    namespace uno { class XInterface; }
    namespace embed { class XStorage; }
    namespace xml {
        namespace sax { struct InputSource; } }
} } }

class ScXMLImportWrapper
{
    ScDocument&     rDoc;
    SfxMedium*      pMedium;
    ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > xStorage;

    com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator> GetStatusIndicator(
        com::sun::star::uno::Reference< com::sun::star::frame::XModel >& rModel);
    com::sun::star::uno::Reference< com::sun::star::task::XStatusIndicator> GetStatusIndicator();

    sal_uInt32 ImportFromComponent(com::sun::star::uno::Reference<com::sun::star::lang::XMultiServiceFactory>& xServiceFactory,
        com::sun::star::uno::Reference<com::sun::star::frame::XModel>& xModel,
        com::sun::star::uno::Reference<com::sun::star::uno::XInterface>& xXMLParser,
        com::sun::star::xml::sax::InputSource& aParserInput,
        const rtl::OUString& sComponentName, const rtl::OUString& sDocName, const rtl::OUString& sOldDocName,
        com::sun::star::uno::Sequence<com::sun::star::uno::Any>& aArgs,
        sal_Bool bMustBeSuccessfull);

    sal_Bool ExportToComponent(com::sun::star::uno::Reference<com::sun::star::lang::XMultiServiceFactory>& xServiceFactory,
        com::sun::star::uno::Reference<com::sun::star::frame::XModel>& xModel,
        com::sun::star::uno::Reference<com::sun::star::uno::XInterface>& xWriter,
        com::sun::star::uno::Sequence<com::sun::star::beans::PropertyValue>& aDescriptor,
        const rtl::OUString& sName, const rtl::OUString& sMediaType, const rtl::OUString& sComponentName,
        const sal_Bool bPlainText, com::sun::star::uno::Sequence<com::sun::star::uno::Any>& aArgs,
        ScMySharedData*& pSharedData);

public:
    ScXMLImportWrapper(ScDocument& rD, SfxMedium* pM, const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >&);
    BOOL Import(sal_Bool bStylesOnly, ErrCode& );
    BOOL Export(sal_Bool bStylesOnly);
};

#endif

<|endoftext|>