<commit_before>
#include "gpio.h"
#include <iostream>
#include <string>
#include <stdexcept>
#include <map>
#include <cstring>

namespace
{
   struct Comp
   {
      bool operator()( const char *a, const char *b ) const
      {
         return strcmp( a, b ) < 0;
      }
   };

   const std::map<const char *,int, Comp> nameMap =
   {
      { "P8.3", 32 + 6 },
      { "P8.4", 32 + 7 },
      { "P8.5", 32 + 2 },
      { "P8.6", 32 + 3 },
      { "P8.7", 64 + 2 },
      { "P8.8", 64 + 3 },
      { "P8.9", 64 + 5 },
      { "P8.10", 64 + 4 },
      { "P8.11", 32 + 13 },
      { "P8.12", 32 + 12 },
      { "P8.13", 0 + 23 },
      { "P8.14", 0 + 26 },
      { "P8.15", 32 + 15 },
      { "P8.16", 32 + 14 },
      { "P8.17", 0 + 27 },
      { "P8.18", 64 + 1 },
      { "P8.19", 0 + 22 },
      { "P8.20", 32 + 31 },
      { "P8.21", 32 + 30 },
      { "P8.22", 32 + 5 },
      { "P8.23", 32 + 4 },
      { "P8.24", 32 + 1 },
      { "P8.25", 32 + 0 },
      { "P8.26", 32 + 29 },
      { "P8.27", 64 + 22 },
      { "P8.28", 64 + 24 },
      { "P8.29", 64 + 23 },
      { "P8.30", 64 + 25 },
      { "P8.31", 0 + 10 },
      { "P8.32", 0 + 11 },
      { "P8.33", 0 + 9 },
      { "P8.34", 64 + 17 },
      { "P8.35", 0 + 8 },
      { "P8.36", 64 + 16 },
      { "P8.37", 64 + 14 },
      { "P8.38", 64 + 15 },
      { "P8.39", 64 + 12 },
      { "P8.40", 64 + 13 },
      { "P8.41", 64 + 10 },
      { "P8.42", 64 + 11 },
      { "P8.43", 64 + 8 },
      { "P8.44", 64 + 9 },
      { "P8.45", 64 + 6 },
      { "P8.46", 64 + 7 },
      { "P9.11", 0 + 30 },
      { "P9.12", 32 + 28 },
      { "P9.13", 0 + 31 },
      { "P9.14", 32 + 18 },
      { "P9.15", 32 + 16 },
      { "P9.16", 32 + 19 },
      { "P9.17", 0 + 5 },
      { "P9.18", 0 + 4 },
      { "P9.19", 0 + 13 },
      { "P9.20", 0 + 12 },
      { "P9.21", 0 + 3 },
      { "P9.22", 0 + 2 },
      { "P9.23", 32 + 17 },
      { "P9.24", 0 + 15 },
      { "P9.25", 96 + 21 },
      { "P9.26", 0 + 14 },
      { "P9.27", 96 + 19 },
      { "P9.28", 96 + 17 },
      { "P9.29", 96 + 15 },
      { "P9.30", 96 + 16 },
      { "P9.31", 96 + 14 },
      // LEDs
      { "USR0", 32 + 21 },
      { "USR1", 32 + 22 },
      { "USR2", 32 + 23 },
      { "USR3", 32 + 24 },
   };

   int getNumberFromName( const char *name )
   {
      if( strncmp( name, "GPIO", 4 ) == 0 )
      {
         const int bank = atoi( name + 4 );
         const char *p = strchr( name, '_' );
         if( p == nullptr )
            throw std::invalid_argument( "Invalid GPIO name" );
         const int num = atoi( p + 1 );
         return bank * 32 + num;
      }
      auto p( nameMap.find( name ) );
      if( p == nameMap.end() )
         throw std::invalid_argument( "Invalid header name" );
      return p->second;
   }
}

void GPO::unexport( )
{
   const std::string path(  "/sys/class/gpio/" );
   std::fstream f( (path + "unexport" ).c_str(), std::ios_base::out );
   f << gpio;
   f.close();
}

GPO::GPO( int gpio_ ) : gpio( gpio_ )
{
   const std::string path(  "/sys/class/gpio/" );
   std::fstream f( (path + "export" ).c_str(), std::ios_base::out );
   f.exceptions ( std::ifstream::failbit | std::ifstream::badbit );
   f << gpio;
   f.close();

   try
   {
      f.open( (path + "gpio" + std::to_string( gpio ) + "/direction").c_str(),
            std::ios_base::out );
      f << "out";
      f.close();
      fstr.open( (path + "gpio" + std::to_string( gpio ) + "/value").c_str(),
            std::ios_base::out );
      fstr.exceptions ( std::ifstream::failbit | std::ifstream::badbit );
   }
   catch( ... )
   {
      unexport( );
      throw;
   }
}

GPO::GPO( const char *name ) : GPO( getNumberFromName( name ) )
{
}

GPO::~GPO( )
{
   if( fstr.is_open() )
      close();
}

void GPO::set( bool val )
{
   fstr << (int)val;
   fstr.flush();
}

void GPO::close( )
{
   fstr.close();
   unexport();
}
<commit_msg>Use fstream::put(), which is faster<commit_after>
#include "gpio.h"
#include <iostream>
#include <string>
#include <stdexcept>
#include <map>
#include <cstring>

namespace
{
   struct Comp
   {
      bool operator()( const char *a, const char *b ) const
      {
         return strcmp( a, b ) < 0;
      }
   };

   const std::map<const char *,int, Comp> nameMap =
   {
      { "P8.3", 32 + 6 },
      { "P8.4", 32 + 7 },
      { "P8.5", 32 + 2 },
      { "P8.6", 32 + 3 },
      { "P8.7", 64 + 2 },
      { "P8.8", 64 + 3 },
      { "P8.9", 64 + 5 },
      { "P8.10", 64 + 4 },
      { "P8.11", 32 + 13 },
      { "P8.12", 32 + 12 },
      { "P8.13", 0 + 23 },
      { "P8.14", 0 + 26 },
      { "P8.15", 32 + 15 },
      { "P8.16", 32 + 14 },
      { "P8.17", 0 + 27 },
      { "P8.18", 64 + 1 },
      { "P8.19", 0 + 22 },
      { "P8.20", 32 + 31 },
      { "P8.21", 32 + 30 },
      { "P8.22", 32 + 5 },
      { "P8.23", 32 + 4 },
      { "P8.24", 32 + 1 },
      { "P8.25", 32 + 0 },
      { "P8.26", 32 + 29 },
      { "P8.27", 64 + 22 },
      { "P8.28", 64 + 24 },
      { "P8.29", 64 + 23 },
      { "P8.30", 64 + 25 },
      { "P8.31", 0 + 10 },
      { "P8.32", 0 + 11 },
      { "P8.33", 0 + 9 },
      { "P8.34", 64 + 17 },
      { "P8.35", 0 + 8 },
      { "P8.36", 64 + 16 },
      { "P8.37", 64 + 14 },
      { "P8.38", 64 + 15 },
      { "P8.39", 64 + 12 },
      { "P8.40", 64 + 13 },
      { "P8.41", 64 + 10 },
      { "P8.42", 64 + 11 },
      { "P8.43", 64 + 8 },
      { "P8.44", 64 + 9 },
      { "P8.45", 64 + 6 },
      { "P8.46", 64 + 7 },
      { "P9.11", 0 + 30 },
      { "P9.12", 32 + 28 },
      { "P9.13", 0 + 31 },
      { "P9.14", 32 + 18 },
      { "P9.15", 32 + 16 },
      { "P9.16", 32 + 19 },
      { "P9.17", 0 + 5 },
      { "P9.18", 0 + 4 },
      { "P9.19", 0 + 13 },
      { "P9.20", 0 + 12 },
      { "P9.21", 0 + 3 },
      { "P9.22", 0 + 2 },
      { "P9.23", 32 + 17 },
      { "P9.24", 0 + 15 },
      { "P9.25", 96 + 21 },
      { "P9.26", 0 + 14 },
      { "P9.27", 96 + 19 },
      { "P9.28", 96 + 17 },
      { "P9.29", 96 + 15 },
      { "P9.30", 96 + 16 },
      { "P9.31", 96 + 14 },
      // LEDs
      { "USR0", 32 + 21 },
      { "USR1", 32 + 22 },
      { "USR2", 32 + 23 },
      { "USR3", 32 + 24 },
   };

   int getNumberFromName( const char *name )
   {
      if( strncmp( name, "GPIO", 4 ) == 0 )
      {
         const int bank = atoi( name + 4 );
         const char *p = strchr( name, '_' );
         if( p == nullptr )
            throw std::invalid_argument( "Invalid GPIO name" );
         const int num = atoi( p + 1 );
         return bank * 32 + num;
      }
      auto p( nameMap.find( name ) );
      if( p == nameMap.end() )
         throw std::invalid_argument( "Invalid header name" );
      return p->second;
   }
}

void GPO::unexport( )
{
   const std::string path(  "/sys/class/gpio/" );
   std::fstream f( (path + "unexport" ).c_str(), std::ios_base::out );
   f << gpio;
   f.close();
}

GPO::GPO( int gpio_ ) : gpio( gpio_ )
{
   const std::string path(  "/sys/class/gpio/" );
   std::fstream f( (path + "export" ).c_str(), std::ios_base::out );
   f.exceptions ( std::ifstream::failbit | std::ifstream::badbit );
   f << gpio;
   f.close();

   try
   {
      f.open( (path + "gpio" + std::to_string( gpio ) + "/direction").c_str(),
            std::ios_base::out );
      f << "out";
      f.close();
      fstr.open( (path + "gpio" + std::to_string( gpio ) + "/value").c_str(),
            std::ios_base::out );
      fstr.exceptions ( std::ifstream::failbit | std::ifstream::badbit );
   }
   catch( ... )
   {
      unexport( );
      throw;
   }
}

GPO::GPO( const char *name ) : GPO( getNumberFromName( name ) )
{
}

GPO::~GPO( )
{
   if( fstr.is_open() )
      close();
}

void GPO::set( bool val )
{
   fstr.put( val ? '1' : '0' );
   fstr.flush();
}

void GPO::close( )
{
   fstr.close();
   unexport();
}
<|endoftext|>


<commit_before>#include "grid.hpp"

#include <cmath>
#include <vector>

std::deque<rectangle>
grid_t::arrange(const rectangle & screen, unsigned int nrects) const
{
  int gap = 5;

  int radix = std::round(std::sqrt(nrects));
  int rest = nrects - (radix * radix);

  std::vector<int> cells(radix, radix);

  if (rest < 0 || (rest > 0 && rest < radix / 2.0)) {
    cells.back() += rest;
  } else if (rest > 0) {
    cells.push_back(rest);
  }

  int ncol = cells.size();
  int colw = screen.width() / ncol;

  std::deque<rectangle> rects;
  for (int c = 0; c < ncol; ++c) {
    int nrow = cells[c];
    int rowh = screen.height() / nrow;
    for (int r = 0; r < nrow; ++r) {
      rects.push_back(rectangle(c * colw + screen.x() + gap,
                                  r * rowh + screen.y() + gap,
                                  colw - 2 * gap, rowh - 2 * gap));
    }
  }

  return rects;
}
<commit_msg>Fix indendation<commit_after>#include "grid.hpp"

