<commit_before>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.

#include "Grappa.hpp"
#include "CompletionEvent.hpp"
#include "ParallelLoop.hpp"
#include "Collective.hpp"
#include "Statistics.hpp"

#include <string>

DECLARE_uint64( num_starting_workers );
DEFINE_uint64( num_test_workers, 4, "Number of workers for the tests");
DEFINE_uint64( iters_per_task, 10000, "Iterations per task" );
DEFINE_string( test_type, "yields", "options: {yields,sequential_updates, sequential_updates16" );
DEFINE_uint64( private_array_size, 1, "Size of private array of 8-bytes for each task" );

using namespace Grappa;

CompletionEvent * final;
CompletionEvent * task_barrier;

struct SixteenBytes {
  uint64_t val1;
  uint64_t val2;
};

struct Cacheline {
  uint64_t val;
  char padding[56];
};

uint64_t * values8;
SixteenBytes * values16;

// Performance output of the test, not used as cumulative statistics
// Initial value 0 should make merge just use Core 0's
GRAPPA_DEFINE_STAT( SimpleStatistic<double>, context_switch_test_runtime_avg, 0 );
GRAPPA_DEFINE_STAT( SimpleStatistic<double>, context_switch_test_runtime_max, 0 );
GRAPPA_DEFINE_STAT( SimpleStatistic<double>, context_switch_test_runtime_min, 0 );

// core-shared counter for counting progress
uint64_t numst;
uint64_t waitCount; // TODO: for traces, change to SimpleStatistic
bool running;

void user_main( void * args ) {
  srand((unsigned int)Grappa_walltime());

  // must have enough threads because they all join a barrier
  CHECK( FLAGS_num_test_workers < FLAGS_num_starting_workers );

  if (FLAGS_test_type.compare("yields")==0) {
    LOG(INFO) << ( "Test yields" );
    {
      struct runtimes_t {
        double runtime_avg, runtime_min, runtime_max;
      };
      runtimes_t r;

      on_all_cores( [&r] {
        // per core timing
        double start, end;
        running = false;

        final = new CompletionEvent(FLAGS_num_test_workers);
        task_barrier = new CompletionEvent(FLAGS_num_test_workers);

        for ( uint64_t t=0; t<FLAGS_num_test_workers; t++ ) {
          privateTask( [&start] {
            // wait for all to start (to hack scheduler yield)
            task_barrier->complete();
            task_barrier->wait();

            // first task to exit the local barrier will start the timer
            if ( !running ) {
              Grappa::Statistics::reset();
              start = Grappa_walltime();
              running = true;
            }

            // do the work
            for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) {
              Grappa_yield();
            }

            final->complete();
          });
        }

        LOG(INFO) << ( "waiting" );
        final->wait();
        end = Grappa_walltime();
        double runtime = end-start;
        LOG(INFO) << "took time " << runtime;

        Grappa::barrier();
        LOG(INFO) << ( "all done" );

        // sort out timing

        double r_sum = Grappa::allreduce<double, collective_add>( runtime );
        double r_min = Grappa::allreduce<double, collective_min>( runtime );
        double r_max = Grappa::allreduce<double, collective_max>( runtime );
        if ( Grappa::mycore()==0 ) {
          r.runtime_avg = r_sum / Grappa::cores();
          r.runtime_min = r_min;
          r.runtime_max = r_max;
        }
      });

      context_switch_test_runtime_avg = r.runtime_avg;
      context_switch_test_runtime_max = r.runtime_max;
      context_switch_test_runtime_min = r.runtime_min;
      Grappa::Statistics::merge_and_print();

//      Streams overlap
//      BOOST_MESSAGE( "cores_time_avg = " << r.runtime_avg
//                      << ", cores_time_max = " << r.runtime_max
//                      << ", cores_time_min = " << r.runtime_min);
    }
  } else if (FLAGS_test_type.compare("cvwakes")==0) {
    LOG(INFO) << ( "Test cv wakes" );
    {
      struct runtimes_t {
        double runtime_avg, runtime_min, runtime_max;
      };
      runtimes_t r;

      on_all_cores( [&r] {
        // per core timing
        double start, end;

        ConditionVariable * cvs = new ConditionVariable[FLAGS_num_test_workers];
        bool * asleep = new bool[FLAGS_num_test_workers];
        for( int i=0; i<FLAGS_num_test_workers; i++) { asleep[i] = false; }

        final = new CompletionEvent(1);
        task_barrier = new CompletionEvent(FLAGS_num_test_workers);

        running = false;
        waitCount = 0;
        numst = 0;

        for ( uint64_t t=0; t<FLAGS_num_test_workers; t++ ) {
          privateTask( [asleep,&start,cvs] {
            // wait for all to start (to hack scheduler yield)
            task_barrier->complete();
            task_barrier->wait();

            // first task to exit the local barrier will start the timer
            if ( !running ) {
              // can safely reset statistics here because
              // no messages are sent between cores in the
              // timed portion
              Grappa::Statistics::reset();
              start = Grappa_walltime();
              running = true;
            }

            uint64_t tid = numst++;

            uint64_t partner = (tid + FLAGS_num_test_workers/2)%FLAGS_num_test_workers;
            uint64_t total_iters = FLAGS_iters_per_task*FLAGS_num_test_workers;

            // do the work
            while( waitCount++ < total_iters ) {
              if ( asleep[partner] ) {   // TODO also test just wake up case
                Grappa::signal( &cvs[partner] );
              }
              asleep[tid] = true;
              Grappa::wait( &cvs[tid] );
              asleep[tid] = false;
            }

            // only first
            if ( running ) {
              final->complete();  // signal to finish as soon as the parent task gets scheduled
              running = false;
            }
          });
        }

        LOG(INFO) << ( "waiting" );
        final->wait();
        end = Grappa_walltime();
        double runtime = end-start;
        LOG(INFO) << "took time " << runtime;

        // wake all
        for (int i=0; i<FLAGS_num_test_workers; i++) { Grappa::signal(&cvs[i]); }
        LOG(INFO) << ( "woke all" );

        Grappa::barrier();

        LOG(INFO) << ( "all done" );

        // sort out timing

        double r_sum = Grappa::allreduce<double, collective_add>( runtime );
        double r_min = Grappa::allreduce<double, collective_min>( runtime );
        double r_max = Grappa::allreduce<double, collective_max>( runtime );
        if ( Grappa::mycore()==0 ) {
          r.runtime_avg = r_sum / Grappa::cores();
          r.runtime_min = r_min;
          r.runtime_max = r_max;
        }
      });

      context_switch_test_runtime_avg = r.runtime_avg;
      context_switch_test_runtime_max = r.runtime_max;
      context_switch_test_runtime_min = r.runtime_min;
      Grappa::Statistics::merge_and_print();

//      Streams overlap
//      BOOST_MESSAGE( "cores_time_avg = " << r.runtime_avg
//                      << ", cores_time_max = " << r.runtime_max
//                      << ", cores_time_min = " << r.runtime_min);
    }

  } else if (FLAGS_test_type.compare("sequential_updates")==0) {
    LOG(INFO) << ( "Test sequential_updates" );
    {

      final = new CompletionEvent(FLAGS_num_starting_workers);
      task_barrier = new CompletionEvent(FLAGS_num_starting_workers);
      values8 = new uint64_t[FLAGS_num_starting_workers];

      double start = Grappa_walltime();

      for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) {
        privateTask( [t] {
          // wait for all to start (to hack scheduler yield)
          task_barrier->complete();
          task_barrier->wait();

          // do the work
          for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) {
            values8[t] += 1;
            Grappa_yield();
          }
          final->complete();
        });
      }

      final->wait();
      double end = Grappa_walltime();

      double runtime = end-start;
      LOG(INFO) << "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task);
    }
  } else if (FLAGS_test_type.compare("sequential_updates16")==0) {

    LOG(INFO) << ( "Test sequential_updates16" );
    {
      final = new CompletionEvent(FLAGS_num_starting_workers);
      task_barrier = new CompletionEvent(FLAGS_num_starting_workers);
      values16 = new SixteenBytes[FLAGS_num_starting_workers];

      double start = Grappa_walltime();

      for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) {
        privateTask( [t] {
            // wait for all to start (to hack scheduler yield)
            task_barrier->complete();
            task_barrier->wait();

            // do the work
            for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) {
            values16[t].val1 += 1;
            values16[t].val2 += 1;
            Grappa_yield();
            }
            final->complete();
            });
      }

      final->wait();
      double end = Grappa_walltime();

      double runtime = end-start;
      LOG(INFO) << "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task);
    }
  } else if (FLAGS_test_type.compare("private_array")==0) {

    LOG(INFO) << ( "Test private_array" );
    {
      final = new CompletionEvent(FLAGS_num_starting_workers);
      task_barrier = new CompletionEvent(FLAGS_num_starting_workers);
      values8 = new uint64_t[FLAGS_num_starting_workers];

      double start = Grappa_walltime();

      for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) {
        privateTask( [t] {
            uint64_t myarray[FLAGS_private_array_size];

            // wait for all to start (to hack scheduler yield)
            task_barrier->complete();
            task_barrier->wait();

            // do the work
            for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) {
            for (uint64_t j=0; j<FLAGS_private_array_size; j++) {
            myarray[j] += 1;
            }
            Grappa_yield();
            }
            values8[t] = myarray[rand()%FLAGS_private_array_size];
            final->complete();
            });
      }

      final->wait();
      double end = Grappa_walltime();

      LOG(INFO) << "result = " << values8[rand()%FLAGS_num_starting_workers];

      double runtime = end-start;
      LOG(INFO) << "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task);
    }
  } else if (FLAGS_test_type.compare("private_array_bycache")==0) {

    LOG(INFO) << ( "Test private_array_bycache" );
    {
      final = new CompletionEvent(FLAGS_num_starting_workers);
      task_barrier = new CompletionEvent(FLAGS_num_starting_workers);
      values8 = new uint64_t[FLAGS_num_starting_workers];

      double start = Grappa_walltime();

      for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) {
        privateTask( [t] {
            Cacheline myarray[FLAGS_private_array_size];

            // wait for all to start (to hack scheduler yield)
            task_barrier->complete();
            task_barrier->wait();

            // do the work
            for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) {
            for (uint64_t j=0; j<FLAGS_private_array_size; j++) {
            myarray[j].val += 1;
            }
            Grappa_yield();
            }
            values8[t] = myarray[rand()%FLAGS_private_array_size].val;
            final->complete();
            });
      }

      final->wait();
      double end = Grappa_walltime();

      LOG(INFO) << "result = " << values8[rand()%FLAGS_num_starting_workers];

      double runtime = end-start;
      LOG(INFO) << "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task);
    }
  } else {
    CHECK( false ); // Unrecognized test_type
  }

  DVLOG(5) << ( "user main is exiting" );
}

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

  Grappa_init( &argc, &argv );

  Grappa_activate();

  DVLOG(1) << "Spawning user main Thread....";
  Grappa_run_user_main( &user_main, (void*)NULL );
  VLOG(5) << "run_user_main returned";
  CHECK( Grappa_done() );

  Grappa_finish( 0 );
}

<commit_msg>remove private barrier from switch test since scheduler already won't run the threads until parent suspends<commit_after>
// Copyright 2010-2012 University of Washington. All Rights Reserved.
// LICENSE_PLACEHOLDER
// This software was created with Government support under DE
// AC05-76RL01830 awarded by the United States Department of
// Energy. The Government has certain rights in the software.

#include "Grappa.hpp"
#include "CompletionEvent.hpp"
#include "ParallelLoop.hpp"
#include "Collective.hpp"
#include "Statistics.hpp"

#include <string>

DECLARE_uint64( num_starting_workers );
DEFINE_uint64( num_test_workers, 4, "Number of workers for the tests");
DEFINE_uint64( iters_per_task, 10000, "Iterations per task" );
DEFINE_string( test_type, "yields", "options: {yields,sequential_updates, sequential_updates16" );
DEFINE_uint64( private_array_size, 1, "Size of private array of 8-bytes for each task" );

using namespace Grappa;

CompletionEvent * final;
CompletionEvent * task_barrier;

struct SixteenBytes {
  uint64_t val1;
  uint64_t val2;
};

