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

  Program:   Monteverdi2
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

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

=========================================================================*/

//
// Configuration include.
//// Included at first position before any other ones.
#include "ConfigureMonteverdi2.h"

/*****************************************************************************/
/* INCLUDE SECTION                                                           */

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
#include <QPixmap>
#include <QSplashScreen>

//
// System includes (sorted by alphabetic order)
#include <exception>

//
// ITK includes (sorted by alphabetic order)
#include "itksys/SystemTools.hxx"

//
// OTB includes (sorted by alphabetic order)

//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdApplication.h"
#include "mvdMainWindow.h"

/*****************************************************************************/
/* FUNCTIONS DECLARATION                                                     */

/*****************************************************************************/
/* MAIN                                                                      */

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

  // 0. Splash-screen.
#if !defined( _DEBUG )
  QPixmap pixmap(QLatin1String( ":/images/application_splash" ));
  QSplashScreen splash(pixmap);
  splash.show();
  qtApp.processEvents();//This is used to accept a click on the screen so that user can cancel the screen
#endif

  // 1. Initialize application and sync settings.
  mvd::Application application( &qtApp );
  application.Initialize();

  // 2. Initialize main-window (UI).
  mvd::MainWindow mainWindow;
  mainWindow.Initialize();

  // 3. Initialize cache directory.
  try
    {
    mainWindow.SetupCacheDir();
    }
  catch( std::exception& exc )
    {
    QMessageBox::critical(
      &mainWindow,
      QCoreApplication::translate(
	PROJECT_NAME,
	PROJECT_NAME " - Critical error!"
      ),
      QCoreApplication::translate(
	PROJECT_NAME,
	"Error when creating repository cache-directory:\n"
	"%1\n"
	"Application will exit!"
      )
      .arg( exc.what() )
    );

    return -1;
    }

  // 4. Initialize database.
  mvd::CountType nb = application.OpenDatabase();
  if( nb > 0 )
    {
#if defined( _DEBUG )
    QMessageBox::StandardButton button =
#endif
      QMessageBox::warning(
  &mainWindow,
  QCoreApplication::translate(
    PROJECT_NAME,
    PROJECT_NAME " " Monteverdi2_VERSION_STRING " - Warning! "
  ),
  QCoreApplication::translate(
    PROJECT_NAME,
    "There are %1 outdated dataset(s) in cache-directory.\n\n"
    "Please remove cache-directory '%2' and restart "
    PROJECT_NAME ".\n\n"
    "Do you to delete cache-directory '%2' before quitting " PROJECT_NAME "?"
  ).arg( nb ).arg( application.GetCacheDir().path() ),
  QMessageBox::Yes | QMessageBox::No,
  QMessageBox::Yes
      );

    if( button==QMessageBox::Yes )
      {
      if( application.GetCacheDir()==QDir::home() )
	{
	throw std::runtime_error(
	  mvd::ToStdString(
	    QCoreApplication::translate(
	      PROJECT_NAME,
	      "Tryed to remove home dir."
	    )
	  )
	);
	}

      itksys::SystemTools::RemoveADirectory(
	QFile::encodeName( application.GetCacheDir().path() ).constData()
      );
      }

    return -2;
    }

  // 5. Show window.
#if defined( _DEBUG )
  // Usefull when developping/debugging to avoid overlapping other windows.
  mainWindow.show();

#else
  splash.finish(&mainWindow);

  // TODO: Correctly manage main-window state via application settings.
  mainWindow.showMaximized();

#endif

  // 6. Let's go: run the application and return exit code.
  return QCoreApplication::instance()->exec();
}

/*****************************************************************************/
/* FUNCTIONS IMPLEMENTATION                                                  */
<commit_msg>COMP: Fixed bad #if defined( _DEBUG ) statement.<commit_after>/*=========================================================================

  Program:   Monteverdi2
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

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

=========================================================================*/

//
// Configuration include.
//// Included at first position before any other ones.
#include "ConfigureMonteverdi2.h"

/*****************************************************************************/
/* INCLUDE SECTION                                                           */

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
#include <QPixmap>
#include <QSplashScreen>

//
// System includes (sorted by alphabetic order)
#include <exception>

//
// ITK includes (sorted by alphabetic order)
#include "itksys/SystemTools.hxx"

//
// OTB includes (sorted by alphabetic order)

//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdApplication.h"
#include "mvdMainWindow.h"

/*****************************************************************************/
/* FUNCTIONS DECLARATION                                                     */

/*****************************************************************************/
/* MAIN                                                                      */

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

  // 0. Splash-screen.
#if !defined( _DEBUG )
  QPixmap pixmap(QLatin1String( ":/images/application_splash" ));
  QSplashScreen splash(pixmap);
  splash.show();
  qtApp.processEvents();//This is used to accept a click on the screen so that user can cancel the screen
#endif

  // 1. Initialize application and sync settings.
  mvd::Application application( &qtApp );
  application.Initialize();

  // 2. Initialize main-window (UI).
  mvd::MainWindow mainWindow;
  mainWindow.Initialize();

  // 3. Initialize cache directory.
  try
    {
    mainWindow.SetupCacheDir();
    }
  catch( std::exception& exc )
    {
    QMessageBox::critical(
      &mainWindow,
      QCoreApplication::translate(
	PROJECT_NAME,
	PROJECT_NAME " - Critical error!"
      ),
      QCoreApplication::translate(
	PROJECT_NAME,
	"Error when creating repository cache-directory:\n"
	"%1\n"
	"Application will exit!"
      )
      .arg( exc.what() )
    );

    return -1;
    }

  // 4. Initialize database.
  mvd::CountType nb = application.OpenDatabase();
  if( nb > 0 )
    {
    QMessageBox::StandardButton button =
      QMessageBox::warning(
	&mainWindow,
	QCoreApplication::translate(
	  PROJECT_NAME,
	  PROJECT_NAME " " Monteverdi2_VERSION_STRING " - Warning! "
	),
	QCoreApplication::translate(
	  PROJECT_NAME,
	  "There are %1 outdated dataset(s) in cache-directory.\n\n"
	  "Please remove cache-directory '%2' and restart "
	  PROJECT_NAME ".\n\n"
	  "Do you to delete cache-directory '%2' before quitting " PROJECT_NAME "?"
	).arg( nb ).arg( application.GetCacheDir().path() ),
	QMessageBox::Yes | QMessageBox::No,
	QMessageBox::Yes
      );

    if( button==QMessageBox::Yes )
      {
      if( application.GetCacheDir()==QDir::home() )
	{
	throw std::runtime_error(
	  mvd::ToStdString(
	    QCoreApplication::translate(
	      PROJECT_NAME,
	      "Tryed to remove home dir."
	    )
	  )
	);
	}

      itksys::SystemTools::RemoveADirectory(
	QFile::encodeName( application.GetCacheDir().path() ).constData()
      );
      }

    return -2;
    }

  // 5. Show window.
#if defined( _DEBUG )
  // Usefull when developping/debugging to avoid overlapping other windows.
  mainWindow.show();

#else
  splash.finish(&mainWindow);

  // TODO: Correctly manage main-window state via application settings.
  mainWindow.showMaximized();

#endif

  // 6. Let's go: run the application and return exit code.
  return QCoreApplication::instance()->exec();
}

/*****************************************************************************/
/* FUNCTIONS IMPLEMENTATION                                                  */
<|endoftext|>


<commit_before>#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include <stdint.h>
#include <stdio.h>

namespace {

  const char kToplevel[] = "$total$";
  const char kOverhead[] = "$overhead$";
  const char kIgnore[] = "$ignore$";

  struct OpInfo {
    std::string op_type;
    std::string op_name;
    std::string parent_type;
    std::string parent_name;
    // number of times called
    int64_t count;
    // ticks used (processor specific, no fixed time interval)
    int64_t ticks;
    // nsec is actually only measured for $total$;
    // it's (approximated) calculated for all others
    double nsec;
    // percentage of total ticks, [0.0..1.0]
    double percent;
    // ticks/nsec/percent used by this op alone (not including callees)
    int64_t ticks_only;
    double nsec_only;
    double percent_only;

    OpInfo()
      : count(0),
        ticks(0),
        nsec(0.0),
        percent(0.0),
        ticks_only(0),
        nsec_only(0.0),
        percent_only(0.0) {}
  };

  // Outer map is keyed by function name,
  // inner map is keyed by op_type + op_name
  typedef std::map<std::string, OpInfo> OpInfoMap;
  typedef std::map<std::string, OpInfoMap> FuncInfoMap;

  std::string qualified_name(const std::string& op_type, const std::string& op_name) {
    // Arbitrary, just join type + name
    return op_type + ":" + op_name;
  }