#include <cmath>
#include <vector>

std::deque<rectangle>
grid_t::arrange(const rectangle & screen, unsigned int nrects) const
{
  int gap = 5;

  int radix = std::round(std::sqrt(nrects));
  int rest = nrects - (radix * radix);

  std::vector<int> cells(radix, radix);

  if (rest < 0 || (rest > 0 && rest < radix / 2.0)) {
    cells.back() += rest;
  } else if (rest > 0) {
    cells.push_back(rest);
  }

  int ncol = cells.size();
  int colw = screen.width() / ncol;

  std::deque<rectangle> rects;
  for (int c = 0; c < ncol; ++c) {
    int nrow = cells[c];
    int rowh = screen.height() / nrow;
    for (int r = 0; r < nrow; ++r) {
      rects.push_back(rectangle(c * colw + screen.x() + gap,
                                r * rowh + screen.y() + gap,
                                colw - 2 * gap,
                                rowh - 2 * gap));
    }
  }

  return rects;
}
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2003-2004 Adam Geitgey <adam@rootnode.org>              *
 *   Copyright (C) 2003 Hans Karlsson <karlsson.h@home.se>                 *
 *                                                                         *
 *   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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/

#include <qstring.h>
#include <qstringlist.h>
#include <qdir.h>
#include <kfiledialog.h>
#include <kcmdlineargs.h>
#include <fcntl.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <khelpmenu.h>

#include <qtooltip.h>
#include <QByteArray>
#include <QtAlgorithms>

#include "themesdlg.h"
#include "karambainterface.h"
#include "karambaapp.h"
#include "dcopinterface_stub.h"
#include "karambawidget.h"
#include "karamba_python.h"
#include "superkarambasettings.h"

int KarambaApplication::fd = -1;

KarambaApplication::KarambaApplication()
    :   KUniqueApplication(),
        m_helpMenu(0),
        iface(0),
        themeListWindow(0),
        dcopIfaceStub(0),
        sysTrayIcon(0)
{
    // god get rid of this shit
    iface = new KarambaIface();
    // register ourselves as a dcop client
    dcopClient()->registerAs(name());
    dcopClient()->setDefaultObject(dcopIface()->objId());

// JESUS
    QStringList lst;
    QString mainAppId = getMainKaramba();
    if(!mainAppId.isEmpty())
    {
        initDcopStub(mainAppId.toAscii());
    }
    else
    {
        //Set up systray icon
        setUpSysTray(/*&about*/ 0);
        initDcopStub();
    }

    // Try to restore a previous session if applicable.
    if (isSessionRestored())
    {
        KConfig* config = sessionConfig();
        config->setGroup("General Options");
        QString restartThemes = config->readEntry("OpenThemes","");

        //Get themes that were running
        lst = QStringList::split(QString(";"), restartThemes);
    }

    if(lst.size() == 0)
    {
/*
        //Not a saved session - check for themes given on command line
        if(args->count() > 0)
        {
            for(int i = 0; i < (args->count()); i++)
            {
                if( args->arg(i) != "" )
                {
                    KURL url = args->url(i);
                    lst.push_back(url.path());
                }
            }
        }
*/

  //      app.checkCommandLine(args, lst);

        if(lst.size() == 0)
        {
            //No themes given on command line and no saved session.
            //Show welcome dialog.
            showThemeDialog();
        }
    }

//    args->clear();

    //qDebug("startThemes");
    if (!lst.isEmpty())
    {
        startThemes(lst);
    }

// End JESUS

    KarambaPython::initPython();
    connect( this, SIGNAL(lastWindowClosed()), SLOT(quit()));
}

KarambaApplication::~KarambaApplication()
{
    KarambaPython::shutdownPython();

    qDeleteAll(m_karambas);
    m_karambas.clear();

    delete iface;
    delete themeListWindow;
    delete dcopIfaceStub;
    //delete m_helpMenu;
}

void KarambaApplication::initDcopStub(QByteArray app)
{
    if(app.isEmpty())
        app = dcopClient()->appId();
    dcopIfaceStub = new dcopIface_stub(app, iface->objId());
}

QString KarambaApplication::getMainKaramba()
{
    QStringList karambas = getKarambas();
    QStringList::Iterator it;

    for (it = karambas.begin(); it != karambas.end(); ++it)
    {
        if((*it).ascii() == dcopClient()->appId())
            continue;
        dcopIface_stub dcop((*it).ascii(), iface->objId());
        if (dcop.isMainKaramba())
            return *it;
    }
    return QString::null;
}

QStringList KarambaApplication::getKarambas()
{
    DCOPCStringList applst = dcopClient()->registeredApplications();
    DCOPCStringList::Iterator it;
    DCOPCString s;
    QStringList result;

    foreach (DCOPCString s, applst)
    {
        if (s.left(strlen(name())) == name())
        {
            result.append(s);

        }
    }
    return result;
}

void KarambaApplication::setUpSysTray(KAboutData* about)
{
    //kdDebug() << k_funcinfo << endl;
    KAction* action;

    //Create theme list window.
    //This will function as the main window for the tray icon
    themeListWindow = new ThemesDlg();

    //Set up systray icon
    sysTrayIcon = new KSystemTray(themeListWindow);

    KPopupMenu *menu = sysTrayIcon->contextMenu();
    menu->insertItem(SmallIconSet("superkaramba"),
                     i18n("Hide System Tray Icon"), this,
                     SLOT(globalHideSysTray()));
    menu->insertSeparator();

    m_helpMenu = new KHelpMenu(themeListWindow, about);
    action = KStdAction::help(m_helpMenu, SLOT(appHelpActivated()),
                              sysTrayIcon->actionCollection());
    action->plug(menu);
    action = KStdAction::aboutApp(m_helpMenu, SLOT(aboutApplication()),
                                  sysTrayIcon->actionCollection());
    action->plug(menu);
    action = KStdAction::aboutKDE(m_helpMenu, SLOT(aboutKDE()),
                                  sysTrayIcon->actionCollection());
    action->plug(menu);

    sysTrayIcon->setPixmap(sysTrayIcon->loadIcon("superkaramba"));
    setToolTip();

    if(SuperKarambaSettings::showSysTray())
        sysTrayIcon->show();
    else
        sysTrayIcon->hide();

    //Connect Systray icon's quit event
    QObject::connect(sysTrayIcon, SIGNAL(quitSelected()),
                     this, SLOT(globalQuitSuperKaramba()));
}

void KarambaApplication::showKarambaMenuExtension(bool show)
{
    if(show)
    {
        foreach (QObject *k, m_karambas)
        {
            ((KarambaWidget*)k)->showMenuExtension();
        }
    }
    else
    {
        foreach (QObject *k, m_karambas)
        {
            ((KarambaWidget*)k)->hideMenuExtension();
        }
    }
}

void KarambaApplication::setToolTip(const QString &tip)
{
    QToolTip::remove
        (sysTrayIcon);
    if(tip.isNull())
        QToolTip::add
            (sysTrayIcon, i18n("SuperKaramba"));
    else
        QToolTip::add
            (sysTrayIcon, tip);
}

void KarambaApplication::buildToolTip()
{
    if(!sysTrayIcon || !themeListWindow)
        return;

    QStringList list = themeListWindow->runningThemes();

    if(list.isEmpty())
    {
        setToolTip();
        return;
    }

    QString toolTip("" + i18n("SuperKaramba") + "");
    toolTip += "
";

    bool firstRun = true;
    for(QStringList::Iterator it = list.begin(); it != list.end(); ++it )
    {
        if(firstRun)
        {
            toolTip +=
                "
" +
                i18n("1 Running Theme:", "%n Running Themes:", list.count()) +
                "	" + (*it) + "
";
            firstRun = false;
        }
        else
        {
            toolTip += "
	" + (*it) + "
";
        }
    }

    toolTip += "
";

    setToolTip(toolTip);
}

bool KarambaApplication::startThemes(QStringList &lst)
{
    bool result = false;

    for(QStringList::Iterator it = lst.begin(); it != lst.end(); ++it )
    {
        KarambaWidget *mainWin = 0;

        mainWin = new KarambaWidget(*it , false);
        mainWin->show();
        result = true;
    }

    buildToolTip();
    return result;
}

void KarambaApplication::addKaramba(KarambaWidget* k, bool reloading)
{
    if(!reloading && karambaApp->dcopStub())
    {
        int instance = karambaApp->dcopStub()->themeAdded(
                           karambaApp->dcopClient()->appId(), k->theme().file());
        k->setInstance(instance);
    }
    m_karambas.append(k);
}

void KarambaApplication::deleteKaramba(KarambaWidget* k, bool reloading)
{
    if(!reloading && karambaApp->dcopStub())
        karambaApp->dcopStub()->themeClosed(
            karambaApp->dcopClient()->appId(), k->theme().file(), k->instance());
    m_karambas.removeAll(k);
}

bool KarambaApplication::hasKaramba(KarambaWidget* k)
{
    return m_karambas.count(k) > 0;
}

void KarambaApplication::hideSysTray(bool hide)
{
    //kdDebug() << k_funcinfo << endl;
    if(hide)
    {
        if(sysTrayIcon)
        {
            KMessageBox::information(0,
                                     i18n("<qt>Hiding the system tray icon will keep SuperKaramba running "
                                          "in background. To show it again use the theme menu.</qt>"),
                                     i18n("Hiding System Tray Icon"), "hideIcon");
            sysTrayIcon->hide();
        }
        showKarambaMenuExtension();
    }
    else
    {
        showKarambaMenuExtension(false);
        if(sysTrayIcon)
            sysTrayIcon->show();
    }
}

void KarambaApplication::showThemeDialog()
{
    //kdDebug() << k_funcinfo << endl;
    if(themeListWindow)
        themeListWindow->show();
}

void KarambaApplication::quitSuperKaramba()
{
    if(themeListWindow)
    {
        themeListWindow->saveUserAddedThemes();
    }

    closeAllWindows();
    quit();
}

void KarambaApplication::globalQuitSuperKaramba()
{
    QStringList apps = getKarambas();
    QStringList::Iterator it;

    for (it = apps.begin(); it != apps.end(); ++it)
    {
        dcopIface_stub dcop((*it).ascii(), dcopIface()->objId());
        dcop.quit();
    }
}

void KarambaApplication::globalHideSysTray(bool hide)
{
    //kdDebug() << k_funcinfo << endl;
    QStringList apps = getKarambas();
    QStringList::Iterator it;

    SuperKarambaSettings::setShowSysTray(!hide);
    SuperKarambaSettings::writeConfig();

    for (it = apps.begin(); it != apps.end(); ++it)
    {
        dcopIface_stub dcop((*it).ascii(), dcopIface()->objId());
        dcop.hideSystemTray(hide);
    }
}