struct Cacheline {
  uint64_t val;
  char padding[56];
};

uint64_t * values8;
SixteenBytes * values16;

// Performance output of the test, not used as cumulative statistics
// Initial value 0 should make merge just use Core 0's
GRAPPA_DEFINE_STAT( SimpleStatistic<double>, context_switch_test_runtime_avg, 0 );
GRAPPA_DEFINE_STAT( SimpleStatistic<double>, context_switch_test_runtime_max, 0 );
GRAPPA_DEFINE_STAT( SimpleStatistic<double>, context_switch_test_runtime_min, 0 );

// core-shared counter for counting progress
uint64_t numst;
uint64_t waitCount; // TODO: for traces, change to SimpleStatistic
bool running;

void user_main( void * args ) {
  srand((unsigned int)Grappa_walltime());

  // must have enough threads because they all join a barrier
  CHECK( FLAGS_num_test_workers < FLAGS_num_starting_workers );

  if (FLAGS_test_type.compare("yields")==0) {
    LOG(INFO) << ( "Test yields" );
    {
      struct runtimes_t {
        double runtime_avg, runtime_min, runtime_max;
      };
      runtimes_t r;

      on_all_cores( [&r] {
        // per core timing
        double start, end;
        running = false;

        final = new CompletionEvent(FLAGS_num_test_workers);
        task_barrier = new CompletionEvent(FLAGS_num_test_workers);

        for ( uint64_t t=0; t<FLAGS_num_test_workers; t++ ) {
          privateTask( [&start] {
            // wait for all to start (to hack scheduler yield)
          //  task_barrier->complete();
           // task_barrier->wait();

            // first task to exit the local barrier will start the timer
            if ( !running ) {
              Grappa::Statistics::reset();
              start = Grappa_walltime();
              running = true;
            }

            // do the work
            for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) {
              Grappa_yield();
            }

            final->complete();
          });
        }

        LOG(INFO) << ( "waiting" );
        final->wait();
        end = Grappa_walltime();
        double runtime = end-start;
        LOG(INFO) << "took time " << runtime;

        Grappa::barrier();
        LOG(INFO) << ( "all done" );

        // sort out timing

        double r_sum = Grappa::allreduce<double, collective_add>( runtime );
        double r_min = Grappa::allreduce<double, collective_min>( runtime );
        double r_max = Grappa::allreduce<double, collective_max>( runtime );
        if ( Grappa::mycore()==0 ) {
          r.runtime_avg = r_sum / Grappa::cores();
          r.runtime_min = r_min;
          r.runtime_max = r_max;
        }
      });

      context_switch_test_runtime_avg = r.runtime_avg;
      context_switch_test_runtime_max = r.runtime_max;
      context_switch_test_runtime_min = r.runtime_min;
      Grappa::Statistics::merge_and_print();

//      Streams overlap
//      BOOST_MESSAGE( "cores_time_avg = " << r.runtime_avg
//                      << ", cores_time_max = " << r.runtime_max
//                      << ", cores_time_min = " << r.runtime_min);
    }
  } else if (FLAGS_test_type.compare("cvwakes")==0) {
    LOG(INFO) << ( "Test cv wakes" );
    {
      struct runtimes_t {
        double runtime_avg, runtime_min, runtime_max;
      };
      runtimes_t r;

      on_all_cores( [&r] {
        // per core timing
        double start, end;

        ConditionVariable * cvs = new ConditionVariable[FLAGS_num_test_workers];
        bool * asleep = new bool[FLAGS_num_test_workers];
        for( int i=0; i<FLAGS_num_test_workers; i++) { asleep[i] = false; }

        final = new CompletionEvent(1);
        task_barrier = new CompletionEvent(FLAGS_num_test_workers);

        running = false;
        waitCount = 0;
        numst = 0;

        for ( uint64_t t=0; t<FLAGS_num_test_workers; t++ ) {
          privateTask( [asleep,&start,cvs] {
            // wait for all to start (to hack scheduler yield)
            //task_barrier->complete();
            //task_barrier->wait();

            // first task to exit the local barrier will start the timer
            if ( !running ) {
              // can safely reset statistics here because
              // no messages are sent between cores in the
              // timed portion
              Grappa::Statistics::reset();
              start = Grappa_walltime();
              running = true;
            }

            uint64_t tid = numst++;

            uint64_t partner = (tid + FLAGS_num_test_workers/2)%FLAGS_num_test_workers;
            uint64_t total_iters = FLAGS_iters_per_task*FLAGS_num_test_workers;

            // do the work
            while( waitCount++ < total_iters ) {
              if ( asleep[partner] ) {   // TODO also test just wake up case
                Grappa::signal( &cvs[partner] );
              }
              asleep[tid] = true;
              Grappa::wait( &cvs[tid] );
              asleep[tid] = false;
            }

            // only first
            if ( running ) {
              final->complete();  // signal to finish as soon as the parent task gets scheduled
              running = false;
            }
          });
        }

        LOG(INFO) << ( "waiting" );
        final->wait();
        end = Grappa_walltime();
        double runtime = end-start;
        LOG(INFO) << "took time " << runtime;

        // wake all
        for (int i=0; i<FLAGS_num_test_workers; i++) { Grappa::signal(&cvs[i]); }
        LOG(INFO) << ( "woke all" );

        Grappa::barrier();

        LOG(INFO) << ( "all done" );

        // sort out timing

        double r_sum = Grappa::allreduce<double, collective_add>( runtime );
        double r_min = Grappa::allreduce<double, collective_min>( runtime );
        double r_max = Grappa::allreduce<double, collective_max>( runtime );
        if ( Grappa::mycore()==0 ) {
          r.runtime_avg = r_sum / Grappa::cores();
          r.runtime_min = r_min;
          r.runtime_max = r_max;
        }
      });

      context_switch_test_runtime_avg = r.runtime_avg;
      context_switch_test_runtime_max = r.runtime_max;
      context_switch_test_runtime_min = r.runtime_min;
      Grappa::Statistics::merge_and_print();

//      Streams overlap
//      BOOST_MESSAGE( "cores_time_avg = " << r.runtime_avg
//                      << ", cores_time_max = " << r.runtime_max
//                      << ", cores_time_min = " << r.runtime_min);
    }

  } else if (FLAGS_test_type.compare("sequential_updates")==0) {
    LOG(INFO) << ( "Test sequential_updates" );
    {

      final = new CompletionEvent(FLAGS_num_starting_workers);
      task_barrier = new CompletionEvent(FLAGS_num_starting_workers);
      values8 = new uint64_t[FLAGS_num_starting_workers];

      double start = Grappa_walltime();

      for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) {
        privateTask( [t] {
          // wait for all to start (to hack scheduler yield)
          task_barrier->complete();
          task_barrier->wait();

          // do the work
          for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) {
            values8[t] += 1;
            Grappa_yield();
          }
          final->complete();
        });
      }

      final->wait();
      double end = Grappa_walltime();

      double runtime = end-start;
      LOG(INFO) << "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task);
    }
  } else if (FLAGS_test_type.compare("sequential_updates16")==0) {

    LOG(INFO) << ( "Test sequential_updates16" );
    {
      final = new CompletionEvent(FLAGS_num_starting_workers);
      task_barrier = new CompletionEvent(FLAGS_num_starting_workers);
      values16 = new SixteenBytes[FLAGS_num_starting_workers];

      double start = Grappa_walltime();

      for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) {
        privateTask( [t] {
            // wait for all to start (to hack scheduler yield)
            task_barrier->complete();
            task_barrier->wait();

            // do the work
            for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) {
            values16[t].val1 += 1;
            values16[t].val2 += 1;
            Grappa_yield();
            }
            final->complete();
            });
      }

      final->wait();
      double end = Grappa_walltime();

      double runtime = end-start;
      LOG(INFO) << "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task);
    }
  } else if (FLAGS_test_type.compare("private_array")==0) {

    LOG(INFO) << ( "Test private_array" );
    {
      final = new CompletionEvent(FLAGS_num_starting_workers);
      task_barrier = new CompletionEvent(FLAGS_num_starting_workers);
      values8 = new uint64_t[FLAGS_num_starting_workers];

      double start = Grappa_walltime();

      for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) {
        privateTask( [t] {
            uint64_t myarray[FLAGS_private_array_size];

            // wait for all to start (to hack scheduler yield)
            task_barrier->complete();
            task_barrier->wait();

            // do the work
            for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) {
            for (uint64_t j=0; j<FLAGS_private_array_size; j++) {
            myarray[j] += 1;
            }
            Grappa_yield();
            }
            values8[t] = myarray[rand()%FLAGS_private_array_size];
            final->complete();
            });
      }

      final->wait();
      double end = Grappa_walltime();

      LOG(INFO) << "result = " << values8[rand()%FLAGS_num_starting_workers];

      double runtime = end-start;
      LOG(INFO) << "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task);
    }
  } else if (FLAGS_test_type.compare("private_array_bycache")==0) {

    LOG(INFO) << ( "Test private_array_bycache" );
    {
      final = new CompletionEvent(FLAGS_num_starting_workers);
      task_barrier = new CompletionEvent(FLAGS_num_starting_workers);
      values8 = new uint64_t[FLAGS_num_starting_workers];

      double start = Grappa_walltime();

      for ( uint64_t t=0; t<FLAGS_num_starting_workers; t++ ) {
        privateTask( [t] {
            Cacheline myarray[FLAGS_private_array_size];

            // wait for all to start (to hack scheduler yield)
            task_barrier->complete();
            task_barrier->wait();

            // do the work
            for ( uint64_t i=0; i<FLAGS_iters_per_task; i++ ) {
            for (uint64_t j=0; j<FLAGS_private_array_size; j++) {
            myarray[j].val += 1;
            }
            Grappa_yield();
            }
            values8[t] = myarray[rand()%FLAGS_private_array_size].val;
            final->complete();
            });
      }

      final->wait();
      double end = Grappa_walltime();

      LOG(INFO) << "result = " << values8[rand()%FLAGS_num_starting_workers];

      double runtime = end-start;
      LOG(INFO) << "time = " << runtime << ", avg_switch_time = " << runtime/(FLAGS_num_starting_workers*FLAGS_iters_per_task);
    }
  } else {
    CHECK( false ); // Unrecognized test_type
  }

  DVLOG(5) << ( "user main is exiting" );
}

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

  Grappa_init( &argc, &argv );

  Grappa_activate();

  DVLOG(1) << "Spawning user main Thread....";
  Grappa_run_user_main( &user_main, (void*)NULL );
  VLOG(5) << "run_user_main returned";
  CHECK( Grappa_done() );

  Grappa_finish( 0 );
}

<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/test/test_timeouts.h"
#include "build/build_config.h"
#include "content/public/common/content_switches.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
#include "webkit/plugins/plugin_switches.h"

namespace {

// Platform-specific filename relative to the chrome executable.
#if defined(OS_WIN)
const wchar_t library_name[] = L"ppapi_tests.dll";
#elif defined(OS_MACOSX)
const char library_name[] = "ppapi_tests.plugin";
#elif defined(OS_POSIX)
const char library_name[] = "libppapi_tests.so";
#endif

}  // namespace

// In-process plugin test runner.  See OutOfProcessPPAPITest below for the
// out-of-process version.
class PPAPITest : public UITest {
 public:
  PPAPITest() {
    // Append the switch to register the pepper plugin.
    // library name = <out dir>/<test_name>.<library_extension>
    // MIME type = application/x-ppapi-<test_name>
    FilePath plugin_dir;
    PathService::Get(base::DIR_EXE, &plugin_dir);

    FilePath plugin_lib = plugin_dir.Append(library_name);
    EXPECT_TRUE(file_util::PathExists(plugin_lib));
    FilePath::StringType pepper_plugin = plugin_lib.value();
    pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests"));
    launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,
                                         pepper_plugin);

    // The test sends us the result via a cookie.
    launch_arguments_.AppendSwitch(switches::kEnableFileCookies);

