<commit_before>
#include "quickviewsurfacefactory.h"

#include <maliit/plugins/abstractsurface.h>
#include <maliit/plugins/quickviewsurface.h>

#include <QtGui>
#include <QtQuick>

using Maliit::Plugins::AbstractSurface;

namespace Maliit {
namespace Server {

class QuickViewSurfaceImpl : public Maliit::Plugins::QuickViewSurface {
public:
    QuickViewSurfaceImpl(QuickViewSurfaceFactory *factory, AbstractSurface::Options options, const QSharedPointer<QuickViewSurfaceImpl> &parent)
        : QuickViewSurface(),
          mFactory(factory),
          mOptions(options),
          mParent(parent),
          mActive(false),
          mVisible(false),
          mRelativePosition(),
          mWindow()
    {
        QWindow *parentWindow = 0;
        if (parent) {
            parentWindow = parent->mWindow.data();
        }
        mWindow.reset(new QQuickView(parentWindow));

        mWindow->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint | Qt::WindowDoesNotAcceptFocus);

        QSurfaceFormat format;
        format.setAlphaBufferSize(8);
        mWindow->setFormat(format);
        mWindow->setColor(QColor(Qt::transparent));

        updateVisibility();
    }

    ~QuickViewSurfaceImpl()
    {
    }

    void show()
    {
        mVisible = true;
        updateVisibility();
    }

    void hide()
    {
        mVisible = false;
        updateVisibility();
    }

    QSize size() const
    {
        return mWindow->size();
    }

    void setSize(const QSize &size)
    {
        const QSize& desktopSize = QGuiApplication::screens().first()->size();

        // stand-alone Maliit server
         if (mOptions & PositionCenterBottom) {
             mWindow->setGeometry(QRect(QPoint((desktopSize.width() - size.width()) / 2, desktopSize.height() - size.height()), size));
         } else {
             mWindow->resize(size);
         }
    }

    QPoint relativePosition() const
    {
        return mRelativePosition;
    }

    void setRelativePosition(const QPoint &position)
    {
        mRelativePosition = position;
        QPoint parentPosition(0, 0);
        if (mParent) {
            parentPosition = mParent->mWindow->position();
        }
        mWindow->setPos(parentPosition + mRelativePosition);
    }

    QSharedPointer<AbstractSurface> parent() const
    {
        return mParent;
    }

    QPoint translateEventPosition(const QPoint &eventPosition, const QSharedPointer<AbstractSurface> &eventSurface = QSharedPointer<AbstractSurface>()) const
    {
        if (!eventSurface)
            return eventPosition;

        QSharedPointer<QuickViewSurfaceImpl> windowedSurface = qSharedPointerDynamicCast<QuickViewSurfaceImpl>(eventSurface);
        if (!windowedSurface)
            return QPoint();

        return -mWindow->position() + eventPosition + windowedSurface->mWindow->position();
    }

    void setActive(bool active)
    {
        mActive = active;
        updateVisibility();
    }

    QRegion inputMethodArea()
    {
        if (!mWindow->isVisible())
            return QRegion();

        return QRegion(mWindow->geometry());
    }

    QQuickView *view() const
    {
        return mWindow.data();
    }

private:
    void updateVisibility()
    {
        mWindow->setVisible(mActive && mVisible);
    }

    QuickViewSurfaceFactory *mFactory;
    AbstractSurface::Options mOptions;
    QSharedPointer<QuickViewSurfaceImpl> mParent;
    bool mActive;
    bool mVisible;
    QPoint mRelativePosition;
    QScopedPointer<QQuickView> mWindow;
};

QuickViewSurfaceFactory::QuickViewSurfaceFactory()
{
}

QuickViewSurfaceFactory::~QuickViewSurfaceFactory()
{
}

QSize QuickViewSurfaceFactory::screenSize() const
{
    return QGuiApplication::screens().first()->size();
}

bool QuickViewSurfaceFactory::supported(Maliit::Plugins::AbstractSurface::Options options) const
{
    return options & Maliit::Plugins::AbstractSurface::TypeQuick2;
}

QSharedPointer<Maliit::Plugins::AbstractSurface> QuickViewSurfaceFactory::create(Maliit::Plugins::AbstractSurface::Options options, const QSharedPointer<Maliit::Plugins::AbstractSurface> &parent)
{
    QSharedPointer<QuickViewSurfaceImpl> defaultSurfaceParent(qSharedPointerDynamicCast<QuickViewSurfaceImpl>(parent));
    if (options & Maliit::Plugins::AbstractSurface::TypeQuick2) {
        QSharedPointer<QuickViewSurfaceImpl> newSurface(new QuickViewSurfaceImpl(this, options, defaultSurfaceParent));
        surfaces.push_back(newSurface);
        return newSurface;
    }
    return QSharedPointer<AbstractSurface>();
}

void QuickViewSurfaceFactory::activate()
{
    mActive = true;

    Q_FOREACH(QWeakPointer<QuickViewSurfaceImpl> weakSurface, surfaces) {
        QSharedPointer<QuickViewSurfaceImpl> surface = weakSurface.toStrongRef();
        if (surface)
            surface->setActive(true);
    }
}

void QuickViewSurfaceFactory::deactivate()
{
    mActive = false;

    Q_FOREACH(QWeakPointer<QuickViewSurfaceImpl> weakSurface, surfaces) {
        QSharedPointer<QuickViewSurfaceImpl> surface = weakSurface.toStrongRef();
        if (surface)
            surface->setActive(false);
    }
}

} // namespace Server
} // namespace Maliit
<commit_msg>Adapt to changed Qt5 method names<commit_after>
#include "quickviewsurfacefactory.h"

#include <maliit/plugins/abstractsurface.h>
#include <maliit/plugins/quickviewsurface.h>

#include <QtGui>
#include <QtQuick>

using Maliit::Plugins::AbstractSurface;

namespace Maliit {
namespace Server {

class QuickViewSurfaceImpl : public Maliit::Plugins::QuickViewSurface {
public:
    QuickViewSurfaceImpl(QuickViewSurfaceFactory *factory, AbstractSurface::Options options, const QSharedPointer<QuickViewSurfaceImpl> &parent)
        : QuickViewSurface(),
          mFactory(factory),
          mOptions(options),
          mParent(parent),
          mActive(false),
          mVisible(false),
          mRelativePosition(),
          mWindow()
    {
        QWindow *parentWindow = 0;
        if (parent) {
            parentWindow = parent->mWindow.data();
        }
        mWindow.reset(new QQuickView(parentWindow));

        mWindow->setFlags(Qt::Dialog | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint
                          | Qt::X11BypassWindowManagerHint | Qt::WindowDoesNotAcceptFocus);

        QSurfaceFormat format;
        format.setAlphaBufferSize(8);
        mWindow->setFormat(format);
        mWindow->setColor(QColor(Qt::transparent));

        updateVisibility();
    }

    ~QuickViewSurfaceImpl()
    {
    }

    void show()
    {
        mVisible = true;
        updateVisibility();
    }

    void hide()
    {
        mVisible = false;
        updateVisibility();
    }

    QSize size() const
    {
        return mWindow->size();
    }

    void setSize(const QSize &size)
    {
        const QSize& desktopSize = QGuiApplication::screens().first()->size();

        // stand-alone Maliit server
         if (mOptions & PositionCenterBottom) {
             mWindow->setGeometry(QRect(QPoint((desktopSize.width() - size.width()) / 2, desktopSize.height() - size.height()), size));
         } else {
             mWindow->resize(size);
         }
    }

    QPoint relativePosition() const
    {
        return mRelativePosition;
    }

    void setRelativePosition(const QPoint &position)
    {
        mRelativePosition = position;
        QPoint parentPosition(0, 0);
        if (mParent) {
            parentPosition = mParent->mWindow->position();
        }
        mWindow->setPosition(parentPosition + mRelativePosition);
    }

    QSharedPointer<AbstractSurface> parent() const
    {
        return mParent;
    }

    QPoint translateEventPosition(const QPoint &eventPosition, const QSharedPointer<AbstractSurface> &eventSurface = QSharedPointer<AbstractSurface>()) const
    {
        if (!eventSurface)
            return eventPosition;

        QSharedPointer<QuickViewSurfaceImpl> windowedSurface = qSharedPointerDynamicCast<QuickViewSurfaceImpl>(eventSurface);
        if (!windowedSurface)
            return QPoint();

        return -mWindow->position() + eventPosition + windowedSurface->mWindow->position();
    }

    void setActive(bool active)
    {
        mActive = active;
        updateVisibility();
    }

    QRegion inputMethodArea()
    {
        if (!mWindow->isVisible())
            return QRegion();

        return QRegion(mWindow->geometry());
    }

    QQuickView *view() const
    {
        return mWindow.data();
    }

private:
    void updateVisibility()
    {
        mWindow->setVisible(mActive && mVisible);
    }

    QuickViewSurfaceFactory *mFactory;
    AbstractSurface::Options mOptions;
    QSharedPointer<QuickViewSurfaceImpl> mParent;
    bool mActive;
    bool mVisible;
    QPoint mRelativePosition;
    QScopedPointer<QQuickView> mWindow;
};

QuickViewSurfaceFactory::QuickViewSurfaceFactory()
{
}

QuickViewSurfaceFactory::~QuickViewSurfaceFactory()
{
}

QSize QuickViewSurfaceFactory::screenSize() const
{
    return QGuiApplication::screens().first()->size();
}

bool QuickViewSurfaceFactory::supported(Maliit::Plugins::AbstractSurface::Options options) const
{
    return options & Maliit::Plugins::AbstractSurface::TypeQuick2;
}

QSharedPointer<Maliit::Plugins::AbstractSurface> QuickViewSurfaceFactory::create(Maliit::Plugins::AbstractSurface::Options options, const QSharedPointer<Maliit::Plugins::AbstractSurface> &parent)
{
    QSharedPointer<QuickViewSurfaceImpl> defaultSurfaceParent(qSharedPointerDynamicCast<QuickViewSurfaceImpl>(parent));
    if (options & Maliit::Plugins::AbstractSurface::TypeQuick2) {
        QSharedPointer<QuickViewSurfaceImpl> newSurface(new QuickViewSurfaceImpl(this, options, defaultSurfaceParent));
        surfaces.push_back(newSurface);
        return newSurface;
    }
    return QSharedPointer<AbstractSurface>();
}

void QuickViewSurfaceFactory::activate()
{
    mActive = true;

    Q_FOREACH(QWeakPointer<QuickViewSurfaceImpl> weakSurface, surfaces) {
        QSharedPointer<QuickViewSurfaceImpl> surface = weakSurface.toStrongRef();
        if (surface)
            surface->setActive(true);
    }
}

void QuickViewSurfaceFactory::deactivate()
{
    mActive = false;

    Q_FOREACH(QWeakPointer<QuickViewSurfaceImpl> weakSurface, surfaces) {
        QSharedPointer<QuickViewSurfaceImpl> surface = weakSurface.toStrongRef();
        if (surface)
            surface->setActive(false);
    }
}

} // namespace Server
} // namespace Maliit
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS ooo20040329 (1.9.70); FILE MERGED 2004/03/17 11:39:43 waratah 1.9.70.1: #i1858# remove unused variable from code<commit_after><|endoftext|>