#include "karambaapp.moc"
<commit_msg>Warning--<commit_after>/***************************************************************************
 *   Copyright (C) 2003-2004 Adam Geitgey <adam@rootnode.org>              *
 *   Copyright (C) 2003 Hans Karlsson <karlsson.h@home.se>                 *
 *                                                                         *
 *   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 2 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/

#include <qstring.h>
#include <qstringlist.h>
#include <qdir.h>
#include <kfiledialog.h>
#include <kcmdlineargs.h>
#include <fcntl.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kdebug.h>
#include <khelpmenu.h>

#include <qtooltip.h>
#include <QByteArray>
#include <QtAlgorithms>

#include "themesdlg.h"
#include "karambainterface.h"
#include "karambaapp.h"
#include "dcopinterface_stub.h"
#include "karambawidget.h"
#include "karamba_python.h"
#include "superkarambasettings.h"

int KarambaApplication::fd = -1;

KarambaApplication::KarambaApplication()
    :   KUniqueApplication(),
		iface(0),
        themeListWindow(0),
		dcopIfaceStub(0),
        sysTrayIcon(0),
		m_helpMenu(0)
{
    // god get rid of this shit
    iface = new KarambaIface();
    // register ourselves as a dcop client
    dcopClient()->registerAs(name());
    dcopClient()->setDefaultObject(dcopIface()->objId());

// JESUS
    QStringList lst;
    QString mainAppId = getMainKaramba();
    if(!mainAppId.isEmpty())
    {
        initDcopStub(mainAppId.toAscii());
    }
    else
    {
        //Set up systray icon
        setUpSysTray(/*&about*/ 0);
        initDcopStub();
    }

    // Try to restore a previous session if applicable.
    if (isSessionRestored())
    {
        KConfig* config = sessionConfig();
        config->setGroup("General Options");
        QString restartThemes = config->readEntry("OpenThemes","");

        //Get themes that were running
        lst = QStringList::split(QString(";"), restartThemes);
    }

    if(lst.size() == 0)
    {
/*
        //Not a saved session - check for themes given on command line
        if(args->count() > 0)
        {
            for(int i = 0; i < (args->count()); i++)
            {
                if( args->arg(i) != "" )
                {
                    KURL url = args->url(i);
                    lst.push_back(url.path());
                }
            }
        }
*/

  //      app.checkCommandLine(args, lst);

        if(lst.size() == 0)
        {
            //No themes given on command line and no saved session.
            //Show welcome dialog.
            showThemeDialog();
        }
    }

//    args->clear();

    //qDebug("startThemes");
    if (!lst.isEmpty())
    {
        startThemes(lst);
    }

// End JESUS

    KarambaPython::initPython();
    connect( this, SIGNAL(lastWindowClosed()), SLOT(quit()));
}

KarambaApplication::~KarambaApplication()
{
    KarambaPython::shutdownPython();

    qDeleteAll(m_karambas);
    m_karambas.clear();

    delete iface;
    delete themeListWindow;
    delete dcopIfaceStub;
    //delete m_helpMenu;
}

void KarambaApplication::initDcopStub(QByteArray app)
{
    if(app.isEmpty())
        app = dcopClient()->appId();
    dcopIfaceStub = new dcopIface_stub(app, iface->objId());
}

QString KarambaApplication::getMainKaramba()
{
    QStringList karambas = getKarambas();
    QStringList::Iterator it;

    for (it = karambas.begin(); it != karambas.end(); ++it)
    {
        if((*it).ascii() == dcopClient()->appId())
            continue;
        dcopIface_stub dcop((*it).ascii(), iface->objId());
        if (dcop.isMainKaramba())
            return *it;
    }
    return QString::null;
}

QStringList KarambaApplication::getKarambas()
{
    DCOPCStringList applst = dcopClient()->registeredApplications();
    DCOPCStringList::Iterator it;
    DCOPCString s;
    QStringList result;

    foreach (DCOPCString s, applst)
    {
        if (s.left(strlen(name())) == name())
        {
            result.append(s);

        }
    }
    return result;
}

void KarambaApplication::setUpSysTray(KAboutData* about)
{
    //kdDebug() << k_funcinfo << endl;
    KAction* action;

    //Create theme list window.
    //This will function as the main window for the tray icon
    themeListWindow = new ThemesDlg();

    //Set up systray icon
    sysTrayIcon = new KSystemTray(themeListWindow);

    KPopupMenu *menu = sysTrayIcon->contextMenu();
    menu->insertItem(SmallIconSet("superkaramba"),
                     i18n("Hide System Tray Icon"), this,
                     SLOT(globalHideSysTray()));
    menu->insertSeparator();

    m_helpMenu = new KHelpMenu(themeListWindow, about);
    action = KStdAction::help(m_helpMenu, SLOT(appHelpActivated()),
                              sysTrayIcon->actionCollection());
    action->plug(menu);
    action = KStdAction::aboutApp(m_helpMenu, SLOT(aboutApplication()),
                                  sysTrayIcon->actionCollection());
    action->plug(menu);
    action = KStdAction::aboutKDE(m_helpMenu, SLOT(aboutKDE()),
                                  sysTrayIcon->actionCollection());
    action->plug(menu);

    sysTrayIcon->setPixmap(sysTrayIcon->loadIcon("superkaramba"));
    setToolTip();

    if(SuperKarambaSettings::showSysTray())
        sysTrayIcon->show();
    else
        sysTrayIcon->hide();

    //Connect Systray icon's quit event
    QObject::connect(sysTrayIcon, SIGNAL(quitSelected()),
                     this, SLOT(globalQuitSuperKaramba()));
}

void KarambaApplication::showKarambaMenuExtension(bool show)
{
    if(show)
    {
        foreach (QObject *k, m_karambas)
        {
            ((KarambaWidget*)k)->showMenuExtension();
        }
    }
    else
    {
        foreach (QObject *k, m_karambas)
        {
            ((KarambaWidget*)k)->hideMenuExtension();
        }
    }
}

void KarambaApplication::setToolTip(const QString &tip)
{
    QToolTip::remove
        (sysTrayIcon);
    if(tip.isNull())
        QToolTip::add
            (sysTrayIcon, i18n("SuperKaramba"));
    else
        QToolTip::add
            (sysTrayIcon, tip);
}

void KarambaApplication::buildToolTip()
{
    if(!sysTrayIcon || !themeListWindow)
        return;

    QStringList list = themeListWindow->runningThemes();

    if(list.isEmpty())
    {
        setToolTip();
        return;
    }

    QString toolTip("" + i18n("SuperKaramba") + "");
    toolTip += "
";

    bool firstRun = true;
    for(QStringList::Iterator it = list.begin(); it != list.end(); ++it )
    {
        if(firstRun)
        {
            toolTip +=
                "
" +
                i18n("1 Running Theme:", "%n Running Themes:", list.count()) +
                "	" + (*it) + "
";
            firstRun = false;
        }
        else
        {
            toolTip += "
	" + (*it) + "
";
        }
    }

    toolTip += "
";

    setToolTip(toolTip);
}

bool KarambaApplication::startThemes(QStringList &lst)
{
    bool result = false;

    for(QStringList::Iterator it = lst.begin(); it != lst.end(); ++it )
    {
        KarambaWidget *mainWin = 0;

        mainWin = new KarambaWidget(*it , false);
        mainWin->show();
        result = true;
    }

    buildToolTip();
    return result;
}

void KarambaApplication::addKaramba(KarambaWidget* k, bool reloading)
{
    if(!reloading && karambaApp->dcopStub())
    {
        int instance = karambaApp->dcopStub()->themeAdded(
                           karambaApp->dcopClient()->appId(), k->theme().file());
        k->setInstance(instance);
    }
    m_karambas.append(k);
}

void KarambaApplication::deleteKaramba(KarambaWidget* k, bool reloading)
{
    if(!reloading && karambaApp->dcopStub())
        karambaApp->dcopStub()->themeClosed(
            karambaApp->dcopClient()->appId(), k->theme().file(), k->instance());
    m_karambas.removeAll(k);
}

bool KarambaApplication::hasKaramba(KarambaWidget* k)
{
    return m_karambas.count(k) > 0;
}

void KarambaApplication::hideSysTray(bool hide)
{
    //kdDebug() << k_funcinfo << endl;
    if(hide)
    {
        if(sysTrayIcon)
        {
            KMessageBox::information(0,
                                     i18n("<qt>Hiding the system tray icon will keep SuperKaramba running "
                                          "in background. To show it again use the theme menu.</qt>"),
                                     i18n("Hiding System Tray Icon"), "hideIcon");
            sysTrayIcon->hide();
        }
        showKarambaMenuExtension();
    }
    else
    {
        showKarambaMenuExtension(false);
        if(sysTrayIcon)
            sysTrayIcon->show();
    }
}

void KarambaApplication::showThemeDialog()
{
    //kdDebug() << k_funcinfo << endl;
    if(themeListWindow)
        themeListWindow->show();
}

void KarambaApplication::quitSuperKaramba()
{
    if(themeListWindow)
    {
        themeListWindow->saveUserAddedThemes();
    }

    closeAllWindows();
    quit();
}

void KarambaApplication::globalQuitSuperKaramba()
{
    QStringList apps = getKarambas();
    QStringList::Iterator it;

    for (it = apps.begin(); it != apps.end(); ++it)
    {
        dcopIface_stub dcop((*it).ascii(), dcopIface()->objId());
        dcop.quit();
    }
}

void KarambaApplication::globalHideSysTray(bool hide)
{
    //kdDebug() << k_funcinfo << endl;
    QStringList apps = getKarambas();
    QStringList::Iterator it;

    SuperKarambaSettings::setShowSysTray(!hide);
    SuperKarambaSettings::writeConfig();

    for (it = apps.begin(); it != apps.end(); ++it)
    {
        dcopIface_stub dcop((*it).ascii(), dcopIface()->objId());
        dcop.hideSystemTray(hide);
    }
}

#include "karambaapp.moc"
<|endoftext|>


<commit_before><commit_msg>return empty sequence rather than error when 0-length sequence is requested<commit_after><|endoftext|>


<commit_before>#include "Main.hpp"
using namespace std;