  // How is it posible that there is no string-split function in the C++
  // standard library?
  std::vector<std::string> Split(const std::string& s, char delim) {
    std::vector<std::string> v;
    std::istringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        v.push_back(item);
    }
    return v;
  }

  bool HasOpt(char** begin, char** end, const std::string& opt) {
    return std::find(begin, end, opt) != end;
  }

  // look for string "opt"; if found, return subsequent string;
  // if not found, return empty string.
  std::string GetOpt(char** begin, char** end, const std::string& opt) {
    char** it = std::find(begin, end, opt);
    if (it != end && ++it != end) {
        return std::string(*it);
    }
    return std::string();
  }

  void ProcessLine(const std::string& s, FuncInfoMap& info, bool accumulate_runs) {
    std::vector<std::string> v = Split(s, ' ');
    if (v.size() < 8) {
      return;
    }
    // Some environments (e.g. Android logging) will emit a prefix
    // for each line; skip the first few words we see before
    // deciding to ignore the line.
    int first = -1;
    for (int i = 0; i < 4; ++i) {
      if (v[i] == "halide_profiler") {
        first = i;
        break;
      }
    }
    if (first < 0) {
      return;
    }
    const std::string& metric = v[first + 1];
    const std::string& func_name = v[first + 2];
    const std::string& op_type = v[first + 3];
    const std::string& op_name = v[first + 4];
    const std::string& parent_type = v[first + 5];
    const std::string& parent_name = v[first + 6];
    if (op_type == kIgnore || op_name == kIgnore) {
      return;
    }
    std::istringstream value_stream(v[first + 7]);
    int64_t value;
    value_stream >> value;
    OpInfoMap& op_info_map = info[func_name];
    OpInfo& op_info = op_info_map[qualified_name(op_type, op_name)];
    op_info.op_type = op_type;
    op_info.op_name = op_name;
    op_info.parent_type = parent_type;
    op_info.parent_name = parent_name;
    if (metric == "count") {
      op_info.count = (accumulate_runs ? op_info.count : 0) + value;
    } else if (metric == "ticks") {
      op_info.ticks = (accumulate_runs ? op_info.ticks : 0) + value;
    } else if (metric == "nsec") {
      op_info.nsec = (accumulate_runs ? op_info.nsec : 0) + value;
    }
  }

  typedef std::map<std::string, std::vector<OpInfo*> > ChildMap;

  int64_t AdjustOverhead(OpInfo& op_info, ChildMap& child_map, double overhead_ticks_avg) {
    int64_t overhead_local = op_info.count * overhead_ticks_avg;
    int64_t overhead_ticks = overhead_local;

    std::string qual_name = qualified_name(op_info.op_type, op_info.op_name);
    const std::vector<OpInfo*>& children = child_map[qual_name];
    for (std::vector<OpInfo*>::const_iterator it = children.begin(); it != children.end(); ++it) {
      OpInfo* c = *it;
      int64_t child_overhead = AdjustOverhead(*c, child_map, overhead_ticks_avg);
      overhead_ticks += child_overhead;
    }

    op_info.ticks -= overhead_ticks;

    // double the overhead of this level
    return overhead_ticks + overhead_local;
  }

  void FinishOpInfo(OpInfoMap& op_info_map, bool adjust_for_overhead) {

    std::string toplevel_qual_name = qualified_name(kToplevel, kToplevel);
    OpInfo& total = op_info_map[toplevel_qual_name];
    total.percent = 1.0;

    double ticks_per_nsec = (double)total.ticks / (double)total.nsec;

    // Note that overhead (if present) is measured outside the rest
    // of the "total", so it should not be included (or subtracted from)
    // the total.
    double overhead_ticks_avg = 0;
    std::string overhead_qual_name = qualified_name(kOverhead, kOverhead);
    OpInfoMap::iterator it = op_info_map.find(overhead_qual_name);
    if (it != op_info_map.end()) {
      OpInfo overhead = it->second;
      overhead_ticks_avg = (double)overhead.ticks / ((double)overhead.count * 2.0);
      op_info_map.erase(it);
    }

    ChildMap child_map;
    for (OpInfoMap::iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {
      OpInfo& op_info = o->second;
      std::string parent_qual_name = qualified_name(op_info.parent_type, op_info.parent_name);
      child_map[parent_qual_name].push_back(&op_info);
    }

    if (adjust_for_overhead) {
      // Adjust values to account for profiling overhead
      AdjustOverhead(total, child_map, overhead_ticks_avg);
    }

    for (OpInfoMap::iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {
      OpInfo& op_info = o->second;
      op_info.ticks_only = op_info.ticks;
      const std::vector<OpInfo*>& children = child_map[o->first];
      for (std::vector<OpInfo*>::const_iterator it = children.begin(); it != children.end(); ++it) {
        OpInfo* c = *it;
        op_info.ticks_only -= c->ticks;
      }
    }

    // Calc the derived fields
    for (OpInfoMap::iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {
      OpInfo& op_info = o->second;
      op_info.nsec = op_info.ticks / ticks_per_nsec;
      op_info.nsec_only = op_info.ticks_only / ticks_per_nsec;
      op_info.percent = (double)op_info.ticks / (double)total.ticks;
      op_info.percent_only = (double)op_info.ticks_only / (double)total.ticks;
    }
  }

  template <typename CmpFunc>
  std::vector<OpInfo> SortOpInfo(const OpInfoMap& op_info_map, CmpFunc cmp) {
    std::vector<OpInfo> v;
    for (OpInfoMap::const_iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {
      v.push_back(o->second);
    }
    // Note: using reverse iterators to get a descending sort
    std::sort(v.rbegin(), v.rend(), cmp);
    return v;
  }

  bool by_count(const OpInfo& a, const OpInfo& b) { return a.count < b.count; }
  bool by_ticks(const OpInfo& a, const OpInfo& b) { return a.ticks < b.ticks; }
  bool by_ticks_only(const OpInfo& a, const OpInfo& b) { return a.ticks_only < b.ticks_only; }

}  // namespace

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

  if (HasOpt(argv, argv + argc, "-h")) {
    printf("HalideProf [-f funcname] [-sort c|t|to] [-top N] [-overhead=0|1] [-accumulate=[0|1]] < profiledata\n");
    return 0;
  }

  std::string func_name_filter = GetOpt(argv, argv + argc, "-f");

  bool (*sort_by_func)(const OpInfo& a, const OpInfo& b);
  std::string sort_by = GetOpt(argv, argv + argc, "-sort");
  if (sort_by.empty() || sort_by == "to") {
    sort_by_func = by_ticks_only;
  } else if (sort_by == "t") {
    sort_by_func = by_ticks;
  } else if (sort_by == "c") {
    sort_by_func = by_count;
  } else {
    std::cerr << "Unknown value for -sort: " << sort_by << "\n";
    exit(-1);
  }

  int32_t top_n = 10;
  std::string top_n_str = GetOpt(argv, argv + argc, "-top");
  if (!top_n_str.empty()) {
    std::istringstream(top_n_str) >> top_n;
  }

  // It's rare that you wouldn't want to try to adjust the times
  // to minimize the effect profiling overhead, but just in case,
  // allow -overhead 0
  int32_t adjust_for_overhead = 1;
  std::string adjust_for_overhead_str = GetOpt(argv, argv + argc, "-overhead");
  if (!adjust_for_overhead_str.empty()) {
    std::istringstream(adjust_for_overhead_str) >> adjust_for_overhead;
  }

  int32_t accumulate_runs = 0;
  std::string accumulate_runs_str = GetOpt(argv, argv + argc, "-accumulate");
  if (!accumulate_runs_str.empty()) {
    std::istringstream(accumulate_runs_str) >> accumulate_runs;
  }

  FuncInfoMap func_info_map;
  std::string line;
  while (std::getline(std::cin, line)) {
    ProcessLine(line, func_info_map, accumulate_runs);
  }

  for (FuncInfoMap::iterator f = func_info_map.begin(); f != func_info_map.end(); ++f) {
    FinishOpInfo(f->second, adjust_for_overhead != 0);
  }

  for (FuncInfoMap::iterator f = func_info_map.begin(); f != func_info_map.end(); ++f) {
    const std::string& func_name = f->first;
    if (!func_name_filter.empty() && func_name_filter != func_name) {
      continue;
    }
    std::cout << "Func: " << func_name << "\n";
    std::cout << "--------------------------\n";
    std::cout
      << std::setw(10) << std::left << "op_type"
      << std::setw(40) << std::left << "op_name"
      << std::setw(16) << std::right << "count"
      << std::setw(16) << "ticks-cum"
      << std::setw(12) << "msec-cum"
      << std::setw(8) << std::fixed << "%-cum"
      << std::setw(16) << "ticks-only"
      << std::setw(12) << "msec-only"
      << std::setw(8) << std::fixed << "%-only"
      << "\n";
    std::vector<OpInfo> op_info = SortOpInfo(f->second, sort_by_func);
    for (std::vector<OpInfo>::const_iterator o = op_info.begin(); o != op_info.end(); ++o) {
      const OpInfo& op_info = *o;
      std::cout
        << std::setw(10) << std::left << op_info.op_type
        << std::setw(40) << std::left << op_info.op_name
        << std::setw(16) << std::right << op_info.count
        << std::setw(16) << op_info.ticks
        << std::setw(12) << std::setprecision(2) << std::fixed << (op_info.nsec / 1000000.0)
        << std::setw(8) << std::setprecision(2) << std::fixed << (op_info.percent * 100.0)
        << std::setw(16) << op_info.ticks_only
        << std::setw(12) << std::setprecision(2) << std::fixed << (op_info.nsec_only / 1000000.0)
        << std::setw(8) << std::setprecision(2) << std::fixed << (op_info.percent_only * 100.0)
        << "\n";
      if (--top_n <= 0) {
        break;
      }
    }
  }
}
<commit_msg>HalideProf should check the entire line for "halide_profiler" tag.<commit_after>#include <algorithm>
#include <iomanip>
#include <ios>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include <stdint.h>
#include <stdio.h>

namespace {

  const char kToplevel[] = "$total$";
  const char kOverhead[] = "$overhead$";
  const char kIgnore[] = "$ignore$";

  struct OpInfo {
    std::string op_type;
    std::string op_name;
    std::string parent_type;
    std::string parent_name;
    // number of times called
    int64_t count;
    // ticks used (processor specific, no fixed time interval)
    int64_t ticks;
    // nsec is actually only measured for $total$;
    // it's (approximated) calculated for all others
    double nsec;
    // percentage of total ticks, [0.0..1.0]
    double percent;
    // ticks/nsec/percent used by this op alone (not including callees)
    int64_t ticks_only;
    double nsec_only;
    double percent_only;

    OpInfo()
      : count(0),
        ticks(0),
        nsec(0.0),
        percent(0.0),
        ticks_only(0),
        nsec_only(0.0),
        percent_only(0.0) {}
  };

  // Outer map is keyed by function name,
  // inner map is keyed by op_type + op_name
  typedef std::map<std::string, OpInfo> OpInfoMap;
  typedef std::map<std::string, OpInfoMap> FuncInfoMap;

  std::string qualified_name(const std::string& op_type, const std::string& op_name) {
    // Arbitrary, just join type + name
    return op_type + ":" + op_name;
  }

  // How is it posible that there is no string-split function in the C++
  // standard library?
  std::vector<std::string> Split(const std::string& s, char delim) {
    std::vector<std::string> v;
    std::istringstream ss(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        v.push_back(item);
    }
    return v;
  }

  bool HasOpt(char** begin, char** end, const std::string& opt) {
    return std::find(begin, end, opt) != end;
  }

  // look for string "opt"; if found, return subsequent string;
  // if not found, return empty string.
  std::string GetOpt(char** begin, char** end, const std::string& opt) {
    char** it = std::find(begin, end, opt);
    if (it != end && ++it != end) {
        return std::string(*it);
    }
    return std::string();
  }

  void ProcessLine(const std::string& s, FuncInfoMap& info, bool accumulate_runs) {
    std::vector<std::string> v = Split(s, ' ');
    if (v.size() < 8) {
      return;
    }
    // Some environments (e.g. Android logging) will emit a prefix
    // for each line; just check all the words on the line.
    int first = -1;
    // We know v.size() >= 8 due to earlier check, so this will never underflow.
    for (int i = 0; i < v.size() - 8; ++i) {
      if (v[i] == "halide_profiler") {
        first = i;
        break;
      }
    }
    if (first < 0) {
      return;
    }
    const std::string& metric = v[first + 1];
    const std::string& func_name = v[first + 2];
    const std::string& op_type = v[first + 3];
    const std::string& op_name = v[first + 4];
    const std::string& parent_type = v[first + 5];
    const std::string& parent_name = v[first + 6];
    if (op_type == kIgnore || op_name == kIgnore) {
      return;
    }
    std::istringstream value_stream(v[first + 7]);
    int64_t value;
    value_stream >> value;
    OpInfoMap& op_info_map = info[func_name];
    OpInfo& op_info = op_info_map[qualified_name(op_type, op_name)];
    op_info.op_type = op_type;
    op_info.op_name = op_name;
    op_info.parent_type = parent_type;
    op_info.parent_name = parent_name;
    if (metric == "count") {
      op_info.count = (accumulate_runs ? op_info.count : 0) + value;
    } else if (metric == "ticks") {
      op_info.ticks = (accumulate_runs ? op_info.ticks : 0) + value;
    } else if (metric == "nsec") {
      op_info.nsec = (accumulate_runs ? op_info.nsec : 0) + value;
    }
  }

  typedef std::map<std::string, std::vector<OpInfo*> > ChildMap;

  int64_t AdjustOverhead(OpInfo& op_info, ChildMap& child_map, double overhead_ticks_avg) {
    int64_t overhead_local = op_info.count * overhead_ticks_avg;
    int64_t overhead_ticks = overhead_local;

    std::string qual_name = qualified_name(op_info.op_type, op_info.op_name);
    const std::vector<OpInfo*>& children = child_map[qual_name];
    for (std::vector<OpInfo*>::const_iterator it = children.begin(); it != children.end(); ++it) {
      OpInfo* c = *it;
      int64_t child_overhead = AdjustOverhead(*c, child_map, overhead_ticks_avg);
      overhead_ticks += child_overhead;
    }

    op_info.ticks -= overhead_ticks;

    // double the overhead of this level
    return overhead_ticks + overhead_local;
  }

  void FinishOpInfo(OpInfoMap& op_info_map, bool adjust_for_overhead) {

    std::string toplevel_qual_name = qualified_name(kToplevel, kToplevel);
    OpInfo& total = op_info_map[toplevel_qual_name];
    total.percent = 1.0;

    double ticks_per_nsec = (double)total.ticks / (double)total.nsec;

    // Note that overhead (if present) is measured outside the rest
    // of the "total", so it should not be included (or subtracted from)
    // the total.
    double overhead_ticks_avg = 0;
    std::string overhead_qual_name = qualified_name(kOverhead, kOverhead);
    OpInfoMap::iterator it = op_info_map.find(overhead_qual_name);
    if (it != op_info_map.end()) {
      OpInfo overhead = it->second;
      overhead_ticks_avg = (double)overhead.ticks / ((double)overhead.count * 2.0);
      op_info_map.erase(it);
    }

    ChildMap child_map;
    for (OpInfoMap::iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {
      OpInfo& op_info = o->second;
      std::string parent_qual_name = qualified_name(op_info.parent_type, op_info.parent_name);
      child_map[parent_qual_name].push_back(&op_info);
    }

    if (adjust_for_overhead) {
      // Adjust values to account for profiling overhead
      AdjustOverhead(total, child_map, overhead_ticks_avg);
    }

    for (OpInfoMap::iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {
      OpInfo& op_info = o->second;
      op_info.ticks_only = op_info.ticks;
      const std::vector<OpInfo*>& children = child_map[o->first];
      for (std::vector<OpInfo*>::const_iterator it = children.begin(); it != children.end(); ++it) {
        OpInfo* c = *it;
        op_info.ticks_only -= c->ticks;
      }
    }

    // Calc the derived fields
    for (OpInfoMap::iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {
      OpInfo& op_info = o->second;
      op_info.nsec = op_info.ticks / ticks_per_nsec;
      op_info.nsec_only = op_info.ticks_only / ticks_per_nsec;
      op_info.percent = (double)op_info.ticks / (double)total.ticks;
      op_info.percent_only = (double)op_info.ticks_only / (double)total.ticks;
    }
  }

  template <typename CmpFunc>
  std::vector<OpInfo> SortOpInfo(const OpInfoMap& op_info_map, CmpFunc cmp) {
    std::vector<OpInfo> v;
    for (OpInfoMap::const_iterator o = op_info_map.begin(); o != op_info_map.end(); ++o) {
      v.push_back(o->second);
    }
    // Note: using reverse iterators to get a descending sort
    std::sort(v.rbegin(), v.rend(), cmp);
    return v;
  }

  bool by_count(const OpInfo& a, const OpInfo& b) { return a.count < b.count; }
  bool by_ticks(const OpInfo& a, const OpInfo& b) { return a.ticks < b.ticks; }
  bool by_ticks_only(const OpInfo& a, const OpInfo& b) { return a.ticks_only < b.ticks_only; }

}  // namespace

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

  if (HasOpt(argv, argv + argc, "-h")) {
    printf("HalideProf [-f funcname] [-sort c|t|to] [-top N] [-overhead=0|1] [-accumulate=[0|1]] < profiledata\n");
    return 0;
  }

  std::string func_name_filter = GetOpt(argv, argv + argc, "-f");

  bool (*sort_by_func)(const OpInfo& a, const OpInfo& b);
  std::string sort_by = GetOpt(argv, argv + argc, "-sort");
  if (sort_by.empty() || sort_by == "to") {
    sort_by_func = by_ticks_only;
  } else if (sort_by == "t") {
    sort_by_func = by_ticks;
  } else if (sort_by == "c") {
    sort_by_func = by_count;
  } else {
    std::cerr << "Unknown value for -sort: " << sort_by << "\n";
    exit(-1);
  }

  int32_t top_n = 10;
  std::string top_n_str = GetOpt(argv, argv + argc, "-top");
  if (!top_n_str.empty()) {
    std::istringstream(top_n_str) >> top_n;
  }

  // It's rare that you wouldn't want to try to adjust the times
  // to minimize the effect profiling overhead, but just in case,
  // allow -overhead 0
  int32_t adjust_for_overhead = 1;
  std::string adjust_for_overhead_str = GetOpt(argv, argv + argc, "-overhead");
  if (!adjust_for_overhead_str.empty()) {
    std::istringstream(adjust_for_overhead_str) >> adjust_for_overhead;
  }

  int32_t accumulate_runs = 0;
  std::string accumulate_runs_str = GetOpt(argv, argv + argc, "-accumulate");
  if (!accumulate_runs_str.empty()) {
    std::istringstream(accumulate_runs_str) >> accumulate_runs;
  }

  FuncInfoMap func_info_map;
  std::string line;
  while (std::getline(std::cin, line)) {
    ProcessLine(line, func_info_map, accumulate_runs);
  }

  for (FuncInfoMap::iterator f = func_info_map.begin(); f != func_info_map.end(); ++f) {
    FinishOpInfo(f->second, adjust_for_overhead != 0);
  }

  for (FuncInfoMap::iterator f = func_info_map.begin(); f != func_info_map.end(); ++f) {
    const std::string& func_name = f->first;
    if (!func_name_filter.empty() && func_name_filter != func_name) {
      continue;
    }
    std::cout << "Func: " << func_name << "\n";
    std::cout << "--------------------------\n";
    std::cout
      << std::setw(10) << std::left << "op_type"
      << std::setw(40) << std::left << "op_name"
      << std::setw(16) << std::right << "count"
      << std::setw(16) << "ticks-cum"
      << std::setw(12) << "msec-cum"
      << std::setw(8) << std::fixed << "%-cum"
      << std::setw(16) << "ticks-only"
      << std::setw(12) << "msec-only"
      << std::setw(8) << std::fixed << "%-only"
      << "\n";
    std::vector<OpInfo> op_info = SortOpInfo(f->second, sort_by_func);
    for (std::vector<OpInfo>::const_iterator o = op_info.begin(); o != op_info.end(); ++o) {
      const OpInfo& op_info = *o;
      std::cout
        << std::setw(10) << std::left << op_info.op_type
        << std::setw(40) << std::left << op_info.op_name
        << std::setw(16) << std::right << op_info.count
        << std::setw(16) << op_info.ticks
        << std::setw(12) << std::setprecision(2) << std::fixed << (op_info.nsec / 1000000.0)
        << std::setw(8) << std::setprecision(2) << std::fixed << (op_info.percent * 100.0)
        << std::setw(16) << op_info.ticks_only
        << std::setw(12) << std::setprecision(2) << std::fixed << (op_info.nsec_only / 1000000.0)
        << std::setw(8) << std::setprecision(2) << std::fixed << (op_info.percent_only * 100.0)
        << "\n";
      if (--top_n <= 0) {
        break;
      }
    }
  }
}
<|endoftext|>


<commit_before>#include <mitkStandardFileLocations.h>

#include <mitkConfig.h>
#include <itkObject.h>
#include <itkMacro.h>
#include <itksys/SystemTools.hxx>

const std::string mitk::StandardFileLocations::FindFile(const char* filename, const char* pathInSourceDir)
{
  const char* mitkConf = itksys::SystemTools::GetEnv("MITKCONF");
  std::string xmlFileName;

  if (mitkConf!=NULL)
  {
    // 1. look for MITKCONF environment variable
    xmlFileName = mitkConf;

    xmlFileName += "/";
    xmlFileName = itksys::SystemTools::ConvertToOutputPath(xmlFileName.c_str());
    xmlFileName += filename;

    if(itksys::SystemTools::FileExists(xmlFileName.c_str())) return xmlFileName;
  }

  // 2. use .mitk-subdirectory in home directory of the user
  std::string homeDirectory;
#if defined(_WIN32) && !defined(__CYGWIN__)
  const char* homeDrive = itksys::SystemTools::GetEnv("HOMEDRIVE");
  const char* homePath = itksys::SystemTools::GetEnv("HOMEPATH");
  if((homeDrive==NULL) || (homePath==NULL))
  {
    itkGenericOutputMacro( << "Environment variables HOMEDRIVE and/or HOMEPATH not set" <<
      ". Using current working directory as home directory: " << itksys::SystemTools::GetCurrentWorkingDirectory());
    homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();
  }
  else
  {
    homeDirectory = homeDrive;
    homeDirectory +=homePath;
  }
  if(itksys::SystemTools::FileExists(homeDirectory.c_str())==false)
  {
    itkGenericOutputMacro( << "Could not find home directory at " << homeDirectory <<
      ". Using current working directory as home directory: " << itksys::SystemTools::GetCurrentWorkingDirectory());
    homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();
  }
#else
  const char* home = itksys::SystemTools::GetEnv("HOME");
  if(home==NULL)
  {
    itkGenericOutputMacro( << "Environment variable HOME not set" <<
      ". Using current working directory as home directory: " << itksys::SystemTools::GetCurrentWorkingDirectory());
    homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();
  }
  else
    homeDirectory = home;
  if(itksys::SystemTools::FileExists(homeDirectory.c_str())==false)
  {
    itkGenericOutputMacro( << "Could not find home directory at " << homeDirectory <<
      ". Using current working directory as home directory: " << itksys::SystemTools::GetCurrentWorkingDirectory());
    homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();
  }
#endif // defined(_WIN32) && !defined(__CYGWIN__)

  xmlFileName = homeDirectory;
  xmlFileName += "/.mitk/";
  xmlFileName += filename;

  if(itksys::SystemTools::FileExists(xmlFileName.c_str())) return xmlFileName;

  // 3. look in the current working directory
  xmlFileName = filename;

  if(itksys::SystemTools::FileExists(xmlFileName.c_str())) return xmlFileName;

  // 4. use a source tree location from compile time
  xmlFileName = MITK_ROOT;
  if (pathInSourceDir)
  {
    xmlFileName += pathInSourceDir;
  }
  xmlFileName += '/';
  xmlFileName += filename;

  if(itksys::SystemTools::FileExists(xmlFileName.c_str())) return xmlFileName;

  return std::string("");
}

const std::string mitk::StandardFileLocations::GetOptionDirectory()
{
  const char* mitkoptions = itksys::SystemTools::GetEnv("MITKOPTIONS");
  std::string optionsDirectory;

  if (mitkoptions!=NULL)
  {
    // 1. look for MITKOPTIONS environment variable
    optionsDirectory = mitkoptions;
    optionsDirectory += "/";
  }
  else
  {
    // 2. use .mitk-subdirectory in home directory of the user
    std::string homeDirectory;
#if defined(_WIN32) && !defined(__CYGWIN__)
    const char* homeDrive = itksys::SystemTools::GetEnv("HOMEDRIVE");
    const char* homePath = itksys::SystemTools::GetEnv("HOMEPATH");
    if((homeDrive==NULL) || (homePath==NULL))
    {
      itkGenericOutputMacro( << "Environment variables HOMEDRIVE and/or HOMEPATH not set" <<
        ". Using current working directory as home directory: " << itksys::SystemTools::GetCurrentWorkingDirectory());
      homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();
    }
    else
    {
      homeDirectory = homeDrive;
      homeDirectory +=homePath;
    }
    if(itksys::SystemTools::FileExists(homeDirectory.c_str())==false)
    {
      itkGenericOutputMacro( << "Could not find home directory at " << homeDirectory <<
        ". Using current working directory as home directory: " << itksys::SystemTools::GetCurrentWorkingDirectory());
      homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();
    }
#else
    const char* home = itksys::SystemTools::GetEnv("HOME");
    if(home==NULL)
    {
      itkGenericOutputMacro( << "Environment variable HOME not set" <<
        ". Using current working directory as home directory: " << itksys::SystemTools::GetCurrentWorkingDirectory());
      homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();
    }
    else
      homeDirectory = home;
    if(itksys::SystemTools::FileExists(homeDirectory.c_str())==false)
    {
      itkGenericOutputMacro( << "Could not find home directory at " << homeDirectory <<
        ". Using current working directory as home directory: " << itksys::SystemTools::GetCurrentWorkingDirectory());
      homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();
    }
#endif // defined(_WIN32) && !defined(__CYGWIN__)

    optionsDirectory = homeDirectory;
    optionsDirectory += "/.mitk";
  }

  optionsDirectory = itksys::SystemTools::ConvertToOutputPath(optionsDirectory.c_str());
  if(itksys::SystemTools::CountChar(optionsDirectory.c_str(),'"') > 0)
  {
    char * unquoted = itksys::SystemTools::RemoveChars(optionsDirectory.c_str(),"\"");
    optionsDirectory = unquoted;
    delete [] unquoted;
  }

  if(itksys::SystemTools::MakeDirectory(optionsDirectory.c_str())==false)
  {
    itkGenericExceptionMacro( << "Could not create .mitk directory at " << optionsDirectory );
  }
  return optionsDirectory;
}
<commit_msg>BUGFIX: error in building up a file location might occur, if we do not check for a correct usage of slashes<commit_after>#include <mitkStandardFileLocations.h>

#include <mitkConfig.h>
#include <itkObject.h>
#include <itkMacro.h>
#include <itksys/SystemTools.hxx>

const std::string mitk::StandardFileLocations::FindFile(const char* filename, const char* pathInSourceDir)
{
  const char* mitkConf = itksys::SystemTools::GetEnv("MITKCONF");
  std::string xmlFileName;

  if (mitkConf!=NULL)
  {
    // 1. look for MITKCONF environment variable
    xmlFileName = mitkConf;

    xmlFileName += "/";
    xmlFileName = itksys::SystemTools::ConvertToOutputPath(xmlFileName.c_str());
    xmlFileName += filename;

    if(itksys::SystemTools::FileExists(xmlFileName.c_str())) return xmlFileName;
  }

  // 2. use .mitk-subdirectory in home directory of the user
  std::string homeDirectory;
#if defined(_WIN32) && !defined(__CYGWIN__)
  const char* homeDrive = itksys::SystemTools::GetEnv("HOMEDRIVE");
  const char* homePath = itksys::SystemTools::GetEnv("HOMEPATH");
  if((homeDrive==NULL) || (homePath==NULL))
  {
    itkGenericOutputMacro( << "Environment variables HOMEDRIVE and/or HOMEPATH not set" <<
      ". Using current working directory as home directory: " << itksys::SystemTools::GetCurrentWorkingDirectory());
    homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();
  }
  else
  {
    homeDirectory = homeDrive;
    homeDirectory +=homePath;

    // homeDirectory must not have a slash at the end, otherwise a path like "C:\/.mitk/" might occur.
    if(homeDirectory.find_last_of("\\")+1 == homeDirectory.size() || homeDirectory.find_last_of("/")+1 == homeDirectory.size())
     homeDirectory.erase(homeDirectory.size()-1,homeDirectory.size());
  }
  if(itksys::SystemTools::FileExists(homeDirectory.c_str())==false)
  {
    itkGenericOutputMacro( << "Could not find home directory at " << homeDirectory <<
      ". Using current working directory as home directory: " << itksys::SystemTools::GetCurrentWorkingDirectory());
    homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();
  }
#else
  const char* home = itksys::SystemTools::GetEnv("HOME");
  if(home==NULL)
  {
    itkGenericOutputMacro( << "Environment variable HOME not set" <<
      ". Using current working directory as home directory: " << itksys::SystemTools::GetCurrentWorkingDirectory());
    homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();
  }
  else
    homeDirectory = home;
  if(itksys::SystemTools::FileExists(homeDirectory.c_str())==false)
  {
    itkGenericOutputMacro( << "Could not find home directory at " << homeDirectory <<
      ". Using current working directory as home directory: " << itksys::SystemTools::GetCurrentWorkingDirectory());
    homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();
  }
#endif // defined(_WIN32) && !defined(__CYGWIN__)

  xmlFileName = homeDirectory;
  xmlFileName += "/.mitk/";
  xmlFileName += filename;

  if(itksys::SystemTools::FileExists(xmlFileName.c_str())) return xmlFileName;

  // 3. look in the current working directory
  xmlFileName = filename;

  if(itksys::SystemTools::FileExists(xmlFileName.c_str())) return xmlFileName;

  // 4. use a source tree location from compile time
  xmlFileName = MITK_ROOT;
  if (pathInSourceDir)
  {
    xmlFileName += pathInSourceDir;
  }
  xmlFileName += '/';
  xmlFileName += filename;

  if(itksys::SystemTools::FileExists(xmlFileName.c_str())) return xmlFileName;

  return std::string("");
}

const std::string mitk::StandardFileLocations::GetOptionDirectory()
{
  const char* mitkoptions = itksys::SystemTools::GetEnv("MITKOPTIONS");
  std::string optionsDirectory;

  if (mitkoptions!=NULL)
  {
    // 1. look for MITKOPTIONS environment variable
    optionsDirectory = mitkoptions;
    optionsDirectory += "/";
  }
  else
  {
    // 2. use .mitk-subdirectory in home directory of the user
    std::string homeDirectory;
#if defined(_WIN32) && !defined(__CYGWIN__)
    const char* homeDrive = itksys::SystemTools::GetEnv("HOMEDRIVE");
    const char* homePath = itksys::SystemTools::GetEnv("HOMEPATH");
    if((homeDrive==NULL) || (homePath==NULL))
    {
      itkGenericOutputMacro( << "Environment variables HOMEDRIVE and/or HOMEPATH not set" <<
        ". Using current working directory as home directory: " << itksys::SystemTools::GetCurrentWorkingDirectory());
      homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();
    }
    else
    {
      homeDirectory = homeDrive;
      homeDirectory +=homePath;
    }
    if(itksys::SystemTools::FileExists(homeDirectory.c_str())==false)
    {
      itkGenericOutputMacro( << "Could not find home directory at " << homeDirectory <<
        ". Using current working directory as home directory: " << itksys::SystemTools::GetCurrentWorkingDirectory());
      homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();
    }
#else
    const char* home = itksys::SystemTools::GetEnv("HOME");
    if(home==NULL)
    {
      itkGenericOutputMacro( << "Environment variable HOME not set" <<
        ". Using current working directory as home directory: " << itksys::SystemTools::GetCurrentWorkingDirectory());
      homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();
    }
    else
      homeDirectory = home;
    if(itksys::SystemTools::FileExists(homeDirectory.c_str())==false)
    {
      itkGenericOutputMacro( << "Could not find home directory at " << homeDirectory <<
        ". Using current working directory as home directory: " << itksys::SystemTools::GetCurrentWorkingDirectory());
      homeDirectory = itksys::SystemTools::GetCurrentWorkingDirectory();
    }
#endif // defined(_WIN32) && !defined(__CYGWIN__)

    optionsDirectory = homeDirectory;
    optionsDirectory += "/.mitk";
  }

  optionsDirectory = itksys::SystemTools::ConvertToOutputPath(optionsDirectory.c_str());
  if(itksys::SystemTools::CountChar(optionsDirectory.c_str(),'"') > 0)
  {
    char * unquoted = itksys::SystemTools::RemoveChars(optionsDirectory.c_str(),"\"");
    optionsDirectory = unquoted;
    delete [] unquoted;
  }

  if(itksys::SystemTools::MakeDirectory(optionsDirectory.c_str())==false)
  {
    itkGenericExceptionMacro( << "Could not create .mitk directory at " << optionsDirectory );
  }
  return optionsDirectory;
}
<|endoftext|>


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

#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ENTRYINITMODES_HPP_
#include <com/sun/star/embed/EntryInitModes.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

#include <rtl/logfile.hxx>

#include "xolefactory.hxx"
#include "oleembobj.hxx"

using namespace ::com::sun::star;

// TODO: do not create OLE objects that represent OOo documents

//-------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL OleEmbeddedObjectFactory::impl_staticGetSupportedServiceNames()
{
    uno::Sequence< ::rtl::OUString > aRet(2);
    aRet[0] = ::rtl::OUString::createFromAscii("com.sun.star.embed.OLEEmbeddedObjectFactory");
    aRet[1] = ::rtl::OUString::createFromAscii("com.sun.star.comp.embed.OLEEmbeddedObjectFactory");
    return aRet;
}

//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL OleEmbeddedObjectFactory::impl_staticGetImplementationName()
{
    return ::rtl::OUString::createFromAscii("com.sun.star.comp.embed.OLEEmbeddedObjectFactory");
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::impl_staticCreateSelfInstance(
            const uno::Reference< lang::XMultiServiceFactory >& xServiceManager )
{
    return uno::Reference< uno::XInterface >( *new OleEmbeddedObjectFactory( xServiceManager ) );
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceInitFromEntry(
                                                                    const uno::Reference< embed::XStorage >& xStorage,
                                                                    const ::rtl::OUString& sEntName,
                                                                    const uno::Sequence< beans::PropertyValue >& aMedDescr,
                                                                    const uno::Sequence< beans::PropertyValue >& lObjArgs )
    throw ( lang::IllegalArgumentException,
            container::NoSuchElementException,
            io::IOException,
            uno::Exception,
            uno::RuntimeException)
{
    RTL_LOGFILE_CONTEXT( aLog, "embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceInitFromEntry" );

    if ( !xStorage.is() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "No parent storage is provided!\n" ),
                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            1 );

    if ( !sEntName.getLength() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "Empty element name is provided!\n" ),
                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            2 );

    uno::Reference< container::XNameAccess > xNameAccess( xStorage, uno::UNO_QUERY );
    if ( !xNameAccess.is() )
        throw uno::RuntimeException(); //TODO

    // detect entry existence
    if ( !xNameAccess->hasByName( sEntName ) )
        throw container::NoSuchElementException();

    if ( !xStorage->isStreamElement( sEntName ) )
    {
        // if it is not an OLE object throw an exception
        throw io::IOException(); // TODO:
    }

    uno::Reference< uno::XInterface > xResult(
                    static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, sal_False ) ),
                    uno::UNO_QUERY );

    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );

    if ( !xPersist.is() )
        throw uno::RuntimeException(); // TODO: the interface must be supported by own document objects

    xPersist->setPersistentEntry( xStorage,
                                    sEntName,
                                    embed::EntryInitModes::DEFAULT_INIT,
                                    aMedDescr,
                                    lObjArgs );

    return xResult;
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceInitFromMediaDescriptor(
        const uno::Reference< embed::XStorage >& xStorage,
        const ::rtl::OUString& sEntName,
        const uno::Sequence< beans::PropertyValue >& aMediaDescr,
        const uno::Sequence< beans::PropertyValue >& lObjArgs )
    throw ( lang::IllegalArgumentException,
            io::IOException,
            uno::Exception,
            uno::RuntimeException)
{
    RTL_LOGFILE_CONTEXT( aLog, "embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceInitFromMediaDescriptor" );

    if ( !xStorage.is() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "No parent storage is provided!\n" ),
                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            1 );

    if ( !sEntName.getLength() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "Empty element name is provided!\n" ),
                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            2 );

    uno::Reference< uno::XInterface > xResult(
                    static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, sal_False ) ),
                    uno::UNO_QUERY );

    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );

    if ( !xPersist.is() )
        throw uno::RuntimeException(); // TODO: the interface must be supported ( what about applets? )

    xPersist->setPersistentEntry( xStorage,
                                    sEntName,
                                    embed::EntryInitModes::MEDIA_DESCRIPTOR_INIT,
                                    aMediaDescr,
                                    lObjArgs );

    return xResult;
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceInitNew(
                                            const uno::Sequence< sal_Int8 >& aClassID,
                                            const ::rtl::OUString& aClassName,
                                            const uno::Reference< embed::XStorage >& xStorage,
                                            const ::rtl::OUString& sEntName,
                                            const uno::Sequence< beans::PropertyValue >& lObjArgs )
    throw ( lang::IllegalArgumentException,
            io::IOException,
            uno::Exception,
            uno::RuntimeException)
{
    RTL_LOGFILE_CONTEXT( aLog, "embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceInitNew" );

    if ( !xStorage.is() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "No parent storage is provided!\n" ),
                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            3 );

    if ( !sEntName.getLength() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "Empty element name is provided!\n" ),
                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            4 );

    uno::Reference< uno::XInterface > xResult(
                    static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, aClassID, aClassName ) ),
                    uno::UNO_QUERY );

    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );

    if ( !xPersist.is() )
        throw uno::RuntimeException(); // TODO: the interface must be supported by own document objects

    xPersist->setPersistentEntry( xStorage,
                                    sEntName,
                                    embed::EntryInitModes::TRUNCATE_INIT,
                                    uno::Sequence< beans::PropertyValue >(),
                                    lObjArgs );

    return xResult;
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceLink(
                                            const uno::Reference< embed::XStorage >& xStorage,
                                            const ::rtl::OUString& sEntName,
                                            const uno::Sequence< beans::PropertyValue >& aMediaDescr,
                                            const uno::Sequence< beans::PropertyValue >& lObjArgs )
        throw ( lang::IllegalArgumentException,
                io::IOException,
                uno::Exception,
                uno::RuntimeException )
{
    RTL_LOGFILE_CONTEXT( aLog, "embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceLink" );

    if ( !xStorage.is() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "No parent storage is provided!\n" ),
                                            uno::Reference< uno::XInterface >(
                                                reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            1 );

    if ( !sEntName.getLength() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "Empty element name is provided!\n" ),
                                            uno::Reference< uno::XInterface >(
                                                reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            2 );

    uno::Reference< uno::XInterface > xResult(
                static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, sal_True ) ),
                uno::UNO_QUERY );

    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );

    if ( !xPersist.is() )
        throw uno::RuntimeException(); // TODO: the interface must be supported by own document objects

    xPersist->setPersistentEntry( xStorage,
                                    sEntName,
                                    embed::EntryInitModes::MEDIA_DESCRIPTOR_INIT,
                                    aMediaDescr,
                                    lObjArgs );

    return xResult;
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceUserInit(
            const uno::Sequence< sal_Int8 >& aClassID,
            const ::rtl::OUString& aClassName,
            const uno::Reference< embed::XStorage >& xStorage,
            const ::rtl::OUString& sEntName,
            sal_Int32 /*nEntryConnectionMode*/,
            const uno::Sequence< beans::PropertyValue >& /*lArguments*/,
            const uno::Sequence< beans::PropertyValue >& lObjArgs )
    throw ( lang::IllegalArgumentException,
            io::IOException,
            uno::Exception,
            uno::RuntimeException )
{
    RTL_LOGFILE_CONTEXT( aLog, "embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceUserInit" );

    // the initialization is completelly controlled by user
    if ( !xStorage.is() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "No parent storage is provided!\n" ),
                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            1 );

    if ( !sEntName.getLength() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "Empty element name is provided!\n" ),
                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            2 );

    uno::Reference< uno::XInterface > xResult(
                static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, aClassID, aClassName ) ),
                uno::UNO_QUERY );

    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );
    if ( xPersist.is() )
    {
        xPersist->setPersistentEntry( xStorage,
                                    sEntName,
                                    embed::EntryInitModes::DEFAULT_INIT,
                                    uno::Sequence< beans::PropertyValue >(),
                                    lObjArgs );

    }
    else
        throw uno::RuntimeException(); // TODO:

    return xResult;
}