    // Some stuff is hung off of the testing interface which is not enabled
    // by default.
    launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);

    // Smooth scrolling confuses the scrollbar test.
    launch_arguments_.AppendSwitch(switches::kDisableSmoothScrolling);
  }

  void RunTest(const std::string& test_case) {
    FilePath test_path;
    PathService::Get(base::DIR_SOURCE_ROOT, &test_path);
    test_path = test_path.Append(FILE_PATH_LITERAL("ppapi"));
    test_path = test_path.Append(FILE_PATH_LITERAL("tests"));
    test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html"));

    // Sanity check the file name.
    EXPECT_TRUE(file_util::PathExists(test_path));

    GURL::Replacements replacements;
    std::string query("testcase=");
    query += test_case;
    replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size()));
    GURL test_url = net::FilePathToFileURL(test_path);
    RunTestURL(test_url.ReplaceComponents(replacements));
  }

  void RunTestViaHTTP(const std::string& test_case) {
    net::TestServer test_server(
        net::TestServer::TYPE_HTTP,
        FilePath(FILE_PATH_LITERAL("ppapi/tests")));
    ASSERT_TRUE(test_server.Start());
    RunTestURL(
        test_server.GetURL("files/test_case.html?testcase=" + test_case));
  }

 private:
  void RunTestURL(const GURL& test_url) {
    scoped_refptr<TabProxy> tab(GetActiveTab());
    ASSERT_TRUE(tab.get());
    ASSERT_TRUE(tab->NavigateToURL(test_url));

    // See comment above TestingInstance in ppapi/test/testing_instance.h.
    // Basically it sets a series of numbered cookies. The value of "..." means
    // it's still working and we should continue to wait, any other value
    // indicates completion (in this case it will start with "PASS" or "FAIL").
    // This keeps us from timing out on cookie waits for long tests.
    int progress_number = 0;
    std::string progress;
    while (true) {
      std::string cookie_name = StringPrintf("PPAPI_PROGRESS_%d",
                                             progress_number);
      progress = WaitUntilCookieNonEmpty(tab.get(), test_url,
            cookie_name.c_str(), TestTimeouts::large_test_timeout_ms());
      if (progress != "...")
        break;
      progress_number++;
    }

    if (progress_number == 0) {
      // Failing the first time probably means the plugin wasn't loaded.
      ASSERT_FALSE(progress.empty())
          << "Plugin couldn't be loaded. Make sure the PPAPI test plugin is "
          << "built, in the right place, and doesn't have any missing symbols.";
    } else {
      ASSERT_FALSE(progress.empty()) << "Test timed out.";
    }

    EXPECT_STREQ("PASS", progress.c_str());
  }
};

// Variant of PPAPITest that runs plugins out-of-process to test proxy
// codepaths.
class OutOfProcessPPAPITest : public PPAPITest {
 public:
  OutOfProcessPPAPITest() {
    // Run PPAPI out-of-process to exercise proxy implementations.
    launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess);
  }
};