unsigned int Level::levelCounter = 0;
string Level::current = "NULL";
string Level::next = "NULL";
Level::Level(string name)
{
    init(name, true);
}
void Level::init(string name, bool full)
{
	if (name.empty() or (name == "NULL"))
    {
        current = "level1";
        levelCounter = 0;
        menus.push_back(new Menu(MAIN));
    }
    else {current = name;}
    stringstream ss;
    GLfloat x;
    GLfloat y = 0;
    fstream file(("levels/" + current + ".lvl").c_str(), fstream::in);
    string caption;
    if(!REPEAT_LEVEL) {levelCounter++;}
    if(!file.is_open()) {cerr << "Error with loading file: " << strerror(errno) << endl; QUIT = true; return;}
    textures.loadIMG("textures.png");
    getline(file, caption);
    next = caption;
    getline(file, caption);
    ss << "Pertotman, Level " << levelCounter << ": " << caption;
    caption = ss.str();
    SDL_WM_SetCaption(caption.c_str(), "Pertotman");
    for(unsigned int counter = 1; file.eof() == false; counter++)
    {
		x = 0;
		string line;
		file >> line;
		for(unsigned int i = 0; i < line.size(); i++)
		{
			switch (line[i])
			{
				case 'w':
                case 'W':
                 walls.push_back(new Wall(x, y, textures));
                 break;
				case 'c':
                case 'C':
                 if(full){coffees.push_back(new Coffee(x, y, textures));}
                 spaces.push_back(new Space(x, y, textures));
                 break;
				case 'b':
                case 'B':
                 if(full){enemies.push_back(new Enemy(x, y, textures));}
                 spaces.push_back(new Space(x, y, textures));
                 break;
				case 'p':
                case 'P':
                 if(full){pacmans.push_back(new Pacman(x, y, textures));}
                 spaces.push_back(new Space(x, y, textures));
                 break;
				case 's':
                case 'S':
                 spaces.push_back(new Space(x, y, textures));
                 break;
				default:
                 cerr << "Error with loading level: Invalid character." << endl; QUIT = true; return;
                 break;
			}
			x += 32;
		}
		y += 32;
	}
	for (unsigned int i = 0; i < spaces.size(); i++)
	{
		spaces[i]->neighbours(this);
    }
	if (full and(pacmans.size() != 1)) {cerr << "Error with loading level: Too many pacman instances." << endl; QUIT = true; return;}
}
void Level::save() const
{
    size_t unit = sizeof(GLfloat);
    size_t sizeTemp;
    fstream file("savegame.sav", fstream::out | fstream::binary | fstream::trunc);
    if(!file.is_open()) {cerr << "Error with opening file: " << strerror(errno) << endl; QUIT = true; return;}
    file.write(reinterpret_cast<char*>(&unit), sizeof(size_t));
    sizeTemp = sizeof(int);
    file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    file.write(reinterpret_cast<char*>(&levelCounter), sizeTemp);
    sizeTemp = current.size();
    file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    file.write(current.c_str(), sizeTemp);
    sizeTemp = pacmans.size();
    file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    for (unsigned int i = 0; i < pacmans.size(); i++)
        {
            file.write(reinterpret_cast<char*>(&pacmans[i]->x), unit);
            file.write(reinterpret_cast<char*>(&pacmans[i]->y), unit);
        }
    sizeTemp = coffees.size();
    for (unsigned int i = 0; i < coffees.size(); i++)
    {
        if(!coffees[i]->armed){sizeTemp--;}
    }
    file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    for (unsigned int i = 0; i < coffees.size(); i++)
        {
            if(coffees[i]->armed)
            {
                file.write(reinterpret_cast<char*>(&coffees[i]->x), unit);
                file.write(reinterpret_cast<char*>(&coffees[i]->y), unit);
            }
        }
    sizeTemp = enemies.size();
    file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    for (unsigned int i = 0; i < enemies.size(); i++)
        {
            file.write(reinterpret_cast<char*>(&enemies[i]->x), unit);
            file.write(reinterpret_cast<char*>(&enemies[i]->y), unit);
        }
}
void Level::load()
{
    size_t unit = sizeof(GLfloat);
    size_t sizeTemp;
    char lvlName[50];
    GLfloat xTemp, yTemp;
    fstream file("savegame.sav", fstream::in | fstream::binary);
    if(!file.is_open())
    {
        levelCounter = 0;
        init("level1", true);
        return;
    }
    file.read(reinterpret_cast<char*>(&unit), sizeof(size_t));
    file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    file.read(reinterpret_cast<char*>(&levelCounter), sizeTemp);
    levelCounter--;
    file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    file.read(lvlName, sizeTemp);
    lvlName[sizeTemp] = 0;
    init(lvlName, false);
    file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    for (unsigned int i = 0; i < sizeTemp; i++)
        {
            file.read(reinterpret_cast<char*>(&xTemp), unit);
            file.read(reinterpret_cast<char*>(&yTemp), unit);
            pacmans.push_back(new Pacman(xTemp, yTemp, textures));
        }
    file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    for (unsigned int i = 0; i < sizeTemp; i++)
        {
            file.read(reinterpret_cast<char*>(&xTemp), unit);
            file.read(reinterpret_cast<char*>(&yTemp), unit);
            coffees.push_back(new Coffee(xTemp, yTemp, textures));
        }
    file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    for (unsigned int i = 0; i < sizeTemp; i++)
        {
            file.read(reinterpret_cast<char*>(&xTemp), unit);
            file.read(reinterpret_cast<char*>(&yTemp), unit);
            enemies.push_back(new Enemy(xTemp, yTemp, textures));
        }
    menus.push_back(new Menu(ESCAPE));
}
void Level::handle(SDL_Event inputEvent)
{
    if((inputEvent.type == SDL_KEYDOWN) and (inputEvent.key.keysym.sym == SDLK_ESCAPE))
    {
        if (PAUSE == 0)
        {
            PAUSE = -1;
        }
        else
        {
            PAUSE = 0;
        }
        if(menus.empty()) {menus.push_back(new Menu(ESCAPE));}
        else {menus.pop_back();}
    }
    else
    {
        if(menus.size() > 0)
        {
            if(!menus[menus.size() - 1]->handle(inputEvent)) {menus.pop_back();}
        }
        for (unsigned int i = 0; i < pacmans.size(); i++)
        {
            pacmans[i]->handle(inputEvent);
        }
    }
}
void Level::update()
{
    if(menus.empty())
    {
        for (unsigned int i = 0; i < spaces.size(); i++)
        {
            spaces[i]->update();
        }
        for (unsigned int i = 0; i < walls.size(); i++)
        {
            walls[i]->update();
        }
        for (unsigned int i = 0; i < coffees.size(); i++)
        {
            coffees[i]->update();
        }
        for (unsigned int i = 0; i < enemies.size(); i++)
        {
            enemies[i]->update();
        }
        for (unsigned int i = 0; i < pacmans.size(); i++)
        {
            pacmans[i]->update();
        }
    }
}
void Level::render() const
{
	glClear(GL_COLOR_BUFFER_BIT);
	bool bgrender = true;
	if(menus.size() > 0)
    {
        if(menus[0]->type == MAIN) {bgrender = false;}
    }
	if (bgrender)
    {
        for (unsigned int i = 0; i < spaces.size(); i++)
        {
            spaces[i]->render();
        }
        for (unsigned int i = 0; i < walls.size(); i++)
        {
            walls[i]->render();
        }
        for (unsigned int i = 0; i < coffees.size(); i++)
        {
            coffees[i]->render();
        }
        for (unsigned int i = 0; i < enemies.size(); i++)
        {
            enemies[i]->render();
        }
        for (unsigned int i = 0; i < pacmans.size(); i++)
        {
            pacmans[i]->render();
        }
    }
	if(menus.size() > 0) {menus[menus.size() - 1]->render();}
}
void Level::destroy()
{
    for (unsigned int i = 0; i < menus.size(); i++)
	{
		menus.erase(menus.begin() + i);
	}
    for (unsigned int i = 0; i < spaces.size(); i++)
	{
	    spaces.erase(spaces.begin() + i);
	}
	for (unsigned int i = 0; i < walls.size(); i++)
	{
	    walls.erase(walls.begin() + i);
	}
	for (unsigned int i = 0; i < coffees.size(); i++)
	{
	    coffees.erase(coffees.begin() + i);
	}
	for (unsigned int i = 0; i < enemies.size(); i++)
	{
	    enemies.erase(enemies.begin() + i);
	}
	for (unsigned int i = 0; i < pacmans.size(); i++)
	{
	    pacmans.erase(pacmans.begin() + i);
	}
	menus.clear();
	spaces.clear();
	walls.clear();
	coffees.clear();
    enemies.clear();
    pacmans.clear();
    Coffee::count = 0;
}
<commit_msg>Starting from level 9 for now<commit_after>#include "Main.hpp"
using namespace std;