//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL OleEmbeddedObjectFactory::getImplementationName()
    throw ( uno::RuntimeException )
{
    return impl_staticGetImplementationName();
}

//-------------------------------------------------------------------------
sal_Bool SAL_CALL OleEmbeddedObjectFactory::supportsService( const ::rtl::OUString& ServiceName )
    throw ( uno::RuntimeException )
{
    uno::Sequence< ::rtl::OUString > aSeq = impl_staticGetSupportedServiceNames();

    for ( sal_Int32 nInd = 0; nInd < aSeq.getLength(); nInd++ )
        if ( ServiceName.compareTo( aSeq[nInd] ) == 0 )
            return sal_True;

    return sal_False;
}

//-------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL OleEmbeddedObjectFactory::getSupportedServiceNames()
    throw ( uno::RuntimeException )
{
    return impl_staticGetSupportedServiceNames();
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.7.18); FILE MERGED 2006/09/01 17:25:54 kaib 1.7.18.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xolefactory.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 00:46:03 $
 *
 *  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_embeddedobj.hxx"

#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ENTRYINITMODES_HPP_
#include <com/sun/star/embed/EntryInitModes.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif

#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif

#include <rtl/logfile.hxx>

#include "xolefactory.hxx"
#include "oleembobj.hxx"

using namespace ::com::sun::star;