// Use these macros to run the tests for a specific interface.
// Most interfaces should be tested with both macros.
#define TEST_PPAPI_IN_PROCESS(test_name) \
    TEST_F(PPAPITest, test_name) { \
      RunTest(#test_name); \
    }
#define TEST_PPAPI_OUT_OF_PROCESS(test_name) \
    TEST_F(OutOfProcessPPAPITest, test_name) { \
      RunTest(#test_name); \
    }

// Similar macros that test over HTTP.
#define TEST_PPAPI_IN_PROCESS_VIA_HTTP(test_name) \
    TEST_F(PPAPITest, test_name) { \
      RunTestViaHTTP(#test_name); \
    }
#define TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(test_name) \
    TEST_F(OutOfProcessPPAPITest, test_name) { \
      RunTestViaHTTP(#test_name); \
    }

//
// Interface tests.
//

TEST_PPAPI_IN_PROCESS(Broker)
TEST_PPAPI_OUT_OF_PROCESS(Broker)

TEST_PPAPI_IN_PROCESS(Core)
TEST_PPAPI_OUT_OF_PROCESS(Core)

TEST_PPAPI_IN_PROCESS(CursorControl)
TEST_PPAPI_OUT_OF_PROCESS(CursorControl)

TEST_PPAPI_IN_PROCESS(Instance)
// http://crbug.com/91729
TEST_PPAPI_OUT_OF_PROCESS(DISABLED_Instance)

TEST_PPAPI_IN_PROCESS(Graphics2D)
TEST_PPAPI_OUT_OF_PROCESS(Graphics2D)

TEST_PPAPI_IN_PROCESS(ImageData)
TEST_PPAPI_OUT_OF_PROCESS(ImageData)

TEST_PPAPI_IN_PROCESS(Buffer)
TEST_PPAPI_OUT_OF_PROCESS(Buffer)

TEST_PPAPI_IN_PROCESS_VIA_HTTP(URLLoader)

// http://crbug.com/89961
#if defined(OS_WIN)
// It often takes too long time (and fails otherwise) on Windows.
#define MAYBE_URLLoader DISABLED_URLLoader
#else
#define MAYBE_URLLoader FAILS_URLLoader
#endif

TEST_F(OutOfProcessPPAPITest, MAYBE_URLLoader) {
  RunTestViaHTTP("URLLoader");
}

TEST_PPAPI_IN_PROCESS(PaintAggregator)
TEST_PPAPI_OUT_OF_PROCESS(PaintAggregator)

TEST_PPAPI_IN_PROCESS(Scrollbar)
// http://crbug.com/89961
TEST_F(OutOfProcessPPAPITest, FAILS_Scrollbar) {
  RunTest("Scrollbar");
}

TEST_PPAPI_IN_PROCESS(URLUtil)
TEST_PPAPI_OUT_OF_PROCESS(URLUtil)

TEST_PPAPI_IN_PROCESS(CharSet)
TEST_PPAPI_OUT_OF_PROCESS(CharSet)

TEST_PPAPI_IN_PROCESS(Crypto)
TEST_PPAPI_OUT_OF_PROCESS(Crypto)

TEST_PPAPI_IN_PROCESS(Var)
// http://crbug.com/89961
TEST_F(OutOfProcessPPAPITest, FAILS_Var) {
  RunTest("Var");
}

TEST_PPAPI_IN_PROCESS(VarDeprecated)
// Disabled because it times out: http://crbug.com/89961
//TEST_PPAPI_OUT_OF_PROCESS(VarDeprecated)

// Windows defines 'PostMessage', so we have to undef it.
#ifdef PostMessage
#undef PostMessage
#endif
TEST_PPAPI_IN_PROCESS(PostMessage)
#if !defined(OS_WIN)
// Times out on Windows XP: http://crbug.com/95557
TEST_PPAPI_OUT_OF_PROCESS(PostMessage)
#endif

TEST_PPAPI_IN_PROCESS(Memory)
TEST_PPAPI_OUT_OF_PROCESS(Memory)

TEST_PPAPI_IN_PROCESS(VideoDecoder)
TEST_PPAPI_OUT_OF_PROCESS(VideoDecoder)

// http://crbug.com/90039 and http://crbug.com/83443 (Mac)
TEST_F(PPAPITest, FAILS_FileIO) {
  RunTestViaHTTP("FileIO");
}
// http://crbug.com/101154
TEST_F(OutOfProcessPPAPITest, DISABLED_FileIO) {
  RunTestViaHTTP("FileIO");
}

TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileRef)
// Disabled because it times out: http://crbug.com/89961
//TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileRef)

TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileSystem)
TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileSystem)

// http://crbug.com/96767
#if !defined(OS_MACOSX)
TEST_F(PPAPITest, FLAKY_FlashFullscreen) {
  RunTestViaHTTP("FlashFullscreen");
}
TEST_F(OutOfProcessPPAPITest, FLAKY_FlashFullscreen) {
  RunTestViaHTTP("FlashFullscreen");
}
// New implementation only honors fullscreen requests within a context of
// a user gesture. Since we do not yet have an infrastructure for testing
// those under ppapi_tests, the tests below time out when run automtically.
// To test the code, run them manually following the directions here:
//   www.chromium.org/developers/design-documents/pepper-plugin-implementation
// and click on the plugin area (gray square) to force fullscreen mode and
// get the test unstuck.
TEST_F(PPAPITest, DISABLED_Fullscreen) {
  RunTestViaHTTP("Fullscreen");
}
TEST_F(OutOfProcessPPAPITest, DISABLED_Fullscreen) {
  RunTestViaHTTP("Fullscreen");
}
#endif

TEST_PPAPI_IN_PROCESS(FlashClipboard)
TEST_PPAPI_OUT_OF_PROCESS(FlashClipboard)

#if defined(OS_POSIX)
#define MAYBE_DirectoryReader FLAKY_DirectoryReader
#else
#define MAYBE_DirectoryReader DirectoryReader
#endif

// Flaky on Mac + Linux, maybe http://codereview.chromium.org/7094008
TEST_F(PPAPITest, MAYBE_DirectoryReader) {
  RunTestViaHTTP("DirectoryReader");
}
// http://crbug.com/89961
TEST_F(OutOfProcessPPAPITest, FAILS_DirectoryReader) {
  RunTestViaHTTP("DirectoryReader");
}

#if defined(ENABLE_P2P_APIS)
// Flaky. http://crbug.com/84294
TEST_F(PPAPITest, FLAKY_Transport) {
  RunTest("Transport");
}
// http://crbug.com/89961
TEST_F(OutOfProcessPPAPITest, FAILS_Transport) {
  RunTestViaHTTP("Transport");
}
#endif // ENABLE_P2P_APIS

TEST_PPAPI_IN_PROCESS(UMA)
// There is no proxy.
TEST_F(OutOfProcessPPAPITest, FAILS_UMA) {
  RunTest("UMA");
}

TEST_PPAPI_IN_PROCESS(FAILS_NetAddressPrivate)
TEST_PPAPI_OUT_OF_PROCESS(FAILS_NetAddressPrivate)
<commit_msg>Reenable PPB_NetAddress_Private test.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/file_util.h"
#include "base/path_service.h"
#include "base/test/test_timeouts.h"
#include "build/build_config.h"
#include "content/public/common/content_switches.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/test/test_server.h"
#include "webkit/plugins/plugin_switches.h"

namespace {

// Platform-specific filename relative to the chrome executable.
#if defined(OS_WIN)
const wchar_t library_name[] = L"ppapi_tests.dll";
#elif defined(OS_MACOSX)
const char library_name[] = "ppapi_tests.plugin";
#elif defined(OS_POSIX)
const char library_name[] = "libppapi_tests.so";
#endif

}  // namespace

// In-process plugin test runner.  See OutOfProcessPPAPITest below for the
// out-of-process version.
class PPAPITest : public UITest {
 public:
  PPAPITest() {
    // Append the switch to register the pepper plugin.
    // library name = <out dir>/<test_name>.<library_extension>
    // MIME type = application/x-ppapi-<test_name>
    FilePath plugin_dir;
    PathService::Get(base::DIR_EXE, &plugin_dir);

    FilePath plugin_lib = plugin_dir.Append(library_name);
    EXPECT_TRUE(file_util::PathExists(plugin_lib));
    FilePath::StringType pepper_plugin = plugin_lib.value();
    pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests"));
    launch_arguments_.AppendSwitchNative(switches::kRegisterPepperPlugins,
                                         pepper_plugin);

    // The test sends us the result via a cookie.
    launch_arguments_.AppendSwitch(switches::kEnableFileCookies);

    // Some stuff is hung off of the testing interface which is not enabled
    // by default.
    launch_arguments_.AppendSwitch(switches::kEnablePepperTesting);

    // Smooth scrolling confuses the scrollbar test.
    launch_arguments_.AppendSwitch(switches::kDisableSmoothScrolling);
  }

  void RunTest(const std::string& test_case) {
    FilePath test_path;
    PathService::Get(base::DIR_SOURCE_ROOT, &test_path);
    test_path = test_path.Append(FILE_PATH_LITERAL("ppapi"));
    test_path = test_path.Append(FILE_PATH_LITERAL("tests"));
    test_path = test_path.Append(FILE_PATH_LITERAL("test_case.html"));

    // Sanity check the file name.
    EXPECT_TRUE(file_util::PathExists(test_path));

    GURL::Replacements replacements;
    std::string query("testcase=");
    query += test_case;
    replacements.SetQuery(query.c_str(), url_parse::Component(0, query.size()));
    GURL test_url = net::FilePathToFileURL(test_path);
    RunTestURL(test_url.ReplaceComponents(replacements));
  }

  void RunTestViaHTTP(const std::string& test_case) {
    net::TestServer test_server(
        net::TestServer::TYPE_HTTP,
        FilePath(FILE_PATH_LITERAL("ppapi/tests")));
    ASSERT_TRUE(test_server.Start());
    RunTestURL(
        test_server.GetURL("files/test_case.html?testcase=" + test_case));
  }

 private:
  void RunTestURL(const GURL& test_url) {
    scoped_refptr<TabProxy> tab(GetActiveTab());
    ASSERT_TRUE(tab.get());
    ASSERT_TRUE(tab->NavigateToURL(test_url));

    // See comment above TestingInstance in ppapi/test/testing_instance.h.
    // Basically it sets a series of numbered cookies. The value of "..." means
    // it's still working and we should continue to wait, any other value
    // indicates completion (in this case it will start with "PASS" or "FAIL").
    // This keeps us from timing out on cookie waits for long tests.
    int progress_number = 0;
    std::string progress;
    while (true) {
      std::string cookie_name = StringPrintf("PPAPI_PROGRESS_%d",
                                             progress_number);
      progress = WaitUntilCookieNonEmpty(tab.get(), test_url,
            cookie_name.c_str(), TestTimeouts::large_test_timeout_ms());
      if (progress != "...")
        break;
      progress_number++;
    }

    if (progress_number == 0) {
      // Failing the first time probably means the plugin wasn't loaded.
      ASSERT_FALSE(progress.empty())
          << "Plugin couldn't be loaded. Make sure the PPAPI test plugin is "
          << "built, in the right place, and doesn't have any missing symbols.";
    } else {
      ASSERT_FALSE(progress.empty()) << "Test timed out.";
    }

    EXPECT_STREQ("PASS", progress.c_str());
  }
};

// Variant of PPAPITest that runs plugins out-of-process to test proxy
// codepaths.
class OutOfProcessPPAPITest : public PPAPITest {
 public:
  OutOfProcessPPAPITest() {
    // Run PPAPI out-of-process to exercise proxy implementations.
    launch_arguments_.AppendSwitch(switches::kPpapiOutOfProcess);
  }
};

// Use these macros to run the tests for a specific interface.
// Most interfaces should be tested with both macros.
#define TEST_PPAPI_IN_PROCESS(test_name) \
    TEST_F(PPAPITest, test_name) { \
      RunTest(#test_name); \
    }
#define TEST_PPAPI_OUT_OF_PROCESS(test_name) \
    TEST_F(OutOfProcessPPAPITest, test_name) { \
      RunTest(#test_name); \
    }

// Similar macros that test over HTTP.
#define TEST_PPAPI_IN_PROCESS_VIA_HTTP(test_name) \
    TEST_F(PPAPITest, test_name) { \
      RunTestViaHTTP(#test_name); \
    }
#define TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(test_name) \
    TEST_F(OutOfProcessPPAPITest, test_name) { \
      RunTestViaHTTP(#test_name); \
    }

//
// Interface tests.
//

TEST_PPAPI_IN_PROCESS(Broker)
TEST_PPAPI_OUT_OF_PROCESS(Broker)

TEST_PPAPI_IN_PROCESS(Core)
TEST_PPAPI_OUT_OF_PROCESS(Core)

TEST_PPAPI_IN_PROCESS(CursorControl)
TEST_PPAPI_OUT_OF_PROCESS(CursorControl)

TEST_PPAPI_IN_PROCESS(Instance)
// http://crbug.com/91729
TEST_PPAPI_OUT_OF_PROCESS(DISABLED_Instance)

TEST_PPAPI_IN_PROCESS(Graphics2D)
TEST_PPAPI_OUT_OF_PROCESS(Graphics2D)

TEST_PPAPI_IN_PROCESS(ImageData)
TEST_PPAPI_OUT_OF_PROCESS(ImageData)

TEST_PPAPI_IN_PROCESS(Buffer)
TEST_PPAPI_OUT_OF_PROCESS(Buffer)

TEST_PPAPI_IN_PROCESS_VIA_HTTP(URLLoader)

// http://crbug.com/89961
#if defined(OS_WIN)
// It often takes too long time (and fails otherwise) on Windows.
#define MAYBE_URLLoader DISABLED_URLLoader
#else
#define MAYBE_URLLoader FAILS_URLLoader
#endif

TEST_F(OutOfProcessPPAPITest, MAYBE_URLLoader) {
  RunTestViaHTTP("URLLoader");
}

TEST_PPAPI_IN_PROCESS(PaintAggregator)
TEST_PPAPI_OUT_OF_PROCESS(PaintAggregator)

TEST_PPAPI_IN_PROCESS(Scrollbar)
// http://crbug.com/89961
TEST_F(OutOfProcessPPAPITest, FAILS_Scrollbar) {
  RunTest("Scrollbar");
}

TEST_PPAPI_IN_PROCESS(URLUtil)
TEST_PPAPI_OUT_OF_PROCESS(URLUtil)

TEST_PPAPI_IN_PROCESS(CharSet)
TEST_PPAPI_OUT_OF_PROCESS(CharSet)

TEST_PPAPI_IN_PROCESS(Crypto)
TEST_PPAPI_OUT_OF_PROCESS(Crypto)

TEST_PPAPI_IN_PROCESS(Var)
// http://crbug.com/89961
TEST_F(OutOfProcessPPAPITest, FAILS_Var) {
  RunTest("Var");
}

TEST_PPAPI_IN_PROCESS(VarDeprecated)
// Disabled because it times out: http://crbug.com/89961
//TEST_PPAPI_OUT_OF_PROCESS(VarDeprecated)

// Windows defines 'PostMessage', so we have to undef it.
#ifdef PostMessage
#undef PostMessage
#endif
TEST_PPAPI_IN_PROCESS(PostMessage)
#if !defined(OS_WIN)
// Times out on Windows XP: http://crbug.com/95557
TEST_PPAPI_OUT_OF_PROCESS(PostMessage)
#endif

TEST_PPAPI_IN_PROCESS(Memory)
TEST_PPAPI_OUT_OF_PROCESS(Memory)

TEST_PPAPI_IN_PROCESS(VideoDecoder)
TEST_PPAPI_OUT_OF_PROCESS(VideoDecoder)

// http://crbug.com/90039 and http://crbug.com/83443 (Mac)
TEST_F(PPAPITest, FAILS_FileIO) {
  RunTestViaHTTP("FileIO");
}
// http://crbug.com/101154
TEST_F(OutOfProcessPPAPITest, DISABLED_FileIO) {
  RunTestViaHTTP("FileIO");
}

TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileRef)
// Disabled because it times out: http://crbug.com/89961
//TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileRef)

TEST_PPAPI_IN_PROCESS_VIA_HTTP(FileSystem)
TEST_PPAPI_OUT_OF_PROCESS_VIA_HTTP(FileSystem)

// http://crbug.com/96767
#if !defined(OS_MACOSX)
TEST_F(PPAPITest, FLAKY_FlashFullscreen) {
  RunTestViaHTTP("FlashFullscreen");
}
TEST_F(OutOfProcessPPAPITest, FLAKY_FlashFullscreen) {
  RunTestViaHTTP("FlashFullscreen");
}
// New implementation only honors fullscreen requests within a context of
// a user gesture. Since we do not yet have an infrastructure for testing
// those under ppapi_tests, the tests below time out when run automtically.
// To test the code, run them manually following the directions here:
//   www.chromium.org/developers/design-documents/pepper-plugin-implementation
// and click on the plugin area (gray square) to force fullscreen mode and
// get the test unstuck.
TEST_F(PPAPITest, DISABLED_Fullscreen) {
  RunTestViaHTTP("Fullscreen");
}
TEST_F(OutOfProcessPPAPITest, DISABLED_Fullscreen) {
  RunTestViaHTTP("Fullscreen");
}
#endif

TEST_PPAPI_IN_PROCESS(FlashClipboard)
TEST_PPAPI_OUT_OF_PROCESS(FlashClipboard)

#if defined(OS_POSIX)
#define MAYBE_DirectoryReader FLAKY_DirectoryReader
#else
#define MAYBE_DirectoryReader DirectoryReader
#endif

// Flaky on Mac + Linux, maybe http://codereview.chromium.org/7094008
TEST_F(PPAPITest, MAYBE_DirectoryReader) {
  RunTestViaHTTP("DirectoryReader");
}
// http://crbug.com/89961
TEST_F(OutOfProcessPPAPITest, FAILS_DirectoryReader) {
  RunTestViaHTTP("DirectoryReader");
}

#if defined(ENABLE_P2P_APIS)
// Flaky. http://crbug.com/84294
TEST_F(PPAPITest, FLAKY_Transport) {
  RunTest("Transport");
}
// http://crbug.com/89961
TEST_F(OutOfProcessPPAPITest, FAILS_Transport) {
  RunTestViaHTTP("Transport");
}
#endif // ENABLE_P2P_APIS

TEST_PPAPI_IN_PROCESS(UMA)
// There is no proxy.
TEST_F(OutOfProcessPPAPITest, FAILS_UMA) {
  RunTest("UMA");
}

TEST_PPAPI_IN_PROCESS(NetAddressPrivate)
TEST_PPAPI_OUT_OF_PROCESS(NetAddressPrivate)
<|endoftext|>


<commit_before>//
//  Copyright (C) 2013-2014 mogemimi.
//
//  Distributed under the MIT License.
//  See accompanying file LICENSE.md or copy at
//  http://enginetrouble.net/pomdog/LICENSE.md for details.
//

#include "DebugNavigator.hpp"
#include "DrawingContext.hpp"

namespace Pomdog {
namespace UI {
//-----------------------------------------------------------------------
DebugNavigator::DebugNavigator(std::shared_ptr<GameClock> const& clockIn)
	: Control(Matrix3x2::Identity, 150, 40)
	, clock(clockIn)
	, duration(DurationSeconds(0))
	, frameRateString("-- fps")
{}
//-----------------------------------------------------------------------
void DebugNavigator::Draw(DrawingContext & drawingContext)
{
	constexpr float minFramerate = 15.0f;
	constexpr float maxFramerate = 61.0f;
	constexpr std::uint16_t maxHistories = 20;

	{
		if (clock->TotalGameTime() - duration > DurationSeconds(0.2))
		{
			auto frameRate = clock->FrameRate();
			frameRateString = StringFormat("%4.2f fps", frameRate);
			frameRates.push_back(MathHelper::Clamp(frameRate, minFramerate, maxFramerate));

			if (frameRates.size() > maxHistories)
			{
				frameRates.pop_front();
			}
			duration = clock->TotalGameTime();
		}
	}

	auto transform = Transform() * drawingContext.Top();
	{
		auto graphTransform = Matrix3x2::CreateTranslation(Vector2{0, 16}) * transform;

		constexpr float maxGraphHeight = 26.0f;
		constexpr float graphMarginLeft = 1.0f;

		auto graghWidth = (static_cast<float>(Width()) / maxHistories);

		std::int32_t graphX = 0;
		for (auto & frameRate: frameRates)
		{
			auto amount = ((frameRate - minFramerate) / (maxFramerate - minFramerate));
			auto graphHeight = std::max(1.0f, maxGraphHeight * amount);

			drawingContext.DrawRectangle(graphTransform, Color::CornflowerBlue,
				Rectangle(graphX, maxGraphHeight - graphHeight, graghWidth - graphMarginLeft, graphHeight));
			graphX += graghWidth;
		}
	}

	drawingContext.DrawString(transform * Matrix3x2::CreateTranslation(Vector2(5, -2.5f)),
		Color::White, FontWeight::Bold, FontSize::Medium, frameRateString);
}
//-----------------------------------------------------------------------
}// namespace UI
}// namespace Pomdog
<commit_msg>Fix debug navigator<commit_after>//
//  Copyright (C) 2013-2014 mogemimi.
//
//  Distributed under the MIT License.
//  See accompanying file LICENSE.md or copy at
//  http://enginetrouble.net/pomdog/LICENSE.md for details.
//

#include "DebugNavigator.hpp"
#include "DrawingContext.hpp"

namespace Pomdog {
namespace UI {
//-----------------------------------------------------------------------
DebugNavigator::DebugNavigator(std::shared_ptr<GameClock> const& clockIn)
	: Control(Matrix3x2::Identity, 150, 40)
	, clock(clockIn)
	, duration(DurationSeconds(0))
	, frameRateString("-- fps")
{}
//-----------------------------------------------------------------------
void DebugNavigator::Draw(DrawingContext & drawingContext)
{
	constexpr float minFramerate = 10.0f;
	constexpr float maxFramerate = 60.0f;
	constexpr std::uint16_t maxHistories = 20;

	{
		if (clock->TotalGameTime() - duration > DurationSeconds(0.2))
		{
			auto frameRate = clock->FrameRate();
			frameRateString = StringFormat("%4.2f fps", frameRate);
			frameRates.push_back(MathHelper::Clamp(frameRate, minFramerate, maxFramerate));

			if (frameRates.size() > maxHistories)
			{
				frameRates.pop_front();
			}
			duration = clock->TotalGameTime();
		}
	}

	auto transform = Transform() * drawingContext.Top();
	{
		auto graphTransform = Matrix3x2::CreateTranslation(Vector2{0, 16}) * transform;

		constexpr std::uint16_t maxGraphHeight = 26;
		constexpr float graphMarginLeft = 1.0f;

		auto graghWidth = (static_cast<float>(Width()) / maxHistories);

		std::int32_t graphX = 0;
		for (auto & frameRate: frameRates)
		{
			auto amount = ((frameRate - minFramerate) / (maxFramerate - minFramerate));
			auto graphHeight = MathHelper::Clamp<std::uint16_t>(maxGraphHeight * amount, 1, maxGraphHeight);

			drawingContext.DrawRectangle(graphTransform, Color::CornflowerBlue,
				Rectangle(graphX, maxGraphHeight - graphHeight, graghWidth - graphMarginLeft, graphHeight));
			graphX += graghWidth;
		}
	}

	drawingContext.DrawString(transform * Matrix3x2::CreateTranslation(Vector2(5, -2.5f)),
		Color::White, FontWeight::Bold, FontSize::Medium, frameRateString);
}
//-----------------------------------------------------------------------
}// namespace UI
}// namespace Pomdog
<|endoftext|>


<commit_before>//===-- lldb.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/lldb-private.h"

using namespace lldb;
using namespace lldb_private;

#if defined (__APPLE__)
// Xcode writes this file out in a build step.
// cmake builds get this through another mechanism.
// Both produce LLDB_REVISION.
#include "lldb_revision.h"
extern "C" const unsigned char liblldb_coreVersionString[];
#endif

#if defined(LLDB_USE_OSS_VERSION_SCHEME)

#include "llvm/Support/raw_ostream.h"
#include "swift/Basic/Version.h"

#endif

#if !defined (__APPLE__) || defined(LLDB_USE_OSS_VERSION_SCHEME)

#include "clang/Basic/Version.h"

static const char *
GetLLDBRevision()
{
#ifdef LLDB_REVISION
    static const char *s_revision = LLDB_REVISION;
#else
    static const char *s_revision = nullptr;
#endif

    if (s_revision != nullptr)
        return s_revision;
    else
        return "";
}

#endif

#if !defined (__APPLE__)

static const char *
GetLLDBRepository()
{
#ifdef LLDB_REPOSITORY
    return LLDB_REPOSITORY;
#else
    return NULL;
#endif

}

#endif

#if defined(LLDB_USE_OSS_VERSION_SCHEME)

// TODO remove this function once swift revision is directly exposed.
std::string ExtractSwiftRevision(const std::string &fullVersion)
{
    // Find spot right before Swift revision.
    const std::string search_prefix = "Swift ";
    const size_t prefix_start_pos = fullVersion.rfind(search_prefix);
    if (prefix_start_pos == std::string::npos)
        return "";

    // Find spot where Swift revision ends.
    const size_t revision_end_pos = fullVersion.rfind(')');
    if (revision_end_pos == std::string::npos)
        return "";

    // Return the revision.
    return fullVersion.substr(prefix_start_pos + search_prefix.length(), revision_end_pos - prefix_start_pos - search_prefix.length());
}

static std::string
GetBuildDate()
{
    // The following code helps distinguish between a defined preprocessor
    // value that gets the default value assigned vs. one with an explicit value.
#define LLDB_DO_MACRO_EXPAND(macro_value) macro_value ## 1
#define LLDB_MACRO_EXPAND(macro_value) LLDB_DO_MACRO_EXPAND(macro_value)

#if defined(LLDB_BUILD_DATE)
    return std::string(LLDB_BUILD_DATE);
#else
    return std::string();
#endif
}

static const char*
_GetVersionOSS ()
{
    static std::string g_version_string;
    if (g_version_string.empty())
    {
        std::string build_string;
        llvm::raw_string_ostream out(build_string);

        std::string build_flavor = "local";
#if defined (LLDB_IS_BUILDBOT_BUILD)
# if (LLDB_IS_BUILDBOT_BUILD != 0)
        build_flavor = "buildbot";
# endif
#endif
        out << "lldb-" << build_flavor;

        // We only run this code when the build date is both set and non-default.
        // Otherwise this code doesn't compile.
        const std::string build_date(GetBuildDate());
        if (!build_date.empty())
            out << "-" << build_date;

        out << " (";

        std::string lldb_revision = GetLLDBRevision();
        if (lldb_revision.length() > 0)
        {
            const size_t MAX_REVISION_LENGTH = 10;

            out << "LLDB ";
            out << lldb_revision.substr(0, MAX_REVISION_LENGTH);

            const std::string llvm_revision = clang::getLLVMRevision();
            if (!llvm_revision.empty())
                out << ", LLVM " << llvm_revision.substr(0, MAX_REVISION_LENGTH);

            const std::string clang_revision = clang::getClangRevision();
            if (!clang_revision.empty())
                out << ", Clang " << clang_revision.substr(0, MAX_REVISION_LENGTH);

            // TODO replace this with a swift::version::GetSwiftRevision() call
            // once added.
            const std::string swift_revision = ExtractSwiftRevision(swift::version::getSwiftFullVersion());
            if (!swift_revision.empty())
            {
                auto const swift_version = swift::version::getSwiftNumericVersion();
                out << ", Swift-" << swift_version.first << "." << swift_version.second << " " << swift_revision.substr(0, MAX_REVISION_LENGTH);
            }
        }
        out << ")";

        g_version_string = out.str();
    }
    return g_version_string.c_str();
}

#endif

#if defined(__APPLE__) && !defined(LLDB_USE_OSS_VERSION_SCHEME)

static const char*
_GetVersionAppleStandard ()
{
    static char g_version_string[32];
    if (g_version_string[0] == '\0')
    {
        const char *version_string = ::strstr ((const char *)liblldb_coreVersionString, "PROJECT:");

        if (version_string)
            version_string += sizeof("PROJECT:") - 1;
        else
            version_string = "unknown";

        const char *newline_loc = strchr(version_string, '\n');

        size_t version_len = sizeof(g_version_string) - 1;

        if (newline_loc &&
            (newline_loc - version_string < static_cast<ptrdiff_t>(version_len)))
            version_len = newline_loc - version_string;

        ::snprintf(g_version_string, version_len + 1, "%s", version_string);
    }

    return g_version_string;
}

#endif

const char *
lldb_private::GetVersion ()
{
#if defined (__APPLE__)
# if defined(LLDB_USE_OSS_VERSION_SCHEME)
    return _GetVersionOSS ();
# else
    return _GetVersionAppleStandard ();
# endif
#else
# if defined(LLDB_USE_OSS_VERSION_SCHEME)
    return _GetVersionOSS ();
# else
    // On platforms other than Darwin, report a version number in the same style as the clang tool.
    static std::string g_version_str;
    if (g_version_str.empty())
    {
        g_version_str += "lldb version ";
        g_version_str += CLANG_VERSION_STRING;
        const char * lldb_repo = GetLLDBRepository();
        if (lldb_repo)
        {
            g_version_str += " (";
            g_version_str += lldb_repo;
        }

        const char *lldb_rev = GetLLDBRevision();
        if (lldb_rev)
        {
            g_version_str += " revision ";
            g_version_str += lldb_rev;
        }
        std::string clang_rev (clang::getClangRevision());
        if (clang_rev.length() > 0)
        {
            g_version_str += " clang revision ";
            g_version_str += clang_rev;
        }
        std::string llvm_rev (clang::getLLVMRevision());
        if (llvm_rev.length() > 0)
        {
            g_version_str += " llvm revision ";
            g_version_str += llvm_rev;
        }

        if (lldb_repo)
            g_version_str += ")";
    }
    return g_version_str.c_str();
# endif
#endif
}
<commit_msg>added a comment to clarify a check in previous version fixup code<commit_after>//===-- lldb.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/lldb-private.h"

using namespace lldb;
using namespace lldb_private;

#if defined (__APPLE__)
// Xcode writes this file out in a build step.
// cmake builds get this through another mechanism.
// Both produce LLDB_REVISION.
#include "lldb_revision.h"
extern "C" const unsigned char liblldb_coreVersionString[];
#endif

#if defined(LLDB_USE_OSS_VERSION_SCHEME)

#include "llvm/Support/raw_ostream.h"
#include "swift/Basic/Version.h"

#endif

#if !defined (__APPLE__) || defined(LLDB_USE_OSS_VERSION_SCHEME)

#include "clang/Basic/Version.h"

static const char *
GetLLDBRevision()
{
#ifdef LLDB_REVISION
    static const char *s_revision = LLDB_REVISION;
#else
    static const char *s_revision = nullptr;
#endif

    // If LLDB_REVISION is defined but isn't set to a string, it
    // can still be the equivalent of NULL.  Hence we always do
    // this check below and return an empty string when we don't
    // otherwise have a valid const string for it.
    if (s_revision != nullptr)
        return s_revision;
    else
        return "";
}

#endif

#if !defined (__APPLE__)

static const char *
GetLLDBRepository()
{
#ifdef LLDB_REPOSITORY
    return LLDB_REPOSITORY;
#else
    return NULL;
#endif

}

#endif

#if defined(LLDB_USE_OSS_VERSION_SCHEME)

// TODO remove this function once swift revision is directly exposed.
std::string ExtractSwiftRevision(const std::string &fullVersion)
{
    // Find spot right before Swift revision.
    const std::string search_prefix = "Swift ";
    const size_t prefix_start_pos = fullVersion.rfind(search_prefix);
    if (prefix_start_pos == std::string::npos)
        return "";

    // Find spot where Swift revision ends.
    const size_t revision_end_pos = fullVersion.rfind(')');
    if (revision_end_pos == std::string::npos)
        return "";

    // Return the revision.
    return fullVersion.substr(prefix_start_pos + search_prefix.length(), revision_end_pos - prefix_start_pos - search_prefix.length());
}

static std::string
GetBuildDate()
{
    // The following code helps distinguish between a defined preprocessor
    // value that gets the default value assigned vs. one with an explicit value.
#define LLDB_DO_MACRO_EXPAND(macro_value) macro_value ## 1
#define LLDB_MACRO_EXPAND(macro_value) LLDB_DO_MACRO_EXPAND(macro_value)

#if defined(LLDB_BUILD_DATE)
    return std::string(LLDB_BUILD_DATE);
#else
    return std::string();
#endif
}

static const char*
_GetVersionOSS ()
{
    static std::string g_version_string;
    if (g_version_string.empty())
    {
        std::string build_string;
        llvm::raw_string_ostream out(build_string);

        std::string build_flavor = "local";
#if defined (LLDB_IS_BUILDBOT_BUILD)
# if (LLDB_IS_BUILDBOT_BUILD != 0)
        build_flavor = "buildbot";
# endif
#endif
        out << "lldb-" << build_flavor;

        // We only run this code when the build date is both set and non-default.
        // Otherwise this code doesn't compile.
        const std::string build_date(GetBuildDate());
        if (!build_date.empty())
            out << "-" << build_date;

        out << " (";

        std::string lldb_revision = GetLLDBRevision();
        if (lldb_revision.length() > 0)
        {
            const size_t MAX_REVISION_LENGTH = 10;

            out << "LLDB ";
            out << lldb_revision.substr(0, MAX_REVISION_LENGTH);

            const std::string llvm_revision = clang::getLLVMRevision();
            if (!llvm_revision.empty())
                out << ", LLVM " << llvm_revision.substr(0, MAX_REVISION_LENGTH);

            const std::string clang_revision = clang::getClangRevision();
            if (!clang_revision.empty())
                out << ", Clang " << clang_revision.substr(0, MAX_REVISION_LENGTH);

            // TODO replace this with a swift::version::GetSwiftRevision() call
            // once added.
            const std::string swift_revision = ExtractSwiftRevision(swift::version::getSwiftFullVersion());
            if (!swift_revision.empty())
            {
                auto const swift_version = swift::version::getSwiftNumericVersion();
                out << ", Swift-" << swift_version.first << "." << swift_version.second << " " << swift_revision.substr(0, MAX_REVISION_LENGTH);
            }
        }
        out << ")";

        g_version_string = out.str();
    }
    return g_version_string.c_str();
}

#endif

#if defined(__APPLE__) && !defined(LLDB_USE_OSS_VERSION_SCHEME)

static const char*
_GetVersionAppleStandard ()
{
    static char g_version_string[32];
    if (g_version_string[0] == '\0')
    {
        const char *version_string = ::strstr ((const char *)liblldb_coreVersionString, "PROJECT:");

        if (version_string)
            version_string += sizeof("PROJECT:") - 1;
        else
            version_string = "unknown";

        const char *newline_loc = strchr(version_string, '\n');

        size_t version_len = sizeof(g_version_string) - 1;

        if (newline_loc &&
            (newline_loc - version_string < static_cast<ptrdiff_t>(version_len)))
            version_len = newline_loc - version_string;

        ::snprintf(g_version_string, version_len + 1, "%s", version_string);
    }

    return g_version_string;
}

#endif

const char *
lldb_private::GetVersion ()
{
#if defined (__APPLE__)
# if defined(LLDB_USE_OSS_VERSION_SCHEME)
    return _GetVersionOSS ();
# else
    return _GetVersionAppleStandard ();
# endif
#else
# if defined(LLDB_USE_OSS_VERSION_SCHEME)
    return _GetVersionOSS ();
# else
    // On platforms other than Darwin, report a version number in the same style as the clang tool.
    static std::string g_version_str;
    if (g_version_str.empty())
    {
        g_version_str += "lldb version ";
        g_version_str += CLANG_VERSION_STRING;
        const char * lldb_repo = GetLLDBRepository();
        if (lldb_repo)
        {
            g_version_str += " (";
            g_version_str += lldb_repo;
        }

        const char *lldb_rev = GetLLDBRevision();
        if (lldb_rev)
        {
            g_version_str += " revision ";
            g_version_str += lldb_rev;
        }
        std::string clang_rev (clang::getClangRevision());
        if (clang_rev.length() > 0)
        {
            g_version_str += " clang revision ";
            g_version_str += clang_rev;
        }
        std::string llvm_rev (clang::getLLVMRevision());
        if (llvm_rev.length() > 0)
        {
            g_version_str += " llvm revision ";
            g_version_str += llvm_rev;
        }

        if (lldb_repo)
            g_version_str += ")";
    }
    return g_version_str.c_str();
# endif
#endif
}
<|endoftext|>


<commit_before>/*
 * (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others.
 *
 * 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.
 *
 * Contributors:
 *     Markus Pilman <mpilman@inf.ethz.ch>
 *     Simon Loesing <sloesing@inf.ethz.ch>
 *     Thomas Etter <etterth@gmail.com>
 *     Kevin Bocksrocker <kevin.bocksrocker@gmail.com>
 *     Lucas Braun <braunl@inf.ethz.ch>
 */
#include "Client.hpp"
#include <util/Protocol.hpp>
#include "sqlite3.h"

#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>

#include <vector>
#include <thread>

namespace mbench {

std::string cmdString(Commands cmd) {
    switch (cmd) {
    case mbench::Commands::CreateSchema:
        return "CreateSchema";
    case mbench::Commands::Populate:
        return "Populate";
    case mbench::Commands::BatchOp:
        return "BatchOp";
    case mbench::Commands::Q1:
        return "Q1";
    case mbench::Commands::Q2:
        return "Q2";
    case mbench::Commands::Q3:
        return "Q3";
    throw std::runtime_error("Invalid command");
    }
    throw std::runtime_error("This has to be dead code");
}

} // namespace mbench

#define sqlOk(code) assertSql(code, __FILE__, __LINE__)

void assertSql(int code, const char* file, int line) {
    if (code != SQLITE_OK) {
        auto msg = (boost::format("ERROR (%1%:%2%): %3%") % file % line % sqlite3_errstr(code)).str();
        throw std::runtime_error(msg.c_str());
    }
}

int main(int argc, const char* argv[]) {
    namespace po = boost::program_options;
    unsigned numThreads = 1;
    unsigned sf;
    unsigned oltpClients;
    bool populate = false;
    unsigned time = 5;
    unsigned numAnalytical;
    unsigned numOps;
    double insProb, delProb, updProb;
    bool noWarmup;
    bool onlyQ1;
    std::string hostStr;
    std::string dbFile("out.db");
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help,h", "Show help message")
        ("hosts,H", po::value<std::string>(&hostStr)->required(), "Adress to servers")
        ("scaling-factor,s", po::value<unsigned>(&sf)->required(), "Scaling factor")
        ("clients,c", po::value<unsigned>(&oltpClients)->default_value(29), "Number of get/put clients (in total)")
        ("analytical,a", po::value<unsigned>(&numAnalytical)->default_value(0), "Number of analytical clients (in total)")
        ("threads,t", po::value<unsigned>(&numThreads), "Number of network threads")
        ("populate,P", "Run population instead of benchmark")
        ("db,o", po::value<std::string>(&dbFile), "Output to write to")
        ("time", po::value<unsigned>(&time), "Number of minutes to run")
        ("batch-size,b", po::value<unsigned>(&numOps)->default_value(100), "Number of operations per batch")
        ("inserts,i", po::value<double>(&insProb)->default_value(0.166), "Fraction of insert operations")
        ("deletes,d", po::value<double>(&delProb)->default_value(0.166), "Fraction of delete operations")
        ("update,u", po::value<double>(&updProb)->default_value(0.166), "Fraction of update operations")
        ("no-warmup", po::bool_switch(&noWarmup)->default_value(false), "No warm up time")
        ("only-q1,q", po::bool_switch(&onlyQ1)->default_value(false), "Execute only q1")
        ;

    po::variables_map vm;
    store(parse_command_line(argc, argv, desc), vm);
    if (vm.count("help")) {
        std::cout << desc << std::endl;
        return 0;
    }

    if (vm.count("populate")) {
        populate = true;
    }
    notify(vm);
    if (insProb + updProb + delProb > 1.0) {
        std::cerr << "sum(insert,delete,update) > 1.0\n";
        return 1;
    }

    if (oltpClients == 0 && populate) {
        std::cerr << "can not populate without oltp clients\n";
        return 1;
    }

    if (!noWarmup)
        time += 2;

    std::vector<std::string> hosts;
    boost::split(hosts, hostStr, boost::is_any_of(";,"), boost::token_compress_on);

    boost::asio::io_service service;
    boost::asio::io_service::strand ioStrand(service);
    std::vector<std::unique_ptr<mbench::Client>> clients;
    clients.reserve(oltpClients + numAnalytical);
    boost::asio::ip::tcp::resolver resolver(service);
    std::vector<std::string> hostPort;
    hostPort.reserve(2);

    bool allAnalytical = oltpClients == 0;
    auto hostIter = hosts.begin();
    if (populate) numAnalytical = 0;
    for (unsigned i = 0; i < numAnalytical; ++i) {
        if (hostIter == hosts.end()) hostIter = hosts.begin();
        clients.emplace_back(new mbench::Client(service, ioStrand, sf,
                    oltpClients, 0, true, numOps, insProb, delProb,
                    updProb, onlyQ1));
        auto& client = *clients.back();
        boost::split(hostPort, *hostIter, boost::is_any_of(":"), boost::token_compress_on);
        if (hostPort.size() == 1) {
            boost::asio::connect(client.socket(), resolver.resolve({hostPort[0]}));
        } else if (hostPort.size() == 2) {
            boost::asio::connect(client.socket(), resolver.resolve({hostPort[0], hostPort[1]}));
        } else {
            std::cerr << "Format error while parsing hosts" << std::endl;
            return 1;
        }
        ++hostIter;
    }
    for (unsigned clientId = 0; clientId < oltpClients; ++clientId) {
        if (hostIter == hosts.end()) hostIter = hosts.begin();
        clients.emplace_back(new mbench::Client(service, ioStrand, sf,
                    oltpClients, clientId, false, numOps, insProb,
                    delProb, updProb, onlyQ1));
        auto& client = *clients.back();
        boost::split(hostPort, *hostIter, boost::is_any_of(":"), boost::token_compress_on);
        if (hostPort.size() == 1) {
            boost::asio::connect(client.socket(), resolver.resolve({hostPort[0]}));
        } else if (hostPort.size() == 2) {
            boost::asio::connect(client.socket(), resolver.resolve({hostPort[0], hostPort[1]}));
        } else {
            std::cerr << "Format error while parsing hosts" << std::endl;
            return 1;
        }
        ++hostIter;
    }
    auto duration = std::chrono::minutes(time);
    bool timerChosen = true;
    if (populate) {
        std::cout << "start population\n";
        clients[0]->populate(clients);
    } else {
        for (auto& client : clients) {
            if (timerChosen && allAnalytical) {
                client->run(duration, true);
                timerChosen = false;
            }
            else if (timerChosen && !client->isAnalytical()) {
                client->run(duration, true);
                timerChosen = false;
            } else {
                client->run(duration, false);
            }
        }
    }

    std::cout << "Will run for " << time << " minutes with " << clients.size() << " clients\n";
    auto startTime = mbench::Clock::now();
    std::vector<std::thread> threads;
    threads.reserve(numThreads - 1);
    for (unsigned i = 0; i < numThreads - 1; ++i) {
        threads.emplace_back([&service](){ service.run(); });
    }
    service.run();
    for (auto& t : threads) {
        t.join();
    }
    if (populate) {
        std::cout << "                                                                                \r";
        std::cout << "Done\n";
    }
    std::cout << "Done - writing results\n";
    sqlOk(sqlite3_config(SQLITE_CONFIG_SINGLETHREAD));
    sqlite3* db;
    sqlOk(sqlite3_open(dbFile.c_str(), &db));
    sqlOk(sqlite3_exec(db, "CREATE TABLE results(start int, end int, rt int, tx text, success text, msg text)",
                nullptr, nullptr, nullptr));

    // Insert data
    sqlOk(sqlite3_exec(db, "BEGIN TRANSACTION", nullptr, nullptr, nullptr));
    sqlite3_stmt* stmt;
    sqlOk(sqlite3_prepare_v2(db, "INSERT INTO results VALUES(?, ?, ?, ?, ?, ?)", -1, &stmt, nullptr));

    for (auto& client : clients) {
        const auto& log = client->log();
        for (const auto& e : log) {
            auto start = int(std::chrono::duration_cast<std::chrono::microseconds>(e.start - startTime).count());
            auto end   = int(std::chrono::duration_cast<std::chrono::microseconds>(e.end - startTime).count());
            std::string trans = cmdString(e.transaction);
            std::string success = e.success ? "true" : "false";
            std::string msg(e.error.data(), e.error.size());
            sqlOk(sqlite3_bind_int(stmt, 1, start));
            sqlOk(sqlite3_bind_int(stmt, 2, end));
            sqlOk(sqlite3_bind_int(stmt, 3, e.responseTime));
            sqlOk(sqlite3_bind_text(stmt, 4, trans.data(), trans.size(), nullptr));
            sqlOk(sqlite3_bind_text(stmt, 5, success.data(), success.size(), nullptr));
            sqlOk(sqlite3_bind_text(stmt, 6, msg.data(), msg.size(), nullptr));
            int s;
            while ((s = sqlite3_step(stmt)) != SQLITE_DONE) {
                if (s == SQLITE_ERROR) {
                    throw std::runtime_error(sqlite3_errmsg(db));
                }
            }
            sqlite3_reset(stmt);
        }
    }
    sqlOk(sqlite3_exec(db, "END TRANSACTION", nullptr, nullptr, nullptr));
    sqlOk(sqlite3_finalize(stmt));

    std::cout << "Inserted data, calculating results...\n";
    std::string cutWarmup = noWarmup ? "" : "start >= 60000000 AND end <= 360000000 AND success LIKE 'true'";
    std::string getPutTP = (boost::format(
            "SELECT count(*)/%1% "
            "FROM results "
            "WHERE tx LIKE 'BatchOp' "
            "AND %2%"
            ) % double((time - 2)*60) % cutWarmup).str();
    std::string scanTP = (boost::format(
            "SELECT count(*)/%1% "
            "FROM results "
            "WHERE tx LIKE 'Q%%' "
            "AND %2%"
            ) % double((time - 2)) % cutWarmup).str();
    std::string responseTime = (boost::format(
            "SELECT tx, avg(rt) "
            "FROM results "
            "WHERE %1% "
            "GROUP BY tx;"
            ) % cutWarmup).str();
    std::cout << "================\n";
    std::cout << "Get/Put throughput:\n";
    std::cout << "===================\n";
    std::cout << getPutTP << std::endl;
    std::cout << "---------------------\n";
    sqlOk(sqlite3_prepare_v2(db, getPutTP.data(), getPutTP.size() + 1, &stmt, nullptr));
    int s;
    while ((s = sqlite3_step(stmt)) != SQLITE_DONE) {
        if (s == SQLITE_ERROR) throw std::runtime_error(sqlite3_errmsg(db));
        double tp = sqlite3_column_double(stmt, 0);
        std::cout << tp << " / second\n";
    }
    sqlOk(sqlite3_finalize(stmt));
    sqlOk(sqlite3_prepare_v2(db, scanTP.data(), scanTP.size() + 1, &stmt, nullptr));
    std::cout << "================\n";
    std::cout << "Scan throughput:\n";
    std::cout << "================\n";
    std::cout << scanTP << std::endl;
    std::cout << "---------------------\n";
    while ((s = sqlite3_step(stmt)) != SQLITE_DONE) {
        if (s == SQLITE_ERROR) throw std::runtime_error(sqlite3_errmsg(db));
        double tp = sqlite3_column_double(stmt, 0);
        std::cout << tp << " / minute\n";
    }
    std::cout << "================\n";
    std::cout << "Response Times:\n";
    std::cout << "================\n";
    std::cout << responseTime << std::endl;
    sqlOk(sqlite3_finalize(stmt));
    sqlOk(sqlite3_prepare_v2(db, responseTime.data(), responseTime.size() + 1, &stmt, nullptr));
    while ((s = sqlite3_step(stmt)) != SQLITE_DONE) {
        if (s == SQLITE_ERROR) throw std::runtime_error(sqlite3_errmsg(db));
        auto name = sqlite3_column_text(stmt, 0);
        double rt = sqlite3_column_double(stmt, 1);
        std::cout << name << ": " << rt/1000.0 << " microseconds" << std::endl;
    }
    std::cout << "done";
    sqlite3_close(db);
    return 0;
}
<commit_msg>fixed writing to sqlite - don't print results.<commit_after>/*
 * (C) Copyright 2015 ETH Zurich Systems Group (http://www.systems.ethz.ch/) and others.
 *
 * 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.
 *
 * Contributors:
 *     Markus Pilman <mpilman@inf.ethz.ch>
 *     Simon Loesing <sloesing@inf.ethz.ch>
 *     Thomas Etter <etterth@gmail.com>
 *     Kevin Bocksrocker <kevin.bocksrocker@gmail.com>
 *     Lucas Braun <braunl@inf.ethz.ch>
 */
#include "Client.hpp"
#include <util/Protocol.hpp>
#include "sqlite3.h"

#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>

#include <vector>
#include <thread>

namespace mbench {

std::string cmdString(Commands cmd) {
    switch (cmd) {
    case mbench::Commands::CreateSchema:
        return "CreateSchema";
    case mbench::Commands::Populate:
        return "Populate";
    case mbench::Commands::BatchOp:
        return "BatchOp";
    case mbench::Commands::Q1:
        return "Q1";
    case mbench::Commands::Q2:
        return "Q2";
    case mbench::Commands::Q3:
        return "Q3";
    throw std::runtime_error("Invalid command");
    }
    throw std::runtime_error("This has to be dead code");
}

} // namespace mbench

#define sqlOk(code) assertSql(code, __FILE__, __LINE__)

void assertSql(int code, const char* file, int line) {
    if (code != SQLITE_OK) {
        auto msg = (boost::format("ERROR (%1%:%2%): %3%") % file % line % sqlite3_errstr(code)).str();
        throw std::runtime_error(msg.c_str());
    }
}

int main(int argc, const char* argv[]) {
    namespace po = boost::program_options;
    unsigned numThreads = 1;
    unsigned sf;
    unsigned oltpClients;
    bool populate = false;
    unsigned time = 5;
    unsigned numAnalytical;
    unsigned numOps;
    double insProb, delProb, updProb;
    bool noWarmup;
    bool onlyQ1;
    std::string hostStr;
    std::string dbFile("out.db");
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help,h", "Show help message")
        ("hosts,H", po::value<std::string>(&hostStr)->required(), "Adress to servers")
        ("scaling-factor,s", po::value<unsigned>(&sf)->required(), "Scaling factor")
        ("clients,c", po::value<unsigned>(&oltpClients)->default_value(29), "Number of get/put clients (in total)")
        ("analytical,a", po::value<unsigned>(&numAnalytical)->default_value(0), "Number of analytical clients (in total)")
        ("threads,t", po::value<unsigned>(&numThreads), "Number of network threads")
        ("populate,P", "Run population instead of benchmark")
        ("db,o", po::value<std::string>(&dbFile), "Output to write to")
        ("time", po::value<unsigned>(&time), "Number of minutes to run")
        ("batch-size,b", po::value<unsigned>(&numOps)->default_value(100), "Number of operations per batch")
        ("inserts,i", po::value<double>(&insProb)->default_value(0.166), "Fraction of insert operations")
        ("deletes,d", po::value<double>(&delProb)->default_value(0.166), "Fraction of delete operations")
        ("update,u", po::value<double>(&updProb)->default_value(0.166), "Fraction of update operations")
        ("no-warmup", po::bool_switch(&noWarmup)->default_value(false), "No warm up time")
        ("only-q1,q", po::bool_switch(&onlyQ1)->default_value(false), "Execute only q1")
        ;

    po::variables_map vm;
    store(parse_command_line(argc, argv, desc), vm);
    if (vm.count("help")) {
        std::cout << desc << std::endl;
        return 0;
    }

    if (vm.count("populate")) {
        populate = true;
    }
    notify(vm);
    if (insProb + updProb + delProb > 1.0) {
        std::cerr << "sum(insert,delete,update) > 1.0\n";
        return 1;
    }

    if (oltpClients == 0 && populate) {
        std::cerr << "can not populate without oltp clients\n";
        return 1;
    }

    if (!noWarmup)
        time += 2;

    std::vector<std::string> hosts;
    boost::split(hosts, hostStr, boost::is_any_of(";,"), boost::token_compress_on);

    boost::asio::io_service service;
    boost::asio::io_service::strand ioStrand(service);
    std::vector<std::unique_ptr<mbench::Client>> clients;
    clients.reserve(oltpClients + numAnalytical);
    boost::asio::ip::tcp::resolver resolver(service);
    std::vector<std::string> hostPort;
    hostPort.reserve(2);

    bool allAnalytical = oltpClients == 0;
    auto hostIter = hosts.begin();
    if (populate) numAnalytical = 0;
    for (unsigned i = 0; i < numAnalytical; ++i) {
        if (hostIter == hosts.end()) hostIter = hosts.begin();
        clients.emplace_back(new mbench::Client(service, ioStrand, sf,
                    oltpClients, 0, true, numOps, insProb, delProb,
                    updProb, onlyQ1));
        auto& client = *clients.back();
        boost::split(hostPort, *hostIter, boost::is_any_of(":"), boost::token_compress_on);
        if (hostPort.size() == 1) {
            boost::asio::connect(client.socket(), resolver.resolve({hostPort[0]}));
        } else if (hostPort.size() == 2) {
            boost::asio::connect(client.socket(), resolver.resolve({hostPort[0], hostPort[1]}));
        } else {
            std::cerr << "Format error while parsing hosts" << std::endl;
            return 1;
        }
        ++hostIter;
    }
    for (unsigned clientId = 0; clientId < oltpClients; ++clientId) {
        if (hostIter == hosts.end()) hostIter = hosts.begin();
        clients.emplace_back(new mbench::Client(service, ioStrand, sf,
                    oltpClients, clientId, false, numOps, insProb,
                    delProb, updProb, onlyQ1));
        auto& client = *clients.back();
        boost::split(hostPort, *hostIter, boost::is_any_of(":"), boost::token_compress_on);
        if (hostPort.size() == 1) {
            boost::asio::connect(client.socket(), resolver.resolve({hostPort[0]}));
        } else if (hostPort.size() == 2) {
            boost::asio::connect(client.socket(), resolver.resolve({hostPort[0], hostPort[1]}));
        } else {
            std::cerr << "Format error while parsing hosts" << std::endl;
            return 1;
        }
        ++hostIter;
    }
    auto duration = std::chrono::minutes(time);
    bool timerChosen = true;
    if (populate) {
        std::cout << "start population\n";
        clients[0]->populate(clients);
    } else {
        for (auto& client : clients) {
            if (timerChosen && allAnalytical) {
                client->run(duration, true);
                timerChosen = false;
            }
            else if (timerChosen && !client->isAnalytical()) {
                client->run(duration, true);
                timerChosen = false;
            } else {
                client->run(duration, false);
            }
        }
    }

    std::cout << "Will run for " << time << " minutes with " << clients.size() << " clients\n";
    auto startTime = mbench::Clock::now();
    std::vector<std::thread> threads;
    threads.reserve(numThreads - 1);
    for (unsigned i = 0; i < numThreads - 1; ++i) {
        threads.emplace_back([&service](){ service.run(); });
    }
    service.run();
    for (auto& t : threads) {
        t.join();
    }
    if (populate) {
        std::cout << "                                                                                \r";
        std::cout << "Done\n";
    }
    std::cout << "Done - writing results\n";
    sqlOk(sqlite3_config(SQLITE_CONFIG_SINGLETHREAD));
    sqlite3* db;
    sqlOk(sqlite3_open(dbFile.c_str(), &db));
    sqlOk(sqlite3_exec(db, "CREATE TABLE results(start int, end int, rt int, tx text, success text, msg text)",
                nullptr, nullptr, nullptr));
    sqlOk(sqlite3_exec(db, "CREATE TABLE clientArgs(idx int, param text)", nullptr, nullptr, nullptr));

    sqlOk(sqlite3_exec(db, "BEGIN TRANSACTION", nullptr, nullptr, nullptr));
    // Insert arguments
    sqlite3_stmt* stmt;
    sqlOk(sqlite3_prepare_v2(db, "INSERT INTO clientArgs VALUES(?, ?)", -1, &stmt, nullptr));
    for (int i = 0; i < argc; ++i) {
        sqlOk(sqlite3_bind_int(stmt, 1, i));
        sqlOk(sqlite3_bind_text(stmt, 2, argv[i], -1, nullptr));
        int s;
        while ((s = sqlite3_step(stmt)) != SQLITE_DONE) {
            if (s == SQLITE_ERROR) {
                throw std::runtime_error(sqlite3_errmsg(db));
            }
        }
        sqlite3_reset(stmt);
    }
    sqlOk(sqlite3_finalize(stmt));
    sqlOk(sqlite3_exec(db, "END TRANSACTION", nullptr, nullptr, nullptr));
    // insert data
    sqlOk(sqlite3_exec(db, "BEGIN TRANSACTION", nullptr, nullptr, nullptr));
    sqlOk(sqlite3_prepare_v2(db, "INSERT INTO results VALUES(?, ?, ?, ?, ?, ?)", -1, &stmt, nullptr));

    for (auto& client : clients) {
        const auto& log = client->log();
        for (const auto& e : log) {
            auto start = int(std::chrono::duration_cast<std::chrono::microseconds>(e.start - startTime).count());
            auto end   = int(std::chrono::duration_cast<std::chrono::microseconds>(e.end - startTime).count());
            std::string trans = cmdString(e.transaction);
            std::string success = e.success ? "true" : "false";
            std::string msg(e.error.data(), e.error.size());
            sqlOk(sqlite3_bind_int(stmt, 1, start));
            sqlOk(sqlite3_bind_int(stmt, 2, end));
            sqlOk(sqlite3_bind_int64(stmt, 3, e.responseTime));
            sqlOk(sqlite3_bind_text(stmt, 4, trans.data(), trans.size(), nullptr));
            sqlOk(sqlite3_bind_text(stmt, 5, success.data(), success.size(), nullptr));
            sqlOk(sqlite3_bind_text(stmt, 6, msg.data(), msg.size(), nullptr));
            int s;
            while ((s = sqlite3_step(stmt)) != SQLITE_DONE) {
                if (s == SQLITE_ERROR) {
                    throw std::runtime_error(sqlite3_errmsg(db));
                }
            }
            sqlite3_reset(stmt);
        }
    }
    sqlOk(sqlite3_finalize(stmt));
    sqlOk(sqlite3_exec(db, "END TRANSACTION", nullptr, nullptr, nullptr));

    std::cout << "done\n";
    sqlite3_close(db);
    return 0;
}
<|endoftext|>


<commit_before><commit_msg>No need to rotate U/V components returned by qengine<commit_after><|endoftext|>


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

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

#ifdef MAC
#ifdef ITEMID_NUMBERINFO
#undef ITEMID_NUMBERINFO
#endif
#endif

#define ITEMID_NUMBERINFO 0

#ifndef DBAUI_SBATTRDLG_HXX
#include "dlgattr.hxx"
#endif

#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif

#ifndef _SVX_NUMINF_HXX //autogen
#include <svx/numinf.hxx>
#endif

//CHINA001 #ifndef _SVX_CHARDLG_HXX //autogen
//CHINA001 #include <svx/chardlg.hxx>
//CHINA001 #endif

//CHINA001 #ifndef _SVX_NUMFMT_HXX //autogen
//CHINA001 #include <svx/numfmt.hxx>
//CHINA001 #endif
#ifndef _SVX_NUMINF_HXX
#include <svx/numinf.hxx>
#endif

//CHINA001 #ifndef _SVX_ALIGN_HXX //autogen
//CHINA001 #include <svx/align.hxx>
//CHINA001 #endif

#ifndef _SVX_DIALOGS_HRC
#include <svx/dialogs.hrc>
#endif

#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif
#define _ZFORLIST_DECLARE_TABLE
#ifndef _ZFORLIST_HXX
#include <svtools/zforlist.hxx>
#endif
#include <svx/svxids.hrc> //CHINA001
#include <svx/flagsdef.hxx> //CHINA001
#ifndef _SFXINTITEM_HXX //CHINA001
#include <svtools/intitem.hxx> //CHINA001
#endif //CHINA001

using namespace dbaui;

DBG_NAME(SbaSbAttrDlg)
//==================================================================
SbaSbAttrDlg::SbaSbAttrDlg(Window* pParent, const SfxItemSet* pCellAttrs, SvNumberFormatter* pFormatter, USHORT nFlags, BOOL bRow)
             : SfxTabDialog(pParent, ModuleRes( DLG_ATTR ), pCellAttrs )
             ,aTitle(ModuleRes(ST_ROW))
{
    DBG_CTOR(SbaSbAttrDlg,NULL);

    pNumberInfoItem = new SvxNumberInfoItem( pFormatter );

    if (bRow)
        SetText(aTitle);
    if( nFlags & TP_ATTR_CHAR )
    {
//        AddTabPage( RID_SVXPAGE_CHAR_STD,String(ModuleRes(TP_ATTR_CHAR)),SvxCharStdPage::Create,            0 );
        DBG_ERROR( "found flag TP_ATTR_CHAR" );
    }
    if( nFlags & TP_ATTR_NUMBER )
        AddTabPage( RID_SVXPAGE_NUMBERFORMAT,String(ModuleRes(TP_ATTR_NUMBER)) ); //CHINA001 AddTabPage( RID_SVXPAGE_NUMBERFORMAT,String(ModuleRes(TP_ATTR_NUMBER)),SvxNumberFormatTabPage::Create, 0 );
    if( nFlags & TP_ATTR_ALIGN )
        AddTabPage( RID_SVXPAGE_ALIGNMENT,String(ModuleRes(TP_ATTR_ALIGN)) );//CHINA001 AddTabPage( RID_SVXPAGE_ALIGNMENT,String(ModuleRes(TP_ATTR_ALIGN)),SvxAlignmentTabPage::Create, 0 );
    FreeResource();
}

// -----------------------------------------------------------------------
SbaSbAttrDlg::~SbaSbAttrDlg()
{
    delete pNumberInfoItem;

    DBG_DTOR(SbaSbAttrDlg,NULL);
}

// -----------------------------------------------------------------------
void SbaSbAttrDlg::PageCreated( sal_uInt16 nPageId, SfxTabPage& rTabPage )
{
    SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));
    switch ( nPageId )
    {
        case RID_SVXPAGE_NUMBERFORMAT:
        {
            //CHINA001 ((SvxNumberFormatTabPage&)rTabPage).
                //CHINA001 SetNumberFormatList( *pNumberInfoItem );
            aSet.Put (SvxNumberInfoItem( pNumberInfoItem->GetNumberFormatter(), (const USHORT)SID_ATTR_NUMBERFORMAT_INFO));
            rTabPage.PageCreated(aSet);
        }
        break;

        case RID_SVXPAGE_CHAR_STD:
        {
            //  ((SvxCharStdPage&)rTabPage).SetFontList(SBA_MOD_EXT()->FontListItem());
        }
        break;

        case RID_SVXPAGE_ALIGNMENT:
        {
            //CHINA001 ((SvxAlignmentTabPage&)rTabPage).SetFlags(WBA_NO_ORIENTATION|WBA_NO_LINEBREAK|WBA_NO_GRIDLINES|WBA_NO_VERTICAL|WBA_NO_LEFTINDENT);
//           aSet.Put (SfxUInt32Item(SID_FLAG_TYPE, WBA_NO_ORIENTATION|WBA_NO_LINEBREAK|WBA_NO_GRIDLINES|WBA_NO_VERTICAL|WBA_NO_LEFTINDENT));
//           rTabPage.PageCreated(aSet);
        }
        break;

        default:
        break;
    }
}

<commit_msg>INTEGRATION: CWS pchfix04 (1.9.32); FILE MERGED 2007/02/05 08:45:41 os 1.9.32.1: #i73604# usage of ITEMID_* removed<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: dlgattr.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: kz $ $Date: 2007-05-10 15:06:12 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef DBAUI_SBATTRDLG_HXX
#include "dlgattr.hxx"
#endif

#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif

#ifndef _SVX_NUMINF_HXX //autogen
#include <svx/numinf.hxx>
#endif

//CHINA001 #ifndef _SVX_CHARDLG_HXX //autogen
//CHINA001 #include <svx/chardlg.hxx>
//CHINA001 #endif

//CHINA001 #ifndef _SVX_NUMFMT_HXX //autogen
//CHINA001 #include <svx/numfmt.hxx>
//CHINA001 #endif
#ifndef _SVX_NUMINF_HXX
#include <svx/numinf.hxx>
#endif

//CHINA001 #ifndef _SVX_ALIGN_HXX //autogen
//CHINA001 #include <svx/align.hxx>
//CHINA001 #endif

#ifndef _SVX_DIALOGS_HRC
#include <svx/dialogs.hrc>
#endif

#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _SFXITEMSET_HXX
#include <svtools/itemset.hxx>
#endif
#define _ZFORLIST_DECLARE_TABLE
#ifndef _ZFORLIST_HXX
#include <svtools/zforlist.hxx>
#endif
#include <svx/svxids.hrc> //CHINA001
#include <svx/flagsdef.hxx> //CHINA001
#ifndef _SFXINTITEM_HXX //CHINA001
#include <svtools/intitem.hxx> //CHINA001
#endif //CHINA001

using namespace dbaui;

DBG_NAME(SbaSbAttrDlg)
//==================================================================
SbaSbAttrDlg::SbaSbAttrDlg(Window* pParent, const SfxItemSet* pCellAttrs, SvNumberFormatter* pFormatter, USHORT nFlags, BOOL bRow)
             : SfxTabDialog(pParent, ModuleRes( DLG_ATTR ), pCellAttrs )
             ,aTitle(ModuleRes(ST_ROW))
{
    DBG_CTOR(SbaSbAttrDlg,NULL);

    pNumberInfoItem = new SvxNumberInfoItem( pFormatter, 0 );

    if (bRow)
        SetText(aTitle);
    if( nFlags & TP_ATTR_CHAR )
    {
//        AddTabPage( RID_SVXPAGE_CHAR_STD,String(ModuleRes(TP_ATTR_CHAR)),SvxCharStdPage::Create,            0 );
        DBG_ERROR( "found flag TP_ATTR_CHAR" );
    }
    if( nFlags & TP_ATTR_NUMBER )
        AddTabPage( RID_SVXPAGE_NUMBERFORMAT,String(ModuleRes(TP_ATTR_NUMBER)) ); //CHINA001 AddTabPage( RID_SVXPAGE_NUMBERFORMAT,String(ModuleRes(TP_ATTR_NUMBER)),SvxNumberFormatTabPage::Create, 0 );
    if( nFlags & TP_ATTR_ALIGN )
        AddTabPage( RID_SVXPAGE_ALIGNMENT,String(ModuleRes(TP_ATTR_ALIGN)) );//CHINA001 AddTabPage( RID_SVXPAGE_ALIGNMENT,String(ModuleRes(TP_ATTR_ALIGN)),SvxAlignmentTabPage::Create, 0 );
    FreeResource();
}

// -----------------------------------------------------------------------
SbaSbAttrDlg::~SbaSbAttrDlg()
{
    delete pNumberInfoItem;

    DBG_DTOR(SbaSbAttrDlg,NULL);
}

// -----------------------------------------------------------------------
void SbaSbAttrDlg::PageCreated( sal_uInt16 nPageId, SfxTabPage& rTabPage )
{
    SfxAllItemSet aSet(*(GetInputSetImpl()->GetPool()));
    switch ( nPageId )
    {
        case RID_SVXPAGE_NUMBERFORMAT:
        {
            //CHINA001 ((SvxNumberFormatTabPage&)rTabPage).
                //CHINA001 SetNumberFormatList( *pNumberInfoItem );
            aSet.Put (SvxNumberInfoItem( pNumberInfoItem->GetNumberFormatter(), (const USHORT)SID_ATTR_NUMBERFORMAT_INFO));
            rTabPage.PageCreated(aSet);
        }
        break;

        case RID_SVXPAGE_CHAR_STD:
        {
            //  ((SvxCharStdPage&)rTabPage).SetFontList(SBA_MOD_EXT()->FontListItem());
        }
        break;

        case RID_SVXPAGE_ALIGNMENT:
        {
            //CHINA001 ((SvxAlignmentTabPage&)rTabPage).SetFlags(WBA_NO_ORIENTATION|WBA_NO_LINEBREAK|WBA_NO_GRIDLINES|WBA_NO_VERTICAL|WBA_NO_LEFTINDENT);
//           aSet.Put (SfxUInt32Item(SID_FLAG_TYPE, WBA_NO_ORIENTATION|WBA_NO_LINEBREAK|WBA_NO_GRIDLINES|WBA_NO_VERTICAL|WBA_NO_LEFTINDENT));
//           rTabPage.PageCreated(aSet);
        }
        break;

        default:
        break;
    }
}

<|endoftext|>