unsigned int Level::levelCounter = 0;
string Level::current = "NULL";
string Level::next = "NULL";
Level::Level(string name)
{
    init(name, true);
}
void Level::init(string name, bool full)
{
	if (name.empty() or (name == "NULL"))
    {
        current = "level9";
        levelCounter = 0;
        menus.push_back(new Menu(MAIN));
    }
    else {current = name;}
    stringstream ss;
    GLfloat x;
    GLfloat y = 0;
    fstream file(("levels/" + current + ".lvl").c_str(), fstream::in);
    string caption;
    if(!REPEAT_LEVEL) {levelCounter++;}
    if(!file.is_open()) {cerr << "Error with loading file: " << strerror(errno) << endl; QUIT = true; return;}
    textures.loadIMG("textures.png");
    getline(file, caption);
    next = caption;
    getline(file, caption);
    ss << "Pertotman, Level " << levelCounter << ": " << caption;
    caption = ss.str();
    SDL_WM_SetCaption(caption.c_str(), "Pertotman");
    for(unsigned int counter = 1; file.eof() == false; counter++)
    {
		x = 0;
		string line;
		file >> line;
		for(unsigned int i = 0; i < line.size(); i++)
		{
			switch (line[i])
			{
				case 'w':
                case 'W':
                 walls.push_back(new Wall(x, y, textures));
                 break;
				case 'c':
                case 'C':
                 if(full){coffees.push_back(new Coffee(x, y, textures));}
                 spaces.push_back(new Space(x, y, textures));
                 break;
				case 'b':
                case 'B':
                 if(full){enemies.push_back(new Enemy(x, y, textures));}
                 spaces.push_back(new Space(x, y, textures));
                 break;
				case 'p':
                case 'P':
                 if(full){pacmans.push_back(new Pacman(x, y, textures));}
                 spaces.push_back(new Space(x, y, textures));
                 break;
				case 's':
                case 'S':
                 spaces.push_back(new Space(x, y, textures));
                 break;
				default:
                 cerr << "Error with loading level: Invalid character." << endl; QUIT = true; return;
                 break;
			}
			x += 32;
		}
		y += 32;
	}
	for (unsigned int i = 0; i < spaces.size(); i++)
	{
		spaces[i]->neighbours(this);
    }
	if (full and(pacmans.size() != 1)) {cerr << "Error with loading level: Too many pacman instances." << endl; QUIT = true; return;}
}
void Level::save() const
{
    size_t unit = sizeof(GLfloat);
    size_t sizeTemp;
    fstream file("savegame.sav", fstream::out | fstream::binary | fstream::trunc);
    if(!file.is_open()) {cerr << "Error with opening file: " << strerror(errno) << endl; QUIT = true; return;}
    file.write(reinterpret_cast<char*>(&unit), sizeof(size_t));
    sizeTemp = sizeof(int);
    file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    file.write(reinterpret_cast<char*>(&levelCounter), sizeTemp);
    sizeTemp = current.size();
    file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    file.write(current.c_str(), sizeTemp);
    sizeTemp = pacmans.size();
    file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    for (unsigned int i = 0; i < pacmans.size(); i++)
        {
            file.write(reinterpret_cast<char*>(&pacmans[i]->x), unit);
            file.write(reinterpret_cast<char*>(&pacmans[i]->y), unit);
        }
    sizeTemp = coffees.size();
    for (unsigned int i = 0; i < coffees.size(); i++)
    {
        if(!coffees[i]->armed){sizeTemp--;}
    }
    file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    for (unsigned int i = 0; i < coffees.size(); i++)
        {
            if(coffees[i]->armed)
            {
                file.write(reinterpret_cast<char*>(&coffees[i]->x), unit);
                file.write(reinterpret_cast<char*>(&coffees[i]->y), unit);
            }
        }
    sizeTemp = enemies.size();
    file.write(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    for (unsigned int i = 0; i < enemies.size(); i++)
        {
            file.write(reinterpret_cast<char*>(&enemies[i]->x), unit);
            file.write(reinterpret_cast<char*>(&enemies[i]->y), unit);
        }
}
void Level::load()
{
    size_t unit = sizeof(GLfloat);
    size_t sizeTemp;
    char lvlName[50];
    GLfloat xTemp, yTemp;
    fstream file("savegame.sav", fstream::in | fstream::binary);
    if(!file.is_open())
    {
        levelCounter = 0;
        init("level1", true);
        return;
    }
    file.read(reinterpret_cast<char*>(&unit), sizeof(size_t));
    file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    file.read(reinterpret_cast<char*>(&levelCounter), sizeTemp);
    levelCounter--;
    file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    file.read(lvlName, sizeTemp);
    lvlName[sizeTemp] = 0;
    init(lvlName, false);
    file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    for (unsigned int i = 0; i < sizeTemp; i++)
        {
            file.read(reinterpret_cast<char*>(&xTemp), unit);
            file.read(reinterpret_cast<char*>(&yTemp), unit);
            pacmans.push_back(new Pacman(xTemp, yTemp, textures));
        }
    file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    for (unsigned int i = 0; i < sizeTemp; i++)
        {
            file.read(reinterpret_cast<char*>(&xTemp), unit);
            file.read(reinterpret_cast<char*>(&yTemp), unit);
            coffees.push_back(new Coffee(xTemp, yTemp, textures));
        }
    file.read(reinterpret_cast<char*>(&sizeTemp), sizeof(size_t));
    for (unsigned int i = 0; i < sizeTemp; i++)
        {
            file.read(reinterpret_cast<char*>(&xTemp), unit);
            file.read(reinterpret_cast<char*>(&yTemp), unit);
            enemies.push_back(new Enemy(xTemp, yTemp, textures));
        }
    menus.push_back(new Menu(ESCAPE));
}
void Level::handle(SDL_Event inputEvent)
{
    if((inputEvent.type == SDL_KEYDOWN) and (inputEvent.key.keysym.sym == SDLK_ESCAPE))
    {
        if (PAUSE == 0)
        {
            PAUSE = -1;
        }
        else
        {
            PAUSE = 0;
        }
        if(menus.empty()) {menus.push_back(new Menu(ESCAPE));}
        else {menus.pop_back();}
    }
    else
    {
        if(menus.size() > 0)
        {
            if(!menus[menus.size() - 1]->handle(inputEvent)) {menus.pop_back();}
        }
        for (unsigned int i = 0; i < pacmans.size(); i++)
        {
            pacmans[i]->handle(inputEvent);
        }
    }
}
void Level::update()
{
    if(menus.empty())
    {
        for (unsigned int i = 0; i < spaces.size(); i++)
        {
            spaces[i]->update();
        }
        for (unsigned int i = 0; i < walls.size(); i++)
        {
            walls[i]->update();
        }
        for (unsigned int i = 0; i < coffees.size(); i++)
        {
            coffees[i]->update();
        }
        for (unsigned int i = 0; i < enemies.size(); i++)
        {
            enemies[i]->update();
        }
        for (unsigned int i = 0; i < pacmans.size(); i++)
        {
            pacmans[i]->update();
        }
    }
}
void Level::render() const
{
	glClear(GL_COLOR_BUFFER_BIT);
	bool bgrender = true;
	if(menus.size() > 0)
    {
        if(menus[0]->type == MAIN) {bgrender = false;}
    }
	if (bgrender)
    {
        for (unsigned int i = 0; i < spaces.size(); i++)
        {
            spaces[i]->render();
        }
        for (unsigned int i = 0; i < walls.size(); i++)
        {
            walls[i]->render();
        }
        for (unsigned int i = 0; i < coffees.size(); i++)
        {
            coffees[i]->render();
        }
        for (unsigned int i = 0; i < enemies.size(); i++)
        {
            enemies[i]->render();
        }
        for (unsigned int i = 0; i < pacmans.size(); i++)
        {
            pacmans[i]->render();
        }
    }
	if(menus.size() > 0) {menus[menus.size() - 1]->render();}
}
void Level::destroy()
{
    for (unsigned int i = 0; i < menus.size(); i++)
	{
		menus.erase(menus.begin() + i);
	}
    for (unsigned int i = 0; i < spaces.size(); i++)
	{
	    spaces.erase(spaces.begin() + i);
	}
	for (unsigned int i = 0; i < walls.size(); i++)
	{
	    walls.erase(walls.begin() + i);
	}
	for (unsigned int i = 0; i < coffees.size(); i++)
	{
	    coffees.erase(coffees.begin() + i);
	}
	for (unsigned int i = 0; i < enemies.size(); i++)
	{
	    enemies.erase(enemies.begin() + i);
	}
	for (unsigned int i = 0; i < pacmans.size(); i++)
	{
	    pacmans.erase(pacmans.begin() + i);
	}
	menus.clear();
	spaces.clear();
	walls.clear();
	coffees.clear();
    enemies.clear();
    pacmans.clear();
    Coffee::count = 0;
}
<|endoftext|>


<commit_before>/*****************************************************************************
*                                                                            *
*  OpenNI 1.x Alpha                                                          *
*  Copyright (C) 2012 PrimeSense Ltd.                                        *
*                                                                            *
*  This file is part of OpenNI.                                              *
*                                                                            *
*  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.                                            *
*                                                                            *
*****************************************************************************/
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include <cstdlib> // for EXIT_SUCCESS
#include <iostream>
#include <XnOpenNI.h>
#include <XnCodecIDs.h>
#include <XnCppWrapper.h>
#include <XnPropNames.h>

#include "io.h"

//---------------------------------------------------------------------------
// Globals
//---------------------------------------------------------------------------
xn::Context g_Context;
xn::ScriptNode g_scriptNode;
xn::DepthGenerator g_DepthGenerator;
xn::UserGenerator g_UserGenerator;
xn::Player g_Player;

XnBool g_bNeedPose = FALSE;
XnChar g_strPose[20] = "";

DepthMapLogger g_Log;

//---------------------------------------------------------------------------
// Forward declrarations
//---------------------------------------------------------------------------
void XN_CALLBACK_TYPE User_NewUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE User_LostUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE UserPose_PoseDetected(xn::PoseDetectionCapability& /*capability*/, const XnChar* strPose, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE UserCalibration_CalibrationStart(xn::SkeletonCapability& /*capability*/, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE UserCalibration_CalibrationComplete(xn::SkeletonCapability& /*capability*/, XnUserID nId, XnCalibrationStatus eStatus, void* /*pCookie*/);

//---------------------------------------------------------------------------
// Code
//---------------------------------------------------------------------------

#define SAMPLE_XML_PATH "../Data/SamplesConfig.xml"

#define CHECK_RC(nRetVal, what)										\
	if (nRetVal != XN_STATUS_OK)									\
	{																\
		printf("%s failed: %s\n", what, xnGetStatusString(nRetVal));\
		return nRetVal;												\
	}

int main(int argc, char **argv)
{
	XnStatus nRetVal = XN_STATUS_OK;

	if (argc > 1)
	{
		nRetVal = g_Context.Init();
		CHECK_RC(nRetVal, "Init");
		nRetVal = g_Context.OpenFileRecording(argv[1], g_Player);
		if (nRetVal != XN_STATUS_OK)
		{
			printf("Can't open recording %s: %s\n", argv[1], xnGetStatusString(nRetVal));
			return 1;
		}
	}
	else
	{
		xn::EnumerationErrors errors;
		nRetVal = g_Context.InitFromXmlFile(SAMPLE_XML_PATH, g_scriptNode, &errors);
		if (nRetVal == XN_STATUS_NO_NODE_PRESENT)
		{
			XnChar strError[1024];
			errors.ToString(strError, 1024);
			printf("%s\n", strError);
			return (nRetVal);
		}
		else if (nRetVal != XN_STATUS_OK)
		{
			printf("Open failed: %s\n", xnGetStatusString(nRetVal));
			return (nRetVal);
		}
	}

	nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_DEPTH, g_DepthGenerator);
	if (nRetVal != XN_STATUS_OK)
	{
		printf("No depth generator found. Using a default one...");
		xn::MockDepthGenerator mockDepth;
		nRetVal = mockDepth.Create(g_Context);
		CHECK_RC(nRetVal, "Create mock depth");

		// set some defaults
		XnMapOutputMode defaultMode;
		defaultMode.nXRes = 320;
		defaultMode.nYRes = 240;
		defaultMode.nFPS = 30;
		nRetVal = mockDepth.SetMapOutputMode(defaultMode);
		CHECK_RC(nRetVal, "set default mode");

		// set FOV
		XnFieldOfView fov;
		fov.fHFOV = 1.0225999419141749;
		fov.fVFOV = 0.79661567681716894;
		nRetVal = mockDepth.SetGeneralProperty(XN_PROP_FIELD_OF_VIEW, sizeof(fov), &fov);
		CHECK_RC(nRetVal, "set FOV");

		XnUInt32 nDataSize = defaultMode.nXRes * defaultMode.nYRes * sizeof(XnDepthPixel);
		XnDepthPixel* pData = (XnDepthPixel*)xnOSCallocAligned(nDataSize, 1, XN_DEFAULT_MEM_ALIGN);

		nRetVal = mockDepth.SetData(1, 0, nDataSize, pData);
		CHECK_RC(nRetVal, "set empty depth map");

		g_DepthGenerator = mockDepth;
	}

	nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_USER, g_UserGenerator);
	if (nRetVal != XN_STATUS_OK)
	{
		nRetVal = g_UserGenerator.Create(g_Context);
		CHECK_RC(nRetVal, "Find user generator");
	}

	XnCallbackHandle hUserCallbacks, hCalibrationStart, hCalibrationComplete, hPoseDetected, hCalibrationInProgress, hPoseInProgress;
	if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_SKELETON))
	{
		printf("Supplied user generator doesn't support skeleton\n");
		return 1;
	}
	nRetVal = g_UserGenerator.RegisterUserCallbacks(User_NewUser, User_LostUser, NULL, hUserCallbacks);
	CHECK_RC(nRetVal, "Register to user callbacks");
	nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationStart(UserCalibration_CalibrationStart, NULL, hCalibrationStart);
	CHECK_RC(nRetVal, "Register to calibration start");
	nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationComplete(UserCalibration_CalibrationComplete, NULL, hCalibrationComplete);
	CHECK_RC(nRetVal, "Register to calibration complete");

	if (g_UserGenerator.GetSkeletonCap().NeedPoseForCalibration())
	{
		g_bNeedPose = TRUE;
		if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_POSE_DETECTION))
		{
			printf("Pose required, but not supported\n");
			return 1;
		}
		nRetVal = g_UserGenerator.GetPoseDetectionCap().RegisterToPoseDetected(UserPose_PoseDetected, NULL, hPoseDetected);
		CHECK_RC(nRetVal, "Register to Pose Detected");
		g_UserGenerator.GetSkeletonCap().GetCalibrationPose(g_strPose);
	}

	g_UserGenerator.GetSkeletonCap().SetSkeletonProfile(XN_SKEL_PROFILE_ALL);

	nRetVal = g_Context.StartGeneratingAll();
	CHECK_RC(nRetVal, "StartGenerating");

	g_Log.Open("log.h5", "log.txt");

	// Main event loop
	xn::SceneMetaData sceneMD;
	xn::DepthMetaData depthMD;
	while (!xnOSWasKeyboardHit())
	{
		// Wait for an update
		g_Context.WaitOneUpdateAll(g_UserGenerator);

		// Process the data
		g_DepthGenerator.GetMetaData(depthMD);
		g_UserGenerator.GetUserPixels(0, sceneMD);

		// Log the data
		g_Log.DumpDepthMap(depthMD, sceneMD);
	}

	// Clean up all resources
	g_scriptNode.Release();
	g_DepthGenerator.Release();
	g_UserGenerator.Release();
	g_Player.Release();
	g_Context.Release();

	return EXIT_SUCCESS;
}