// TODO: do not create OLE objects that represent OOo documents

//-------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL OleEmbeddedObjectFactory::impl_staticGetSupportedServiceNames()
{
    uno::Sequence< ::rtl::OUString > aRet(2);
    aRet[0] = ::rtl::OUString::createFromAscii("com.sun.star.embed.OLEEmbeddedObjectFactory");
    aRet[1] = ::rtl::OUString::createFromAscii("com.sun.star.comp.embed.OLEEmbeddedObjectFactory");
    return aRet;
}

//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL OleEmbeddedObjectFactory::impl_staticGetImplementationName()
{
    return ::rtl::OUString::createFromAscii("com.sun.star.comp.embed.OLEEmbeddedObjectFactory");
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::impl_staticCreateSelfInstance(
            const uno::Reference< lang::XMultiServiceFactory >& xServiceManager )
{
    return uno::Reference< uno::XInterface >( *new OleEmbeddedObjectFactory( xServiceManager ) );
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceInitFromEntry(
                                                                    const uno::Reference< embed::XStorage >& xStorage,
                                                                    const ::rtl::OUString& sEntName,
                                                                    const uno::Sequence< beans::PropertyValue >& aMedDescr,
                                                                    const uno::Sequence< beans::PropertyValue >& lObjArgs )
    throw ( lang::IllegalArgumentException,
            container::NoSuchElementException,
            io::IOException,
            uno::Exception,
            uno::RuntimeException)
{
    RTL_LOGFILE_CONTEXT( aLog, "embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceInitFromEntry" );

    if ( !xStorage.is() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "No parent storage is provided!\n" ),
                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            1 );

    if ( !sEntName.getLength() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "Empty element name is provided!\n" ),
                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            2 );

    uno::Reference< container::XNameAccess > xNameAccess( xStorage, uno::UNO_QUERY );
    if ( !xNameAccess.is() )
        throw uno::RuntimeException(); //TODO

    // detect entry existence
    if ( !xNameAccess->hasByName( sEntName ) )
        throw container::NoSuchElementException();

    if ( !xStorage->isStreamElement( sEntName ) )
    {
        // if it is not an OLE object throw an exception
        throw io::IOException(); // TODO:
    }

    uno::Reference< uno::XInterface > xResult(
                    static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, sal_False ) ),
                    uno::UNO_QUERY );

    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );

    if ( !xPersist.is() )
        throw uno::RuntimeException(); // TODO: the interface must be supported by own document objects

    xPersist->setPersistentEntry( xStorage,
                                    sEntName,
                                    embed::EntryInitModes::DEFAULT_INIT,
                                    aMedDescr,
                                    lObjArgs );

    return xResult;
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceInitFromMediaDescriptor(
        const uno::Reference< embed::XStorage >& xStorage,
        const ::rtl::OUString& sEntName,
        const uno::Sequence< beans::PropertyValue >& aMediaDescr,
        const uno::Sequence< beans::PropertyValue >& lObjArgs )
    throw ( lang::IllegalArgumentException,
            io::IOException,
            uno::Exception,
            uno::RuntimeException)
{
    RTL_LOGFILE_CONTEXT( aLog, "embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceInitFromMediaDescriptor" );

    if ( !xStorage.is() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "No parent storage is provided!\n" ),
                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            1 );

    if ( !sEntName.getLength() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "Empty element name is provided!\n" ),
                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            2 );

    uno::Reference< uno::XInterface > xResult(
                    static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, sal_False ) ),
                    uno::UNO_QUERY );

    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );

    if ( !xPersist.is() )
        throw uno::RuntimeException(); // TODO: the interface must be supported ( what about applets? )

    xPersist->setPersistentEntry( xStorage,
                                    sEntName,
                                    embed::EntryInitModes::MEDIA_DESCRIPTOR_INIT,
                                    aMediaDescr,
                                    lObjArgs );

    return xResult;
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceInitNew(
                                            const uno::Sequence< sal_Int8 >& aClassID,
                                            const ::rtl::OUString& aClassName,
                                            const uno::Reference< embed::XStorage >& xStorage,
                                            const ::rtl::OUString& sEntName,
                                            const uno::Sequence< beans::PropertyValue >& lObjArgs )
    throw ( lang::IllegalArgumentException,
            io::IOException,
            uno::Exception,
            uno::RuntimeException)
{
    RTL_LOGFILE_CONTEXT( aLog, "embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceInitNew" );

    if ( !xStorage.is() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "No parent storage is provided!\n" ),
                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            3 );

    if ( !sEntName.getLength() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "Empty element name is provided!\n" ),
                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            4 );

    uno::Reference< uno::XInterface > xResult(
                    static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, aClassID, aClassName ) ),
                    uno::UNO_QUERY );

    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );

    if ( !xPersist.is() )
        throw uno::RuntimeException(); // TODO: the interface must be supported by own document objects

    xPersist->setPersistentEntry( xStorage,
                                    sEntName,
                                    embed::EntryInitModes::TRUNCATE_INIT,
                                    uno::Sequence< beans::PropertyValue >(),
                                    lObjArgs );

    return xResult;
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceLink(
                                            const uno::Reference< embed::XStorage >& xStorage,
                                            const ::rtl::OUString& sEntName,
                                            const uno::Sequence< beans::PropertyValue >& aMediaDescr,
                                            const uno::Sequence< beans::PropertyValue >& lObjArgs )
        throw ( lang::IllegalArgumentException,
                io::IOException,
                uno::Exception,
                uno::RuntimeException )
{
    RTL_LOGFILE_CONTEXT( aLog, "embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceLink" );

    if ( !xStorage.is() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "No parent storage is provided!\n" ),
                                            uno::Reference< uno::XInterface >(
                                                reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            1 );

    if ( !sEntName.getLength() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "Empty element name is provided!\n" ),
                                            uno::Reference< uno::XInterface >(
                                                reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            2 );

    uno::Reference< uno::XInterface > xResult(
                static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, sal_True ) ),
                uno::UNO_QUERY );

    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );

    if ( !xPersist.is() )
        throw uno::RuntimeException(); // TODO: the interface must be supported by own document objects

    xPersist->setPersistentEntry( xStorage,
                                    sEntName,
                                    embed::EntryInitModes::MEDIA_DESCRIPTOR_INIT,
                                    aMediaDescr,
                                    lObjArgs );

    return xResult;
}