<commit_before><commit_msg>Revert "Revert "perfetto: reenable integration tests on tree Android build""<commit_after><|endoftext|>


<commit_before>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

#include "grins_config.h"

// GRINS
#include "grins/mesh_builder.h"
#include "grins/simulation.h"
#include "grins/simulation_builder.h"
#include "grins/multiphysics_sys.h"

//libMesh
#include "libmesh/exact_solution.h"

void test_error_norm( libMesh::ExactSolution& exact_sol,
                      const std::string& system_name,
                      const std::string& var,
                      const std::string& norm,
                      const double tol,
                      int& return_flag );

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

  if( !command_line.search("--input") )
    {
      std::cerr << "ERROR: Must specify input file on command line with --input=<file>." << std::endl;
      exit(1);
    }

  if( !command_line.search("--soln-data") )
    {
      std::cerr << "ERROR: Must specify solution data on command line with --soln-data=<file>." << std::endl;
      exit(1);
    }

  if( !command_line.search("--vars") )
    {
      std::cerr << "ERROR: Must specify variables on command line with --vars='var1 var2'" << std::endl;
      exit(1);
    }

  if( !command_line.search("--norms") )
    {
      std::cerr << "ERROR: Must specify variables on command line with --norms='L2 H1'" << std::endl;
      exit(1);
    }

  // libMesh input file should be first argument
  std::string libMesh_input_filename = command_line("--input", "DIE!");

  // Create our GetPot object.
  GetPot libMesh_inputfile( libMesh_input_filename );

  // Initialize libMesh library.
  libMesh::LibMeshInit libmesh_init(argc, argv);

  GRINS::SimulationBuilder sim_builder;

  GRINS::Simulation grins( libMesh_inputfile,
			   sim_builder,
                           libmesh_init.comm() );

  // Do solve here
  grins.run();

  // Get equation systems to create ExactSolution object
  std::tr1::shared_ptr<libMesh::EquationSystems> es = grins.get_equation_system();

   // Create Exact solution object and attach exact solution quantities
  libMesh::ExactSolution exact_sol(*es);

  libMesh::EquationSystems es_ref( es->get_mesh() );

  // Filename of file where comparison solution is stashed
  std::string solution_file = command_line("--soln-data", "DIE!");
  es_ref.read( solution_file );

  exact_sol.attach_reference_solution( &es_ref );

  // Now grab the variables for which we want to compare
  unsigned int n_vars = command_line.vector_variable_size("--vars");
  std::vector<std::string> vars(n_vars);
  for( unsigned int v = 0; v < n_vars; v++ )
    {
      vars[v] = command_line("--vars", "DIE!", v);
    }

  // Now grab the norms to compute for each variable error
  unsigned int n_norms = command_line.vector_variable_size("--norms");
  std::vector<std::string> norms(n_norms);
  for( unsigned int n = 0; n < n_norms; n++ )
    {
      norms[n] = command_line("--norms", "DIE!", n);
      if( norms[n] != std::string("L2") &&
          norms[n] != std::string("H1") )
        {
          std::cerr << "ERROR: Invalid norm input " << norms[n] << std::endl
                    << "       Valid values are: L2" << std::endl
                    << "                         H1" << std::endl;
        }
    }

  const std::string& system_name = grins.get_multiphysics_system_name();

  // Now compute error for each variable
  for( unsigned int v = 0; v < n_vars; v++ )
    {
      exact_sol.compute_error(system_name, vars[v]);
    }

  int return_flag = 0;

  double tol = 1.0e-10;

  // Now test error for each variable, for each norm
  for( unsigned int v = 0; v < n_vars; v++ )
    {
      for( unsigned int n = 0; n < n_norms; n++ )
        {
          test_error_norm( exact_sol, system_name, vars[v], norms[n], tol, return_flag );
        }
    }

  return return_flag;
}

void test_error_norm( libMesh::ExactSolution& exact_sol,
                      const std::string& system_name,
                      const std::string& var,
                      const std::string& norm,
                      const double tol,
                      int& return_flag )
{
  // We don't set return_flag unless we are setting it 1
  // since this function gets called multiple times and we don't
  // want to overwrite a previous "fail" (return_flag = 1) with
  // a "pass" (return_flag = 0)

  double error = 0.0;

  if( norm == std::string("L2") )
    {
      error = exact_sol.l2_error(system_name, var);
    }
  else if( norm == std::string("H1") )
    {
      error = exact_sol.h1_error(system_name, var);
    }
  else
    {
      std::cerr << "ERROR: Invalid norm " << norm << std::endl;
      exit(1);
    }

  if( error > tol )
    {
      return_flag = 1;

      std::cerr << "Tolerance exceeded for generic regression test!" << std::endl
                << "tolerance     = " << tol << std::endl
                << "norm of error = " << error << std::endl
                << "norm type     = " << norm << std::endl
                << "var           = " << var << std::endl;
    }

  return;
}
<commit_msg>--option is an "option", not a variable.<commit_after>//-----------------------------------------------------------------------bl-
//--------------------------------------------------------------------------
//
// GRINS - General Reacting Incompressible Navier-Stokes
//
// Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner
// Copyright (C) 2010-2013 The PECOS Development Team
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the Version 2.1 GNU Lesser General
// Public License 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. 51 Franklin Street, Fifth Floor,
// Boston, MA  02110-1301  USA
//
//-----------------------------------------------------------------------el-

#include "grins_config.h"

// GRINS
#include "grins/mesh_builder.h"
#include "grins/simulation.h"
#include "grins/simulation_builder.h"
#include "grins/multiphysics_sys.h"

//libMesh
#include "libmesh/exact_solution.h"

void test_error_norm( libMesh::ExactSolution& exact_sol,
                      const std::string& system_name,
                      const std::string& var,
                      const std::string& norm,
                      const double tol,
                      int& return_flag );

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

  if( !command_line.have_variable("input") )
    {
      std::cerr << "ERROR: Must specify input file on command line with input=<file>." << std::endl;
      exit(1);
    }

  if( !command_line.have_variable("soln-data") )
    {
      std::cerr << "ERROR: Must specify solution data on command line with soln-data=<file>." << std::endl;
      exit(1);
    }

  if( !command_line.have_variable("vars") )
    {
      std::cerr << "ERROR: Must specify variables on command line with vars='var1 var2'" << std::endl;
      exit(1);
    }

  if( !command_line.have_variable("norms") )
    {
      std::cerr << "ERROR: Must specify variables on command line with norms='L2 H1'" << std::endl;
      exit(1);
    }

  // libMesh input file should be first argument
  std::string libMesh_input_filename = command_line("input", "DIE!");

  // Create our GetPot object.
  GetPot libMesh_inputfile( libMesh_input_filename );

  // Initialize libMesh library.
  libMesh::LibMeshInit libmesh_init(argc, argv);

  GRINS::SimulationBuilder sim_builder;

  GRINS::Simulation grins( libMesh_inputfile,
			   sim_builder,
                           libmesh_init.comm() );

  // Do solve here
  grins.run();

  // Get equation systems to create ExactSolution object
  std::tr1::shared_ptr<libMesh::EquationSystems> es = grins.get_equation_system();

   // Create Exact solution object and attach exact solution quantities
  libMesh::ExactSolution exact_sol(*es);

  libMesh::EquationSystems es_ref( es->get_mesh() );

  // Filename of file where comparison solution is stashed
  std::string solution_file = command_line("soln-data", "DIE!");
  es_ref.read( solution_file );

  exact_sol.attach_reference_solution( &es_ref );

  // Now grab the variables for which we want to compare
  unsigned int n_vars = command_line.vector_variable_size("vars");
  std::vector<std::string> vars(n_vars);
  for( unsigned int v = 0; v < n_vars; v++ )
    {
      vars[v] = command_line("vars", "DIE!", v);
    }

  // Now grab the norms to compute for each variable error
  unsigned int n_norms = command_line.vector_variable_size("norms");
  std::vector<std::string> norms(n_norms);
  for( unsigned int n = 0; n < n_norms; n++ )
    {
      norms[n] = command_line("norms", "DIE!", n);
      if( norms[n] != std::string("L2") &&
          norms[n] != std::string("H1") )
        {
          std::cerr << "ERROR: Invalid norm input " << norms[n] << std::endl
                    << "       Valid values are: L2" << std::endl
                    << "                         H1" << std::endl;
        }
    }

  const std::string& system_name = grins.get_multiphysics_system_name();

  // Now compute error for each variable
  for( unsigned int v = 0; v < n_vars; v++ )
    {
      exact_sol.compute_error(system_name, vars[v]);
    }

  int return_flag = 0;

  double tol = 1.0e-10;

  // Now test error for each variable, for each norm
  for( unsigned int v = 0; v < n_vars; v++ )
    {
      for( unsigned int n = 0; n < n_norms; n++ )
        {
          test_error_norm( exact_sol, system_name, vars[v], norms[n], tol, return_flag );
        }
    }

  return return_flag;
}

void test_error_norm( libMesh::ExactSolution& exact_sol,
                      const std::string& system_name,
                      const std::string& var,
                      const std::string& norm,
                      const double tol,
                      int& return_flag )
{
  // We don't set return_flag unless we are setting it 1
  // since this function gets called multiple times and we don't
  // want to overwrite a previous "fail" (return_flag = 1) with
  // a "pass" (return_flag = 0)

  double error = 0.0;

  if( norm == std::string("L2") )
    {
      error = exact_sol.l2_error(system_name, var);
    }
  else if( norm == std::string("H1") )
    {
      error = exact_sol.h1_error(system_name, var);
    }
  else
    {
      std::cerr << "ERROR: Invalid norm " << norm << std::endl;
      exit(1);
    }

  if( error > tol )
    {
      return_flag = 1;

      std::cerr << "Tolerance exceeded for generic regression test!" << std::endl
                << "tolerance     = " << tol << std::endl
                << "norm of error = " << error << std::endl
                << "norm type     = " << norm << std::endl
                << "var           = " << var << std::endl;
    }

  return;
}
<|endoftext|>