// Callback: New user was detected
void XN_CALLBACK_TYPE User_NewUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	printf("%d New User %d\n", epochTime, nId);
	// New user found
	if (g_bNeedPose)
	{
		g_UserGenerator.GetPoseDetectionCap().StartPoseDetection(g_strPose, nId);
	}
	else
	{
		g_UserGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
	}
}

// Callback: An existing user was lost
void XN_CALLBACK_TYPE User_LostUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	printf("%d Lost user %d\n", epochTime, nId);
}

// Callback: Detected a pose
void XN_CALLBACK_TYPE UserPose_PoseDetected(xn::PoseDetectionCapability& /*capability*/, const XnChar* strPose, XnUserID nId, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	printf("%d Pose %s detected for user %d\n", epochTime, strPose, nId);
	g_UserGenerator.GetPoseDetectionCap().StopPoseDetection(nId);
	g_UserGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
}

// Callback: Started calibration
void XN_CALLBACK_TYPE UserCalibration_CalibrationStart(xn::SkeletonCapability& /*capability*/, XnUserID nId, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	printf("%d Calibration started for user %d\n", epochTime, nId);
}

// Callback: Finished calibration
void XN_CALLBACK_TYPE UserCalibration_CalibrationComplete(xn::SkeletonCapability& /*capability*/, XnUserID nId, XnCalibrationStatus eStatus, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	if (eStatus == XN_CALIBRATION_STATUS_OK)
	{
		// Calibration succeeded
		printf("%d Calibration complete, start tracking user %d\n", epochTime, nId);
		g_UserGenerator.GetSkeletonCap().StartTracking(nId);
	}
	else
	{
		// Calibration failed
		printf("%d Calibration failed for user %d\n", epochTime, nId);
		if(eStatus==XN_CALIBRATION_STATUS_MANUAL_ABORT)
		{
			printf("Manual abort occured, stop attempting to calibrate!");
			return;
		}
		if (g_bNeedPose)
		{
			g_UserGenerator.GetPoseDetectionCap().StartPoseDetection(g_strPose, nId);
		}
		else
		{
			g_UserGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
		}
	}
}
<commit_msg>main_nogui: refactor context initialisation to separate functions<commit_after>/*****************************************************************************
*                                                                            *
*  OpenNI 1.x Alpha                                                          *
*  Copyright (C) 2012 PrimeSense Ltd.                                        *
*                                                                            *
*  This file is part of OpenNI.                                              *
*                                                                            *
*  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.                                            *
*                                                                            *
*****************************************************************************/
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include <cstdlib> // for EXIT_SUCCESS
#include <iostream>
#include <XnOpenNI.h>
#include <XnCodecIDs.h>
#include <XnCppWrapper.h>
#include <XnPropNames.h>

#include "io.h"

//---------------------------------------------------------------------------
// Globals
//---------------------------------------------------------------------------
xn::Context g_Context;
xn::ScriptNode g_scriptNode;
xn::DepthGenerator g_DepthGenerator;
xn::UserGenerator g_UserGenerator;
xn::Player g_Player;

XnBool g_bNeedPose = FALSE;
XnChar g_strPose[20] = "";

DepthMapLogger g_Log;

//---------------------------------------------------------------------------
// Forward declrarations
//---------------------------------------------------------------------------
bool InitialiseContextFromRecording(const char* recordingFilename);
bool InitialiseContextFromXmlConfig(const char* xmlConfigFilename);

void XN_CALLBACK_TYPE User_NewUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE User_LostUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE UserPose_PoseDetected(xn::PoseDetectionCapability& /*capability*/, const XnChar* strPose, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE UserCalibration_CalibrationStart(xn::SkeletonCapability& /*capability*/, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE UserCalibration_CalibrationComplete(xn::SkeletonCapability& /*capability*/, XnUserID nId, XnCalibrationStatus eStatus, void* /*pCookie*/);

//---------------------------------------------------------------------------
// Code
//---------------------------------------------------------------------------

#define SAMPLE_XML_PATH "../Data/SamplesConfig.xml"

#define CHECK_RC(nRetVal, what)										\
	if (nRetVal != XN_STATUS_OK)									\
	{																\
		printf("%s failed: %s\n", what, xnGetStatusString(nRetVal));\
		return nRetVal;												\
	}

#define CHECK_RC_RETURNING(rv, nRetVal, what)										\
	if (nRetVal != XN_STATUS_OK)									\
	{																\
		printf("%s failed: %s\n", what, xnGetStatusString(nRetVal));\
		return rv;												\
	}

int main(int argc, char **argv)
{
	XnStatus nRetVal = XN_STATUS_OK;

	if (argc > 1)
	{
		if(!InitialiseContextFromRecording(argv[1]))
		{
			return EXIT_FAILURE;
		}
	}
	else
	{
		if(!InitialiseContextFromXmlConfig(SAMPLE_XML_PATH))
		{
			return EXIT_FAILURE;
		}
	}

	nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_DEPTH, g_DepthGenerator);
	if (nRetVal != XN_STATUS_OK)
	{
		printf("No depth generator found. Using a default one...");
		xn::MockDepthGenerator mockDepth;
		nRetVal = mockDepth.Create(g_Context);
		CHECK_RC(nRetVal, "Create mock depth");

		// set some defaults
		XnMapOutputMode defaultMode;
		defaultMode.nXRes = 320;
		defaultMode.nYRes = 240;
		defaultMode.nFPS = 30;
		nRetVal = mockDepth.SetMapOutputMode(defaultMode);
		CHECK_RC(nRetVal, "set default mode");

		// set FOV
		XnFieldOfView fov;
		fov.fHFOV = 1.0225999419141749;
		fov.fVFOV = 0.79661567681716894;
		nRetVal = mockDepth.SetGeneralProperty(XN_PROP_FIELD_OF_VIEW, sizeof(fov), &fov);
		CHECK_RC(nRetVal, "set FOV");

		XnUInt32 nDataSize = defaultMode.nXRes * defaultMode.nYRes * sizeof(XnDepthPixel);
		XnDepthPixel* pData = (XnDepthPixel*)xnOSCallocAligned(nDataSize, 1, XN_DEFAULT_MEM_ALIGN);

		nRetVal = mockDepth.SetData(1, 0, nDataSize, pData);
		CHECK_RC(nRetVal, "set empty depth map");

		g_DepthGenerator = mockDepth;
	}

	nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_USER, g_UserGenerator);
	if (nRetVal != XN_STATUS_OK)
	{
		nRetVal = g_UserGenerator.Create(g_Context);
		CHECK_RC(nRetVal, "Find user generator");
	}

	XnCallbackHandle hUserCallbacks, hCalibrationStart, hCalibrationComplete, hPoseDetected, hCalibrationInProgress, hPoseInProgress;
	if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_SKELETON))
	{
		printf("Supplied user generator doesn't support skeleton\n");
		return 1;
	}
	nRetVal = g_UserGenerator.RegisterUserCallbacks(User_NewUser, User_LostUser, NULL, hUserCallbacks);
	CHECK_RC(nRetVal, "Register to user callbacks");
	nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationStart(UserCalibration_CalibrationStart, NULL, hCalibrationStart);
	CHECK_RC(nRetVal, "Register to calibration start");
	nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationComplete(UserCalibration_CalibrationComplete, NULL, hCalibrationComplete);
	CHECK_RC(nRetVal, "Register to calibration complete");

	if (g_UserGenerator.GetSkeletonCap().NeedPoseForCalibration())
	{
		g_bNeedPose = TRUE;
		if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_POSE_DETECTION))
		{
			printf("Pose required, but not supported\n");
			return 1;
		}
		nRetVal = g_UserGenerator.GetPoseDetectionCap().RegisterToPoseDetected(UserPose_PoseDetected, NULL, hPoseDetected);
		CHECK_RC(nRetVal, "Register to Pose Detected");
		g_UserGenerator.GetSkeletonCap().GetCalibrationPose(g_strPose);
	}

	g_UserGenerator.GetSkeletonCap().SetSkeletonProfile(XN_SKEL_PROFILE_ALL);

	nRetVal = g_Context.StartGeneratingAll();
	CHECK_RC(nRetVal, "StartGenerating");

	g_Log.Open("log.h5", "log.txt");

	// Main event loop
	xn::SceneMetaData sceneMD;
	xn::DepthMetaData depthMD;
	while (!xnOSWasKeyboardHit())
	{
		// Wait for an update
		g_Context.WaitOneUpdateAll(g_UserGenerator);

		// Process the data
		g_DepthGenerator.GetMetaData(depthMD);
		g_UserGenerator.GetUserPixels(0, sceneMD);

		// Log the data
		g_Log.DumpDepthMap(depthMD, sceneMD);
	}

	// Clean up all resources
	g_scriptNode.Release();
	g_DepthGenerator.Release();
	g_UserGenerator.Release();
	g_Player.Release();
	g_Context.Release();

	return EXIT_SUCCESS;
}