//-------------------------------------------------------------------------
uno::Reference< uno::XInterface > SAL_CALL OleEmbeddedObjectFactory::createInstanceUserInit(
            const uno::Sequence< sal_Int8 >& aClassID,
            const ::rtl::OUString& aClassName,
            const uno::Reference< embed::XStorage >& xStorage,
            const ::rtl::OUString& sEntName,
            sal_Int32 /*nEntryConnectionMode*/,
            const uno::Sequence< beans::PropertyValue >& /*lArguments*/,
            const uno::Sequence< beans::PropertyValue >& lObjArgs )
    throw ( lang::IllegalArgumentException,
            io::IOException,
            uno::Exception,
            uno::RuntimeException )
{
    RTL_LOGFILE_CONTEXT( aLog, "embeddedobj (mv76033) OleEmbeddedObjectFactory::createInstanceUserInit" );

    // the initialization is completelly controlled by user
    if ( !xStorage.is() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "No parent storage is provided!\n" ),
                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            1 );

    if ( !sEntName.getLength() )
        throw lang::IllegalArgumentException( ::rtl::OUString::createFromAscii( "Empty element name is provided!\n" ),
                                            uno::Reference< uno::XInterface >( reinterpret_cast< ::cppu::OWeakObject* >(this) ),
                                            2 );

    uno::Reference< uno::XInterface > xResult(
                static_cast< ::cppu::OWeakObject* > ( new OleEmbeddedObject( m_xFactory, aClassID, aClassName ) ),
                uno::UNO_QUERY );

    uno::Reference< embed::XEmbedPersist > xPersist( xResult, uno::UNO_QUERY );
    if ( xPersist.is() )
    {
        xPersist->setPersistentEntry( xStorage,
                                    sEntName,
                                    embed::EntryInitModes::DEFAULT_INIT,
                                    uno::Sequence< beans::PropertyValue >(),
                                    lObjArgs );

    }
    else
        throw uno::RuntimeException(); // TODO:

    return xResult;
}