<commit_before><commit_msg>Adding Imlib2 include (temporary I hope)<commit_after><|endoftext|>


<commit_before><commit_msg>Added a test for settings parser.<commit_after><|endoftext|>


<commit_before>// randdelay.cpp -- sit in a loop where things happen based on random time delays
// using time.h/unistd.h clock_gettime().  based on:
// https://blog.habets.se/2010/09/gettimeofday-should-never-be-used-to-measure-time.html

// nice discussion of history of int, long, etc.:
// http://stackoverflow.com/a/32924794

#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include <ncurses.h>
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

volatile int sink;

typedef struct
{
    timespec    now;
    timespec    future;
    int         delaysec;
} waitertype;

waitertype waiter;

unsigned long convmstotimespec(int millisecs)
{
    int secs;
    unsigned long nanosecs;
    timespec now;

    clock_gettime(CLOCK_MONOTONIC, &now);

    secs = trunc(millisecs/1000);
    nanosecs = (millisecs*1000000)-(secs*1000000000);

    cout << "\nconvmstotimespec(): millisecs: " << millisecs << " secs: " << secs << " nanosecs: " << nanosecs << "\n";

    return(nanosecs);
}

void schedulefuturetimespec(long delayms, timespec * futuretime)
{
    //long secs;
    unsigned long secs, nanosecs;
    timespec now;

    clock_gettime(CLOCK_MONOTONIC, &now);
    secs = trunc(delayms/1000);
    nanosecs = (delayms*1000000)-(secs*1000000000);
    futuretime->tv_sec = now.tv_sec + secs;
    futuretime->tv_nsec = now.tv_nsec + nanosecs;
}

int main()
{
    timespec currenttime, futuretime;
    //long currenttimens, futuretimens;

    /*
    cout << "\nmain(): ms 500: " << convmstotimespec(500);
    cout << "\nmain(): ms 1500: " << convmstotimespec(1700);
    cout << "\nmain(): ms 3900: " << convmstotimespec(3900);
    */

    clock_gettime(CLOCK_MONOTONIC, &waiter.now);
    printf("\nwaiter.now.tv_sec: %ld  waiter.now.tv_nsec: %ld\n", waiter.now.tv_sec, waiter.now.tv_nsec);

    /*
    schedulefuturetimespec(550, &futuretime);
    printf("futuretime.tv_sec=%ld futuretime.tv_nsec=%ld\n", futuretime.tv_sec, futuretime.tv_nsec);
    schedulefuturetimespec(2147, &futuretime);
    printf("futuretime.tv_sec=%ld futuretime.tv_nsec=%ld\n", futuretime.tv_sec, futuretime.tv_nsec);
    schedulefuturetimespec(2148, &futuretime);
    printf("futuretime.tv_sec=%ld futuretime.tv_nsec=%ld\n", futuretime.tv_sec, futuretime.tv_nsec);
    */

    //std::vector<int> v(100000000, 42);
    //sink = std::accumulate(v.begin(), v.end(), 0u);

    clock_gettime(CLOCK_MONOTONIC, &waiter.now);
    schedulefuturetimespec(2112, &waiter.future);
    printf("main(): waiter.now.tv_sec: %ld  waiter.now.tv_nsec: %ld\n", waiter.now.tv_sec, waiter.now.tv_nsec);
    printf("main(): waiter.future.tv_sec: %ld  waiter.future.tv_nsec: %ld\n", waiter.future.tv_sec, waiter.future.tv_nsec);

    long i;
    bool bail=false;
    clock_gettime(CLOCK_MONOTONIC, &currenttime);
    while(!bail)
    {
        i++;
        clock_gettime(CLOCK_MONOTONIC, &currenttime);
        if(currenttime.tv_sec >= waiter.future.tv_sec)
            if(currenttime.tv_nsec >= waiter.future.tv_nsec)
        //if(currenttime.tv_sec >= futuretime.tv_sec && currenttime.tv_nsec >= futuretime.tv_nsec)
        {
            bail=true;
        }
        //napms(300);
        //printf("main(): waiter.future.tv_sec: %ld  waiter.future.tv_nsec: %ld\n", waiter.future.tv_sec, waiter.future.tv_nsec);
        //cout << "\nsec: " << currenttime.tv_sec << " nsec: " << currenttime.tv_nsec << "\n";
        //printf("sec: %ld nsec: %ld\n", currenttime.tv_sec, currenttime.tv_nsec);
    }

    cout << "\nDONE!\n";
    //clock_gettime(CLOCK_MONOTONIC, &waiter.later);
    //printf("waiter.later.tv_sec: %ld  waiter.later.tv_nsec: %ld\n", waiter.later.tv_sec, waiter.later.tv_nsec);

}
<commit_msg>cleaned up randdelay.cpp<commit_after>// randdelay.cpp -- sit in a loop where things happen based on random time delays
// using time.h/unistd.h clock_gettime().  based on:
// https://blog.habets.se/2010/09/gettimeofday-should-never-be-used-to-measure-time.html

// nice discussion of history of int, long, etc.:
// http://stackoverflow.com/a/32924794

#include <time.h>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include <ncurses.h>
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

volatile int sink;

typedef struct
{
    timespec    now;
    timespec    future;
    int         delaysec;
} waitertype;

waitertype waiter;

unsigned long convmstotimespec(int millisecs)
{
    int secs;
    unsigned long nanosecs;
    timespec now;

    clock_gettime(CLOCK_MONOTONIC, &now);
    secs = trunc(millisecs/1000);
    nanosecs = (millisecs*1000000)-(secs*1000000000);
    return(nanosecs);
}

void schedulefuturetimespec(long delayms, timespec * futuretime)
{
    //long secs;
    unsigned long secs, nanosecs;
    timespec now;

    clock_gettime(CLOCK_MONOTONIC, &now);
    secs = trunc(delayms/1000);
    nanosecs = (delayms*1000000)-(secs*1000000000);
    futuretime->tv_sec = now.tv_sec + secs;
    futuretime->tv_nsec = now.tv_nsec + nanosecs;
}

int main()
{
    long delayms=2112;
    timespec currenttime;

    cout << "\n\nThis program uses clock_gettime() to wait " << delayms << " milliseconds.\n\n";
    clock_gettime(CLOCK_MONOTONIC, &waiter.now);
    schedulefuturetimespec(2112, &waiter.future);
    printf("main(): Start time:                waiter.now.tv_sec:    %ld  waiter.now.tv_nsec:    %ld\n", waiter.now.tv_sec, waiter.now.tv_nsec);
    printf("main(): Scheduled completion time: waiter.future.tv_sec: %ld  waiter.future.tv_nsec: %ld\n", waiter.future.tv_sec, waiter.future.tv_nsec);

    long i;
    bool bail=false;
    clock_gettime(CLOCK_MONOTONIC, &currenttime);
    while(!bail)
    {
        i++;
        clock_gettime(CLOCK_MONOTONIC, &currenttime);
        if(currenttime.tv_sec >= waiter.future.tv_sec)
            if(currenttime.tv_nsec >= waiter.future.tv_nsec)
        {
            bail=true;
        }
    }
    clock_gettime(CLOCK_MONOTONIC, &waiter.now);
    printf("main(): Actual completion time:    waiter.now.tv_sec:    %ld  waiter.now.tv_nsec:    %ld\n", waiter.now.tv_sec, waiter.now.tv_nsec);
    cout << "DONE!\n\n";
}
<|endoftext|>


<commit_before>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <cassert>

#include "store/api/item.h"
#include "common/common.h"
#include "store/api/store.h"
#include "store/api/item_factory.h"
#include "system/globalenv.h"
#include "types/root_typemanager.h"
#include "types/typeops.h"

using namespace zorba;