bool InitialiseContextFromRecording(const char* recordingFilename)
{
	XnStatus nRetVal = XN_STATUS_OK;

	nRetVal = g_Context.Init();
	CHECK_RC_RETURNING(false, nRetVal, "Init");
	nRetVal = g_Context.OpenFileRecording(recordingFilename, g_Player);
	if (nRetVal != XN_STATUS_OK)
	{
		printf("Can't open recording %s: %s\n", recordingFilename, xnGetStatusString(nRetVal));
		return false;
	}
	return true;
}

bool InitialiseContextFromXmlConfig(const char* xmlConfigFilename)
{
	XnStatus nRetVal = XN_STATUS_OK;
	xn::EnumerationErrors errors;

	nRetVal = g_Context.InitFromXmlFile(xmlConfigFilename, g_scriptNode, &errors);
	if (nRetVal == XN_STATUS_NO_NODE_PRESENT)
	{
		XnChar strError[1024];
		errors.ToString(strError, 1024);
		printf("%s\n", strError);
		return false;
	}
	else if (nRetVal != XN_STATUS_OK)
	{
		printf("Open failed: %s\n", xnGetStatusString(nRetVal));
		return false;
	}

	return true;
}

// Callback: New user was detected
void XN_CALLBACK_TYPE User_NewUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	printf("%d New User %d\n", epochTime, nId);
	// New user found
	if (g_bNeedPose)
	{
		g_UserGenerator.GetPoseDetectionCap().StartPoseDetection(g_strPose, nId);
	}
	else
	{
		g_UserGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
	}
}

// Callback: An existing user was lost
void XN_CALLBACK_TYPE User_LostUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	printf("%d Lost user %d\n", epochTime, nId);
}

// Callback: Detected a pose
void XN_CALLBACK_TYPE UserPose_PoseDetected(xn::PoseDetectionCapability& /*capability*/, const XnChar* strPose, XnUserID nId, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	printf("%d Pose %s detected for user %d\n", epochTime, strPose, nId);
	g_UserGenerator.GetPoseDetectionCap().StopPoseDetection(nId);
	g_UserGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
}

// Callback: Started calibration
void XN_CALLBACK_TYPE UserCalibration_CalibrationStart(xn::SkeletonCapability& /*capability*/, XnUserID nId, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	printf("%d Calibration started for user %d\n", epochTime, nId);
}

// Callback: Finished calibration
void XN_CALLBACK_TYPE UserCalibration_CalibrationComplete(xn::SkeletonCapability& /*capability*/, XnUserID nId, XnCalibrationStatus eStatus, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	if (eStatus == XN_CALIBRATION_STATUS_OK)
	{
		// Calibration succeeded
		printf("%d Calibration complete, start tracking user %d\n", epochTime, nId);
		g_UserGenerator.GetSkeletonCap().StartTracking(nId);
	}
	else
	{
		// Calibration failed
		printf("%d Calibration failed for user %d\n", epochTime, nId);
		if(eStatus==XN_CALIBRATION_STATUS_MANUAL_ABORT)
		{
			printf("Manual abort occured, stop attempting to calibrate!");
			return;
		}
		if (g_bNeedPose)
		{
			g_UserGenerator.GetPoseDetectionCap().StartPoseDetection(g_strPose, nId);
		}
		else
		{
			g_UserGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
		}
	}
}
<|endoftext|>


<commit_before>/*****************************************************************************
*                                                                            *
*  OpenNI 1.x Alpha                                                          *
*  Copyright (C) 2012 PrimeSense Ltd.                                        *
*                                                                            *
*  This file is part of OpenNI.                                              *
*                                                                            *
*  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.                                            *
*                                                                            *
*****************************************************************************/
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include <iostream>
#include <XnOpenNI.h>
#include <XnCodecIDs.h>
#include <XnCppWrapper.h>
#include <XnPropNames.h>

#include "io.h"

//---------------------------------------------------------------------------
// Globals
//---------------------------------------------------------------------------
xn::Context g_Context;
xn::ScriptNode g_scriptNode;
xn::DepthGenerator g_DepthGenerator;
xn::UserGenerator g_UserGenerator;
xn::Player g_Player;

XnBool g_bNeedPose = FALSE;
XnChar g_strPose[20] = "";

DepthMapLogger g_Log;

//---------------------------------------------------------------------------
// Forward declrarations
//---------------------------------------------------------------------------
void XN_CALLBACK_TYPE User_NewUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE User_LostUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE UserPose_PoseDetected(xn::PoseDetectionCapability& /*capability*/, const XnChar* strPose, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE UserCalibration_CalibrationStart(xn::SkeletonCapability& /*capability*/, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE UserCalibration_CalibrationComplete(xn::SkeletonCapability& /*capability*/, XnUserID nId, XnCalibrationStatus eStatus, void* /*pCookie*/);

//---------------------------------------------------------------------------
// Code
//---------------------------------------------------------------------------

#define SAMPLE_XML_PATH "../Data/SamplesConfig.xml"

#define CHECK_RC(nRetVal, what)										\
	if (nRetVal != XN_STATUS_OK)									\
	{																\
		printf("%s failed: %s\n", what, xnGetStatusString(nRetVal));\
		return nRetVal;												\
	}

int main(int argc, char **argv)
{
	XnStatus nRetVal = XN_STATUS_OK;

	if (argc > 1)
	{
		nRetVal = g_Context.Init();
		CHECK_RC(nRetVal, "Init");
		nRetVal = g_Context.OpenFileRecording(argv[1], g_Player);
		if (nRetVal != XN_STATUS_OK)
		{
			printf("Can't open recording %s: %s\n", argv[1], xnGetStatusString(nRetVal));
			return 1;
		}
	}
	else
	{
		xn::EnumerationErrors errors;
		nRetVal = g_Context.InitFromXmlFile(SAMPLE_XML_PATH, g_scriptNode, &errors);
		if (nRetVal == XN_STATUS_NO_NODE_PRESENT)
		{
			XnChar strError[1024];
			errors.ToString(strError, 1024);
			printf("%s\n", strError);
			return (nRetVal);
		}
		else if (nRetVal != XN_STATUS_OK)
		{
			printf("Open failed: %s\n", xnGetStatusString(nRetVal));
			return (nRetVal);
		}
	}

	nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_DEPTH, g_DepthGenerator);
	if (nRetVal != XN_STATUS_OK)
	{
		printf("No depth generator found. Using a default one...");
		xn::MockDepthGenerator mockDepth;
		nRetVal = mockDepth.Create(g_Context);
		CHECK_RC(nRetVal, "Create mock depth");

		// set some defaults
		XnMapOutputMode defaultMode;
		defaultMode.nXRes = 320;
		defaultMode.nYRes = 240;
		defaultMode.nFPS = 30;
		nRetVal = mockDepth.SetMapOutputMode(defaultMode);
		CHECK_RC(nRetVal, "set default mode");

		// set FOV
		XnFieldOfView fov;
		fov.fHFOV = 1.0225999419141749;
		fov.fVFOV = 0.79661567681716894;
		nRetVal = mockDepth.SetGeneralProperty(XN_PROP_FIELD_OF_VIEW, sizeof(fov), &fov);
		CHECK_RC(nRetVal, "set FOV");

		XnUInt32 nDataSize = defaultMode.nXRes * defaultMode.nYRes * sizeof(XnDepthPixel);
		XnDepthPixel* pData = (XnDepthPixel*)xnOSCallocAligned(nDataSize, 1, XN_DEFAULT_MEM_ALIGN);

		nRetVal = mockDepth.SetData(1, 0, nDataSize, pData);
		CHECK_RC(nRetVal, "set empty depth map");

		g_DepthGenerator = mockDepth;
	}

	nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_USER, g_UserGenerator);
	if (nRetVal != XN_STATUS_OK)
	{
		nRetVal = g_UserGenerator.Create(g_Context);
		CHECK_RC(nRetVal, "Find user generator");
	}

	XnCallbackHandle hUserCallbacks, hCalibrationStart, hCalibrationComplete, hPoseDetected, hCalibrationInProgress, hPoseInProgress;
	if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_SKELETON))
	{
		printf("Supplied user generator doesn't support skeleton\n");
		return 1;
	}
	nRetVal = g_UserGenerator.RegisterUserCallbacks(User_NewUser, User_LostUser, NULL, hUserCallbacks);
	CHECK_RC(nRetVal, "Register to user callbacks");
	nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationStart(UserCalibration_CalibrationStart, NULL, hCalibrationStart);
	CHECK_RC(nRetVal, "Register to calibration start");
	nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationComplete(UserCalibration_CalibrationComplete, NULL, hCalibrationComplete);
	CHECK_RC(nRetVal, "Register to calibration complete");

	if (g_UserGenerator.GetSkeletonCap().NeedPoseForCalibration())
	{
		g_bNeedPose = TRUE;
		if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_POSE_DETECTION))
		{
			printf("Pose required, but not supported\n");
			return 1;
		}
		nRetVal = g_UserGenerator.GetPoseDetectionCap().RegisterToPoseDetected(UserPose_PoseDetected, NULL, hPoseDetected);
		CHECK_RC(nRetVal, "Register to Pose Detected");
		g_UserGenerator.GetSkeletonCap().GetCalibrationPose(g_strPose);
	}

	g_UserGenerator.GetSkeletonCap().SetSkeletonProfile(XN_SKEL_PROFILE_ALL);

	nRetVal = g_Context.StartGeneratingAll();
	CHECK_RC(nRetVal, "StartGenerating");

	g_Log.Open("log.h5", "log.txt");

	// Main event loop
	xn::SceneMetaData sceneMD;
	xn::DepthMetaData depthMD;
	while (!xnOSWasKeyboardHit())
	{
		// Wait for an update
		g_Context.WaitOneUpdateAll(g_UserGenerator);

		// Process the data
		g_DepthGenerator.GetMetaData(depthMD);
		g_UserGenerator.GetUserPixels(0, sceneMD);

		// Log the data
		g_Log.DumpDepthMap(depthMD, sceneMD);
	}
}

// Callback: New user was detected
void XN_CALLBACK_TYPE User_NewUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	printf("%d New User %d\n", epochTime, nId);
	// New user found
	if (g_bNeedPose)
	{
		g_UserGenerator.GetPoseDetectionCap().StartPoseDetection(g_strPose, nId);
	}
	else
	{
		g_UserGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
	}
}

// Callback: An existing user was lost
void XN_CALLBACK_TYPE User_LostUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	printf("%d Lost user %d\n", epochTime, nId);
}

// Callback: Detected a pose
void XN_CALLBACK_TYPE UserPose_PoseDetected(xn::PoseDetectionCapability& /*capability*/, const XnChar* strPose, XnUserID nId, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	printf("%d Pose %s detected for user %d\n", epochTime, strPose, nId);
	g_UserGenerator.GetPoseDetectionCap().StopPoseDetection(nId);
	g_UserGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
}

