<commit_before>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXDE-Qt - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2010-2011 Razor team
 * Authors:
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "lxqtmainmenu.h"
#include "lxqtmainmenuconfiguration.h"
#include "../panel/lxqtpanel.h"
#include <QDebug>
#include <XdgDesktopFile>
#include <XmlHelper>
#include <QSettings>
#include <QFileInfo>
#include <QAction>
#include <QTimer>
#include <QMessageBox>
#include <QEvent>
#include <QKeyEvent>
#include <LXQt/PowerManager>
#include <LXQt/ScreenSaver>
#include <lxqt-globalkeys.h>
#include <algorithm> // for find_if()
#include <KWindowSystem/KWindowSystem>

#include <XdgIcon>
#include <XdgDesktopFile>
#include <XdgMenuWidget>

#ifdef HAVE_MENU_CACHE
#include "xdgcachedmenu.h"
#endif

#include <QPixmap>
#include <QStack>
#include <QCursor>

#define DEFAULT_SHORTCUT "Alt+F1"

LXQtMainMenu::LXQtMainMenu(const ILXQtPanelPluginStartupInfo &startupInfo):
    QObject(),
    ILXQtPanelPlugin(startupInfo),
    mMenu(0),
    mShortcut(0)
{
#ifdef HAVE_MENU_CACHE
    mMenuCache = NULL;
    mMenuCacheNotify = 0;
#endif

    mDelayedPopup.setSingleShot(true);
    mDelayedPopup.setInterval(250);
    connect(&mDelayedPopup, &QTimer::timeout, this, &LXQtMainMenu::showHideMenu);
    mHideTimer.setSingleShot(true);
    mHideTimer.setInterval(250);

    mButton.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
    mButton.installEventFilter(this);

    connect(&mButton, &QToolButton::clicked, this, &LXQtMainMenu::showHideMenu);

    settingsChanged();

    mShortcut = GlobalKeyShortcut::Client::instance()->addAction(QString{}, QString("/panel/%1/show_hide").arg(settings()->group()), tr("Show/hide main menu"), this);
    if (mShortcut)
    {
        connect(mShortcut, &GlobalKeyShortcut::Action::registrationFinished, [this] {
            if (mShortcut->shortcut().isEmpty())
                mShortcut->changeShortcut(DEFAULT_SHORTCUT);
        });
        connect(mShortcut, &GlobalKeyShortcut::Action::activated, [this] { if (!mHideTimer.isActive()) mDelayedPopup.start(); });
    }
}

/************************************************

 ************************************************/
LXQtMainMenu::~LXQtMainMenu()
{
    mButton.removeEventFilter(this);
#ifdef HAVE_MENU_CACHE
    if(mMenuCache)
    {
        menu_cache_remove_reload_notify(mMenuCache, mMenuCacheNotify);
        menu_cache_unref(mMenuCache);
    }
#endif
}

/************************************************

 ************************************************/
void LXQtMainMenu::showHideMenu()
{
    if (mMenu && mMenu->isVisible())
        mMenu->hide();
    else
        showMenu();
}

/************************************************

 ************************************************/
void LXQtMainMenu::showMenu()
{
    if (!mMenu)
        return;

    willShowWindow(mMenu);
    // Just using Qt`s activateWindow() won't work on some WMs like Kwin.
    // Solution is to execute menu 1ms later using timer
    mMenu->popup(calculatePopupWindowPos(mMenu->sizeHint()).topLeft());
}

#ifdef HAVE_MENU_CACHE
// static
void LXQtMainMenu::menuCacheReloadNotify(MenuCache* cache, gpointer user_data)
{
    reinterpret_cast<LXQtMainMenu*>(user_data)->buildMenu();
}
#endif

/************************************************

 ************************************************/
void LXQtMainMenu::settingsChanged()
{
    setButtonIcon();
    if (settings()->value("showText", false).toBool())
    {
        mButton.setText(settings()->value("text", "Start").toString());
        mButton.setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
    }
    else
    {
        mButton.setText("");
        mButton.setToolButtonStyle(Qt::ToolButtonIconOnly);
    }

    mLogDir = settings()->value("log_dir", "").toString();

    QString menu_file = settings()->value("menu_file", "").toString();
    if (menu_file.isEmpty())
        menu_file = XdgMenu::getMenuFileName();

    if (mMenuFile != menu_file)
    {
        mMenuFile = menu_file;
#ifdef HAVE_MENU_CACHE
        menu_cache_init(0);
        if(mMenuCache)
        {
            menu_cache_remove_reload_notify(mMenuCache, mMenuCacheNotify);
            menu_cache_unref(mMenuCache);
        }
        mMenuCache = menu_cache_lookup(mMenuFile.toLocal8Bit());
        if (menu_cache_get_root_dir(mMenuCache))
            buildMenu();
        mMenuCacheNotify = menu_cache_add_reload_notify(mMenuCache, (MenuCacheReloadNotify)menuCacheReloadNotify, this);
#else
        mXdgMenu.setEnvironments(QStringList() << "X-LXQT" << "LXQt");
        mXdgMenu.setLogDir(mLogDir);

        bool res = mXdgMenu.read(mMenuFile);
        connect(&mXdgMenu, SIGNAL(changed()), this, SLOT(buildMenu()));
        if (res)
        {
            QTimer::singleShot(1000, this, SLOT(buildMenu()));
        }
        else
        {
            QMessageBox::warning(0, "Parse error", mXdgMenu.errorString());
            return;
        }
#endif
    }

    setMenuFontSize();

    realign();
}

/************************************************

 ************************************************/
void LXQtMainMenu::buildMenu()
{
#ifdef HAVE_MENU_CACHE
    XdgCachedMenu* menu = new XdgCachedMenu(mMenuCache, &mButton);
#else
    XdgMenuWidget *menu = new XdgMenuWidget(mXdgMenu, "", &mButton);
#endif
    menu->setObjectName("TopLevelMainMenu");
    menu->setStyle(&mTopMenuStyle);

    menu->addSeparator();

    Q_FOREACH(QAction* action, menu->actions())
    {
        if (action->menu())
            action->menu()->installEventFilter(this);
    }

    menu->installEventFilter(this);
    connect(menu, &QMenu::aboutToHide, &mHideTimer, static_cast<void (QTimer::*)()>(&QTimer::start));
    connect(menu, &QMenu::aboutToShow, &mHideTimer, &QTimer::stop);

    QMenu *oldMenu = mMenu;
    mMenu = menu;
    if(oldMenu)
        delete oldMenu;

    setMenuFontSize();
}

/************************************************

 ************************************************/
void LXQtMainMenu::setMenuFontSize()
{
    if (!mMenu)
        return;

    QFont menuFont = mButton.font();
    if(settings()->value("customFont", false).toBool())
    {
        menuFont = mMenu->font();
        menuFont.setPointSize(settings()->value("customFontSize").toInt());
    }

    if (mMenu->font() != menuFont)
    {
        mMenu->setFont(menuFont);
        QList<QMenu*> subMenuList = mMenu->findChildren<QMenu*>();
        foreach (QMenu* subMenu, subMenuList)
        {
            subMenu->setFont(menuFont);
        }
    }

    //icon size the same as the font height
    mTopMenuStyle.setIconSize(QFontMetrics(menuFont).height());
}

/************************************************

 ************************************************/
void LXQtMainMenu::setButtonIcon()
{
    if (settings()->value("ownIcon", false).toBool())
    {
        mButton.setIcon(QIcon{settings()->value(QLatin1String("icon"), QLatin1String(LXQT_GRAPHICS_DIR"/helix.svg")).toString()});
    } else
    {
        mButton.setIcon(QIcon{});
        mButton.style()->unpolish(&mButton);
        mButton.style()->polish(&mButton);
    }
}

/************************************************

 ************************************************/
QDialog *LXQtMainMenu::configureDialog()
{
    return new LXQtMainMenuConfiguration(settings(), mShortcut, DEFAULT_SHORTCUT);
}
/************************************************

 ************************************************/

// functor used to match a QAction by prefix
struct MatchAction
{
    MatchAction(QString key):key_(key) {}
    bool operator()(QAction* action) { return action->text().startsWith(key_, Qt::CaseInsensitive); }
    QString key_;
};

bool LXQtMainMenu::eventFilter(QObject *obj, QEvent *event)
{
    if(obj == &mButton)
    {
        // the application is given a new QStyle
        if(event->type() == QEvent::StyleChange)
        {
            // reset proxy style for the menus so they can apply the new styles
            mTopMenuStyle.setBaseStyle(NULL);
            setMenuFontSize();
            setButtonIcon();
        }
    }
    else if(QMenu* menu = qobject_cast<QMenu*>(obj))
    {
        if(event->type() == QEvent::KeyPress)
        {
            // if our shortcut key is pressed while the menu is open, close the menu
            QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
            if (keyEvent->modifiers() & ~Qt::ShiftModifier)
            {
                mHideTimer.start();
                mMenu->hide(); // close the app menu
                return true;
            }
            else // go to the menu item starts with the pressed key
            {
                QString key = keyEvent->text();
                if(key.isEmpty())
                    return false;
                QAction* action = menu->activeAction();
                QList<QAction*> actions = menu->actions();
                QList<QAction*>::iterator it = qFind(actions.begin(), actions.end(), action);
                it = std::find_if(it + 1, actions.end(), MatchAction(key));
                if(it == actions.end())
                    it = std::find_if(actions.begin(), it, MatchAction(key));
                if(it != actions.end())
                    menu->setActiveAction(*it);
            }
        }
    }
    return false;
}

#undef DEFAULT_SHORTCUT
<commit_msg>mainmenu: Fix freeze for some widget styles (e.g. breeze)<commit_after>/* BEGIN_COMMON_COPYRIGHT_HEADER
 * (c)LGPL2+
 *
 * LXDE-Qt - a lightweight, Qt based, desktop toolset
 * http://razor-qt.org
 *
 * Copyright: 2010-2011 Razor team
 * Authors:
 *   Alexander Sokoloff <sokoloff.a@gmail.com>
 *
 * This program or library is free software; you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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
 *
 * END_COMMON_COPYRIGHT_HEADER */

#include "lxqtmainmenu.h"
#include "lxqtmainmenuconfiguration.h"
#include "../panel/lxqtpanel.h"
#include <QDebug>
#include <XdgDesktopFile>
#include <XmlHelper>
#include <QSettings>
#include <QFileInfo>
#include <QAction>
#include <QTimer>
#include <QMessageBox>
#include <QEvent>
#include <QKeyEvent>
#include <LXQt/PowerManager>
#include <LXQt/ScreenSaver>
#include <lxqt-globalkeys.h>
#include <algorithm> // for find_if()
#include <KWindowSystem/KWindowSystem>