int typesystem_isSubtype(int argc, char* argv[]) {
  {
    store::Store& store = GENV.getStore();
    store::Item_t lInteger = store.getItemFactory()->createInteger(Integer::parseInt((int32_t)1));
    store::Item_t lInt = store.getItemFactory()->createInt(1);
    store::Item_t lDecimal = store.getItemFactory()->createDecimal(Decimal::parseInt((int32_t)1));

    xqtref_t lIntegerType = GENV_TYPESYSTEM.create_named_type(lInteger->getType(), TypeConstants::QUANT_ONE);
    xqtref_t lIntType = GENV_TYPESYSTEM.create_named_type(lInt->getType(), TypeConstants::QUANT_ONE);
    xqtref_t lDecimalType = GENV_TYPESYSTEM.create_named_type(lDecimal->getType(), TypeConstants::QUANT_ONE);

    assert(TypeOps::is_atomic(*lIntType));
    assert(TypeOps::is_subtype(*lIntType, *lIntegerType));
    assert(TypeOps::is_subtype(*lIntType, *lDecimalType));
    assert(TypeOps::is_subtype(*lIntegerType, *lDecimalType));
  }

  GlobalEnvironment::destroy();

  return 0;
}
<commit_msg>typesystem test uses new C++ api<commit_after>/*
 * Copyright 2006-2008 The FLWOR Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <cassert>

#include <zorba/zorba.h>

#include "store/api/item.h"
#include "common/common.h"
#include "store/api/store.h"
#include "store/api/item_factory.h"
#include "system/globalenv.h"
#include "types/root_typemanager.h"
#include "types/typeops.h"

using namespace zorba;

int typesystem_isSubtype(int argc, char* argv[])
{
  Zorba* lZorba = Zorba::getInstance();

  store::Store& store = GENV.getStore();
  store::Item_t lInteger = store.getItemFactory()->createInteger(Integer::parseInt((int32_t)1));
  store::Item_t lInt = store.getItemFactory()->createInt(1);
  store::Item_t lDecimal = store.getItemFactory()->createDecimal(Decimal::parseInt((int32_t)1));

  xqtref_t lIntegerType = GENV_TYPESYSTEM.create_named_type(lInteger->getType(), TypeConstants::QUANT_ONE);
  xqtref_t lIntType = GENV_TYPESYSTEM.create_named_type(lInt->getType(), TypeConstants::QUANT_ONE);
  xqtref_t lDecimalType = GENV_TYPESYSTEM.create_named_type(lDecimal->getType(), TypeConstants::QUANT_ONE);

  assert(TypeOps::is_atomic(*lIntType));
  assert(TypeOps::is_subtype(*lIntType, *lIntegerType));
  assert(TypeOps::is_subtype(*lIntType, *lDecimalType));
  assert(TypeOps::is_subtype(*lIntegerType, *lDecimalType));

  lZorba->shutdown();
  return 0;
}
<|endoftext|>


<commit_before>#define usint unsigned short int
#define uncast reinterpret_cast<unsigned short int>
#define recast reinterpret_cast<char *>
#define rechcast reinterpret_cast<const char *>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

struct DirEntry{
    char[11] filename;
    char attributes;
    unsigned long created_time;
    usint address;
    unsigned int filesize;
    char[6] reserved;
}

usint getFATindex(int);
void setFATindex(int, usint);
char* getDataCluster(int);
void setDataCluster(int,char*);
bool hasNextCluster(int);
DirEntry makeDirEntry(char*,char,usint,unsigned int);
char* getDirRawData(int, char*);
DirEntry* parseDirEntries(char*);
char* packDirEntries(DirEntry*);
vector<string> getTokens(string, char);

const int FAT_OFFSET = 512; // 1 sector
const int DATA_OFFSET = FAT_OFFSET + 256*1024; // 1 sector + 256kB
const int CLUSTER_SIZE = 512*8; // 4kB (8 sectors/cluster at 512B/sector)
const usint FAT_EOF = 0xFFFF;

fstream FAT;
string CURR_DIR;

int main(int argc, char* argv[]){
    if(argc > 1){
        FAT.open(argv[1], ios::binary | ios::in);
    }else{
        cout << "Please include filename in args" << endl;
        return 0;
    }
    if(!FAT.is_open()){
        cout << "Can't open file!" << endl;
        return 1;
    }
    cout << "File opened succesfully." << endl;
    cout << "READING BOOT SECTOR" << endl;
    char* OS_name = new char[8];
    FAT.seekg(FAT.beg+3);
    FAT.read(OS_name,8);
    cout << "OS NAME: " << OS_name << endl;
    /* Check FS Initalized status */
    cout << "Checking FS status..." << endl;
    cout << "FAT index 0: " << getFATindex(0) << endl;
    cout << "FAT index 1: " << getFATindex(1) << endl;
    cout << "FAT index 2 (ROOT): " << getFATindex(2) << endl;
    if (getFATindex(2)==0){
        cout << "FAT still uninitalized. Writing root..." << endl;
        DirEntry* root = parseDirEntries(getDataCluster(2));
        root[0]=makeDirEntry(".",0x10,2,0);
        root[1]=makeDirEntry("..",0x10,2,0);
        setDataCluster(2,packDirEntries(root));
        setFATindex(2,FAT_EOF);
        cout << "Root written."
    }
    //Welcome to the shell
    int status = 0;
	while(!status) {
		cout << OS_name << "> ";
		string line;
		getline(cin,line);
		vector<string> tokens = getTokens(line, ' ');
        if(tokens.size() > 0)
            cout << "cmd to execute: " << tokens[0] << endl;
        if(tokens.size() == 0 || tokens[0] == "exit")
            status = 1;
		//status = executeCommand(tokens);
	};
    if(status != 1){
		cerr << "ERROR " << status << ": al ejecutar el comando" << endl;
	}
    delete[] OS_name;
    FAT.close();
    return 0;
}

usint getFATindex(int index){
    FAT.seekg(FAT.beg+FAT_OFFSET+(index*2));
    usint value;
    FAT.read(recast(&value),2);
    return value;
}

void setFATindex(int index, usint value){
    FAT.seekg(FAT.beg+FAT_OFFSET+(index*2));
    FAT.write(rechcast(&value),2);
}

char* getDataCluster(int index){
    FAT.seekg(FAT.beg+DATA_OFFSET+(index*CLUSTER_SIZE));
    char* data = new char[CLUSTER_SIZE];
    FAT.read(data,CLUSTER_SIZE);
    return data;
}

void setDataCluster(int index, char* data){
    FAT.seekg(FAT.beg+DATA_OFFSET+(index*CLUSTER_SIZE));
    FAT.write(data,CLUSTER_SIZE);
}

bool hasNextCluster(int index){
    return getFATindex(index)!=FAT_EOF;
}

DirEntry makeDirEntry(char* fn, char attr, usint addr, unsigned int size){
    DirEntry entry;
    entry.filename=fn;
    entry.attributes=attr;
    entry.created_time=chrono::system_clock::now().time_since_epoch() / chrono::milliseconds(1);
    entry.address=addr;
    entry.filesize=size;
    return entry;
}

char* getDirRawData(int index, char* data){
    char* entry = new char[32];
    for(int i=0; i<32; i++){
        entry[i]=data[index*32+i];
    }
    return entry;
}

/**
    Transforms a 4kB cluster of data into 512 DirEntries.

    @param data The 4kB cluster as a char array.
    @return The array of 512 DirEntries.
*/
DirEntry* parseDirEntries(char* data){
    DirEntry* entries = new DirEntry[512];
    for(int i=0; i<512; i++){
        DirEntry[i] = reinterpret_cast<DirEntry>(getDirRawData(i));
    }
    return entries;
}

/**
    The reverse of parseDirEntries. It packs 512 DirEntries into a 4kB cluster.

    @param entries Array of 512 DirEntries to pack.
    @return The 4kB cluster as a char array.
*/
char* packDirEntries(DirEntry* entries){
    char* data = new char[CLUSTER_SIZE];
    char* entry;
    for(i=0; i<512; i++){
        entry=recast(&(entries[i]));
        for(j=0; j<32; j++){
            data[i*32+j]=entry[j];
        }
    }
    return data;
}

/**
    Only works with one char delimiter but it works!!

    @param entries Array of 512 DirEntries to pack.
    @return The 4kB cluster as a char array.
*/
vector<string> getTokens(string toTokenize, char delimiter){
	vector<string> v;
	string::iterator stringIT = toTokenize.begin();
	for(string::iterator i = toTokenize.begin(); i != toTokenize.end(); i++){
		if(*i == delimiter){
			v.push_back(string(stringIT,i));
			stringIT=i+1;
		}
	}
	v.push_back(string(stringIT,toTokenize.end()));
	return v;
}<commit_msg>Less errors.<commit_after>#define usint unsigned short int
#define uncast reinterpret_cast<unsigned short int>
#define recast reinterpret_cast<char *>
#define rechcast reinterpret_cast<const char *>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

struct DirEntry{
    char filename[11];
    char attributes;
    unsigned long created_time;
    usint address;
    unsigned int filesize;
    char reserved[6];
};

usint getFATindex(int);
void setFATindex(int, usint);
char* getDataCluster(int);
void setDataCluster(int,char*);
bool hasNextCluster(int);
DirEntry makeDirEntry(char*,char,usint,unsigned int);
char* getDirRawData(int, char*);
DirEntry* parseDirEntries(char*);
char* packDirEntries(DirEntry*);
vector<string> getTokens(string, char);

const int FAT_OFFSET = 512; // 1 sector
const int DATA_OFFSET = FAT_OFFSET + 256*1024; // 1 sector + 256kB
const int CLUSTER_SIZE = 512*8; // 4kB (8 sectors/cluster at 512B/sector)
const usint FAT_EOF = 0xFFFF;

fstream FAT;
string CURR_DIR;

int main(int argc, char* argv[]){
    if(argc > 1){
        FAT.open(argv[1], ios::binary | ios::in);
    }else{
        cout << "Please include filename in args" << endl;
        return 0;
    }
    if(!FAT.is_open()){
        cout << "Can't open file!" << endl;
        return 1;
    }
    cout << "File opened succesfully." << endl;
    cout << "READING BOOT SECTOR" << endl;
    char* OS_name = new char[8];
    FAT.seekg(FAT.beg+3);
    FAT.read(OS_name,8);
    cout << "OS NAME: " << OS_name << endl;
    /* Check FS Initalized status */
    cout << "Checking FS status..." << endl;
    cout << "FAT index 0: " << getFATindex(0) << endl;
    cout << "FAT index 1: " << getFATindex(1) << endl;
    cout << "FAT index 2 (ROOT): " << getFATindex(2) << endl;
    if (getFATindex(2)==0){
        cout << "FAT still uninitalized. Writing root..." << endl;
        DirEntry* root = parseDirEntries(getDataCluster(2));
        root[0]=makeDirEntry(".",0x10,2,0);
        root[1]=makeDirEntry("..",0x10,2,0);
        setDataCluster(2,packDirEntries(root));
        setFATindex(2,FAT_EOF);
        cout << "Root written." << endl;
    }
    //Welcome to the shell
    int status = 0;
	while(!status) {
		cout << OS_name << "> ";
		string line;
		getline(cin,line);
		vector<string> tokens = getTokens(line, ' ');
        if(tokens.size() > 0)
            cout << "cmd to execute: " << tokens[0] << endl;
        if(tokens.size() == 0 || tokens[0] == "exit")
            status = 1;
		//status = executeCommand(tokens);
	};
    if(status != 1){
		cerr << "ERROR " << status << ": al ejecutar el comando" << endl;
	}
    delete[] OS_name;
    FAT.close();
    return 0;
}

usint getFATindex(int index){
    FAT.seekg(FAT.beg+FAT_OFFSET+(index*2));
    usint value;
    FAT.read(recast(&value),2);
    return value;
}

void setFATindex(int index, usint value){
    FAT.seekg(FAT.beg+FAT_OFFSET+(index*2));
    FAT.write(rechcast(&value),2);
}

char* getDataCluster(int index){
    FAT.seekg(FAT.beg+DATA_OFFSET+(index*CLUSTER_SIZE));
    char* data = new char[CLUSTER_SIZE];
    FAT.read(data,CLUSTER_SIZE);
    return data;
}

void setDataCluster(int index, char* data){
    FAT.seekg(FAT.beg+DATA_OFFSET+(index*CLUSTER_SIZE));
    FAT.write(data,CLUSTER_SIZE);
}

bool hasNextCluster(int index){
    return getFATindex(index)!=FAT_EOF;
}

DirEntry makeDirEntry(char* fn, char attr, usint addr, unsigned int size){
    DirEntry entry;
    entry.filename=fn;
    entry.attributes=attr;
    entry.created_time=std::chrono::system_clock::now().time_since_epoch() / std::chrono::milliseconds(1);
    entry.address=addr;
    entry.filesize=size;
    return entry;
}