// Callback: Started calibration
void XN_CALLBACK_TYPE UserCalibration_CalibrationStart(xn::SkeletonCapability& /*capability*/, XnUserID nId, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	printf("%d Calibration started for user %d\n", epochTime, nId);
}

// Callback: Finished calibration
void XN_CALLBACK_TYPE UserCalibration_CalibrationComplete(xn::SkeletonCapability& /*capability*/, XnUserID nId, XnCalibrationStatus eStatus, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	if (eStatus == XN_CALIBRATION_STATUS_OK)
	{
		// Calibration succeeded
		printf("%d Calibration complete, start tracking user %d\n", epochTime, nId);
		g_UserGenerator.GetSkeletonCap().StartTracking(nId);
	}
	else
	{
		// Calibration failed
		printf("%d Calibration failed for user %d\n", epochTime, nId);
		if(eStatus==XN_CALIBRATION_STATUS_MANUAL_ABORT)
		{
			printf("Manual abort occured, stop attempting to calibrate!");
			return;
		}
		if (g_bNeedPose)
		{
			g_UserGenerator.GetPoseDetectionCap().StartPoseDetection(g_strPose, nId);
		}
		else
		{
			g_UserGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
		}
	}
}
<commit_msg>main_nogui: clean up before exiting<commit_after>/*****************************************************************************
*                                                                            *
*  OpenNI 1.x Alpha                                                          *
*  Copyright (C) 2012 PrimeSense Ltd.                                        *
*                                                                            *
*  This file is part of OpenNI.                                              *
*                                                                            *
*  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.                                            *
*                                                                            *
*****************************************************************************/
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include <iostream>
#include <XnOpenNI.h>
#include <XnCodecIDs.h>
#include <XnCppWrapper.h>
#include <XnPropNames.h>

#include "io.h"

//---------------------------------------------------------------------------
// Globals
//---------------------------------------------------------------------------
xn::Context g_Context;
xn::ScriptNode g_scriptNode;
xn::DepthGenerator g_DepthGenerator;
xn::UserGenerator g_UserGenerator;
xn::Player g_Player;

XnBool g_bNeedPose = FALSE;
XnChar g_strPose[20] = "";

DepthMapLogger g_Log;

//---------------------------------------------------------------------------
// Forward declrarations
//---------------------------------------------------------------------------
void XN_CALLBACK_TYPE User_NewUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE User_LostUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE UserPose_PoseDetected(xn::PoseDetectionCapability& /*capability*/, const XnChar* strPose, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE UserCalibration_CalibrationStart(xn::SkeletonCapability& /*capability*/, XnUserID nId, void* /*pCookie*/);
void XN_CALLBACK_TYPE UserCalibration_CalibrationComplete(xn::SkeletonCapability& /*capability*/, XnUserID nId, XnCalibrationStatus eStatus, void* /*pCookie*/);

//---------------------------------------------------------------------------
// Code
//---------------------------------------------------------------------------

#define SAMPLE_XML_PATH "../Data/SamplesConfig.xml"

#define CHECK_RC(nRetVal, what)										\
	if (nRetVal != XN_STATUS_OK)									\
	{																\
		printf("%s failed: %s\n", what, xnGetStatusString(nRetVal));\
		return nRetVal;												\
	}

int main(int argc, char **argv)
{
	XnStatus nRetVal = XN_STATUS_OK;

	if (argc > 1)
	{
		nRetVal = g_Context.Init();
		CHECK_RC(nRetVal, "Init");
		nRetVal = g_Context.OpenFileRecording(argv[1], g_Player);
		if (nRetVal != XN_STATUS_OK)
		{
			printf("Can't open recording %s: %s\n", argv[1], xnGetStatusString(nRetVal));
			return 1;
		}
	}
	else
	{
		xn::EnumerationErrors errors;
		nRetVal = g_Context.InitFromXmlFile(SAMPLE_XML_PATH, g_scriptNode, &errors);
		if (nRetVal == XN_STATUS_NO_NODE_PRESENT)
		{
			XnChar strError[1024];
			errors.ToString(strError, 1024);
			printf("%s\n", strError);
			return (nRetVal);
		}
		else if (nRetVal != XN_STATUS_OK)
		{
			printf("Open failed: %s\n", xnGetStatusString(nRetVal));
			return (nRetVal);
		}
	}

	nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_DEPTH, g_DepthGenerator);
	if (nRetVal != XN_STATUS_OK)
	{
		printf("No depth generator found. Using a default one...");
		xn::MockDepthGenerator mockDepth;
		nRetVal = mockDepth.Create(g_Context);
		CHECK_RC(nRetVal, "Create mock depth");

		// set some defaults
		XnMapOutputMode defaultMode;
		defaultMode.nXRes = 320;
		defaultMode.nYRes = 240;
		defaultMode.nFPS = 30;
		nRetVal = mockDepth.SetMapOutputMode(defaultMode);
		CHECK_RC(nRetVal, "set default mode");

		// set FOV
		XnFieldOfView fov;
		fov.fHFOV = 1.0225999419141749;
		fov.fVFOV = 0.79661567681716894;
		nRetVal = mockDepth.SetGeneralProperty(XN_PROP_FIELD_OF_VIEW, sizeof(fov), &fov);
		CHECK_RC(nRetVal, "set FOV");

		XnUInt32 nDataSize = defaultMode.nXRes * defaultMode.nYRes * sizeof(XnDepthPixel);
		XnDepthPixel* pData = (XnDepthPixel*)xnOSCallocAligned(nDataSize, 1, XN_DEFAULT_MEM_ALIGN);

		nRetVal = mockDepth.SetData(1, 0, nDataSize, pData);
		CHECK_RC(nRetVal, "set empty depth map");

		g_DepthGenerator = mockDepth;
	}

	nRetVal = g_Context.FindExistingNode(XN_NODE_TYPE_USER, g_UserGenerator);
	if (nRetVal != XN_STATUS_OK)
	{
		nRetVal = g_UserGenerator.Create(g_Context);
		CHECK_RC(nRetVal, "Find user generator");
	}

	XnCallbackHandle hUserCallbacks, hCalibrationStart, hCalibrationComplete, hPoseDetected, hCalibrationInProgress, hPoseInProgress;
	if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_SKELETON))
	{
		printf("Supplied user generator doesn't support skeleton\n");
		return 1;
	}
	nRetVal = g_UserGenerator.RegisterUserCallbacks(User_NewUser, User_LostUser, NULL, hUserCallbacks);
	CHECK_RC(nRetVal, "Register to user callbacks");
	nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationStart(UserCalibration_CalibrationStart, NULL, hCalibrationStart);
	CHECK_RC(nRetVal, "Register to calibration start");
	nRetVal = g_UserGenerator.GetSkeletonCap().RegisterToCalibrationComplete(UserCalibration_CalibrationComplete, NULL, hCalibrationComplete);
	CHECK_RC(nRetVal, "Register to calibration complete");

	if (g_UserGenerator.GetSkeletonCap().NeedPoseForCalibration())
	{
		g_bNeedPose = TRUE;
		if (!g_UserGenerator.IsCapabilitySupported(XN_CAPABILITY_POSE_DETECTION))
		{
			printf("Pose required, but not supported\n");
			return 1;
		}
		nRetVal = g_UserGenerator.GetPoseDetectionCap().RegisterToPoseDetected(UserPose_PoseDetected, NULL, hPoseDetected);
		CHECK_RC(nRetVal, "Register to Pose Detected");
		g_UserGenerator.GetSkeletonCap().GetCalibrationPose(g_strPose);
	}

	g_UserGenerator.GetSkeletonCap().SetSkeletonProfile(XN_SKEL_PROFILE_ALL);

	nRetVal = g_Context.StartGeneratingAll();
	CHECK_RC(nRetVal, "StartGenerating");

	g_Log.Open("log.h5", "log.txt");

	// Main event loop
	xn::SceneMetaData sceneMD;
	xn::DepthMetaData depthMD;
	while (!xnOSWasKeyboardHit())
	{
		// Wait for an update
		g_Context.WaitOneUpdateAll(g_UserGenerator);

		// Process the data
		g_DepthGenerator.GetMetaData(depthMD);
		g_UserGenerator.GetUserPixels(0, sceneMD);

		// Log the data
		g_Log.DumpDepthMap(depthMD, sceneMD);
	}

	// Clean up all resources
	g_scriptNode.Release();
	g_DepthGenerator.Release();
	g_UserGenerator.Release();
	g_Player.Release();
	g_Context.Release();

	return EXIT_SUCCESS;
}

// Callback: New user was detected
void XN_CALLBACK_TYPE User_NewUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	printf("%d New User %d\n", epochTime, nId);
	// New user found
	if (g_bNeedPose)
	{
		g_UserGenerator.GetPoseDetectionCap().StartPoseDetection(g_strPose, nId);
	}
	else
	{
		g_UserGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
	}
}

// Callback: An existing user was lost
void XN_CALLBACK_TYPE User_LostUser(xn::UserGenerator& /*generator*/, XnUserID nId, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	printf("%d Lost user %d\n", epochTime, nId);
}

// Callback: Detected a pose
void XN_CALLBACK_TYPE UserPose_PoseDetected(xn::PoseDetectionCapability& /*capability*/, const XnChar* strPose, XnUserID nId, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	printf("%d Pose %s detected for user %d\n", epochTime, strPose, nId);
	g_UserGenerator.GetPoseDetectionCap().StopPoseDetection(nId);
	g_UserGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
}

// Callback: Started calibration
void XN_CALLBACK_TYPE UserCalibration_CalibrationStart(xn::SkeletonCapability& /*capability*/, XnUserID nId, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	printf("%d Calibration started for user %d\n", epochTime, nId);
}

// Callback: Finished calibration
void XN_CALLBACK_TYPE UserCalibration_CalibrationComplete(xn::SkeletonCapability& /*capability*/, XnUserID nId, XnCalibrationStatus eStatus, void* /*pCookie*/)
{
	XnUInt32 epochTime = 0;
	xnOSGetEpochTime(&epochTime);
	if (eStatus == XN_CALIBRATION_STATUS_OK)
	{
		// Calibration succeeded
		printf("%d Calibration complete, start tracking user %d\n", epochTime, nId);
		g_UserGenerator.GetSkeletonCap().StartTracking(nId);
	}
	else
	{
		// Calibration failed
		printf("%d Calibration failed for user %d\n", epochTime, nId);
		if(eStatus==XN_CALIBRATION_STATUS_MANUAL_ABORT)
		{
			printf("Manual abort occured, stop attempting to calibrate!");
			return;
		}
		if (g_bNeedPose)
		{
			g_UserGenerator.GetPoseDetectionCap().StartPoseDetection(g_strPose, nId);
		}
		else
		{
			g_UserGenerator.GetSkeletonCap().RequestCalibration(nId, TRUE);
		}
	}
}
<|endoftext|>