#include <XdgIcon>
#include <XdgDesktopFile>
#include <XdgMenuWidget>

#ifdef HAVE_MENU_CACHE
#include "xdgcachedmenu.h"
#endif

#include <QPixmap>
#include <QStack>
#include <QCursor>

#define DEFAULT_SHORTCUT "Alt+F1"

LXQtMainMenu::LXQtMainMenu(const ILXQtPanelPluginStartupInfo &startupInfo):
    QObject(),
    ILXQtPanelPlugin(startupInfo),
    mMenu(0),
    mShortcut(0)
{
#ifdef HAVE_MENU_CACHE
    mMenuCache = NULL;
    mMenuCacheNotify = 0;
#endif

    mDelayedPopup.setSingleShot(true);
    mDelayedPopup.setInterval(250);
    connect(&mDelayedPopup, &QTimer::timeout, this, &LXQtMainMenu::showHideMenu);
    mHideTimer.setSingleShot(true);
    mHideTimer.setInterval(250);

    mButton.setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum);
    mButton.installEventFilter(this);

    connect(&mButton, &QToolButton::clicked, this, &LXQtMainMenu::showHideMenu);

    QTimer::singleShot(0, [this] { settingsChanged(); });

    mShortcut = GlobalKeyShortcut::Client::instance()->addAction(QString{}, QString("/panel/%1/show_hide").arg(settings()->group()), tr("Show/hide main menu"), this);
    if (mShortcut)
    {
        connect(mShortcut, &GlobalKeyShortcut::Action::registrationFinished, [this] {
            if (mShortcut->shortcut().isEmpty())
                mShortcut->changeShortcut(DEFAULT_SHORTCUT);
        });
        connect(mShortcut, &GlobalKeyShortcut::Action::activated, [this] { if (!mHideTimer.isActive()) mDelayedPopup.start(); });
    }
}

/************************************************

 ************************************************/
LXQtMainMenu::~LXQtMainMenu()
{
    mButton.removeEventFilter(this);
#ifdef HAVE_MENU_CACHE
    if(mMenuCache)
    {
        menu_cache_remove_reload_notify(mMenuCache, mMenuCacheNotify);
        menu_cache_unref(mMenuCache);
    }
#endif
}

/************************************************

 ************************************************/
void LXQtMainMenu::showHideMenu()
{
    if (mMenu && mMenu->isVisible())
        mMenu->hide();
    else
        showMenu();
}

/************************************************

 ************************************************/
void LXQtMainMenu::showMenu()
{
    if (!mMenu)
        return;

    willShowWindow(mMenu);
    // Just using Qt`s activateWindow() won't work on some WMs like Kwin.
    // Solution is to execute menu 1ms later using timer
    mMenu->popup(calculatePopupWindowPos(mMenu->sizeHint()).topLeft());
}

#ifdef HAVE_MENU_CACHE
// static
void LXQtMainMenu::menuCacheReloadNotify(MenuCache* cache, gpointer user_data)
{
    reinterpret_cast<LXQtMainMenu*>(user_data)->buildMenu();
}
#endif

/************************************************

 ************************************************/
void LXQtMainMenu::settingsChanged()
{
    setButtonIcon();
    if (settings()->value("showText", false).toBool())
    {
        mButton.setText(settings()->value("text", "Start").toString());
        mButton.setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
    }
    else
    {
        mButton.setText("");
        mButton.setToolButtonStyle(Qt::ToolButtonIconOnly);
    }

    mLogDir = settings()->value("log_dir", "").toString();

    QString menu_file = settings()->value("menu_file", "").toString();
    if (menu_file.isEmpty())
        menu_file = XdgMenu::getMenuFileName();

    if (mMenuFile != menu_file)
    {
        mMenuFile = menu_file;
#ifdef HAVE_MENU_CACHE
        menu_cache_init(0);
        if(mMenuCache)
        {
            menu_cache_remove_reload_notify(mMenuCache, mMenuCacheNotify);
            menu_cache_unref(mMenuCache);
        }
        mMenuCache = menu_cache_lookup(mMenuFile.toLocal8Bit());
        if (menu_cache_get_root_dir(mMenuCache))
            buildMenu();
        mMenuCacheNotify = menu_cache_add_reload_notify(mMenuCache, (MenuCacheReloadNotify)menuCacheReloadNotify, this);
#else
        mXdgMenu.setEnvironments(QStringList() << "X-LXQT" << "LXQt");
        mXdgMenu.setLogDir(mLogDir);

        bool res = mXdgMenu.read(mMenuFile);
        connect(&mXdgMenu, SIGNAL(changed()), this, SLOT(buildMenu()));
        if (res)
        {
            QTimer::singleShot(1000, this, SLOT(buildMenu()));
        }
        else
        {
            QMessageBox::warning(0, "Parse error", mXdgMenu.errorString());
            return;
        }
#endif
    }

    setMenuFontSize();

    realign();
}

/************************************************

 ************************************************/
void LXQtMainMenu::buildMenu()
{
#ifdef HAVE_MENU_CACHE
    XdgCachedMenu* menu = new XdgCachedMenu(mMenuCache, &mButton);
#else
    XdgMenuWidget *menu = new XdgMenuWidget(mXdgMenu, "", &mButton);
#endif
    menu->setObjectName("TopLevelMainMenu");
    menu->setStyle(&mTopMenuStyle);

    menu->addSeparator();

    Q_FOREACH(QAction* action, menu->actions())
    {
        if (action->menu())
            action->menu()->installEventFilter(this);
    }

    menu->installEventFilter(this);
    connect(menu, &QMenu::aboutToHide, &mHideTimer, static_cast<void (QTimer::*)()>(&QTimer::start));
    connect(menu, &QMenu::aboutToShow, &mHideTimer, &QTimer::stop);

    QMenu *oldMenu = mMenu;
    mMenu = menu;
    if(oldMenu)
        delete oldMenu;

    setMenuFontSize();
}

/************************************************

 ************************************************/
void LXQtMainMenu::setMenuFontSize()
{
    if (!mMenu)
        return;

    QFont menuFont = mButton.font();
    if(settings()->value("customFont", false).toBool())
    {
        menuFont = mMenu->font();
        menuFont.setPointSize(settings()->value("customFontSize").toInt());
    }

    if (mMenu->font() != menuFont)
    {
        mMenu->setFont(menuFont);
        QList<QMenu*> subMenuList = mMenu->findChildren<QMenu*>();
        foreach (QMenu* subMenu, subMenuList)
        {
            subMenu->setFont(menuFont);
        }
    }

    //icon size the same as the font height
    mTopMenuStyle.setIconSize(QFontMetrics(menuFont).height());
}

/************************************************

 ************************************************/
void LXQtMainMenu::setButtonIcon()
{
    if (settings()->value("ownIcon", false).toBool())
    {
        mButton.setIcon(QIcon{settings()->value(QLatin1String("icon"), QLatin1String(LXQT_GRAPHICS_DIR"/helix.svg")).toString()});
    } else
    {
        mButton.setIcon(QIcon{});
        mButton.style()->polish(&mButton);
    }
}

/************************************************

 ************************************************/
QDialog *LXQtMainMenu::configureDialog()
{
    return new LXQtMainMenuConfiguration(settings(), mShortcut, DEFAULT_SHORTCUT);
}
/************************************************

 ************************************************/

// functor used to match a QAction by prefix
struct MatchAction
{
    MatchAction(QString key):key_(key) {}
    bool operator()(QAction* action) { return action->text().startsWith(key_, Qt::CaseInsensitive); }
    QString key_;
};

bool LXQtMainMenu::eventFilter(QObject *obj, QEvent *event)
{
    if(obj == &mButton)
    {
        // the application is given a new QStyle
        if(event->type() == QEvent::StyleChange)
        {
            // reset proxy style for the menus so they can apply the new styles
            mTopMenuStyle.setBaseStyle(NULL);
            setMenuFontSize();
            setButtonIcon();
        }
    }
    else if(QMenu* menu = qobject_cast<QMenu*>(obj))
    {
        if(event->type() == QEvent::KeyPress)
        {
            // if our shortcut key is pressed while the menu is open, close the menu
            QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
            if (keyEvent->modifiers() & ~Qt::ShiftModifier)
            {
                mHideTimer.start();
                mMenu->hide(); // close the app menu
                return true;
            }
            else // go to the menu item starts with the pressed key
            {
                QString key = keyEvent->text();
                if(key.isEmpty())
                    return false;
                QAction* action = menu->activeAction();
                QList<QAction*> actions = menu->actions();
                QList<QAction*>::iterator it = qFind(actions.begin(), actions.end(), action);
                it = std::find_if(it + 1, actions.end(), MatchAction(key));
                if(it == actions.end())
                    it = std::find_if(actions.begin(), it, MatchAction(key));
                if(it != actions.end())
                    menu->setActiveAction(*it);
            }
        }
    }
    return false;
}

#undef DEFAULT_SHORTCUT
<|endoftext|>


<commit_before>#include <QtXml>
#include <QDebug>

void traverseNode(QDomNode const& node);

int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) {
    QDomDocument domDoc{};
    QFile file{"address_book.xml"};
    if (file.open(QIODevice::ReadOnly)) {
        if (domDoc.setContent(&file)) {
            QDomElement domElement = domDoc.documentElement();
            traverseNode(domElement);
        }
        file.close();
    }

	return 0;
}

void traverseNode(QDomNode const& node) {
    QDomNode domNode = node.firstChild();
    while (not domNode.isNull()) {
        if (domNode.isElement()) {
            QDomElement domElement = domNode.toElement();
            if (not domElement.isNull()) {
                if ("contact" == domElement.tagName()) {
                    qDebug() << "attr: " << domElement.attribute("number", "");
                }
                else {
                    qDebug() << "TagName: " << domElement.tagName() << "\tText: " << domElement.text();
                }
            }
        }
        traverseNode(domNode);
        domNode = domNode.nextSibling();
    }
}
<commit_msg>[m_shlee-qt_5_10][ch 40] slightly modify the 1-st example<commit_after>#include <QtXml>
#include <QFile>
#include <QDebug>

void traverseNode(QDomNode const& node);

int main([[maybe_unused]] int argc, [[maybe_unused]] char** argv) {
    QDomDocument domDoc{};
    QFile file{"address_book.xml"};
    if (file.open(QIODevice::ReadOnly)) {
        if (domDoc.setContent(&file)) {
            QDomElement domElement = domDoc.documentElement();
            traverseNode(domElement);
        }
        file.close();
    }

    return 0;
}