char* getDirRawData(int index, char* data){
    char* entry = new char[32];
    for(int i=0; i<32; i++){
        entry[i]=data[index*32+i];
    }
    return entry;
}

/**
    Transforms a 4kB cluster of data into 512 DirEntries.

    @param data The 4kB cluster as a char array.
    @return The array of 512 DirEntries.
*/
DirEntry* parseDirEntries(char* data){
    DirEntry* entries = new DirEntry[512];
    for(int i=0; i<512; i++){
        entries[i] = reinterpret_cast<DirEntry>(getDirRawData(i,data));
    }
    return entries;
}

/**
    The reverse of parseDirEntries. It packs 512 DirEntries into a 4kB cluster.

    @param entries Array of 512 DirEntries to pack.
    @return The 4kB cluster as a char array.
*/
char* packDirEntries(DirEntry* entries){
    char* data = new char[CLUSTER_SIZE];
    char* entry;
    for(int i=0; i<512; i++){
        entry=recast(&(entries[i]));
        for(int j=0; j<32; j++){
            data[i*32+j]=entry[j];
        }
    }
    return data;
}

/**
    Only works with one char delimiter but it works!!

    @param entries Array of 512 DirEntries to pack.
    @return The 4kB cluster as a char array.
*/
vector<string> getTokens(string toTokenize, char delimiter){
	vector<string> v;
	string::iterator stringIT = toTokenize.begin();
	for(string::iterator i = toTokenize.begin(); i != toTokenize.end(); i++){
		if(*i == delimiter){
			v.push_back(string(stringIT,i));
			stringIT=i+1;
		}
	}
	v.push_back(string(stringIT,toTokenize.end()));
	return v;
}<|endoftext|>


<commit_before>#define usint unsigned short int
#define uncast reinterpret_cast<unsigned short int>
#define recast reinterpret_cast<char *>
#define rechcast reinterpret_cast<const char *>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sys/time.h>

using namespace std;

struct DirEntry{
    char filename[11];
    char attributes;
    unsigned long created_time;
    usint address;
    unsigned int filesize;
    char reserved[6];
};

usint getFATindex(int);
void setFATindex(int, usint);
char* getDataCluster(int);
void setDataCluster(int,char*);
bool hasNextCluster(int);
DirEntry makeDirEntry(char*,char,usint,unsigned int);
char* getDirRawData(int, char*);
DirEntry* parseDirEntries(char*);
char* packDirEntries(DirEntry*);
vector<string> getTokens(string, char);

const int FAT_OFFSET = 512; // 1 sector
const int DATA_OFFSET = FAT_OFFSET + 256*1024; // 1 sector + 256kB
const int CLUSTER_SIZE = 512*8; // 4kB (8 sectors/cluster at 512B/sector)
const usint FAT_EOF = 0xFFFF;
// DirEntry Attribute Constants
const char ATTR_READONLY = 0x01;
const char ATTR_HIDDEN = 0x02;
const char ATTR_SYSTEMFILE = 0x04;
const char ATTR_VOLUMELABEL = 0x08;
const char ATTR_DIRECTORY = 0x10;
const char ATTR_FILE = 0x20;

fstream FAT;
string currentDir="/";
int currentIndex=2;

int main(int argc, char* argv[]){
    if(argc > 1){
        FAT.open(argv[1], ios::binary | ios::in);
    }else{
        cout << "Please include filename in args" << endl;
        return 0;
    }
    if(!FAT.is_open()){
        cout << "Can't open file!" << endl;
        return 1;
    }
    cout << "File opened succesfully." << endl;
    cout << "READING BOOT SECTOR" << endl;
    char* OS_name = new char[8];
    FAT.seekg(FAT.beg+3);
    FAT.read(OS_name,8);
    cout << "OS NAME: " << OS_name << endl;
    /* Check FS Initalized status */
    cout << "Checking FS status..." << endl;
    cout << "FAT index 0: " << getFATindex(0) << endl;
    cout << "FAT index 1: " << getFATindex(1) << endl;
    cout << "FAT index 2 (ROOT): " << getFATindex(2) << endl;
    if (getFATindex(2)==0){
        cout << "FAT still uninitalized. Writing root..." << endl;
        DirEntry* root = parseDirEntries(getDataCluster(2));
        root[0]=makeDirEntry(".",ATTR_DIRECTORY | ATTR_SYSTEMFILE,2,0);
        root[1]=makeDirEntry("..",ATTR_DIRECTORY | ATTR_SYSTEMFILE,2,0);
        setDataCluster(2,packDirEntries(root));
        setFATindex(2,FAT_EOF);
        cout << "Root written." << endl;
    }
    //Welcome to the shell
    int status = 0;
	while(!status) {
		cout << OS_name << "> ";
		string line;
		getline(cin,line);
		vector<string> tokens = getTokens(line, ' ');
        if(tokens.size() > 0)
            cout << "cmd to execute: " << tokens[0] << endl;
        if(tokens.size() == 0 || tokens[0] == "exit"){
            status = 1;
        }else if(tokens[0]=="ls"){
            DirEntry* myDir = parseDirEntries(getDataCluster(currentIndex));
            cout << "Filename   |Type |Date      |Size" << endl;
            cout << "=======================================" << endl;
            for(int i=0; i<512; i++){
                if(myDir[i].filename[0]!='\0'){//Check if valid DirEntry
                    cout << myDir[i].filename << " ";
                    if(myDir[i].attributes & ATTR_DIRECTORY){
                        cout << "DIR  ";
                    }else{
                        cout << "FILE ";
                    }
                    cout << myDir[i].created_time; //UNFORMATTED!!!
                    cout << myDir[i].filesize << "B" << endl;
                }
            }
        }
        //status = executeCommand(tokens);
	};
    if(status != 1){
		cerr << "ERROR " << status << ": al ejecutar el comando" << endl;
	}
    delete[] OS_name;
    FAT.close();
    return 0;
}

usint getFATindex(int index){
    FAT.seekg(FAT.beg+FAT_OFFSET+(index*2));
    usint value;
    FAT.read(recast(&value),2);
    return value;
}

void setFATindex(int index, usint value){
    FAT.seekg(FAT.beg+FAT_OFFSET+(index*2));
    FAT.write(rechcast(&value),2);
}

char* getDataCluster(int index){
    FAT.seekg(FAT.beg+DATA_OFFSET+(index*CLUSTER_SIZE));
    char* data = new char[CLUSTER_SIZE];
    FAT.read(data,CLUSTER_SIZE);
    return data;
}

void setDataCluster(int index, char* data){
    FAT.seekg(FAT.beg+DATA_OFFSET+(index*CLUSTER_SIZE));
    FAT.write(data,CLUSTER_SIZE);
}

bool hasNextCluster(int index){
    return getFATindex(index)!=FAT_EOF;
}

DirEntry makeDirEntry(char* fn, char attr, usint addr, unsigned int size){
    DirEntry entry;
    //entry.filename=fn;
    for(int i=0; i<11; i++){
        entry.filename[i]=fn[i];
        if(fn[i]=='\0'){
            break;
        }
    }
    entry.attributes=attr;
    struct timeval tp;
    gettimeofday(&tp, NULL);
    entry.created_time = tp.tv_sec * 1000 + tp.tv_usec / 1000;
    //entry.created_time=std::chrono::system_clock::now().time_since_epoch() / std::chrono::milliseconds(1);
    entry.address=addr;
    entry.filesize=size;
    return entry;
}

char* getDirRawData(int index, char* data){
    char* entry = new char[32];
    for(int i=0; i<32; i++){
        entry[i]=data[index*32+i];
    }
    return entry;
}

/**
    Transforms a 4kB cluster of data into 512 DirEntries.

    @param data The 4kB cluster as a char array.
    @return The array of 512 DirEntries.
*/
DirEntry* parseDirEntries(char* data){
    DirEntry* entries = new DirEntry[512];
    for(int i=0; i<512; i++){
        entries[i] = *(reinterpret_cast<DirEntry*>(getDirRawData(i,data)));
    }
    return entries;
}

/**
    The reverse of parseDirEntries. It packs 512 DirEntries into a 4kB cluster.

    @param entries Array of 512 DirEntries to pack.
    @return The 4kB cluster as a char array.
*/
char* packDirEntries(DirEntry* entries){
    char* data = new char[CLUSTER_SIZE];
    char* entry;
    for(int i=0; i<512; i++){
        entry=recast(&(entries[i]));
        for(int j=0; j<32; j++){
            data[i*32+j]=entry[j];
        }
    }
    return data;
}

/**
    Only works with one char delimiter but it works!!
*/
vector<string> getTokens(string toTokenize, char delimiter){
	vector<string> v;
	string::iterator stringIT = toTokenize.begin();
	for(string::iterator i = toTokenize.begin(); i != toTokenize.end(); i++){
		if(*i == delimiter){
			v.push_back(string(stringIT,i));
			stringIT=i+1;
		}
	}
	v.push_back(string(stringIT,toTokenize.end()));
	return v;
}<commit_msg>small changes to fix segfault<commit_after>#define usint unsigned short int
#define uncast reinterpret_cast<unsigned short int>
#define recast reinterpret_cast<char *>
#define rechcast reinterpret_cast<const char *>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <ctime>

using namespace std;

struct DirEntry{
    char filename[11];
    char attributes;
    unsigned long created_time;
    usint address;
    unsigned int filesize;
    char reserved[6];
};

usint getFATindex(int);
void setFATindex(int, usint);
char* getDataCluster(int);
void setDataCluster(int,char*);
bool hasNextCluster(int);
DirEntry makeDirEntry(string, char, usint, unsigned int);
char* getDirRawData(int, char*);
DirEntry* parseDirEntries(char*);
char* packDirEntries(DirEntry*);
vector<string> getTokens(string, char);

const int FAT_OFFSET = 512; // 1 sector
const int DATA_OFFSET = FAT_OFFSET + 256*1024; // 1 sector + 256kB
const int CLUSTER_SIZE = 512*8; // 4kB (8 sectors/cluster at 512B/sector)
const usint FAT_EOF = 0xFFFF;
// DirEntry Attribute Constants
const char ATTR_READONLY = 0x01;
const char ATTR_HIDDEN = 0x02;
const char ATTR_SYSTEMFILE = 0x04;
const char ATTR_VOLUMELABEL = 0x08;
const char ATTR_DIRECTORY = 0x10;
const char ATTR_FILE = 0x20;

fstream FAT;
string currentDir="/";
int currentIndex=2;