//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL OleEmbeddedObjectFactory::getImplementationName()
    throw ( uno::RuntimeException )
{
    return impl_staticGetImplementationName();
}

//-------------------------------------------------------------------------
sal_Bool SAL_CALL OleEmbeddedObjectFactory::supportsService( const ::rtl::OUString& ServiceName )
    throw ( uno::RuntimeException )
{
    uno::Sequence< ::rtl::OUString > aSeq = impl_staticGetSupportedServiceNames();

    for ( sal_Int32 nInd = 0; nInd < aSeq.getLength(); nInd++ )
        if ( ServiceName.compareTo( aSeq[nInd] ) == 0 )
            return sal_True;

    return sal_False;
}

//-------------------------------------------------------------------------
uno::Sequence< ::rtl::OUString > SAL_CALL OleEmbeddedObjectFactory::getSupportedServiceNames()
    throw ( uno::RuntimeException )
{
    return impl_staticGetSupportedServiceNames();
}

<|endoftext|>


<commit_before>/*******************************************************************************
 * src/benchmark.cpp
 *
 * Copyright (C) 2017 Florian Kurpicz <florian.kurpicz@tu-dortmund.de>
 *
 * All rights reserved. Published under the BSD-2 license in the LICENSE file.
 ******************************************************************************/

#include <tlx/cmdline_parser.hpp>
#include <vector>

#include "benchmark/algorithm.hpp"
#include "util/alphabet_util.hpp"
#include "util/file_util.hpp"
#include "util/print.hpp"
#include "util/structure_decode.hpp"

#ifdef MALLOC_COUNT
#include "benchmark/malloc_count.h"
#endif // MALLOC_COUNT

#define GUARD_LOOP(x) if (!(x)) { continue; }

auto filter_parallel(bool only_parallel, bool is_parallel) {
  return (!only_parallel || is_parallel);
}