void traverseNode(QDomNode const& node) {
    QDomNode domNode = node.firstChild();
    while (not domNode.isNull()) {
        if (domNode.isElement()) {
            QDomElement domElement = domNode.toElement();
            if (not domElement.isNull()) {
                if ("contact" == domElement.tagName()) {
                    qDebug() << "attr: " << domElement.attribute("number", "");
                }
                else {
                    qDebug() << "TagName: " << domElement.tagName() << "\tText: " << domElement.text();
                }
           }
        }
        traverseNode(domNode);
        domNode = domNode.nextSibling();
    }
}<|endoftext|>


<commit_before>// See LICENSE file for copyright and license details.

#ifndef CORE__MISC_HPP
#define CORE__MISC_HPP

#include <cassert>
#include <list>

// TODO: Rewrite :(
template <class T>
T* getNext(std::list<T*> &list, T* node) {
  assert(node);
  auto it = list.begin();
  while (it != list.end()) {
    if (*it == node) {
      ++it;
      if (it == list.end()) {
        return nullptr;
      }
      return *it;
    }
    ++it;
  }
  return nullptr;
}

void die(const char *message, ...);

#define UNUSED(x) ((void)x)

#endif
<commit_msg>core/misc.hpp: getNex(..): Simplified<commit_after>// See LICENSE file for copyright and license details.

#ifndef CORE__MISC_HPP
#define CORE__MISC_HPP

#include <cassert>
#include <list>

// TODO: Rewrite :(
template <class T>
T* getNext(std::list<T*> &list, T* node) {
  assert(node);
  for (auto it = list.begin(); it != list.end(); ++it) {
    if (*it == node) {
      ++it;
      if (it != list.end()) {
        return *it;
      }
      return nullptr;
    }
  }
  return nullptr;
}

void die(const char *message, ...);

#define UNUSED(x) ((void)x)

#endif
<|endoftext|>


<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "newrestdialog.h"
#include "intervalrest.h"
#include "singleshotrest.h"

#include <QDesktopWidget>
#include <QPalette>
#include <QStandardItemModel>
#include <QStandardItem>

// TODO
// 1. ESC to hide curtain
// 2. Add options to show countdown in curtain

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    timer(new QTimer),
    dirty(false)
{
    ui->setupUi(this);
    setupCurtain();

    // connect signals & slots
    connect(ui->actionAdd, SIGNAL(triggered()), SLOT(newRestDialog()));
    connect(ui->btnRemoveAll, SIGNAL(clicked()), SLOT(removeAll()));
    connect(ui->btnRemoveSelected, SIGNAL(clicked()), SLOT(removeSelected()));
    connect(timer, SIGNAL(timeout()), SLOT(updateClock()));
    connect(timer, SIGNAL(timeout()), SLOT(updateCurtainVisibility()));
    connect(timer, SIGNAL(timeout()), SLOT(cleanupExpired()));
    connect(timer, SIGNAL(timeout()), SLOT(refreshList()));

    // start clock
    timer->setInterval(50);
    timer->start();

    // update UI immediately
    updateClock();
    refreshList();
}

MainWindow::~MainWindow()
{
    delete timer;
    qDeleteAll(curtain);
    removeAll();
    delete ui;
}

void MainWindow::newRestDialog()
{
    NewRestDialog dialog;
    if (dialog.exec() == NewRestDialog::Accepted)
    {
        rests.append(dialog.rest());
        dirty = true;
    }
}

void MainWindow::updateClock()
{
    QTime now = QTime::currentTime();
    QString msg = QString("Clock: %0").arg(now.toString());
    ui->statusBar->showMessage(msg);
}

void MainWindow::updateCurtainVisibility()
{
    QDateTime now = QDateTime::currentDateTime();

    if (curtainExpiration.isValid())
    {
        if (now.msecsTo(curtainExpiration) <= 0)
        {
            curtainExpiration = QDateTime();
            showCurtain(false);
        }
        return;
    }

    foreach (const Rest *r, rests)
        if (r->triggeredAt(now))
        {
            int durationSeconds = QTime(0, 0, 0).secsTo(r->duration);
            curtainExpiration = QDateTime::currentDateTime().addSecs(durationSeconds);
            showCurtain(true);
            return;
        }
}

void MainWindow::cleanupExpired()
{
    QDateTime now = QDateTime::currentDateTime();

    QMutableListIterator<Rest*> iterator(rests);
    while (iterator.hasNext())
    {
        Rest *r = iterator.next();
        if (r->expiresAt(now))
        {
            iterator.remove();
            delete r;
            dirty = true;
        }
    }
}

void MainWindow::refreshList()
{
    if (!dirty)
        return;

    QStandardItemModel *model = new QStandardItemModel(0, 5);

    // create header

    {
        QStringList labels;
        labels.append("Type");
        labels.append("Start");
        labels.append("End");
        labels.append("Interval");
        labels.append("Duration");
        model->setHorizontalHeaderLabels(labels);
    }

    // create items

    foreach (const Rest *r, rests)
    {
        QList<QStandardItem*> cols;
        QString dateFormat = "yyyy/MM/dd hh:mm:ss";

        if (const SingleShotRest *ssr = dynamic_cast<const SingleShotRest*>(r))
        {
            cols.append(new QStandardItem("Single Shot"));
            cols.append(new QStandardItem(ssr->triggerTime.toString(dateFormat)));
            cols.append(new QStandardItem("N/A"));
            cols.append(new QStandardItem("N/A"));
            cols.append(new QStandardItem(ssr->duration.toString()));
        }
        else if (const IntervalRest *ir = dynamic_cast<const IntervalRest*>(r))
        {
            cols.append(new QStandardItem("Interval"));
            cols.append(new QStandardItem(ir->start.toString(dateFormat)));
            cols.append(new QStandardItem(ir->end.toString(dateFormat)));
            cols.append(new QStandardItem(ir->interval.toString()));
            cols.append(new QStandardItem(ir->duration.toString()));
        }

        model->appendRow(cols);
    }

    delete ui->tableView->model();
    ui->tableView->setModel(model);
    ui->tableView->resizeColumnsToContents();
    dirty = false;
}

void MainWindow::removeAll()
{
    qDeleteAll(rests);
    rests.clear();
    dirty = true;
}

void MainWindow::removeSelected()
{
    QModelIndex idx = ui->tableView->currentIndex();
    if (idx.isValid())
    {
        rests.erase(rests.begin() + idx.row());
        dirty = true;
    }
}

void MainWindow::setupCurtain()
{
    QList<QWidget*> result;
    QDesktopWidget *desktop = QApplication::desktop();

    QPalette palette;
    palette.setColor(QPalette::Background, Qt::black);

    for (int i = 0; i < desktop->screenCount(); i++)
    {
        QWidget *screenCurtain = new QWidget;
        screenCurtain->setAutoFillBackground(true);
        screenCurtain->setPalette(palette);
        screenCurtain->setCursor(QCursor(Qt::BlankCursor));
        screenCurtain->setWindowFlags(Qt::WindowStaysOnTopHint);
        screenCurtain->setGeometry(desktop->screenGeometry(i));
        result.append(screenCurtain);
    }

    curtain.swap(result);
}

void MainWindow::showCurtain(bool isVisible)
{
    foreach (QWidget *screenCurtain, curtain)
        if (isVisible)
            screenCurtain->showFullScreen();
        else
            screenCurtain->hide();
}

<commit_msg>Fix memory leak on remove selected<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "newrestdialog.h"
#include "intervalrest.h"
#include "singleshotrest.h"

#include <QDesktopWidget>
#include <QPalette>
#include <QStandardItemModel>
#include <QStandardItem>

// TODO
// 1. ESC to hide curtain
// 2. Add options to show countdown in curtain

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    timer(new QTimer),
    dirty(false)
{
    ui->setupUi(this);
    setupCurtain();

    // connect signals & slots
    connect(ui->actionAdd, SIGNAL(triggered()), SLOT(newRestDialog()));
    connect(ui->btnRemoveAll, SIGNAL(clicked()), SLOT(removeAll()));
    connect(ui->btnRemoveSelected, SIGNAL(clicked()), SLOT(removeSelected()));
    connect(timer, SIGNAL(timeout()), SLOT(updateClock()));
    connect(timer, SIGNAL(timeout()), SLOT(updateCurtainVisibility()));
    connect(timer, SIGNAL(timeout()), SLOT(cleanupExpired()));
    connect(timer, SIGNAL(timeout()), SLOT(refreshList()));

    // start clock
    timer->setInterval(50);
    timer->start();

    // update UI immediately
    updateClock();
    refreshList();
}

MainWindow::~MainWindow()
{
    delete timer;
    qDeleteAll(curtain);
    removeAll();
    delete ui;
}

void MainWindow::newRestDialog()
{
    NewRestDialog dialog;
    if (dialog.exec() == NewRestDialog::Accepted)
    {
        rests.append(dialog.rest());
        dirty = true;
    }
}

void MainWindow::updateClock()
{
    QTime now = QTime::currentTime();
    QString msg = QString("Clock: %0").arg(now.toString());
    ui->statusBar->showMessage(msg);
}

void MainWindow::updateCurtainVisibility()
{
    QDateTime now = QDateTime::currentDateTime();

    if (curtainExpiration.isValid())
    {
        if (now.msecsTo(curtainExpiration) <= 0)
        {
            curtainExpiration = QDateTime();
            showCurtain(false);
        }
        return;
    }

    foreach (const Rest *r, rests)
        if (r->triggeredAt(now))
        {
            int durationSeconds = QTime(0, 0, 0).secsTo(r->duration);
            curtainExpiration = QDateTime::currentDateTime().addSecs(durationSeconds);
            showCurtain(true);
            return;
        }
}

void MainWindow::cleanupExpired()
{
    QDateTime now = QDateTime::currentDateTime();

    QMutableListIterator<Rest*> iterator(rests);
    while (iterator.hasNext())
    {
        Rest *r = iterator.next();
        if (r->expiresAt(now))
        {
            iterator.remove();
            delete r;
            dirty = true;
        }
    }
}