int main(int argc, char* argv[]){
    if(argc > 1){
        FAT.open(argv[1], ios::binary | ios::in);
    }else{
        cout << "Please include filename in args" << endl;
        return 0;
    }
    if(!FAT.is_open()){
        cout << "Can't open file!" << endl;
        return 1;
    }
    cout << "File opened succesfully." << endl;
    cout << "READING BOOT SECTOR" << endl;
    char OS_name[9];
    FAT.seekg(FAT.beg+3);
    FAT.read(OS_name,8);
    OS_name[8] = '\0';
    cout << "OS NAME: " << OS_name << endl;
    /* Check FS Initalized status */
    cout << "Checking FS status..." << endl;
    cout << "FAT index 0: " << getFATindex(0) << endl;
    cout << "FAT index 1: " << getFATindex(1) << endl;
    cout << "FAT index 2 (ROOT): " << getFATindex(2) << endl;
    if (getFATindex(2)==0){
        cout << "FAT still uninitalized. Writing root..." << endl;
        DirEntry* root = parseDirEntries(getDataCluster(2));
        root[0]=makeDirEntry(".",ATTR_DIRECTORY | ATTR_SYSTEMFILE,2,0);
        root[1]=makeDirEntry("..",ATTR_DIRECTORY | ATTR_SYSTEMFILE,2,0);
        setDataCluster(2,packDirEntries(root));
        cout << "setDataCluster" << endl;
        setFATindex(2,FAT_EOF);
        cout << "Root written." << endl;
    }
    //Welcome to the shell
    int status = 0;
	while(!status) {
		cout << OS_name << "> ";
		string line;
		getline(cin,line);
		vector<string> tokens = getTokens(line, ' ');
        if(tokens.size() > 0)
            cout << "cmd to execute: " << tokens[0] << endl;
        if(tokens.size() == 0 || tokens[0] == "exit"){
            status = 1;
        }else if(tokens[0]=="ls"){
            DirEntry* myDir = parseDirEntries(getDataCluster(currentIndex));
            cout << "Filename  |Type |Date      |Size" << endl;
            cout << "=======================================" << endl;
            for(int i=0; i<128; i++){
                if(myDir[i].filename[0]!='\0'){//Check if valid DirEntry
                    for(int j=1; j <= 10; j++)
                        cout << myDir[i].filename;
                    cout << "|";
                    if(myDir[i].attributes & ATTR_DIRECTORY){
                        cout << "DIR  |";
                    }else{
                        cout << "FILE |";
                    }
                    cout << myDir[i].created_time<<"|"; //UNFORMATTED!!!
                    cout << myDir[i].filesize << "B" << endl;
                }
            }
        }
        //status = executeCommand(tokens);
	};
    if(status != 1){
		cerr << "ERROR " << status << ": al ejecutar el comando" << endl;
	}
    FAT.close();
    return 0;
}

usint getFATindex(int index){
    FAT.seekg(FAT.beg+FAT_OFFSET+(index*2));
    usint value;
    FAT.read(recast(&value),2);
    return value;
}

void setFATindex(int index, usint value){
    FAT.seekg(FAT.beg+FAT_OFFSET+(index*2));
    FAT.write(rechcast(&value),2);
}

char* getDataCluster(int index){
    FAT.seekg(FAT.beg+DATA_OFFSET+(index*CLUSTER_SIZE));
    char* data = new char[CLUSTER_SIZE];
    FAT.read(data,CLUSTER_SIZE);
    return data;
}

void setDataCluster(int index, char* data){
    FAT.seekg(FAT.beg+DATA_OFFSET+(index*CLUSTER_SIZE));
    cout << "Write success" << endl;
    FAT.write(data,CLUSTER_SIZE);
}

bool hasNextCluster(int index){
    return getFATindex(index)!=FAT_EOF;
}

DirEntry makeDirEntry(string fn, char attr, usint addr, unsigned int size){
    DirEntry entry;
    //entry.filename=fn;
    for(int i=0; i<11; i++){
        entry.filename[i]=fn[i];
        if(fn[i]=='\0'){
            break;
        }
    }
    entry.attributes=attr;
    time_t now;
    time(&now);
    entry.created_time = now;
    //entry.created_time=std::chrono::system_clock::now().time_since_epoch() / std::chrono::milliseconds(1);
    entry.address=addr;
    entry.filesize=size;
    return entry;
}

char* getDirRawData(int index, char* data){
    char* entry = new char[32];
    for(int i=0; i<32; i++){
        entry[i]=data[index*32+i];
    }
    return entry;
}

/**
    Transforms a 4kB cluster of data into 128 DirEntries.

    @param data The 4kB cluster as a char array.
    @return The array of 128 DirEntries.
*/
DirEntry* parseDirEntries(char* data){
    DirEntry* entries = new DirEntry[128];
    for(int i=0; i<128; i++){
        entries[i] = *(reinterpret_cast<DirEntry*>(getDirRawData(i,data)));
    }
    return entries;
}

/**
    The reverse of parseDirEntries. It packs 128 DirEntries into a 4kB cluster.

    @param entries Array of 128 DirEntries to pack.
    @return The 4kB cluster as a char array.
*/
char* packDirEntries(DirEntry* entries){
    char* data = new char[CLUSTER_SIZE];
    char* entry;
    for(int i=0; i<128; i++){
        entry=recast(&entries[i]);
        for(int j=0; j<32; j++){
            data[i*32+j]=entry[j];
        }
    }
    return data;
}

/**
    Only works with one char delimiter but it works!!
*/
vector<string> getTokens(string toTokenize, char delimiter){
	vector<string> v;
	string::iterator stringIT = toTokenize.begin();
	for(string::iterator i = toTokenize.begin(); i != toTokenize.end(); i++){
		if(*i == delimiter){
			v.push_back(string(stringIT,i));
			stringIT=i+1;
		}
	}
	v.push_back(string(stringIT,toTokenize.end()));
	return v;
}<|endoftext|>


<commit_before>// ConsoleApplication1.cpp : Defines the entry point for the console application.
// TODO: Run a bunch of times and average runtimes

#include "stdio.h"
#include "math.h"
#include "string.h"
#include <iostream>

using namespace std;

/// This function performs a serial Sieve of Eratosthenes to find all prime number
void eratosthenesSieve(int bound, bool * primeArray)
{
	int sqrtBound = (int)sqrt((double)bound);
	memset(primeArray, 1, sizeof(bool) * (bound + 1));
	for (int m = 2; m <= sqrtBound; m++)
	{
		if (!primeArray[m])
		{
			for (int k = m * m; k <= bound; k += m)
			{
				primeArray[k] = false;
			}
		}
	}

	//this code block was used for debugging
	//for (int m = 2; m < bound; m++)
	//{
	//	if (!primeArray[m])
	//	{
	//		std::cout << m << ", ";
	//	}
	//}
}

///This function performs a serial Sieve of sundaram to find all primes
void sundaramSieve(int bound, bool * primeArray)
{
	bool* findArray = new bool[bound + 1];
	memset(findArray, 0, sizeof(bool) * (bound + 1));
	memset(primeArray, 1, sizeof(bool) * (bound + 1));

	for (int i = 1; i < bound; i++)
	{
		for (int j = i; j <= (bound - i) / (2 * i + 1); j++)
		{
			findArray[i + j + (2 * i * j)] = true;
		}
	}
	for (int i = 1; i < ((bound - 1) / 2); i++)
	{
		if (!findArray[i])
		{
			primeArray[((i * 2) + 1)] = false;
		}
	}
	primeArray[2] = false; // Sundaram doesnt find two so ill find it for it

	//code block below used for debuggin purposes
	//for (int m = 2; m < bound; m++)
	//{
	//	if (!primeArray[m])
	//	{
	//		std::cout << m << ", ";
	//	}
	//}
}

void sundPartOneSerial(int bound, bool * findArray)
{
	int max = 0;
	int denom = 0;
	for(int i = 1; i < bound; i++)
	{
		denom = (i << 1) + 1;
		max = (bound - i) / denom;
		for(int j = i; j <= max; j++)
		{
			findArray[i + j * denom] = true;
		}
	}
}

void sundPartTwoSerial(int bound, bool * findArray, bool * primeArray)
{
	int max = (bound - 1) >> 1;
	for(int i = 1; i < max; i++)
	{
		if(!findArray[i])
		{
			primeArray[((i << 1) + 1)] = false;
		}
	}
	primeArray[2] = false;
}

///This function compares two arrays to see if they match in the range of prime numbers
void validatePrimes(int bound, bool* goldArray, bool* checkArray)
{
	for (int i = 0; i <= 100; i++)
	{
		cout << i << ".\t" << goldArray[i] << "\t" << checkArray[i] << endl;
	}

	for (int i = 0; i <= bound; i++)
	{
		if (goldArray[i] != checkArray[i])
		{
			std::cout << "Difference at Position " << i << "\n";
			std::cout << "Array is Incorrect! \n";
			return;
		}
	}
	std::cout << "Found all primes! \n";
}

<commit_msg>again<commit_after>// ConsoleApplication1.cpp : Defines the entry point for the console application.
// TODO: Run a bunch of times and average runtimes

#include "stdio.h"
#include "math.h"
#include "string.h"
#include <iostream>

using namespace std;

/// This function performs a serial Sieve of Eratosthenes to find all prime number
void eratosthenesSieve(int bound, bool * primeArray)
{
	int sqrtBound = (int)sqrt((double)bound);
	memset(primeArray, 1, sizeof(bool) * (bound + 1));
	for (int m = 2; m <= sqrtBound; m++)
	{
		if (primeArray[m])
		{
			for (int k = m * m; k <= bound; k += m)
			{
				primeArray[k] = false;
			}
		}
	}

	//this code block was used for debugging
	//for (int m = 2; m < bound; m++)
	//{
	//	if (!primeArray[m])
	//	{
	//		std::cout << m << ", ";
	//	}
	//}
}

///This function performs a serial Sieve of sundaram to find all primes
void sundaramSieve(int bound, bool * primeArray)
{
	bool* findArray = new bool[bound + 1];
	memset(findArray, 0, sizeof(bool) * (bound + 1));
	memset(primeArray, 1, sizeof(bool) * (bound + 1));

	for (int i = 1; i < bound; i++)
	{
		for (int j = i; j <= (bound - i) / (2 * i + 1); j++)
		{
			findArray[i + j + (2 * i * j)] = true;
		}
	}
	for (int i = 1; i < ((bound - 1) / 2); i++)
	{
		if (!findArray[i])
		{
			primeArray[((i * 2) + 1)] = false;
		}
	}
	primeArray[2] = false; // Sundaram doesnt find two so ill find it for it

	//code block below used for debuggin purposes
	//for (int m = 2; m < bound; m++)
	//{
	//	if (!primeArray[m])
	//	{
	//		std::cout << m << ", ";
	//	}
	//}
}