auto filter_sequential(bool sequential, bool is_parallel) {
  return (!sequential || !is_parallel);
}

auto filter_wavelet_type(bool is_tree, bool no_trees, bool no_matrices) {
  return (is_tree ? !no_trees : !no_matrices);
}

int32_t main(int32_t argc, char const* argv[]) {
  std::vector<std::string> file_paths;
  std::string filter = "";
  unsigned int word_width = 1;
  unsigned int nr_runs = 5;
  bool list_algorithms_only = false;
  bool run_only_parallel = false;
  bool run_only_sequential = false;
  bool run_only_huffman = false;
  bool no_trees = false;
  bool no_matrices = false;
  bool memory = false;
  bool check = false;
  bool debug_print = false;

  tlx::CmdlineParser cp;

  cp.set_description("Parallel Wavelet Tree and Wavelet Matrix Construction");
  cp.set_author("Florian Kurpicz <florian.kurpicz@tu-dortmund.de>\n"
    "        Marvin Löbel <loebel.marvin@gmail.com>");

  cp.add_stringlist('f', "file", file_paths, "Path(s) to the text file(s).");
  cp.add_string('n', "name", filter,
        "Runs all algorithms that contain the <name> in their name");
  cp.add_uint('b', "byte", word_width, "Bytes per char in the input text.");
  cp.add_uint('r', "runs", nr_runs,
    "Number of repetitions of the construction algorithm.");
  cp.add_flag('l', "list", list_algorithms_only,
    "Print the name and description of all registered algorithms");

  cp.add_flag('p', "parallel", run_only_parallel,
    "Run only parallel construction algorithms.");
  cp.add_flag('s', "sequential", run_only_sequential,
    "Run only sequential construction algorithms.");
  cp.add_flag('h', "huffman", run_only_huffman,
    "Run only huffman-shaped construction algorithms.");
  cp.add_flag('\0', "no_trees", no_trees,
    "Skip all wavelet trees construction algorithms.");
  cp.add_flag('\0', "no_matrices", no_matrices,
    "Skip all wavelet matrices construction algorithms.");

  cp.add_flag('\0', "memory", memory,
    "Compute peak memory during construction.");
  cp.add_flag('c', "check", check,
    "Check the constructed wavelet structure for validity.");
  cp.add_flag('d', "debug_print", debug_print,
    "Output the bit vectors in a human readable format to stdout.");

  if (!cp.process(argc, argv)) {
    return -1;
  }

  int returncode = 0;

  auto& algo_list = algorithm_list::get_algorithm_list();
  if (list_algorithms_only) {
    for (const auto& a : algo_list) {
      a->print_info();
    }
    return 0;
  }

  for (const auto& path : file_paths) {
    std::cout << std::endl << "Text: " << path << std::endl;
    void* txt_prt = nullptr;
    uint64_t text_size = 0;
    uint64_t max_char = 0;
    uint64_t levels = 0;
    std::vector<uint8_t> text_uint8;
    std::vector<uint16_t> text_uint16;
    std::vector<uint32_t> text_uint32;
    std::vector<uint64_t> text_uint64;
#ifdef MALLOC_COUNT
    malloc_count_reset_peak();
#endif
    if (word_width == 1) {
      text_uint8 = file_to_vector<1>(path);
      text_size = text_uint8.size();
      max_char = reduce_alphabet(text_uint8);
      levels = levels_for_max_char(max_char);
      txt_prt = &text_uint8;
    } else if (word_width == 2) {
      text_uint16 = file_to_vector<2>(path);
      text_size = text_uint16.size();
      max_char = reduce_alphabet(text_uint16);
      levels = levels_for_max_char(max_char);
      txt_prt = &text_uint16;
    } else if (word_width == 4) {
      text_uint32 = file_to_vector<4>(path);
      text_size = text_uint32.size();
      max_char = reduce_alphabet(text_uint32);
      levels = levels_for_max_char(max_char);
      txt_prt = &text_uint32;
    } else if (word_width == 8) {
      text_uint64 = file_to_vector<8>(path);
      text_size = text_uint64.size();
      max_char = reduce_alphabet(text_uint64);
      levels = levels_for_max_char(max_char);
      txt_prt = &text_uint64;
    } else {
      std::cerr << "You entered an invalid number of bytes per character "
                   "(parameter 'b')." << std::endl;
      return -1;
    }
    std::cout << "Characters: " << text_size << std::endl;
#ifdef MALLOC_COUNT
    if (memory) {
      std::cout << "Memory peak text: " << malloc_count_peak() << " B, "
                << malloc_count_peak() / (1024 * 1024) << " MiB" << std::endl;
    }
#endif // MALLOC_COUNT
    for (const auto& a : algo_list) {
      GUARD_LOOP(filter == "" || (a->name().find(filter) != std::string::npos));
      GUARD_LOOP(a->word_width() == word_width);
      GUARD_LOOP(filter_parallel(run_only_parallel, a->is_parallel()));
      GUARD_LOOP(filter_sequential(run_only_sequential, a->is_parallel()));
      GUARD_LOOP(filter_wavelet_type(a->is_tree(), no_trees, no_matrices));
      GUARD_LOOP((!run_only_huffman) || a->is_huffman_shaped());

      std::cout << "RESULT " << "algo=" << a->name() << ' ';
      if (memory) {
#ifdef MALLOC_COUNT
        malloc_count_reset_peak();
        a->memory_peak(txt_prt, text_size, levels);
        std::cout << "memory=" << malloc_count_peak() << ' ';
#else
        std::cout << "Memory measurement is NOT enabled."
                  << std::endl;
#endif // MALLOC_COUNT
      }
      std::cout << "runs=" << nr_runs << " ";
      if (nr_runs > 0) {
        std::cout << "median_time=" << a->median_time(
          txt_prt, text_size, levels, nr_runs) << ' ';
      }
      std::cout << "input=" << path << ' '
                << "characters=" << text_size << ' '
                << "word_width=" << word_width << std::endl;

      if (debug_print || check) {
        auto structure =
          a->compute_bitvector(txt_prt, text_size, levels);
        if (debug_print) {
          print_structure(std::cout, structure, true);
        }
        if (check) {
          if (word_width != 1) {
            std::cout << "WARNING:"
                      << " Can only check texts over 1-byte alphabets\n";
          } else {
            construction_algorithm const* naive = nullptr;
            if ((a->is_tree()) && !(a->is_huffman_shaped())) {
              naive = algo_list.filtered([](auto e) {
                return e->name() == "wt_naive";
              }).at(0);
            }
            if (!(a->is_tree()) && !(a->is_huffman_shaped())) {
              naive = algo_list.filtered([](auto e) {
                return e->name() == "wm_naive";
              }).at(0);
            }
            if ((a->is_tree()) && (a->is_huffman_shaped())) {
              naive = algo_list.filtered([](auto e) {
                return e->name() == "huff_wt_naive";
              }).at(0);
            }
            if (!(a->is_tree()) && (a->is_huffman_shaped())) {
              naive = algo_list.filtered([](auto e) {
                return e->name() == "huff_wm_naive";
              }).at(0);
            }
            assert(naive != nullptr);
            auto naive_wx =
            naive->compute_bitvector(txt_prt, text_size, levels);
            bool err_trigger = false;
            auto check_err = [&](bool cond, auto const& msg) {
              if (!cond) {
                std::cout << "ERROR: " << msg << std::endl;
                err_trigger = true;
              }
              return cond;
            };

            if (check_err(structure.levels() == naive_wx.levels(),
                          "structures have different level sizes")) {
              if (!a->is_tree()) {
                size_t sl = structure.levels();
                check_err(structure.zeros().size() == sl,
                          "structure zeros too short");
                if (sl > 0) {
                  auto sz = structure.zeros();
                  auto nz = naive_wx.zeros();
                  sz.pop_back();
                  nz.pop_back();
                  check_err(sz == nz, "zeros arrays differ");
                }
              }
              auto& sbvs = structure.bvs();
              auto& nbvs = naive_wx.bvs();
              for (size_t l = 0; l < structure.levels(); l++) {
                auto sbs = sbvs.level_bit_size(l);
                auto nbs = nbvs.level_bit_size(l);
                if(check_err(sbs == nbs,
                             std::string("bit size differs on level ")
                             + std::to_string(l))) {
                  for (uint64_t bi = 0; bi < sbs; bi++) {
                    if(!check_err(
                      bit_at(sbvs[l], bi) == bit_at(nbvs[l], bi),
                       std::string("bit ")
                       + std::to_string(bi)
                       + " differs on level "
                       + std::to_string(l))) {
                      break;
                    }
                  }
                }
              }
            }
            if (err_trigger) {
              returncode = -2;
            } else {
              std::cout << "Output structurally OK" << std::endl;
            }

            if (err_trigger) {
              if (!debug_print) {
                std::cout << "Output:\n";
                print_structure(std::cout, structure, true);
              }
              std::cout << "Naive result as comparison:\n";
              print_structure(std::cout, naive_wx, true);
            }

            auto pvec = [](auto const& v) {
              std::cout << "[";
              for (auto e : v) {
                  std::cout << uint64_t(e) << ", ";
              }
              std::cout << "]\n";
            };

            std::string decoded_ = decode_structure(structure);
            std::vector<uint8_t> decoded(decoded_.begin(), decoded_.end());
            if (std::equal(text_uint8.begin(), text_uint8.end(),
                           decoded.begin(), decoded.end())) {
              std::cout << "Output decoded OK" << std::endl;
            } else {
              std::cout << "ERROR:"
                        << "Decoded output not equal to input!"
                        << std::endl;
              std::cout << "Input:" << std::endl;
              pvec(text_uint8);
              std::cout << "Decoded:" << std::endl;
              pvec(decoded);
            }
          }
          std::cout << std::endl;
        }
      }
    }
  }
  return returncode;
}

/******************************************************************************/
<commit_msg>Fix naming in benchmark.cpp<commit_after>/*******************************************************************************
 * src/benchmark.cpp
 *
 * Copyright (C) 2017 Florian Kurpicz <florian.kurpicz@tu-dortmund.de>
 *
 * All rights reserved. Published under the BSD-2 license in the LICENSE file.
 ******************************************************************************/

#include <tlx/cmdline_parser.hpp>
#include <vector>