void MainWindow::refreshList()
{
    if (!dirty)
        return;

    QStandardItemModel *model = new QStandardItemModel(0, 5);

    // create header

    {
        QStringList labels;
        labels.append("Type");
        labels.append("Start");
        labels.append("End");
        labels.append("Interval");
        labels.append("Duration");
        model->setHorizontalHeaderLabels(labels);
    }

    // create items

    foreach (const Rest *r, rests)
    {
        QList<QStandardItem*> cols;
        QString dateFormat = "yyyy/MM/dd hh:mm:ss";

        if (const SingleShotRest *ssr = dynamic_cast<const SingleShotRest*>(r))
        {
            cols.append(new QStandardItem("Single Shot"));
            cols.append(new QStandardItem(ssr->triggerTime.toString(dateFormat)));
            cols.append(new QStandardItem("N/A"));
            cols.append(new QStandardItem("N/A"));
            cols.append(new QStandardItem(ssr->duration.toString()));
        }
        else if (const IntervalRest *ir = dynamic_cast<const IntervalRest*>(r))
        {
            cols.append(new QStandardItem("Interval"));
            cols.append(new QStandardItem(ir->start.toString(dateFormat)));
            cols.append(new QStandardItem(ir->end.toString(dateFormat)));
            cols.append(new QStandardItem(ir->interval.toString()));
            cols.append(new QStandardItem(ir->duration.toString()));
        }

        model->appendRow(cols);
    }

    delete ui->tableView->model();
    ui->tableView->setModel(model);
    ui->tableView->resizeColumnsToContents();
    dirty = false;
}

void MainWindow::removeAll()
{
    qDeleteAll(rests);
    rests.clear();
    dirty = true;
}

void MainWindow::removeSelected()
{
    QModelIndex idx = ui->tableView->currentIndex();
    if (idx.isValid())
    {
        QList<Rest*>::iterator rest = rests.begin() + idx.row();
        delete *rest;
        rests.erase(rest);
        dirty = true;
    }
}

void MainWindow::setupCurtain()
{
    QList<QWidget*> result;
    QDesktopWidget *desktop = QApplication::desktop();

    QPalette palette;
    palette.setColor(QPalette::Background, Qt::black);

    for (int i = 0; i < desktop->screenCount(); i++)
    {
        QWidget *screenCurtain = new QWidget;
        screenCurtain->setAutoFillBackground(true);
        screenCurtain->setPalette(palette);
        screenCurtain->setCursor(QCursor(Qt::BlankCursor));
        screenCurtain->setWindowFlags(Qt::WindowStaysOnTopHint);
        screenCurtain->setGeometry(desktop->screenGeometry(i));
        result.append(screenCurtain);
    }

    curtain.swap(result);
}

void MainWindow::showCurtain(bool isVisible)
{
    foreach (QWidget *screenCurtain, curtain)
        if (isVisible)
            screenCurtain->showFullScreen();
        else
            screenCurtain->hide();
}

<|endoftext|>


<commit_before>/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You 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.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee++ Internals -- Catch
 *
 * This file provides convert_exception, a function to aid in converting
 * C++ exceptions into ib_status_t return values.
 *
 * @author Christopher Alfeld <calfeld@qualys.com>
 */

#ifndef __IBPP__INTERNAL__CATCH__
#define __IBPP__INTERNAL__CATCH__

#include <ironbee/types.h>

#include <cstdlib> // for NULL

struct ib_engine_t;

namespace IronBee {

class Engine;

namespace Internal {

/**
 * Handle any exception and translate into an IronBee status code.
 *
 * This function will terminate the process if called outside of a catch
 * block.
 *
 * Use like this:
 * @code
 * try {
 *   my_cpp_func();
 * }
 * catch (...) {
 *   return Internal::convert_exception(ib_engine);
 * }
 * @endcode
 *
 * All exceptions except allocation errors will result in log messages.  If
 * an engine is provided, the engine logger will be used, otherwise the util
 * logger will be used.  This logging behavior can be overridden via the
 * @a logging parameter.
 *
 * - The subclasses of IronBee::error turn into their corresponding
 *   ib_status_t.  E.g., declined becomes IB_DECLINED.
 * - std::invalid_argument becomes IB_EINVAL.
 * - std::bad_alloc becomes IB_EALLOC.
 * - Any other exception becomes IB_EUNKNOWN, including IronBee::error.
 *
 * The log message depends on the exception type:
 *
 * - For any exception that translates to IB_EALLOC, nothing is logged to
 *   avoid further allocations.
 * - For IronBee::error and its subclasses, the errinfo_what will be
 *   extracted and reported.  If IBPP_DEBUG is defined, full diagnostic
 *   info is logged (boost::diagnostic_information()).
 * - For any other boost::exception, a generic message is logged, and
 *   full diagnostic info if IBPP_DEBUG is defined.
 * - For any other std::exception, std::exception::what() is logged.
 * - For any other exception, a generic message is logged.
 *
 * Log level 1 is used unless an errinfo_level is attached to the exception,
 * in which case its value is used instead.
 *
 * @param[in] ib_engine Engine to use for logging; may be NULL
 * @param[in] logging   Can be set to false to prevent any logging.
 **/
ib_status_t convert_exception(
    ib_engine_t* engine  = NULL,
    bool         logging = true
);

//! Overload of previous for Engine.
ib_status_t convert_exception(
    Engine engine,
    bool   logging = true
);

} // Internal
} // IronBee

#endif
<commit_msg>ironbee++: Fix doxygen warning.<commit_after>/*****************************************************************************
 * Licensed to Qualys, Inc. (QUALYS) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * QUALYS licenses this file to You 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.
 ****************************************************************************/

/**
 * @file
 * @brief IronBee++ Internals -- Catch
 *
 * This file provides convert_exception, a function to aid in converting
 * C++ exceptions into ib_status_t return values.
 *
 * @author Christopher Alfeld <calfeld@qualys.com>
 */

#ifndef __IBPP__INTERNAL__CATCH__
#define __IBPP__INTERNAL__CATCH__

#include <ironbee/types.h>

#include <cstdlib> // for NULL

struct ib_engine_t;

namespace IronBee {

class Engine;

namespace Internal {

/**
 * Handle any exception and translate into an IronBee status code.
 *
 * This function will terminate the process if called outside of a catch
 * block.
 *
 * Use like this:
 * @code
 * try {
 *   my_cpp_func();
 * }
 * catch (...) {
 *   return Internal::convert_exception(ib_engine);
 * }
 * @endcode
 *
 * All exceptions except allocation errors will result in log messages.  If
 * an engine is provided, the engine logger will be used, otherwise the util
 * logger will be used.  This logging behavior can be overridden via the
 * @a logging parameter.
 *
 * - The subclasses of IronBee::error turn into their corresponding
 *   ib_status_t.  E.g., declined becomes IB_DECLINED.
 * - std::invalid_argument becomes IB_EINVAL.
 * - std::bad_alloc becomes IB_EALLOC.
 * - Any other exception becomes IB_EUNKNOWN, including IronBee::error.
 *
 * The log message depends on the exception type:
 *
 * - For any exception that translates to IB_EALLOC, nothing is logged to
 *   avoid further allocations.
 * - For IronBee::error and its subclasses, the errinfo_what will be
 *   extracted and reported.  If IBPP_DEBUG is defined, full diagnostic
 *   info is logged (boost::diagnostic_information()).
 * - For any other boost::exception, a generic message is logged, and
 *   full diagnostic info if IBPP_DEBUG is defined.
 * - For any other std::exception, std::exception::what() is logged.
 * - For any other exception, a generic message is logged.
 *
 * Log level 1 is used unless an errinfo_level is attached to the exception,
 * in which case its value is used instead.
 *
 * @param[in] engine  Engine to use for logging; may be NULL
 * @param[in] logging Can be set to false to prevent any logging.
 **/
ib_status_t convert_exception(
    ib_engine_t* engine  = NULL,
    bool         logging = true
);

//! Overload of previous for Engine.
ib_status_t convert_exception(
    Engine engine,
    bool   logging = true
);

} // Internal
} // IronBee

#endif
<|endoftext|>


<commit_before>/*
 NUI3 - C++ cross-platform GUI framework for OpenGL based applications
 Copyright (C) 2002-2003 Sebastien Metrot

 licence: see nui3/LICENCE.TXT
 */

#include "nui.h"
#include "nuiSampleReader.h"
#include "nuiChunksDefinitions.h"

nuiSampleReader::nuiSampleReader(nglIStream& rStream):
mrStream(rStream),
mInitialized(false),
mPosition(0)
{
}

nuiSampleReader::nuiSampleReader(const nuiSampleReader& rReader, nglIStream& rStream):
mrStream(rStream),
mInitialized(rReader.mInitialized),
mPosition(rReader.mPosition),
mInfo(rReader.mInfo)
{
}

nuiSampleReader::~nuiSampleReader()
{
}

bool nuiSampleReader::Init()
{
  mInitialized = ReadInfo();
  if (mInitialized)
    SetPosition(0);

  return mInitialized;
}

uint32 nuiSampleReader::GetPosition() const
{
  return mPosition;
}

void nuiSampleReader::SetPosition(uint32 position)
{
  NGL_ASSERT(mInitialized);
  mPosition = position;
}

bool nuiSampleReader::GetInfo(nuiSampleInfo& rInfo) const
{
  if (!mInitialized)
  {
    return false;
  }

  rInfo = mInfo;
  return true;
}

bool nuiSampleReader::BytesToSampleFrames(uint64 inBytes, uint64& outSampleFrames) const
{
  NGL_ASSERT(mInitialized);
  if (!mInitialized)
    return false;

  outSampleFrames = inBytes * 8 / (mInfo.GetChannels() * mInfo.GetBitsPerSample());
  return true;
}

bool nuiSampleReader::SampleFramesToBytes(uint64 inSampleFrames, uint64& outBytes) const
{
  NGL_ASSERT(mInitialized);
  if (!mInitialized)
    return false;

  outBytes = inSampleFrames * mInfo.GetChannels() * mInfo.GetBitsPerSample() / 8;
  return true;
}
<commit_msg>fixed init<commit_after>/*
 NUI3 - C++ cross-platform GUI framework for OpenGL based applications
 Copyright (C) 2002-2003 Sebastien Metrot

 licence: see nui3/LICENCE.TXT
 */

#include "nui.h"
#include "nuiSampleReader.h"
#include "nuiChunksDefinitions.h"

nuiSampleReader::nuiSampleReader(nglIStream& rStream):
mrStream(rStream),
mInitialized(false),
mPosition(0)
{
}

nuiSampleReader::nuiSampleReader(const nuiSampleReader& rReader, nglIStream& rStream):
mrStream(rStream),
mInitialized(rReader.mInitialized),
mPosition(rReader.mPosition),
mInfo(rReader.mInfo)
{
}

nuiSampleReader::~nuiSampleReader()
{
}