void sundPartOneSerial(int bound, bool * findArray)
{
	int max = 0;
	int denom = 0;
	for(int i = 1; i < bound; i++)
	{
		denom = (i << 1) + 1;
		max = (bound - i) / denom;
		for(int j = i; j <= max; j++)
		{
			findArray[i + j * denom] = true;
		}
	}
}

void sundPartTwoSerial(int bound, bool * findArray, bool * primeArray)
{
	int max = (bound - 1) >> 1;
	for(int i = 1; i < max; i++)
	{
		if(!findArray[i])
		{
			primeArray[((i << 1) + 1)] = false;
		}
	}
	primeArray[2] = false;
}

///This function compares two arrays to see if they match in the range of prime numbers
void validatePrimes(int bound, bool* goldArray, bool* checkArray)
{
	for (int i = 0; i <= 100; i++)
	{
		cout << i << ".\t" << goldArray[i] << "\t" << checkArray[i] << endl;
	}

	for (int i = 0; i <= bound; i++)
	{
		if (goldArray[i] != checkArray[i])
		{
			std::cout << "Difference at Position " << i << "\n";
			std::cout << "Array is Incorrect! \n";
			return;
		}
	}
	std::cout << "Found all primes! \n";
}

<|endoftext|>


<commit_before>#include "StdAfx.h"

#include <algorithm>

#include <common/rhoconf.h>

#include "BrowserFactory.h"
#include "CEBrowserEngine.h"
#include "IEBrowserEngine.h"
#include "EngineEventListner.h"
#include <common/RhodesApp.h>

//////////////////////////////////////////////////////////////////////////

extern "C" HINSTANCE rho_wmimpl_get_appinstance();
extern "C" const char* rho_wmimpl_get_webengine();
extern "C" const char* get_app_build_config_item(const char* key);
extern rho::IBrowserEngine* rho_wmimpl_get_webkitBrowserEngine(HWND hwndParent, HINSTANCE rhoAppInstance);

//////////////////////////////////////////////////////////////////////////

const char* rho::BrowserFactory::IETag     = "ie";
const char* rho::BrowserFactory::webkitTag = "webkit";

//////////////////////////////////////////////////////////////////////////

namespace rho
{

BrowserFactory* BrowserFactory::g_browserFactory = 0;

IBrowserFactory* BrowserFactory::getInstance()
{
    if (g_browserFactory == 0)
    {
        g_browserFactory = new BrowserFactory();
    }

    return g_browserFactory;
}

IBrowserEngine* BrowserFactory::createWebkit(HWND hwndParent)
{
	RHODESAPP().getExtManager().getEngineEventMngr().setEngineType(rho::engineeventlistner::eWebkit);
	return rho_wmimpl_get_webkitBrowserEngine(hwndParent, rho_wmimpl_get_appinstance());

	if (RHO_IS_WMDEVICE)
    {
        return CIEBrowserEngine::getInstance(hwndParent, rho_wmimpl_get_appinstance());
    }
    else
    {
        return new CEBrowserEngine(hwndParent, rho_wmimpl_get_appinstance());
    }
}

IBrowserEngine* BrowserFactory::createIE(HWND hwndParent)
{
    if (RHO_IS_WMDEVICE)
    {
		RHODESAPP().getExtManager().getEngineEventMngr().setEngineType(rho::engineeventlistner::eWmIe);
		//TODO TAU
		return 0;
        //return CIEBrowserEngine::getInstance(hwndParent, rho_wmimpl_get_appinstance());
    }
    else
    {
		RHODESAPP().getExtManager().getEngineEventMngr().setEngineType(rho::engineeventlistner::eCeIe);
        return new CEBrowserEngine(hwndParent, rho_wmimpl_get_appinstance());
    }
}

EBrowserEngineType BrowserFactory::convertBrowserType(rho::String browserType)
{
    rho::String browserTypeTag;

    std::transform(browserType.begin(), browserType.end(),
        std::back_inserter(browserTypeTag), ::tolower);

    if (browserTypeTag == String(IETag))
    {
        return eIE;
    }
    else if (browserTypeTag == String(webkitTag))
    {
        return eWebkit;
    }

    return eNone;
}

IBrowserEngine* BrowserFactory::create(HWND hwndParent)
{
    EBrowserEngineType selBrowserType  = eNone;
    String             buildConfigType = "";
    //TODO TAU
	//String             xmlConfigType   = rho_wmimpl_get_webengine();
	String             xmlConfigType;
    String             rhoConfigType   = RHOCONF().getString("webengine");

    if (get_app_build_config_item("webengine"))
    {
        buildConfigType = get_app_build_config_item("webengine");
    }

    if (buildConfigType.empty())
    {
        if (xmlConfigType.empty())
        {
            selBrowserType = convertBrowserType(rhoConfigType);
        }
        else
        {
            selBrowserType = convertBrowserType(xmlConfigType);
        }
    }
    else
    {
        selBrowserType = convertBrowserType(buildConfigType);
    }

    if (selBrowserType == eNone)
    {
        selBrowserType = eWebkit;
        LOG(INFO) + "Browser engine was not set in config`s. Selected Webkit engine automatically.";
    }

	//TAU
	selBrowserType = eWebkit;
    m_selBrowserType = selBrowserType;

    switch (selBrowserType)
    {
    case eWebkit:
        LOG(INFO) + "Webkit browser engine was created.";
        return createWebkit(hwndParent);
        break;
    case eIE:
        LOG(INFO) + "IE browser engine was created.";
        return createIE(hwndParent);
        break;
    case eNone:
        LOG(ERROR) + "Browser engine was not selected.";
        break;
    }

    return 0;
}

EBrowserEngineType BrowserFactory::getBrowserType() const
{
    return m_selBrowserType;
}

EBrowserEngineType BrowserFactory::getCurrentBrowserType()
{
    if (getInstance())
    {
        return BrowserFactory::g_browserFactory->getBrowserType();
    }

    return eNone;
}

}//end of rho

//////////////////////////////////////////////////////////////////////////

extern "C" bool rho_wmimpl_is_browser_ieforwm()
{
    return (bool)(rho::eIE == rho::BrowserFactory::getCurrentBrowserType());
}<commit_msg>removed legacy code<commit_after>#include "StdAfx.h"

#include <algorithm>

#include <common/rhoconf.h>

#include "BrowserFactory.h"
#include "CEBrowserEngine.h"
#include "IEBrowserEngine.h"
#include "EngineEventListner.h"
#include <common/RhodesApp.h>

//////////////////////////////////////////////////////////////////////////

extern "C" HINSTANCE rho_wmimpl_get_appinstance();
extern "C" const char* rho_wmimpl_get_webengine();
extern "C" const char* get_app_build_config_item(const char* key);
extern rho::IBrowserEngine* rho_wmimpl_get_webkitBrowserEngine(HWND hwndParent, HINSTANCE rhoAppInstance);

//////////////////////////////////////////////////////////////////////////

const char* rho::BrowserFactory::IETag     = "ie";
const char* rho::BrowserFactory::webkitTag = "webkit";

//////////////////////////////////////////////////////////////////////////

namespace rho
{

BrowserFactory* BrowserFactory::g_browserFactory = 0;

IBrowserFactory* BrowserFactory::getInstance()
{
    if (g_browserFactory == 0)
    {
        g_browserFactory = new BrowserFactory();
    }

    return g_browserFactory;
}

IBrowserEngine* BrowserFactory::createWebkit(HWND hwndParent)
{
	RHODESAPP().getExtManager().getEngineEventMngr().setEngineType(rho::engineeventlistner::eWebkit);
	return rho_wmimpl_get_webkitBrowserEngine(hwndParent, rho_wmimpl_get_appinstance());
}

IBrowserEngine* BrowserFactory::createIE(HWND hwndParent)
{
    if (RHO_IS_WMDEVICE)
    {
		RHODESAPP().getExtManager().getEngineEventMngr().setEngineType(rho::engineeventlistner::eWmIe);
		return CIEBrowserEngine::getInstance(hwndParent, rho_wmimpl_get_appinstance());
    }
    else
    {
		RHODESAPP().getExtManager().getEngineEventMngr().setEngineType(rho::engineeventlistner::eCeIe);
        return new CEBrowserEngine(hwndParent, rho_wmimpl_get_appinstance());
    }
}

EBrowserEngineType BrowserFactory::convertBrowserType(rho::String browserType)
{
    rho::String browserTypeTag;

    std::transform(browserType.begin(), browserType.end(),
        std::back_inserter(browserTypeTag), ::tolower);

    if (browserTypeTag == String(IETag))
    {
        return eIE;
    }
    else if (browserTypeTag == String(webkitTag))
    {
        return eWebkit;
    }

    return eNone;
}

IBrowserEngine* BrowserFactory::create(HWND hwndParent)
{
    EBrowserEngineType selBrowserType  = eNone;
    String             buildConfigType = "";
    //TODO TAU
	//String             xmlConfigType   = rho_wmimpl_get_webengine();
	String             xmlConfigType;
    String             rhoConfigType   = RHOCONF().getString("webengine");

    if (get_app_build_config_item("webengine"))
    {
        buildConfigType = get_app_build_config_item("webengine");
    }

    if (buildConfigType.empty())
    {
        if (xmlConfigType.empty())
        {
            selBrowserType = convertBrowserType(rhoConfigType);
        }
        else
        {
            selBrowserType = convertBrowserType(xmlConfigType);
        }
    }
    else
    {
        selBrowserType = convertBrowserType(buildConfigType);
    }

    if (selBrowserType == eNone)
    {
        selBrowserType = eWebkit;
        LOG(INFO) + "Browser engine was not set in config`s. Selected Webkit engine automatically.";
    }

	//TAU
	selBrowserType = eWebkit;
    m_selBrowserType = selBrowserType;

    switch (selBrowserType)
    {
    case eWebkit:
        LOG(INFO) + "Webkit browser engine was created.";
        return createWebkit(hwndParent);
        break;
    case eIE:
        LOG(INFO) + "IE browser engine was created.";
        return createIE(hwndParent);
        break;
    case eNone:
        LOG(ERROR) + "Browser engine was not selected.";
        break;
    }

    return 0;
}

EBrowserEngineType BrowserFactory::getBrowserType() const
{
    return m_selBrowserType;
}

EBrowserEngineType BrowserFactory::getCurrentBrowserType()
{
    if (getInstance())
    {
        return BrowserFactory::g_browserFactory->getBrowserType();
    }

    return eNone;
}

}//end of rho