#include "benchmark/algorithm.hpp"
#include "util/alphabet_util.hpp"
#include "util/file_util.hpp"
#include "util/print.hpp"
#include "util/structure_decode.hpp"

#ifdef MALLOC_COUNT
#include "benchmark/malloc_count.h"
#endif // MALLOC_COUNT

#define GUARD_LOOP(x) if (!(x)) { continue; }

auto filter_parallel(bool only_parallel, bool is_parallel) {
  return (!only_parallel || is_parallel);
}

auto filter_sequential(bool sequential, bool is_parallel) {
  return (!sequential || !is_parallel);
}

auto filter_wavelet_type(bool is_tree, bool no_trees, bool no_matrices) {
  return (is_tree ? !no_trees : !no_matrices);
}

int32_t main(int32_t argc, char const* argv[]) {
  std::vector<std::string> file_paths;
  std::string filter = "";
  unsigned int word_width = 1;
  unsigned int nr_runs = 5;
  bool list_algorithms_only = false;
  bool run_only_parallel = false;
  bool run_only_sequential = false;
  bool run_only_huffman = false;
  bool no_trees = false;
  bool no_matrices = false;
  bool memory = false;
  bool check = false;
  bool debug_print = false;

  tlx::CmdlineParser cp;

  cp.set_description("Parallel Wavelet Tree and Wavelet Matrix Construction");
  cp.set_author("Florian Kurpicz <florian.kurpicz@tu-dortmund.de>\n"
    "        Marvin Löbel <loebel.marvin@gmail.com>");

  cp.add_stringlist('f', "file", file_paths, "Path(s) to the text file(s).");
  cp.add_string('n', "name", filter,
        "Runs all algorithms that contain the <name> in their name");
  cp.add_uint('b', "byte", word_width, "Bytes per char in the input text.");
  cp.add_uint('r', "runs", nr_runs,
    "Number of repetitions of the construction algorithm.");
  cp.add_flag('l', "list", list_algorithms_only,
    "Print the name and description of all registered algorithms");

  cp.add_flag('p', "parallel", run_only_parallel,
    "Run only parallel construction algorithms.");
  cp.add_flag('s', "sequential", run_only_sequential,
    "Run only sequential construction algorithms.");
  cp.add_flag('h', "huffman", run_only_huffman,
    "Run only huffman-shaped construction algorithms.");
  cp.add_flag('\0', "no_trees", no_trees,
    "Skip all wavelet trees construction algorithms.");
  cp.add_flag('\0', "no_matrices", no_matrices,
    "Skip all wavelet matrices construction algorithms.");

  cp.add_flag('\0', "memory", memory,
    "Compute peak memory during construction.");
  cp.add_flag('c', "check", check,
    "Check the constructed wavelet structure for validity.");
  cp.add_flag('d', "debug_print", debug_print,
    "Output the bit vectors in a human readable format to stdout.");

  if (!cp.process(argc, argv)) {
    return -1;
  }

  int returncode = 0;

  auto& algo_list = algorithm_list::get_algorithm_list();
  if (list_algorithms_only) {
    for (const auto& a : algo_list) {
      a->print_info();
    }
    return 0;
  }

  for (const auto& path : file_paths) {
    std::cout << std::endl << "Text: " << path << std::endl;
    void* txt_prt = nullptr;
    uint64_t text_size = 0;
    uint64_t max_char = 0;
    uint64_t levels = 0;
    std::vector<uint8_t> text_uint8;
    std::vector<uint16_t> text_uint16;
    std::vector<uint32_t> text_uint32;
    std::vector<uint64_t> text_uint64;
#ifdef MALLOC_COUNT
    malloc_count_reset_peak();
#endif
    if (word_width == 1) {
      text_uint8 = file_to_vector<1>(path);
      text_size = text_uint8.size();
      max_char = reduce_alphabet(text_uint8);
      levels = levels_for_max_char(max_char);
      txt_prt = &text_uint8;
    } else if (word_width == 2) {
      text_uint16 = file_to_vector<2>(path);
      text_size = text_uint16.size();
      max_char = reduce_alphabet(text_uint16);
      levels = levels_for_max_char(max_char);
      txt_prt = &text_uint16;
    } else if (word_width == 4) {
      text_uint32 = file_to_vector<4>(path);
      text_size = text_uint32.size();
      max_char = reduce_alphabet(text_uint32);
      levels = levels_for_max_char(max_char);
      txt_prt = &text_uint32;
    } else if (word_width == 8) {
      text_uint64 = file_to_vector<8>(path);
      text_size = text_uint64.size();
      max_char = reduce_alphabet(text_uint64);
      levels = levels_for_max_char(max_char);
      txt_prt = &text_uint64;
    } else {
      std::cerr << "You entered an invalid number of bytes per character "
                   "(parameter 'b')." << std::endl;
      return -1;
    }
    std::cout << "Characters: " << text_size << std::endl;
#ifdef MALLOC_COUNT
    if (memory) {
      std::cout << "Memory peak text: " << malloc_count_peak() << " B, "
                << malloc_count_peak() / (1024 * 1024) << " MiB" << std::endl;
    }
#endif // MALLOC_COUNT
    for (const auto& a : algo_list) {
      GUARD_LOOP(filter == "" || (a->name().find(filter) != std::string::npos));
      GUARD_LOOP(a->word_width() == word_width);
      GUARD_LOOP(filter_parallel(run_only_parallel, a->is_parallel()));
      GUARD_LOOP(filter_sequential(run_only_sequential, a->is_parallel()));
      GUARD_LOOP(filter_wavelet_type(a->is_tree(), no_trees, no_matrices));
      GUARD_LOOP((!run_only_huffman) || a->is_huffman_shaped());

      std::cout << "RESULT " << "algo=" << a->name() << ' ';
      if (memory) {
#ifdef MALLOC_COUNT
        malloc_count_reset_peak();
        a->memory_peak(txt_prt, text_size, levels);
        std::cout << "memory=" << malloc_count_peak() << ' ';
#else
        std::cout << "Memory measurement is NOT enabled."
                  << std::endl;
#endif // MALLOC_COUNT
      }
      std::cout << "runs=" << nr_runs << " ";
      if (nr_runs > 0) {
        std::cout << "median_time=" << a->median_time(
          txt_prt, text_size, levels, nr_runs) << ' ';
      }
      std::cout << "input=" << path << ' '
                << "characters=" << text_size << ' '
                << "word_width=" << word_width << std::endl;

      if (debug_print || check) {
        auto structure =
          a->compute_bitvector(txt_prt, text_size, levels);
        if (debug_print) {
          print_structure(std::cout, structure, true);
        }
        if (check) {
          if (word_width != 1) {
            std::cout << "WARNING:"
                      << " Can only check texts over 1-byte alphabets\n";
          } else {
            construction_algorithm const* naive = nullptr;
            if ((a->is_tree()) && !(a->is_huffman_shaped())) {
              naive = algo_list.filtered([](auto e) {
                return e->name() == "wt_naive";
              }).at(0);
            }
            if (!(a->is_tree()) && !(a->is_huffman_shaped())) {
              naive = algo_list.filtered([](auto e) {
                return e->name() == "wm_naive";
              }).at(0);
            }
            if ((a->is_tree()) && (a->is_huffman_shaped())) {
              naive = algo_list.filtered([](auto e) {
                return e->name() == "wt_huff_naive";
              }).at(0);
            }
            if (!(a->is_tree()) && (a->is_huffman_shaped())) {
              naive = algo_list.filtered([](auto e) {
                return e->name() == "wm_huff_naive";
              }).at(0);
            }
            assert(naive != nullptr);
            auto naive_wx =
            naive->compute_bitvector(txt_prt, text_size, levels);
            bool err_trigger = false;
            auto check_err = [&](bool cond, auto const& msg) {
              if (!cond) {
                std::cout << "ERROR: " << msg << std::endl;
                err_trigger = true;
              }
              return cond;
            };

            if (check_err(structure.levels() == naive_wx.levels(),
                          "structures have different level sizes")) {
              if (!a->is_tree()) {
                size_t sl = structure.levels();
                check_err(structure.zeros().size() == sl,
                          "structure zeros too short");
                if (sl > 0) {
                  auto sz = structure.zeros();
                  auto nz = naive_wx.zeros();
                  sz.pop_back();
                  nz.pop_back();
                  check_err(sz == nz, "zeros arrays differ");
                }
              }
              auto& sbvs = structure.bvs();
              auto& nbvs = naive_wx.bvs();
              for (size_t l = 0; l < structure.levels(); l++) {
                auto sbs = sbvs.level_bit_size(l);
                auto nbs = nbvs.level_bit_size(l);
                if(check_err(sbs == nbs,
                             std::string("bit size differs on level ")
                             + std::to_string(l))) {
                  for (uint64_t bi = 0; bi < sbs; bi++) {
                    if(!check_err(
                      bit_at(sbvs[l], bi) == bit_at(nbvs[l], bi),
                       std::string("bit ")
                       + std::to_string(bi)
                       + " differs on level "
                       + std::to_string(l))) {
                      break;
                    }
                  }
                }
              }
            }
            if (err_trigger) {
              returncode = -2;
            } else {
              std::cout << "Output structurally OK" << std::endl;
            }

            if (err_trigger) {
              if (!debug_print) {
                std::cout << "Output:\n";
                print_structure(std::cout, structure, true);
              }
              std::cout << "Naive result as comparison:\n";
              print_structure(std::cout, naive_wx, true);
            }

            auto pvec = [](auto const& v) {
              std::cout << "[";
              for (auto e : v) {
                  std::cout << uint64_t(e) << ", ";
              }
              std::cout << "]\n";
            };

            std::string decoded_ = decode_structure(structure);
            std::vector<uint8_t> decoded(decoded_.begin(), decoded_.end());
            if (std::equal(text_uint8.begin(), text_uint8.end(),
                           decoded.begin(), decoded.end())) {
              std::cout << "Output decoded OK" << std::endl;
            } else {
              std::cout << "ERROR:"
                        << "Decoded output not equal to input!"
                        << std::endl;
              std::cout << "Input:" << std::endl;
              pvec(text_uint8);
              std::cout << "Decoded:" << std::endl;
              pvec(decoded);
            }
          }
          std::cout << std::endl;
        }
      }
    }
  }
  return returncode;
}

/******************************************************************************/
<|endoftext|>