bool nuiSampleReader::Init()
{
  mInitialized = ReadInfo();
  if (mInitialized)
    SetPosition(0);

  return mInitialized;
}

uint32 nuiSampleReader::GetPosition() const
{
  return mPosition;
}

void nuiSampleReader::SetPosition(uint32 position)
{
  NGL_ASSERT(mInitialized);
  mPosition = position;
}

bool nuiSampleReader::GetInfo(nuiSampleInfo& rInfo) const
{
  if (!mInitialized)
  {
    if (!const_cast<nuiSampleReader*>(this)->Init()) // This is a hack but we have to do it if we want to keep on doing lazy inits
      return false;
  }

  rInfo = mInfo;
  return true;
}

bool nuiSampleReader::BytesToSampleFrames(uint64 inBytes, uint64& outSampleFrames) const
{
  NGL_ASSERT(mInitialized);
  outSampleFrames = inBytes * 8 / (mInfo.GetChannels() * mInfo.GetBitsPerSample());
  return true;
}

bool nuiSampleReader::SampleFramesToBytes(uint64 inSampleFrames, uint64& outBytes) const
{
  NGL_ASSERT(mInitialized);
  outBytes = inSampleFrames * mInfo.GetChannels() * mInfo.GetBitsPerSample() / 8;
  return true;
}
<|endoftext|>