//////////////////////////////////////////////////////////////////////////

extern "C" bool rho_wmimpl_is_browser_ieforwm()
{
    return (bool)(rho::eIE == rho::BrowserFactory::getCurrentBrowserType());
}<|endoftext|>


<commit_before>/*
 CodeTree - A whitespace-agnostic, context-oriented code editor
 Copyright (C) 2013  Daniel Randall

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

// tests for library classes/code.

#include <iostream>
#include "../../Library/Queue.h"
#include "../../Library/Stack.h"

int g_tests = 0;
int g_passd = 0;

#define LE_STRING (const char*)pLE->m_pObject

void report(
	const char* fnm,
	const char* got,
	const char* exp)
{
	g_tests++;

	if (got == exp)
	{
		g_passd++;

		std::cout << "PASS: "<< (fnm ? fnm : "NULL") << "() == " << (exp ? exp : "NULL") << ")\n";
	}
	else
	{
		std::cout << "FAIL: "<< (fnm ? fnm : "NULL") << "() == " << (got ? got : "NULL") << ")\n";
	}
}

int main(int argc, const char * argv[])
{
	std::cout << "Testing Queue:\n\n";

	Queue queue;

	static const char alpha[]   = "ALPHA";
	static const char bravo[]   = "BRAVO";
	static const char charlie[] = "CHARLIE";
	static const char delta[]   = "DELTA";
	static const char echo[]    = "ECHO";
	static const char foxtrot[] = "FOXTROT";

	static const char enqueue[] = "Enqueue";

	ListElement* pLE = queue.Enqueue((OBJECT*)alpha);
	report(enqueue, LE_STRING, alpha);

	pLE = queue.Enqueue((OBJECT*)bravo);
	report(enqueue, LE_STRING, bravo);

	pLE = queue.Enqueue((OBJECT*)charlie);
	report(enqueue, LE_STRING, charlie);

	pLE = queue.Enqueue((OBJECT*)delta);
	report(enqueue, LE_STRING, delta);

	pLE = queue.Enqueue((OBJECT*)echo);
	report(enqueue, LE_STRING, echo);

	pLE = queue.Enqueue((OBJECT*)foxtrot);
	report(enqueue, LE_STRING, foxtrot);

	std::cout << "\n";

	std::cout << "Queue front: "<< (const char*)queue.getFront()->m_pObject << "\n";
	std::cout << "Queue back: "<< (const char*)queue.getBack()->m_pObject << "\n";

	std::cout << "\n";

	std::cout << "Dequeue: "<< (const char*)queue.Dequeue() << "\n";
	std::cout << "Dequeue: "<< (const char*)queue.Dequeue() << "\n";
	std::cout << "Dequeue: "<< (const char*)queue.Dequeue() << "\n";
	std::cout << "Dequeue: "<< (const char*)queue.Dequeue() << "\n";
	std::cout << "Dequeue: "<< (const char*)queue.Dequeue() << "\n";
	std::cout << "Dequeue: "<< (const char*)queue.Dequeue() << "\n";

	std::cout << "\n";
	std::cout << "\n";

	std::cout << "Testing Stack:\n\n";

	Stack stack;

	std::cout << "Push("<< (const char*)alpha << ")\n";
	stack.Push((OBJECT*)alpha);
	std::cout << "Push("<< (const char*)bravo << ")\n";
	stack.Push((OBJECT*)bravo);
	std::cout << "Push("<< (const char*)charlie << ")\n";
	stack.Push((OBJECT*)charlie);
	std::cout << "Push("<< (const char*)delta << ")\n";
	stack.Push((OBJECT*)delta);
	std::cout << "Push("<< (const char*)echo << ")\n";
	stack.Push((OBJECT*)echo);
	std::cout << "Push("<< (const char*)foxtrot << ")\n";
	stack.Push((OBJECT*)foxtrot);

	std::cout << "\n";

	std::cout << "Stack top: "<< (const char*)stack.getTop()->m_pObject << "\n";
	std::cout << "Stack bottom: "<< (const char*)stack.getBottom()->m_pObject << "\n";

	std::cout << "\n";

	std::cout << "Pop: "<< (const char*)stack.Pop() << "\n";
	std::cout << "Pop: "<< (const char*)stack.Pop() << "\n";
	std::cout << "Pop: "<< (const char*)stack.Pop() << "\n";
	std::cout << "Pop: "<< (const char*)stack.Pop() << "\n";
	std::cout << "Pop: "<< (const char*)stack.Pop() << "\n";
	std::cout << "Pop: "<< (const char*)stack.Pop() << "\n";

	std::cout << "\n";

	std::cout << "Tests:  "<< g_tests << "\n";
	std::cout << "Passed: "<< g_passd << "\n";

	return 0;
}

<commit_msg>refined tests to check for underflow.<commit_after>/*
 CodeTree - A whitespace-agnostic, context-oriented code editor
 Copyright (C) 2013  Daniel Randall

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

// tests for library classes/code.

#include <iostream>
#include "../../Library/Queue.h"
#include "../../Library/Stack.h"

int g_tests = 0;
int g_passd = 0;

#define LE_STRING (const char*)pLE->m_pObject

// reports on an OBJECT test:
void report(
	const char* fnm,
	OBJECT* got,
	const char* exp)
{
	g_tests++;

	const char* cGot = (const char*)got;
	const char* cExp = (const char*)exp;

	if (got == exp)
	{
		g_passd++;

		std::cout << "PASS: "<< (fnm ? fnm : "NULL") << " == " << (cExp ? cExp : "NULL") << "\n";
	}
	else
	{
		std::cout << "FAIL: "<< (fnm ? fnm : "NULL") << " == " << (cGot ? cGot : "NULL") << "\n";
	}
}

// reports on a list element test:
void reportLE(
  const char* fnm,
  ListElement* pLE,
	const char* exp)
{
	if (exp)
	{
		report(fnm, pLE->m_pObject, exp);
	}
	else
	{
		report(fnm, NULL, exp);
	}
}

int main(int argc, const char * argv[])
{
	static const char alpha[]   = "ALPHA";
	static const char bravo[]   = "BRAVO";
	static const char charlie[] = "CHARLIE";
	static const char delta[]   = "DELTA";
	static const char echo[]    = "ECHO";
	static const char foxtrot[] = "FOXTROT";

	std::cout << "Testing Queue:\n\n";

	static const char enqueue[] = "Enqueue()";
	static const char dequeue[] = "Dequeue()";
	static const char getfront[] = "getFront()";
	static const char getback[] = "getBack()";

	Queue queue;

	std::cout << "queue should be empty:\n";

	report(dequeue, queue.Dequeue(), NULL);
	reportLE(getfront, queue.getFront(), NULL);
	reportLE(getback, queue.getBack(), NULL);

	std::cout << "enqueue some items:\n";

	reportLE(enqueue, queue.Enqueue((OBJECT*)alpha),   alpha);
	reportLE(enqueue, queue.Enqueue((OBJECT*)bravo),   bravo);
	reportLE(enqueue, queue.Enqueue((OBJECT*)charlie), charlie);
	reportLE(enqueue, queue.Enqueue((OBJECT*)delta),   delta);
	reportLE(enqueue, queue.Enqueue((OBJECT*)echo),    echo);
	reportLE(enqueue, queue.Enqueue((OBJECT*)foxtrot), foxtrot);

	std::cout << "queue should have content:\n";

	reportLE(getfront, queue.getFront(), alpha);
	reportLE(getback, queue.getBack(), foxtrot);

	std::cout << "dequeue all items:\n";

	report(dequeue, queue.Dequeue(), alpha);
	report(dequeue, queue.Dequeue(), bravo);
	report(dequeue, queue.Dequeue(), charlie);
	report(dequeue, queue.Dequeue(), delta);
	report(dequeue, queue.Dequeue(), echo);
	report(dequeue, queue.Dequeue(), foxtrot);

	std::cout << "stack should be empty (again):\n";

	report(dequeue, queue.Dequeue(), NULL);
	reportLE(getfront, queue.getFront(), NULL);
	reportLE(getback, queue.getBack(), NULL);

	std::cout << "\n";
	std::cout << "\n";

	std::cout << "Testing Stack:\n\n";

	Stack stack;

	static const char f_push[] = "Push()";
	static const char f_pop[] = "Pop()";
	static const char gettop[] = "getTop()";
	static const char getbottom[] = "getBottom()";

	std::cout << "stack should be empty:\n";

	report(f_pop, stack.Pop(), NULL);
	reportLE(gettop, stack.getTop(), NULL);
	reportLE(getbottom, stack.getBottom(), NULL);

	std::cout << "push some items:\n";

	reportLE(f_push, stack.Push((OBJECT*)alpha),   alpha);
	reportLE(f_push, stack.Push((OBJECT*)bravo),   bravo);
	reportLE(f_push, stack.Push((OBJECT*)charlie), charlie);
	reportLE(f_push, stack.Push((OBJECT*)delta),   delta);
	reportLE(f_push, stack.Push((OBJECT*)echo),    echo);
	reportLE(f_push, stack.Push((OBJECT*)foxtrot), foxtrot);

	std::cout << "stack should have content:\n";

	reportLE(gettop, stack.getTop(), foxtrot);
	reportLE(getbottom, stack.getBottom(), alpha);

	std::cout << "dequeue all items:\n";

	report(f_pop, stack.Pop(), foxtrot);
	report(f_pop, stack.Pop(), echo);
	report(f_pop, stack.Pop(), delta);
	report(f_pop, stack.Pop(), charlie);
	report(f_pop, stack.Pop(), bravo);
	report(f_pop, stack.Pop(), alpha);

	std::cout << "stack should be empty (again):\n";

	report(f_pop, stack.Pop(), NULL);
	reportLE(gettop, stack.getTop(), NULL);
	reportLE(getbottom, stack.getBottom(), NULL);

	std::cout << "\n";
	std::cout << "\n";

	std::cout << "Tests:  "<< g_tests << "\n";
	std::cout << "Passed: "<< g_passd << "\n\n";

	return 0;
}

<|endoftext|>