<commit_before>/***********************************************************************
    filename:   CEGUIScrolledContainer.cpp
    created:    1/3/2005
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/widgets/ScrolledContainer.h"
#include "CEGUI/CoordConverter.h"
#include "CEGUI/RenderingSurface.h"

#if defined(_MSC_VER)
#   pragma warning(push)
#   pragma warning(disable : 4355)
#endif

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
const String ScrolledContainer::WidgetTypeName("ScrolledContainer");
const String ScrolledContainer::EventNamespace("ScrolledContainer");
const String ScrolledContainer::EventContentChanged("ContentChanged");
const String ScrolledContainer::EventAutoSizeSettingChanged("AutoSizeSettingChanged");

//----------------------------------------------------------------------------//
ScrolledContainer::ScrolledContainer(const String& type, const String& name) :
    Window(type, name),
    d_contentArea(0, 0, 0, 0),
    d_autosizePane(true),

    d_clientChildContentArea(this, static_cast<Element::CachedRectf::DataGenerator>(&ScrolledContainer::getClientChildContentArea_impl))
{
    addScrolledContainerProperties();
    setMouseInputPropagationEnabled(true);
}

//----------------------------------------------------------------------------//
ScrolledContainer::~ScrolledContainer(void)
{
}

//----------------------------------------------------------------------------//
bool ScrolledContainer::isContentPaneAutoSized(void) const
{
    return d_autosizePane;
}

//----------------------------------------------------------------------------//
void ScrolledContainer::setContentPaneAutoSized(bool setting)
{
    if (d_autosizePane != setting)
    {
        d_autosizePane = setting;

        // Fire events
        WindowEventArgs args1(this);
        onAutoSizeSettingChanged(args1);
    }
}

//----------------------------------------------------------------------------//
const Rectf& ScrolledContainer::getContentArea(void) const
{
    return d_contentArea;
}

//----------------------------------------------------------------------------//
void ScrolledContainer::setContentArea(const Rectf& area)
{
    if (!d_autosizePane)
    {
        d_contentArea = area;

        // Fire event
        WindowEventArgs args(this);
        onContentChanged(args);
   }

}

//----------------------------------------------------------------------------//
const Element::CachedRectf& ScrolledContainer::getClientChildContentArea() const
{
    return d_clientChildContentArea;
}

//----------------------------------------------------------------------------//
const Element::CachedRectf& ScrolledContainer::getNonClientChildContentArea() const
{
    return d_clientChildContentArea;
}

//----------------------------------------------------------------------------//
void ScrolledContainer::notifyScreenAreaChanged(bool recursive)
{
    d_clientChildContentArea.invalidateCache();

    Window::notifyScreenAreaChanged(recursive);
}

//----------------------------------------------------------------------------//
Rectf ScrolledContainer::getChildExtentsArea(void) const
{
    Rectf extents(0, 0, 0, 0);

    const size_t childCount = getChildCount();
    if (childCount == 0)
        return extents;

    for (size_t i = 0; i < childCount; ++i)
    {
        const Window* const wnd = getChildAtIdx(i);
        Rectf area(
            CoordConverter::asAbsolute(wnd->getPosition(), d_pixelSize),
            wnd->getPixelSize());

        if(wnd->getHorizontalAlignment() == HA_CENTRE)
            area.setPosition( area.getPosition() - CEGUI::Vector2f( area.getWidth() * 0.5f - d_pixelSize.d_width * 0.5f, 0.0f ) );
        if(wnd->getHorizontalAlignment() == VA_CENTRE)
            area.setPosition( area.getPosition() - CEGUI::Vector2f( 0.0f, area.getHeight() * 0.5f - d_pixelSize.d_height * 0.5f ) );

        if (area.d_min.d_x < extents.d_min.d_x)
            extents.d_min.d_x = area.d_min.d_x;

        if (area.d_min.d_y < extents.d_min.d_y)
            extents.d_min.d_y = area.d_min.d_y;

        if (area.d_max.d_x > extents.d_max.d_x)
            extents.d_max.d_x = area.d_max.d_x;

        if (area.d_max.d_y > extents.d_max.d_y)
            extents.d_max.d_y = area.d_max.d_y;
    }

    return extents;
}

//----------------------------------------------------------------------------//
void ScrolledContainer::onContentChanged(WindowEventArgs& e)
{
    if (d_autosizePane)
    {
        d_contentArea = getChildExtentsArea();
    }

    fireEvent(EventContentChanged, e, EventNamespace);
}

//----------------------------------------------------------------------------//
void ScrolledContainer::onAutoSizeSettingChanged(WindowEventArgs& e)
{
    fireEvent(EventAutoSizeSettingChanged, e, EventNamespace);

    if (d_autosizePane)
    {
        WindowEventArgs args(this);
        onContentChanged(args);
    }
}

//----------------------------------------------------------------------------//
bool ScrolledContainer::handleChildSized(const EventArgs&)
{
    // Fire event that notifies that a child's area has changed.
    WindowEventArgs args(this);
    onContentChanged(args);
    return true;
}

//----------------------------------------------------------------------------//
bool ScrolledContainer::handleChildMoved(const EventArgs&)
{
    // Fire event that notifies that a child's area has changed.
    WindowEventArgs args(this);
    onContentChanged(args);
    return true;
}

//----------------------------------------------------------------------------//
Rectf ScrolledContainer::getUnclippedInnerRect_impl(bool skipAllPixelAlignment) const
{
    return d_parent ?
        (skipAllPixelAlignment ? d_parent->getUnclippedInnerRect().getFresh(true) : d_parent->getUnclippedInnerRect().get()) :
        Window::getUnclippedInnerRect_impl(skipAllPixelAlignment);
}

//----------------------------------------------------------------------------//
Rectf ScrolledContainer::getInnerRectClipper_impl() const
{
    return d_parent ?
        getParent()->getInnerRectClipper() :
        Window::getInnerRectClipper_impl();
}

//----------------------------------------------------------------------------//
Rectf ScrolledContainer::getHitTestRect_impl() const
{
    return d_parent ? getParent()->getHitTestRect() :
                      Window::getHitTestRect_impl();
}

//----------------------------------------------------------------------------//
Rectf ScrolledContainer::getClientChildContentArea_impl(bool skipAllPixelAlignment) const
{
    if (!d_parent)
    {
        return skipAllPixelAlignment ? Window::getUnclippedInnerRect().getFresh(true) : Window::getUnclippedInnerRect().get();
    }
    else
    {
        if (skipAllPixelAlignment)
        {
            return Rectf(getUnclippedOuterRect().getFresh(true).getPosition(),
                         getParent()->getUnclippedInnerRect().getFresh(true).getSize());
        }
        else
        {
            return Rectf(getUnclippedOuterRect().get().getPosition(),
                         getParent()->getUnclippedInnerRect().get().getSize());
        }
    }
}

//----------------------------------------------------------------------------//
void ScrolledContainer::onChildAdded(ElementEventArgs& e)
{
    Window::onChildAdded(e);

    // subscribe to some events on this child
    d_eventConnections.insert(std::make_pair(static_cast<Window*>(e.element),
        static_cast<Window*>(e.element)->subscribeEvent(Window::EventSized,
            Event::Subscriber(&ScrolledContainer::handleChildSized, this))));
    d_eventConnections.insert(std::make_pair(static_cast<Window*>(e.element),
        static_cast<Window*>(e.element)->subscribeEvent(Window::EventMoved,
            Event::Subscriber(&ScrolledContainer::handleChildMoved, this))));

    // force window to update what it thinks it's screen / pixel areas are.
    static_cast<Window*>(e.element)->notifyScreenAreaChanged(false);

    // perform notification.
    WindowEventArgs args(this);
    onContentChanged(args);
}

//----------------------------------------------------------------------------//
void ScrolledContainer::onChildRemoved(ElementEventArgs& e)
{
    Window::onChildRemoved(e);

    // disconnect from events for this window.
    ConnectionTracker::iterator conn;
    while ((conn = d_eventConnections.find(static_cast<Window*>(e.element))) != d_eventConnections.end())
    {
        conn->second->disconnect();
        d_eventConnections.erase(conn);
    }

    // perform notification only if we're not currently being destroyed
    if (!d_destructionStarted)
    {
        WindowEventArgs args(this);
        onContentChanged(args);
    }
}

//----------------------------------------------------------------------------//
void ScrolledContainer::onParentSized(ElementEventArgs& e)
{
    Window::onParentSized(e);

    // perform notification.
    WindowEventArgs args(this);
    onContentChanged(args);
}

//----------------------------------------------------------------------------//
void ScrolledContainer::addScrolledContainerProperties(void)
{
    const String& propertyOrigin = WidgetTypeName;

    CEGUI_DEFINE_PROPERTY(ScrolledContainer, bool,
        "ContentPaneAutoSized", "Property to get/set the setting which controls whether the content pane will auto-size itself."
        "  Value is either \"True\" or \"False\".",
        &ScrolledContainer::setContentPaneAutoSized, &ScrolledContainer::isContentPaneAutoSized, true
    );

    CEGUI_DEFINE_PROPERTY(ScrolledContainer, Rectf,
        "ContentArea", "Property to get/set the current content area rectangle of the content pane."
        "  Value is \"l:[float] t:[float] r:[float] b:[float]\" (where l is left, t is top, r is right, and b is bottom).",
        &ScrolledContainer::setContentArea, &ScrolledContainer::getContentArea, Rectf::zero()
    );

    CEGUI_DEFINE_PROPERTY(ScrolledContainer, Rectf,
        "ChildExtentsArea", "Property to get the current content extents rectangle."
        "  Value is \"l:[float] t:[float] r:[float] b:[float]\" (where l is left, t is top, r is right, and b is bottom).",
        0, &ScrolledContainer::getChildExtentsArea, Rectf::zero()
    );
}

//----------------------------------------------------------------------------//
void ScrolledContainer::setArea_impl(const UVector2& pos, const USize& size,
                                     bool topLeftSizing, bool fireEvents)
{
    d_clientChildContentArea.invalidateCache();
    Window::setArea_impl(pos, size, topLeftSizing, fireEvents);
}

//----------------------------------------------------------------------------//

#if defined(_MSC_VER)
#   pragma warning(pop)
#endif

} // End of  CEGUI namespace section
<commit_msg>Fixed a copy-paste error in ScrolledContainer<commit_after>/***********************************************************************
    filename:   CEGUIScrolledContainer.cpp
    created:    1/3/2005
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#include "CEGUI/widgets/ScrolledContainer.h"
#include "CEGUI/CoordConverter.h"
#include "CEGUI/RenderingSurface.h"

#if defined(_MSC_VER)
#   pragma warning(push)
#   pragma warning(disable : 4355)
#endif

// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
const String ScrolledContainer::WidgetTypeName("ScrolledContainer");
const String ScrolledContainer::EventNamespace("ScrolledContainer");
const String ScrolledContainer::EventContentChanged("ContentChanged");
const String ScrolledContainer::EventAutoSizeSettingChanged("AutoSizeSettingChanged");

//----------------------------------------------------------------------------//
ScrolledContainer::ScrolledContainer(const String& type, const String& name) :
    Window(type, name),
    d_contentArea(0, 0, 0, 0),
    d_autosizePane(true),

    d_clientChildContentArea(this, static_cast<Element::CachedRectf::DataGenerator>(&ScrolledContainer::getClientChildContentArea_impl))
{
    addScrolledContainerProperties();
    setMouseInputPropagationEnabled(true);
}

//----------------------------------------------------------------------------//
ScrolledContainer::~ScrolledContainer(void)
{
}

//----------------------------------------------------------------------------//
bool ScrolledContainer::isContentPaneAutoSized(void) const
{
    return d_autosizePane;
}

//----------------------------------------------------------------------------//
void ScrolledContainer::setContentPaneAutoSized(bool setting)
{
    if (d_autosizePane != setting)
    {
        d_autosizePane = setting;

        // Fire events
        WindowEventArgs args1(this);
        onAutoSizeSettingChanged(args1);
    }
}

//----------------------------------------------------------------------------//
const Rectf& ScrolledContainer::getContentArea(void) const
{
    return d_contentArea;
}

//----------------------------------------------------------------------------//
void ScrolledContainer::setContentArea(const Rectf& area)
{
    if (!d_autosizePane)
    {
        d_contentArea = area;

        // Fire event
        WindowEventArgs args(this);
        onContentChanged(args);
   }

}

//----------------------------------------------------------------------------//
const Element::CachedRectf& ScrolledContainer::getClientChildContentArea() const
{
    return d_clientChildContentArea;
}

//----------------------------------------------------------------------------//
const Element::CachedRectf& ScrolledContainer::getNonClientChildContentArea() const
{
    return d_clientChildContentArea;
}

//----------------------------------------------------------------------------//
void ScrolledContainer::notifyScreenAreaChanged(bool recursive)
{
    d_clientChildContentArea.invalidateCache();

    Window::notifyScreenAreaChanged(recursive);
}

//----------------------------------------------------------------------------//
Rectf ScrolledContainer::getChildExtentsArea(void) const
{
    Rectf extents(0, 0, 0, 0);

    const size_t childCount = getChildCount();
    if (childCount == 0)
        return extents;

    for (size_t i = 0; i < childCount; ++i)
    {
        const Window* const wnd = getChildAtIdx(i);
        Rectf area(
            CoordConverter::asAbsolute(wnd->getPosition(), d_pixelSize),
            wnd->getPixelSize());

        if (wnd->getHorizontalAlignment() == HA_CENTRE)
            area.setPosition(area.getPosition() - CEGUI::Vector2f(area.getWidth() * 0.5f - d_pixelSize.d_width * 0.5f, 0.0f));
        if (wnd->getVerticalAlignment() == VA_CENTRE)
            area.setPosition(area.getPosition() - CEGUI::Vector2f(0.0f, area.getHeight() * 0.5f - d_pixelSize.d_height * 0.5f));

        if (area.d_min.d_x < extents.d_min.d_x)
            extents.d_min.d_x = area.d_min.d_x;

        if (area.d_min.d_y < extents.d_min.d_y)
            extents.d_min.d_y = area.d_min.d_y;

        if (area.d_max.d_x > extents.d_max.d_x)
            extents.d_max.d_x = area.d_max.d_x;

        if (area.d_max.d_y > extents.d_max.d_y)
            extents.d_max.d_y = area.d_max.d_y;
    }

    return extents;
}

//----------------------------------------------------------------------------//
void ScrolledContainer::onContentChanged(WindowEventArgs& e)
{
    if (d_autosizePane)
    {
        d_contentArea = getChildExtentsArea();
    }

    fireEvent(EventContentChanged, e, EventNamespace);
}

//----------------------------------------------------------------------------//
void ScrolledContainer::onAutoSizeSettingChanged(WindowEventArgs& e)
{
    fireEvent(EventAutoSizeSettingChanged, e, EventNamespace);

    if (d_autosizePane)
    {
        WindowEventArgs args(this);
        onContentChanged(args);
    }
}

//----------------------------------------------------------------------------//
bool ScrolledContainer::handleChildSized(const EventArgs&)
{
    // Fire event that notifies that a child's area has changed.
    WindowEventArgs args(this);
    onContentChanged(args);
    return true;
}

//----------------------------------------------------------------------------//
bool ScrolledContainer::handleChildMoved(const EventArgs&)
{
    // Fire event that notifies that a child's area has changed.
    WindowEventArgs args(this);
    onContentChanged(args);
    return true;
}

//----------------------------------------------------------------------------//
Rectf ScrolledContainer::getUnclippedInnerRect_impl(bool skipAllPixelAlignment) const
{
    return d_parent ?
        (skipAllPixelAlignment ? d_parent->getUnclippedInnerRect().getFresh(true) : d_parent->getUnclippedInnerRect().get()) :
        Window::getUnclippedInnerRect_impl(skipAllPixelAlignment);
}

//----------------------------------------------------------------------------//
Rectf ScrolledContainer::getInnerRectClipper_impl() const
{
    return d_parent ?
        getParent()->getInnerRectClipper() :
        Window::getInnerRectClipper_impl();
}

//----------------------------------------------------------------------------//
Rectf ScrolledContainer::getHitTestRect_impl() const
{
    return d_parent ? getParent()->getHitTestRect() :
                      Window::getHitTestRect_impl();
}

//----------------------------------------------------------------------------//
Rectf ScrolledContainer::getClientChildContentArea_impl(bool skipAllPixelAlignment) const
{
    if (!d_parent)
    {
        return skipAllPixelAlignment ? Window::getUnclippedInnerRect().getFresh(true) : Window::getUnclippedInnerRect().get();
    }
    else
    {
        if (skipAllPixelAlignment)
        {
            return Rectf(getUnclippedOuterRect().getFresh(true).getPosition(),
                         getParent()->getUnclippedInnerRect().getFresh(true).getSize());
        }
        else
        {
            return Rectf(getUnclippedOuterRect().get().getPosition(),
                         getParent()->getUnclippedInnerRect().get().getSize());
        }
    }
}

//----------------------------------------------------------------------------//
void ScrolledContainer::onChildAdded(ElementEventArgs& e)
{
    Window::onChildAdded(e);

    // subscribe to some events on this child
    d_eventConnections.insert(std::make_pair(static_cast<Window*>(e.element),
        static_cast<Window*>(e.element)->subscribeEvent(Window::EventSized,
            Event::Subscriber(&ScrolledContainer::handleChildSized, this))));
    d_eventConnections.insert(std::make_pair(static_cast<Window*>(e.element),
        static_cast<Window*>(e.element)->subscribeEvent(Window::EventMoved,
            Event::Subscriber(&ScrolledContainer::handleChildMoved, this))));

    // force window to update what it thinks it's screen / pixel areas are.
    static_cast<Window*>(e.element)->notifyScreenAreaChanged(false);

    // perform notification.
    WindowEventArgs args(this);
    onContentChanged(args);
}

//----------------------------------------------------------------------------//
void ScrolledContainer::onChildRemoved(ElementEventArgs& e)
{
    Window::onChildRemoved(e);

    // disconnect from events for this window.
    ConnectionTracker::iterator conn;
    while ((conn = d_eventConnections.find(static_cast<Window*>(e.element))) != d_eventConnections.end())
    {
        conn->second->disconnect();
        d_eventConnections.erase(conn);
    }

    // perform notification only if we're not currently being destroyed
    if (!d_destructionStarted)
    {
        WindowEventArgs args(this);
        onContentChanged(args);
    }
}

//----------------------------------------------------------------------------//
void ScrolledContainer::onParentSized(ElementEventArgs& e)
{
    Window::onParentSized(e);

    // perform notification.
    WindowEventArgs args(this);
    onContentChanged(args);
}

//----------------------------------------------------------------------------//
void ScrolledContainer::addScrolledContainerProperties(void)
{
    const String& propertyOrigin = WidgetTypeName;

    CEGUI_DEFINE_PROPERTY(ScrolledContainer, bool,
        "ContentPaneAutoSized", "Property to get/set the setting which controls whether the content pane will auto-size itself."
        "  Value is either \"True\" or \"False\".",
        &ScrolledContainer::setContentPaneAutoSized, &ScrolledContainer::isContentPaneAutoSized, true
    );

    CEGUI_DEFINE_PROPERTY(ScrolledContainer, Rectf,
        "ContentArea", "Property to get/set the current content area rectangle of the content pane."
        "  Value is \"l:[float] t:[float] r:[float] b:[float]\" (where l is left, t is top, r is right, and b is bottom).",
        &ScrolledContainer::setContentArea, &ScrolledContainer::getContentArea, Rectf::zero()
    );

    CEGUI_DEFINE_PROPERTY(ScrolledContainer, Rectf,
        "ChildExtentsArea", "Property to get the current content extents rectangle."
        "  Value is \"l:[float] t:[float] r:[float] b:[float]\" (where l is left, t is top, r is right, and b is bottom).",
        0, &ScrolledContainer::getChildExtentsArea, Rectf::zero()
    );
}

//----------------------------------------------------------------------------//
void ScrolledContainer::setArea_impl(const UVector2& pos, const USize& size,
                                     bool topLeftSizing, bool fireEvents)
{
    d_clientChildContentArea.invalidateCache();
    Window::setArea_impl(pos, size, topLeftSizing, fireEvents);
}

//----------------------------------------------------------------------------//

#if defined(_MSC_VER)
#   pragma warning(pop)
#endif

} // End of  CEGUI namespace section
<|endoftext|>


<commit_before><commit_msg>Use bitasset_data.current_feed.settlement_price<commit_after><|endoftext|>


<commit_before>#include <stdio.h>
#include <string>

#include <Poco/Net/HTTPClientSession.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/StreamCopier.h>
#include <Poco/Path.h>
#include <Poco/URI.h>
#include <Poco/Exception.h>
#include <iostream>

using namespace Poco::Net;
using namespace Poco;
using namespace std;

namespace Model
{
    class Menus {

    HTTPClientSession session;
    string path;

    public:
        string id;
        string name;
        string main_id;

    public:
        Menus(){
            URI uri("http://192.168.3.6:3000");
            session.setHost(uri.getHost());
            session.setPort(uri.getPort());

            // prepare path
            path = uri.getPathAndQuery();
            if (path.empty()) path = "/";
        }

        long get(string& ans){
            try
            {
                // send request
                HTTPRequest req(HTTPRequest::HTTP_GET, path + "menus.text", HTTPMessage::HTTP_1_1);
                session.sendRequest(req);

                // get response
                HTTPResponse res;

                // print response
                istream &is = session.receiveResponse(res);
                StreamCopier::copyToString(is, ans, 8192);
            }

            catch (Exception &ex)
            {
                cerr << ex.displayText() << endl;
                return -1;
            }
            return 0;
        }

        long create(){
            try
            {
                // send request
                HTTPRequest req(HTTPRequest::HTTP_POST, path + "menus.text", HTTPMessage::HTTP_1_1);
                session.sendRequest(req);
                req.setKeepAlive(true);

                string key_name("menu[name]=");
                string delimiter("&");
                string key_main_id("menu[main_id]=");

                string reqBody(key_name + name + delimiter + key_main_id + main_id);

                req.setContentLength( reqBody.length() );
                session.sendRequest(req) << reqBody;

                // get response
                HTTPResponse res;
                cout << res.getStatus() << " " << res.getReason() << endl;

                // print response
                istream &is = session.receiveResponse(res);
                StreamCopier::copyToString(is, id, 8192);
            }

            catch (Exception &ex)
            {
                cerr << ex.displayText() << endl;
                return -1;
            }
            return 0;
        }

        string select_main_menu(){
            try
            {
                // send request
                HTTPRequest req(HTTPRequest::HTTP_GET, path + "menus/select_main_menu.text", HTTPMessage::HTTP_1_1);
                session.sendRequest(req);

                // get response
                HTTPResponse res;

                // print response
                string ans;
                istream &is = session.receiveResponse(res);
                StreamCopier::copyToString(is, ans, 8192);

                unsigned int pos = ans.find_first_of(":");
                id = ans.substr(0, pos);

                string msg;
                msg = ans.substr(pos + 1, ans.size());
                return msg;
            }

            catch (Exception &ex)
            {
                cerr << ex.displayText() << endl;
                return "";
            }
            return "";
        }

        string select_sub_menu(string main_id){
            try
            {
                // send request
                string key_main_id("menu[main_id]");

                HTTPRequest req(HTTPRequest::HTTP_GET, path + "menus/select_sub_menu.text?" + key_main_id + "=" + main_id, HTTPMessage::HTTP_1_1);
                session.sendRequest(req);

                // get response
                HTTPResponse res;

                // print response
                string ans;
                istream &is = session.receiveResponse(res);
                StreamCopier::copyToString(is, ans, 8192);

                return ans;
            }

            catch (Exception &ex)
            {
                cerr << ex.displayText() << endl;
                return "";
            }
            return "";
        }

    };
}<commit_msg>count_main_menuを追加<commit_after>#include <stdio.h>
#include <string>
#include <typeinfo>

#include <Poco/Net/HTTPClientSession.h>
#include <Poco/Net/HTTPRequest.h>
#include <Poco/Net/HTTPResponse.h>
#include <Poco/StreamCopier.h>
#include <Poco/Path.h>
#include <Poco/URI.h>
#include <Poco/Exception.h>
#include <iostream>

using namespace Poco::Net;
using namespace Poco;
using namespace std;

namespace Model
{
    class Menus {

    HTTPClientSession session;
    string path;

    public:
        string id;
        string name;
        string main_id;

    public:
        Menus(){
            URI uri("http://localhost:3000");
            session.setHost(uri.getHost());
            session.setPort(uri.getPort());

            // prepare path
            path = uri.getPathAndQuery();
            if (path.empty()) path = "/";
        }

        long get(string& ans){
            try
            {
                // send request
                HTTPRequest req(HTTPRequest::HTTP_GET, path + "menus.text", HTTPMessage::HTTP_1_1);
                session.sendRequest(req);

                // get response
                HTTPResponse res;

                // print response
                istream &is = session.receiveResponse(res);
                StreamCopier::copyToString(is, ans, 8192);
            }

            catch (Exception &ex)
            {
                cerr << ex.displayText() << endl;
                return -1;
            }
            return 0;
        }

        long create(){
            try
            {
                // send request
                HTTPRequest req(HTTPRequest::HTTP_POST, path + "menus.text", HTTPMessage::HTTP_1_1);
                session.sendRequest(req);
                req.setKeepAlive(true);

                string key_name("menu[name]=");
                string delimiter("&");
                string key_main_id("menu[main_id]=");

                string reqBody(key_name + name + delimiter + key_main_id + main_id);

                req.setContentLength( reqBody.length() );
                session.sendRequest(req) << reqBody;

                // get response
                HTTPResponse res;
                cout << res.getStatus() << " " << res.getReason() << endl;

                // print response
                istream &is = session.receiveResponse(res);
                StreamCopier::copyToString(is, id, 8192);
            }

            catch (Exception &ex)
            {
                cerr << ex.displayText() << endl;
                return -1;
            }
            return 0;
        }

        string select_main_menu(){
            try
            {
                // send request
                HTTPRequest req(HTTPRequest::HTTP_GET, path + "menus/select_main_menu.text", HTTPMessage::HTTP_1_1);
                session.sendRequest(req);

                // get response
                HTTPResponse res;

                // print response
                string ans;
                istream &is = session.receiveResponse(res);
                StreamCopier::copyToString(is, ans, 8192);

                unsigned int pos = ans.find_first_of(":");
                id = ans.substr(0, pos);

                string msg;
                msg = ans.substr(pos + 1, ans.size());
                return msg;
            }

            catch (Exception &ex)
            {
                cerr << ex.displayText() << endl;
                return "";
            }
            return "";
        }

       int count_main_menu(){
            try
            {
                // send request
                HTTPRequest req(HTTPRequest::HTTP_GET, path + "menus/count_main_menu.text", HTTPMessage::HTTP_1_1);
                session.sendRequest(req);

                // get response
                HTTPResponse res;

                // print response
                string ans;
                istream &is = session.receiveResponse(res);
                StreamCopier::copyToString(is, ans, 8192);

                int i;
                sscanf(ans.c_str(), "%d", &i);
                return i;
            }
            catch (Exception &ex)
            {
                cerr << ex.displayText() << endl;
                return 0;
            }
            return 0;
        }

        string select_sub_menu(string main_id){
            try
            {
                // send request
                string key_main_id("menu[main_id]");

                HTTPRequest req(HTTPRequest::HTTP_GET, path + "menus/select_sub_menu.text?" + key_main_id + "=" + main_id, HTTPMessage::HTTP_1_1);
                session.sendRequest(req);

                // get response
                HTTPResponse res;

                // print response
                string ans;
                istream &is = session.receiveResponse(res);
                StreamCopier::copyToString(is, ans, 8192);

                return ans;
            }

            catch (Exception &ex)
            {
                cerr << ex.displayText() << endl;
                return "";
            }
            return "";
        }

    };
}
<|endoftext|>


<commit_before>#include "rapid_pr2/pr2.h"

#include "agile_grasp/FindGrasps.h"
#include "blinky/FaceAction.h"
#include "pr2_controllers_msgs/PointHeadAction.h"
#include "pr2_controllers_msgs/Pr2GripperCommandAction.h"
#include "ros/node_handle.h"
#include "visualization_msgs/Marker.h"

#include "rapid_display/display.h"
#include "rapid_manipulation/arm.h"
#include "rapid_manipulation/gripper.h"
#include "rapid_manipulation/head.h"
#include "rapid_manipulation/tuck_arms.h"
#include "rapid_ros/action_client.h"
#include "rapid_ros/publisher.h"
#include "rapid_ros/tf_listener.h"
#include "rapid_sound/sound.h"
#include "rapid_viz/markers.h"

using blinky::FaceAction;
using pr2_controllers_msgs::PointHeadAction;
using pr2_controllers_msgs::Pr2GripperCommandAction;
using rapid::display::Blinky;
using rapid::display::DisplayInterface;
using rapid::display::MockDisplay;
using rapid::manipulation::ArmInterface;
using rapid::manipulation::Gripper;
using rapid::manipulation::GripperInterface;
using rapid::manipulation::Head;
using rapid::manipulation::HeadInterface;
using rapid::manipulation::MockArm;
using rapid::manipulation::MockGripper;
using rapid::manipulation::MockHead;
using rapid::manipulation::MockTuckArms;
using rapid::manipulation::MoveItArm;
using rapid::manipulation::Picker;
using rapid::manipulation::Placer;
using rapid::manipulation::Pr2TuckArms;
using rapid::manipulation::TuckArmsInterface;
using rapid::sound::MockSound;
using rapid::sound::SoundInterface;
using rapid::sound::SoundPlay;
using rapid::viz::MarkerPub;
using rapid_ros::ActionClient;
using rapid_ros::ServiceClient;
using rapid_ros::ServiceClientInterface;
using rapid_ros::TfListener;

namespace rapid {
namespace pr2 {
Pr2::Pr2(ArmInterface* left_arm, ArmInterface* right_arm,
         DisplayInterface* display, GripperInterface* left_gripper,
         GripperInterface* right_gripper, HeadInterface* head,
         SoundInterface* sound, TuckArmsInterface* tuck_arms,
         Picker* left_picker, Picker* right_picker, Placer* left_placer,
         Placer* right_placer)
    : left_arm_(left_arm),
      right_arm_(right_arm),
      display_(display),
      left_gripper_(left_gripper),
      right_gripper_(right_gripper),
      head_(head),
      sound_(sound),
      tuck_arms_(tuck_arms),
      left_picker_(left_picker),
      right_picker_(right_picker),
      left_placer_(left_placer),
      right_placer_(right_placer) {}

Pr2::~Pr2() {
  if (left_arm_) {
    delete left_arm_;
  }
  if (right_arm_) {
    delete right_arm_;
  }
  if (display_) {
    delete display_;
  }
  if (left_gripper_) {
    delete left_gripper_;
  }
  if (right_gripper_) {
    delete right_gripper_;
  }
  if (head_) {
    delete head_;
  }
  if (sound_) {
    delete sound_;
  }
  if (tuck_arms_) {
    delete tuck_arms_;
  }
  if (left_picker_) {
    delete left_picker_;
  }
  if (right_picker_) {
    delete right_picker_;
  }
  if (left_placer_) {
    delete left_placer_;
  }
  if (right_placer_) {
    delete right_placer_;
  }
}

ArmInterface* Pr2::left_arm() { return left_arm_; }
ArmInterface* Pr2::right_arm() { return right_arm_; }
DisplayInterface* Pr2::display() { return display_; }
GripperInterface* Pr2::left_gripper() { return left_gripper_; }
GripperInterface* Pr2::right_gripper() { return right_gripper_; }
HeadInterface* Pr2::head() { return head_; }
SoundInterface* Pr2::sound() { return sound_; }
TuckArmsInterface* Pr2::tuck_arms() { return tuck_arms_; }
Picker* Pr2::left_picker() { return left_picker_; }
Picker* Pr2::right_picker() { return right_picker_; }
Placer* Pr2::left_placer() { return left_placer_; }
Placer* Pr2::right_placer() { return right_placer_; }

Pr2* BuildReal(ros::NodeHandle& nh) {
  ArmInterface* left_arm = new MoveItArm(rapid::manipulation::LEFT);
  ArmInterface* right_arm = new MoveItArm(rapid::manipulation::RIGHT);
  DisplayInterface* display =
      new Blinky(new ActionClient<FaceAction>("blinky"));
  GripperInterface* left_gripper = new Gripper(
      Gripper::LEFT_GRIPPER,
      new ActionClient<Pr2GripperCommandAction>(Gripper::LEFT_GRIPPER_ACTION),
      new TfListener());
  GripperInterface* right_gripper = new Gripper(
      Gripper::RIGHT_GRIPPER,
      new ActionClient<Pr2GripperCommandAction>(Gripper::RIGHT_GRIPPER_ACTION),
      new TfListener());
  HeadInterface* head = new Head(new ActionClient<PointHeadAction>(
      "/head_traj_controller/point_head_action"));
  SoundInterface* sound = new SoundPlay("us1_mbrola");
  TuckArmsInterface* tuck_arms = new Pr2TuckArms();

  MarkerPub* marker_pub = new rapid_ros::Publisher<visualization_msgs::Marker>(
      nh.advertise<visualization_msgs::Marker>("visualization_marker", 10));
  ServiceClientInterface<agile_grasp::FindGrasps>* grasp_gen_client =
      new ServiceClient<agile_grasp::FindGrasps>(
          nh.serviceClient<agile_grasp::FindGrasps>("find_grasps/find_grasps"));
  Picker* left_picker =
      new Picker(left_arm, left_gripper, grasp_gen_client, marker_pub);
  Picker* right_picker =
      new Picker(right_arm, right_gripper, grasp_gen_client, marker_pub);
  Placer* left_placer = new Placer(left_arm, left_gripper);
  Placer* right_placer = new Placer(right_arm, right_gripper);
  return new Pr2(left_arm, right_arm, display, left_gripper, right_gripper,
                 head, sound, tuck_arms, left_picker, right_picker, left_placer,
                 right_placer);
}
}  // namespace pr2
}  // namespace rapid
<commit_msg>Fixed voice name. (#54)<commit_after>#include "rapid_pr2/pr2.h"

#include "agile_grasp/FindGrasps.h"
#include "blinky/FaceAction.h"
#include "pr2_controllers_msgs/PointHeadAction.h"
#include "pr2_controllers_msgs/Pr2GripperCommandAction.h"
#include "ros/node_handle.h"
#include "visualization_msgs/Marker.h"

#include "rapid_display/display.h"
#include "rapid_manipulation/arm.h"
#include "rapid_manipulation/gripper.h"
#include "rapid_manipulation/head.h"
#include "rapid_manipulation/tuck_arms.h"
#include "rapid_ros/action_client.h"
#include "rapid_ros/publisher.h"
#include "rapid_ros/tf_listener.h"
#include "rapid_sound/sound.h"
#include "rapid_viz/markers.h"

using blinky::FaceAction;
using pr2_controllers_msgs::PointHeadAction;
using pr2_controllers_msgs::Pr2GripperCommandAction;
using rapid::display::Blinky;
using rapid::display::DisplayInterface;
using rapid::display::MockDisplay;
using rapid::manipulation::ArmInterface;
using rapid::manipulation::Gripper;
using rapid::manipulation::GripperInterface;
using rapid::manipulation::Head;
using rapid::manipulation::HeadInterface;
using rapid::manipulation::MockArm;
using rapid::manipulation::MockGripper;
using rapid::manipulation::MockHead;
using rapid::manipulation::MockTuckArms;
using rapid::manipulation::MoveItArm;
using rapid::manipulation::Picker;
using rapid::manipulation::Placer;
using rapid::manipulation::Pr2TuckArms;
using rapid::manipulation::TuckArmsInterface;
using rapid::sound::MockSound;
using rapid::sound::SoundInterface;
using rapid::sound::SoundPlay;
using rapid::viz::MarkerPub;
using rapid_ros::ActionClient;
using rapid_ros::ServiceClient;
using rapid_ros::ServiceClientInterface;
using rapid_ros::TfListener;

namespace rapid {
namespace pr2 {
Pr2::Pr2(ArmInterface* left_arm, ArmInterface* right_arm,
         DisplayInterface* display, GripperInterface* left_gripper,
         GripperInterface* right_gripper, HeadInterface* head,
         SoundInterface* sound, TuckArmsInterface* tuck_arms,
         Picker* left_picker, Picker* right_picker, Placer* left_placer,
         Placer* right_placer)
    : left_arm_(left_arm),
      right_arm_(right_arm),
      display_(display),
      left_gripper_(left_gripper),
      right_gripper_(right_gripper),
      head_(head),
      sound_(sound),
      tuck_arms_(tuck_arms),
      left_picker_(left_picker),
      right_picker_(right_picker),
      left_placer_(left_placer),
      right_placer_(right_placer) {}

Pr2::~Pr2() {
  if (left_arm_) {
    delete left_arm_;
  }
  if (right_arm_) {
    delete right_arm_;
  }
  if (display_) {
    delete display_;
  }
  if (left_gripper_) {
    delete left_gripper_;
  }
  if (right_gripper_) {
    delete right_gripper_;
  }
  if (head_) {
    delete head_;
  }
  if (sound_) {
    delete sound_;
  }
  if (tuck_arms_) {
    delete tuck_arms_;
  }
  if (left_picker_) {
    delete left_picker_;
  }
  if (right_picker_) {
    delete right_picker_;
  }
  if (left_placer_) {
    delete left_placer_;
  }
  if (right_placer_) {
    delete right_placer_;
  }
}

ArmInterface* Pr2::left_arm() { return left_arm_; }
ArmInterface* Pr2::right_arm() { return right_arm_; }
DisplayInterface* Pr2::display() { return display_; }
GripperInterface* Pr2::left_gripper() { return left_gripper_; }
GripperInterface* Pr2::right_gripper() { return right_gripper_; }
HeadInterface* Pr2::head() { return head_; }
SoundInterface* Pr2::sound() { return sound_; }
TuckArmsInterface* Pr2::tuck_arms() { return tuck_arms_; }
Picker* Pr2::left_picker() { return left_picker_; }
Picker* Pr2::right_picker() { return right_picker_; }
Placer* Pr2::left_placer() { return left_placer_; }
Placer* Pr2::right_placer() { return right_placer_; }

Pr2* BuildReal(ros::NodeHandle& nh) {
  ArmInterface* left_arm = new MoveItArm(rapid::manipulation::LEFT);
  ArmInterface* right_arm = new MoveItArm(rapid::manipulation::RIGHT);
  DisplayInterface* display =
      new Blinky(new ActionClient<FaceAction>("blinky"));
  GripperInterface* left_gripper = new Gripper(
      Gripper::LEFT_GRIPPER,
      new ActionClient<Pr2GripperCommandAction>(Gripper::LEFT_GRIPPER_ACTION),
      new TfListener());
  GripperInterface* right_gripper = new Gripper(
      Gripper::RIGHT_GRIPPER,
      new ActionClient<Pr2GripperCommandAction>(Gripper::RIGHT_GRIPPER_ACTION),
      new TfListener());
  HeadInterface* head = new Head(new ActionClient<PointHeadAction>(
      "/head_traj_controller/point_head_action"));
  SoundInterface* sound = new SoundPlay("voice_cmu_us_slt_arctic_hts");
  TuckArmsInterface* tuck_arms = new Pr2TuckArms();

  MarkerPub* marker_pub = new rapid_ros::Publisher<visualization_msgs::Marker>(
      nh.advertise<visualization_msgs::Marker>("visualization_marker", 10));
  ServiceClientInterface<agile_grasp::FindGrasps>* grasp_gen_client =
      new ServiceClient<agile_grasp::FindGrasps>(
          nh.serviceClient<agile_grasp::FindGrasps>("find_grasps/find_grasps"));
  Picker* left_picker =
      new Picker(left_arm, left_gripper, grasp_gen_client, marker_pub);
  Picker* right_picker =
      new Picker(right_arm, right_gripper, grasp_gen_client, marker_pub);
  Placer* left_placer = new Placer(left_arm, left_gripper);
  Placer* right_placer = new Placer(right_arm, right_gripper);
  return new Pr2(left_arm, right_arm, display, left_gripper, right_gripper,
                 head, sound, tuck_arms, left_picker, right_picker, left_placer,
                 right_placer);
}
}  // namespace pr2
}  // namespace rapid
<|endoftext|>