<commit_before>/***************************************************************************
**
** Copyright (C) 2013 Jolla Ltd.
** Contact: Aaron Kennedy <aaron.kennedy@jollamobile.com>
**
** This file is part of lipstick.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QWaylandInputDevice>
#include "homeapplication.h"
#include "windowmodel.h"
#include "lipstickcompositorprocwindow.h"
#include "lipstickcompositor.h"

LipstickCompositor *LipstickCompositor::m_instance = 0;

LipstickCompositor::LipstickCompositor()
: QWaylandCompositor(this), m_totalWindowCount(0), m_nextWindowId(1), m_homeActive(true), m_shaderEffect(0),
  m_fullscreenSurface(0), m_directRenderingActive(false), m_topmostWindowId(0)
{
    if (m_instance) qFatal("LipstickCompositor: Only one compositor instance per process is supported");
    m_instance = this;

    QObject::connect(this, SIGNAL(frameSwapped()), this, SLOT(windowSwapped()));

    emit HomeApplication::instance()->homeActiveChanged();
}

LipstickCompositor::~LipstickCompositor()
{
    delete m_shaderEffect;
}

LipstickCompositor *LipstickCompositor::instance()
{
    return m_instance;
}

void LipstickCompositor::classBegin()
{
}

void LipstickCompositor::componentComplete()
{
    QWaylandCompositor::setOutputGeometry(QRect(0, 0, width(), height()));
}

void LipstickCompositor::surfaceCreated(QWaylandSurface *surface)
{
    Q_UNUSED(surface)
    connect(surface, SIGNAL(mapped()), this, SLOT(surfaceMapped()));
    connect(surface, SIGNAL(unmapped()), this, SLOT(surfaceUnmapped()));
    connect(surface, SIGNAL(sizeChanged()), this, SLOT(surfaceSizeChanged()));
    connect(surface, SIGNAL(titleChanged()), this, SLOT(surfaceTitleChanged()));
    connect(surface, SIGNAL(windowPropertyChanged(QString,QVariant)), this, SLOT(windowPropertyChanged(QString)));
    connect(surface, SIGNAL(raiseRequested()), this, SLOT(surfaceRaised()));
    connect(surface, SIGNAL(lowerRequested()), this, SLOT(surfaceLowered()));
}

int LipstickCompositor::windowCount() const
{
    return m_mappedSurfaces.count();
}

int LipstickCompositor::ghostWindowCount() const
{
    return m_totalWindowCount - windowCount();
}

bool LipstickCompositor::homeActive() const
{
    return m_homeActive;
}

void LipstickCompositor::setHomeActive(bool a)
{
    if (a == m_homeActive)
        return;

    m_homeActive = a;

    emit homeActiveChanged();
    emit HomeApplication::instance()->homeActiveChanged();
}

bool LipstickCompositor::debug() const
{
    static enum { Yes, No, Unknown } status = Unknown;
    if (status == Unknown) {
        QByteArray v = qgetenv("LIPSTICK_COMPOSITOR_DEBUG");
        bool value = !v.isEmpty() && v != "0" && v != "false";
        if (value) status = Yes;
        else status = No;
    }
    return status == Yes;
}

QObject *LipstickCompositor::windowForId(int id) const
{
    LipstickCompositorWindow *window = m_mappedSurfaces.value(id, 0);
    return window;
}

void LipstickCompositor::closeClientForWindowId(int id)
{
    LipstickCompositorWindow *window = m_mappedSurfaces.value(id, 0);
    if (window && window->surface())
        destroyClientForSurface(window->surface());
}

QWaylandSurface *LipstickCompositor::surfaceForId(int id) const
{
    LipstickCompositorWindow *window = m_mappedSurfaces.value(id, 0);
    return window?window->surface():0;
}

int LipstickCompositor::windowIdForLink(QWaylandSurface *s, uint link) const
{
    for (QHash<int, LipstickCompositorWindow *>::ConstIterator iter = m_mappedSurfaces.begin();
         iter != m_mappedSurfaces.end(); ++iter) {

        QWaylandSurface *windowSurface = iter.value()->surface();

        if (windowSurface && windowSurface->processId() == s->processId() &&
            windowSurface->windowProperties().value("WINID", uint(0)).toUInt() == link)
            return iter.value()->windowId();
    }

    return 0;
}

void LipstickCompositor::clearKeyboardFocus()
{
    defaultInputDevice()->setKeyboardFocus(0);
}

void LipstickCompositor::setFullscreenSurface(QWaylandSurface *surface)
{
    if (surface == m_fullscreenSurface)
        return;
    m_fullscreenSurface = surface;

    const bool directRenderingSucceeded = setDirectRenderSurface(m_fullscreenSurface, openglContext());
    if (surface && !directRenderingSucceeded)
        qWarning() << Q_FUNC_INFO << "failed to set direct render surface";
    if ((surface && directRenderingSucceeded) != m_directRenderingActive) {
        m_directRenderingActive = surface && directRenderingSucceeded;
        emit directRenderingActiveChanged();
    }

    emit fullscreenSurfaceChanged();
}

void LipstickCompositor::setTopmostWindowId(int id)
{
    if (id != m_topmostWindowId) {
        m_topmostWindowId = id;
        emit topmostWindowIdChanged();
    }
}

void LipstickCompositor::surfaceAboutToBeDestroyed(QWaylandSurface *surface)
{
    Q_ASSERT(surface);
    surfaceUnmapped(static_cast<QWaylandSurface *>(surface));
}

void LipstickCompositor::surfaceMapped()
{
    QWaylandSurface *surface = qobject_cast<QWaylandSurface *>(sender());
    //Ignore surface if it's not a window surface
    if (!surface->hasShellSurface())
        return;

    QVariantMap properties = surface->windowProperties();
    QString category = properties.value("CATEGORY").toString();

    Q_ASSERT(surface->surfaceItem() == 0);

    int id = m_nextWindowId++;

    LipstickCompositorWindow *item = new LipstickCompositorWindow(id, category, surface, contentItem());
    item->setSize(surface->size());
    QObject::connect(item, SIGNAL(destroyed(QObject*)), this, SLOT(windowDestroyed()));
    m_totalWindowCount++;
    m_mappedSurfaces.insert(id, item);

    item->setTouchEventsEnabled(true);

    emit windowCountChanged();
    emit windowAdded(item);

    windowAdded(id);

    emit availableWinIdsChanged();
}

void LipstickCompositor::surfaceUnmapped()
{
    surfaceUnmapped(qobject_cast<QWaylandSurface *>(sender()));
}

void LipstickCompositor::surfaceSizeChanged()
{
    QWaylandSurface *surface = qobject_cast<QWaylandSurface *>(sender());

    LipstickCompositorWindow *window = static_cast<LipstickCompositorWindow *>(surface->surfaceItem());
    if (window)
        window->setSize(surface->size());
}

void LipstickCompositor::surfaceTitleChanged()
{
    QWaylandSurface *surface = qobject_cast<QWaylandSurface *>(sender());
    LipstickCompositorWindow *window = static_cast<LipstickCompositorWindow *>(surface->surfaceItem());

    if (window) {
        emit window->titleChanged();

        int windowId = window->windowId();

        for (int ii = 0; ii < m_windowModels.count(); ++ii)
            m_windowModels.at(ii)->titleChanged(windowId);
    }
}

void LipstickCompositor::surfaceRaised()
{
    QWaylandSurface *surface = qobject_cast<QWaylandSurface *>(sender());
    LipstickCompositorWindow *window = static_cast<LipstickCompositorWindow *>(surface->surfaceItem());

    if (window) {
        emit windowRaised(window);
    }
}

void LipstickCompositor::surfaceLowered()
{
    QWaylandSurface *surface = qobject_cast<QWaylandSurface *>(sender());
    LipstickCompositorWindow *window = static_cast<LipstickCompositorWindow *>(surface->surfaceItem());

    if (window) {
        emit windowLowered(window);
    }
}

void LipstickCompositor::windowSwapped()
{
    frameFinished(m_fullscreenSurface);
}

void LipstickCompositor::windowDestroyed()
{
    m_totalWindowCount--;
    emit ghostWindowCountChanged();
}

void LipstickCompositor::windowPropertyChanged(const QString &property)
{
    QWaylandSurface *surface = qobject_cast<QWaylandSurface *>(sender());

    if (debug())
        qDebug() << "Window properties changed:" << surface << surface->windowProperties();

    if (property == QLatin1String("MOUSE_REGION")) {
        LipstickCompositorWindow *window = static_cast<LipstickCompositorWindow *>(surface->surfaceItem());
        if (window)
            window->refreshMouseRegion();
    }
}

void LipstickCompositor::surfaceUnmapped(QWaylandSurface *surface)
{
    LipstickCompositorWindow *item = static_cast<LipstickCompositorWindow *>(surface->surfaceItem());
    surface->setSurfaceItem(0);

    if (surface == m_fullscreenSurface)
        setFullscreenSurface(0);

    if (item) {
        int id = item->windowId();

        int gc = ghostWindowCount();
        m_mappedSurfaces.remove(item->windowId());

        emit windowCountChanged();
        emit windowRemoved(item);

        item->m_windowClosed = true;
        item->tryRemove();

        if (gc != ghostWindowCount())
            emit ghostWindowCountChanged();

        windowRemoved(id);

        emit availableWinIdsChanged();
    }
}

void LipstickCompositor::surfaceUnmapped(LipstickCompositorProcWindow *item)
{
    int id = item->windowId();

    int gc = ghostWindowCount();
    m_mappedSurfaces.remove(item->windowId());

    emit windowCountChanged();
    emit windowRemoved(item);

    item->m_windowClosed = true;
    item->tryRemove();

    if (gc != ghostWindowCount())
        emit ghostWindowCountChanged();

    windowRemoved(id);

    emit availableWinIdsChanged();
}

void LipstickCompositor::windowAdded(int id)
{
    for (int ii = 0; ii < m_windowModels.count(); ++ii)
        m_windowModels.at(ii)->addItem(id);
}

void LipstickCompositor::windowRemoved(int id)
{
    for (int ii = 0; ii < m_windowModels.count(); ++ii)
        m_windowModels.at(ii)->remItem(id);
}

QQmlComponent *LipstickCompositor::shaderEffectComponent()
{
    const char *qml_source =
        "import QtQuick 2.0\n"
        "ShaderEffect {\n"
            "property QtObject window\n"
            "property ShaderEffectSource source: ShaderEffectSource { sourceItem: window }\n"
        "}";

    if (!m_shaderEffect) {
        m_shaderEffect = new QQmlComponent(qmlEngine(this));
        m_shaderEffect->setData(qml_source, QUrl());
    }
    return m_shaderEffect;
}

<commit_msg>[lipstick] Prevent flicker when returning to composited mode<commit_after>/***************************************************************************
**
** Copyright (C) 2013 Jolla Ltd.
** Contact: Aaron Kennedy <aaron.kennedy@jollamobile.com>
**
** This file is part of lipstick.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QWaylandInputDevice>
#include "homeapplication.h"
#include "windowmodel.h"
#include "lipstickcompositorprocwindow.h"
#include "lipstickcompositor.h"

LipstickCompositor *LipstickCompositor::m_instance = 0;

LipstickCompositor::LipstickCompositor()
: QWaylandCompositor(this), m_totalWindowCount(0), m_nextWindowId(1), m_homeActive(true), m_shaderEffect(0),
  m_fullscreenSurface(0), m_directRenderingActive(false), m_topmostWindowId(0)
{
    if (m_instance) qFatal("LipstickCompositor: Only one compositor instance per process is supported");
    m_instance = this;

    QObject::connect(this, SIGNAL(frameSwapped()), this, SLOT(windowSwapped()));

    emit HomeApplication::instance()->homeActiveChanged();
}

LipstickCompositor::~LipstickCompositor()
{
    delete m_shaderEffect;
}

LipstickCompositor *LipstickCompositor::instance()
{
    return m_instance;
}

void LipstickCompositor::classBegin()
{
}

void LipstickCompositor::componentComplete()
{
    QWaylandCompositor::setOutputGeometry(QRect(0, 0, width(), height()));
}

void LipstickCompositor::surfaceCreated(QWaylandSurface *surface)
{
    Q_UNUSED(surface)
    connect(surface, SIGNAL(mapped()), this, SLOT(surfaceMapped()));
    connect(surface, SIGNAL(unmapped()), this, SLOT(surfaceUnmapped()));
    connect(surface, SIGNAL(sizeChanged()), this, SLOT(surfaceSizeChanged()));
    connect(surface, SIGNAL(titleChanged()), this, SLOT(surfaceTitleChanged()));
    connect(surface, SIGNAL(windowPropertyChanged(QString,QVariant)), this, SLOT(windowPropertyChanged(QString)));
    connect(surface, SIGNAL(raiseRequested()), this, SLOT(surfaceRaised()));
    connect(surface, SIGNAL(lowerRequested()), this, SLOT(surfaceLowered()));
}

int LipstickCompositor::windowCount() const
{
    return m_mappedSurfaces.count();
}

int LipstickCompositor::ghostWindowCount() const
{
    return m_totalWindowCount - windowCount();
}

bool LipstickCompositor::homeActive() const
{
    return m_homeActive;
}

void LipstickCompositor::setHomeActive(bool a)
{
    if (a == m_homeActive)
        return;

    m_homeActive = a;

    emit homeActiveChanged();
    emit HomeApplication::instance()->homeActiveChanged();
}

bool LipstickCompositor::debug() const
{
    static enum { Yes, No, Unknown } status = Unknown;
    if (status == Unknown) {
        QByteArray v = qgetenv("LIPSTICK_COMPOSITOR_DEBUG");
        bool value = !v.isEmpty() && v != "0" && v != "false";
        if (value) status = Yes;
        else status = No;
    }
    return status == Yes;
}

QObject *LipstickCompositor::windowForId(int id) const
{
    LipstickCompositorWindow *window = m_mappedSurfaces.value(id, 0);
    return window;
}

void LipstickCompositor::closeClientForWindowId(int id)
{
    LipstickCompositorWindow *window = m_mappedSurfaces.value(id, 0);
    if (window && window->surface())
        destroyClientForSurface(window->surface());
}

QWaylandSurface *LipstickCompositor::surfaceForId(int id) const
{
    LipstickCompositorWindow *window = m_mappedSurfaces.value(id, 0);
    return window?window->surface():0;
}

int LipstickCompositor::windowIdForLink(QWaylandSurface *s, uint link) const
{
    for (QHash<int, LipstickCompositorWindow *>::ConstIterator iter = m_mappedSurfaces.begin();
         iter != m_mappedSurfaces.end(); ++iter) {

        QWaylandSurface *windowSurface = iter.value()->surface();

        if (windowSurface && windowSurface->processId() == s->processId() &&
            windowSurface->windowProperties().value("WINID", uint(0)).toUInt() == link)
            return iter.value()->windowId();
    }

    return 0;
}

void LipstickCompositor::clearKeyboardFocus()
{
    defaultInputDevice()->setKeyboardFocus(0);
}

void LipstickCompositor::setFullscreenSurface(QWaylandSurface *surface)
{
    if (surface == m_fullscreenSurface)
        return;

    // Prevent flicker when returning to composited mode
    if (!surface && m_fullscreenSurface && m_fullscreenSurface->surfaceItem())
        m_fullscreenSurface->surfaceItem()->update();

    m_fullscreenSurface = surface;

    const bool directRenderingSucceeded = setDirectRenderSurface(m_fullscreenSurface, openglContext());
    if (surface && !directRenderingSucceeded)
        qWarning() << Q_FUNC_INFO << "failed to set direct render surface";
    if ((surface && directRenderingSucceeded) != m_directRenderingActive) {
        m_directRenderingActive = surface && directRenderingSucceeded;
        emit directRenderingActiveChanged();
    }

    emit fullscreenSurfaceChanged();
}

void LipstickCompositor::setTopmostWindowId(int id)
{
    if (id != m_topmostWindowId) {
        m_topmostWindowId = id;
        emit topmostWindowIdChanged();
    }
}

void LipstickCompositor::surfaceAboutToBeDestroyed(QWaylandSurface *surface)
{
    Q_ASSERT(surface);
    surfaceUnmapped(static_cast<QWaylandSurface *>(surface));
}

void LipstickCompositor::surfaceMapped()
{
    QWaylandSurface *surface = qobject_cast<QWaylandSurface *>(sender());
    //Ignore surface if it's not a window surface
    if (!surface->hasShellSurface())
        return;

    QVariantMap properties = surface->windowProperties();
    QString category = properties.value("CATEGORY").toString();

    Q_ASSERT(surface->surfaceItem() == 0);

    int id = m_nextWindowId++;

    LipstickCompositorWindow *item = new LipstickCompositorWindow(id, category, surface, contentItem());
    item->setSize(surface->size());
    QObject::connect(item, SIGNAL(destroyed(QObject*)), this, SLOT(windowDestroyed()));
    m_totalWindowCount++;
    m_mappedSurfaces.insert(id, item);

    item->setTouchEventsEnabled(true);

    emit windowCountChanged();
    emit windowAdded(item);

    windowAdded(id);

    emit availableWinIdsChanged();
}

void LipstickCompositor::surfaceUnmapped()
{
    surfaceUnmapped(qobject_cast<QWaylandSurface *>(sender()));
}

void LipstickCompositor::surfaceSizeChanged()
{
    QWaylandSurface *surface = qobject_cast<QWaylandSurface *>(sender());

    LipstickCompositorWindow *window = static_cast<LipstickCompositorWindow *>(surface->surfaceItem());
    if (window)
        window->setSize(surface->size());
}

void LipstickCompositor::surfaceTitleChanged()
{
    QWaylandSurface *surface = qobject_cast<QWaylandSurface *>(sender());
    LipstickCompositorWindow *window = static_cast<LipstickCompositorWindow *>(surface->surfaceItem());

    if (window) {
        emit window->titleChanged();

        int windowId = window->windowId();

        for (int ii = 0; ii < m_windowModels.count(); ++ii)
            m_windowModels.at(ii)->titleChanged(windowId);
    }
}

void LipstickCompositor::surfaceRaised()
{
    QWaylandSurface *surface = qobject_cast<QWaylandSurface *>(sender());
    LipstickCompositorWindow *window = static_cast<LipstickCompositorWindow *>(surface->surfaceItem());

    if (window) {
        emit windowRaised(window);
    }
}

void LipstickCompositor::surfaceLowered()
{
    QWaylandSurface *surface = qobject_cast<QWaylandSurface *>(sender());
    LipstickCompositorWindow *window = static_cast<LipstickCompositorWindow *>(surface->surfaceItem());

    if (window) {
        emit windowLowered(window);
    }
}

void LipstickCompositor::windowSwapped()
{
    frameFinished(m_fullscreenSurface);
}

void LipstickCompositor::windowDestroyed()
{
    m_totalWindowCount--;
    emit ghostWindowCountChanged();
}

void LipstickCompositor::windowPropertyChanged(const QString &property)
{
    QWaylandSurface *surface = qobject_cast<QWaylandSurface *>(sender());

    if (debug())
        qDebug() << "Window properties changed:" << surface << surface->windowProperties();

    if (property == QLatin1String("MOUSE_REGION")) {
        LipstickCompositorWindow *window = static_cast<LipstickCompositorWindow *>(surface->surfaceItem());
        if (window)
            window->refreshMouseRegion();
    }
}

void LipstickCompositor::surfaceUnmapped(QWaylandSurface *surface)
{
    LipstickCompositorWindow *item = static_cast<LipstickCompositorWindow *>(surface->surfaceItem());
    surface->setSurfaceItem(0);

    if (surface == m_fullscreenSurface)
        setFullscreenSurface(0);

    if (item) {
        int id = item->windowId();

        int gc = ghostWindowCount();
        m_mappedSurfaces.remove(item->windowId());

        emit windowCountChanged();
        emit windowRemoved(item);

        item->m_windowClosed = true;
        item->tryRemove();

        if (gc != ghostWindowCount())
            emit ghostWindowCountChanged();

        windowRemoved(id);

        emit availableWinIdsChanged();
    }
}

void LipstickCompositor::surfaceUnmapped(LipstickCompositorProcWindow *item)
{
    int id = item->windowId();

    int gc = ghostWindowCount();
    m_mappedSurfaces.remove(item->windowId());

    emit windowCountChanged();
    emit windowRemoved(item);

    item->m_windowClosed = true;
    item->tryRemove();

    if (gc != ghostWindowCount())
        emit ghostWindowCountChanged();

    windowRemoved(id);

    emit availableWinIdsChanged();
}

void LipstickCompositor::windowAdded(int id)
{
    for (int ii = 0; ii < m_windowModels.count(); ++ii)
        m_windowModels.at(ii)->addItem(id);
}

void LipstickCompositor::windowRemoved(int id)
{
    for (int ii = 0; ii < m_windowModels.count(); ++ii)
        m_windowModels.at(ii)->remItem(id);
}

QQmlComponent *LipstickCompositor::shaderEffectComponent()
{
    const char *qml_source =
        "import QtQuick 2.0\n"
        "ShaderEffect {\n"
            "property QtObject window\n"
            "property ShaderEffectSource source: ShaderEffectSource { sourceItem: window }\n"
        "}";

    if (!m_shaderEffect) {
        m_shaderEffect = new QQmlComponent(qmlEngine(this));
        m_shaderEffect->setData(qml_source, QUrl());
    }
    return m_shaderEffect;
}

<|endoftext|>


<commit_before>#include <QMessageBox>
//#include <QProgressBar>
//#include <QMovie>
//#include <QLabel>
#include <AnnotatorLib/Commands/NewAnnotation.h>
#include <AnnotatorLib/Commands/RemoveAnnotation.h>
#include <AnnotatorLib/Commands/UpdateAnnotation.h>
#include <AnnotatorLib/Commands/UpdateObject.h>
#include <AnnotatorLib/Commands/RemoveObject.h>
#include <AnnotatorLib/Commands/CompressSession.h>
#include <AnnotatorLib/Commands/CompressObject.h>
#include <AnnotatorLib/Commands/CleanSession.h>
#include "gui/qtwaitingspinner/waitingspinnerwidget.h"
#include "selectioncontroller.h"
#include "commandcontroller.h"

using namespace AnnotatorLib;

static CommandController *singleton = nullptr;

CommandController::CommandController(QObject *parent) : QObject(parent) {}

CommandController *CommandController::instance() {
  if (!singleton) singleton = new CommandController();
  return singleton;
}

void CommandController::setSession(std::shared_ptr<Session> session) {
  this->session = session;
}

void CommandController::setParentWidget(QWidget *parent)
{
    main_widget = parent;
}

void CommandController::doEmitRefreshSession()
{
    emit signal_refreshSession();
}

void CommandController::execute(shared_ptr<Commands::Command> command,
                                bool request_gui_reload,
                                bool show_busy_wheel) {

  if (show_busy_wheel) enableBusySpinner(true);
  shared_ptr<Commands::Command> command_executed = session->execute(command);
  if (show_busy_wheel) enableBusySpinner(false);

  if (request_gui_reload && command_executed) {
    send_signals(command_executed, false);
  }
}

void CommandController::redo() {
  try {
    shared_ptr<Commands::Command> command = session->redo();
    if (command) send_signals(command, false);
  } catch (std::exception &e) {
  }
}

void CommandController::undo() {
  try {
    shared_ptr<Commands::Command> command = session->undo();
    if (command) send_signals(command, true);
  } catch (std::exception &e) {
  }
}

void CommandController::send_signals(shared_ptr<Commands::Command> command, bool undo) {

  if (std::dynamic_pointer_cast<Commands::NewAnnotation>(command)) {

      if (!undo) {
          if (std::dynamic_pointer_cast<Commands::NewAnnotation>(command)->newObjectCreated()) {
            shared_ptr<Object> new_obj = std::dynamic_pointer_cast<Commands::NewAnnotation>(command)->getAnnotation()->getObject();
            emit signal_newObject(new_obj);
            SelectionController::instance()->setSelectedObject(new_obj);
          } else
            emit signal_newAnnotation(std::dynamic_pointer_cast<Commands::NewAnnotation>(command)->getAnnotation());
      } else {
          emit signal_removedAnnotation(std::dynamic_pointer_cast<Commands::NewAnnotation>(command)->getAnnotation());
      }
      emit signal_requestFrameRedraw();
      return;
  }
  if (std::dynamic_pointer_cast<Commands::RemoveAnnotation>(command)) {
      shared_ptr<Annotation> a = std::dynamic_pointer_cast<Commands::RemoveAnnotation>(command)->getAnnotation();
      if (!undo) {
          emit signal_removedAnnotation(a);
          if (a->getObject() == SelectionController::instance()->getSelectedObject() && a->getObject()->getAnnotations().size() == 0)
            SelectionController::instance()->setSelectedObject(nullptr);
      } else {
          emit signal_newAnnotation(a);
      }
      emit signal_requestFrameRedraw();
      return;
  }
  if (std::dynamic_pointer_cast<Commands::RemoveObject>(command)) {
      if (!undo) {
          emit signal_removedObject(std::dynamic_pointer_cast<Commands::RemoveObject>(command)->getObject());
          if (SelectionController::instance()->getSelectedObject() ==
              std::dynamic_pointer_cast<Commands::RemoveObject>(command)->getObject()) {
                SelectionController::instance()->setSelectedObject(nullptr);
          }
      } else {
          emit signal_newObject(std::dynamic_pointer_cast<Commands::RemoveObject>(command)->getObject());
      }
      emit signal_requestFrameRedraw();
      return;
  }
  if (std::dynamic_pointer_cast<Commands::UpdateAnnotation>(command)) {
      emit signal_requestFrameRedraw();
      return;
  }
  if (std::dynamic_pointer_cast<Commands::UpdateObject>(command)) {
      emit signal_updateObject(std::dynamic_pointer_cast<Commands::UpdateObject>(command)->getObject());
      return;
  }
  if (std::dynamic_pointer_cast<Commands::CompressObject>(command)) {
      emit signal_removedObject(std::dynamic_pointer_cast<Commands::CompressObject>(command)->getObject());
      emit signal_newObject(std::dynamic_pointer_cast<Commands::CompressObject>(command)->getObject());
      emit signal_requestFrameRedraw();
      return;
  }
  if (std::dynamic_pointer_cast<Commands::CompressSession>(command) ||
      std::dynamic_pointer_cast<Commands::CleanSession>(command)) {
      emit signal_refreshSession();
      emit signal_requestFrameRedraw();
      SelectionController::instance()->setSelectedObject(nullptr);
      return;
    }
}

void CommandController::enableBusySpinner(bool enable) {
  static WaitingSpinnerWidget* spinner;
  if (enable) {
    if (spinner == nullptr) {
      if (main_widget != nullptr)
        spinner = new WaitingSpinnerWidget(Qt::ApplicationModal, main_widget, true, true);
      else
        spinner = new WaitingSpinnerWidget(Qt::ApplicationModal);

      spinner->setRoundness(70.0);
      spinner->setMinimumTrailOpacity(25.0);
      spinner->setTrailFadePercentage(70.0);
      spinner->setNumberOfLines(12);
      spinner->setLineLength(11);
      spinner->setLineWidth(6);
      spinner->setInnerRadius(11);
      spinner->setRevolutionsPerSecond(1);
      spinner->setColor(QColor(81, 81, 81));
    }
    spinner->start(); // starts spinning
  } else {
    spinner->stop();
  }
}

<commit_msg>update widgets when a range of annotations was removed<commit_after>#include <QMessageBox>
//#include <QProgressBar>
//#include <QMovie>
//#include <QLabel>
#include <AnnotatorLib/Commands/NewAnnotation.h>
#include <AnnotatorLib/Commands/RemoveAnnotation.h>
#include <AnnotatorLib/Commands/UpdateAnnotation.h>
#include <AnnotatorLib/Commands/UpdateObject.h>
#include <AnnotatorLib/Commands/RemoveObject.h>
#include <AnnotatorLib/Commands/RemoveAnnotationRange.h>
#include <AnnotatorLib/Commands/CompressSession.h>
#include <AnnotatorLib/Commands/CompressObject.h>
#include <AnnotatorLib/Commands/CleanSession.h>
#include "gui/qtwaitingspinner/waitingspinnerwidget.h"
#include "selectioncontroller.h"
#include "commandcontroller.h"

using namespace AnnotatorLib;

static CommandController *singleton = nullptr;

CommandController::CommandController(QObject *parent) : QObject(parent) {}

CommandController *CommandController::instance() {
  if (!singleton) singleton = new CommandController();
  return singleton;
}

void CommandController::setSession(std::shared_ptr<Session> session) {
  this->session = session;
}

void CommandController::setParentWidget(QWidget *parent)
{
    main_widget = parent;
}

void CommandController::doEmitRefreshSession()
{
    emit signal_refreshSession();
}

void CommandController::execute(shared_ptr<Commands::Command> command,
                                bool request_gui_reload,
                                bool show_busy_wheel) {

  if (show_busy_wheel) enableBusySpinner(true);
  shared_ptr<Commands::Command> command_executed = session->execute(command);
  if (show_busy_wheel) enableBusySpinner(false);

  if (request_gui_reload && command_executed) {
    send_signals(command_executed, false);
  }
}

void CommandController::redo() {
  try {
    shared_ptr<Commands::Command> command = session->redo();
    if (command) send_signals(command, false);
  } catch (std::exception &e) {
  }
}

void CommandController::undo() {
  try {
    shared_ptr<Commands::Command> command = session->undo();
    if (command) send_signals(command, true);
  } catch (std::exception &e) {
  }
}

void CommandController::send_signals(shared_ptr<Commands::Command> command, bool undo) {

  if (std::dynamic_pointer_cast<Commands::NewAnnotation>(command)) {

      if (!undo) {
          if (std::dynamic_pointer_cast<Commands::NewAnnotation>(command)->newObjectCreated()) {
            shared_ptr<Object> new_obj = std::dynamic_pointer_cast<Commands::NewAnnotation>(command)->getAnnotation()->getObject();
            emit signal_newObject(new_obj);
            SelectionController::instance()->setSelectedObject(new_obj);
          } else
            emit signal_newAnnotation(std::dynamic_pointer_cast<Commands::NewAnnotation>(command)->getAnnotation());
      } else {
          emit signal_removedAnnotation(std::dynamic_pointer_cast<Commands::NewAnnotation>(command)->getAnnotation());
      }
      emit signal_requestFrameRedraw();
      return;
  }
  if (std::dynamic_pointer_cast<Commands::RemoveAnnotation>(command)) {
      shared_ptr<Annotation> a = std::dynamic_pointer_cast<Commands::RemoveAnnotation>(command)->getAnnotation();
      if (!undo) {
          emit signal_removedAnnotation(a);
          if (a->getObject() == SelectionController::instance()->getSelectedObject() && a->getObject()->getAnnotations().size() == 0)
            SelectionController::instance()->setSelectedObject(nullptr);
      } else {
          emit signal_newAnnotation(a);
      }
      emit signal_requestFrameRedraw();
      return;
  }
  if (std::dynamic_pointer_cast<Commands::RemoveObject>(command)) {
      if (!undo) {
          emit signal_removedObject(std::dynamic_pointer_cast<Commands::RemoveObject>(command)->getObject());
          if (SelectionController::instance()->getSelectedObject() ==
              std::dynamic_pointer_cast<Commands::RemoveObject>(command)->getObject()) {
                SelectionController::instance()->setSelectedObject(nullptr);
          }
      } else {
          emit signal_newObject(std::dynamic_pointer_cast<Commands::RemoveObject>(command)->getObject());
      }
      emit signal_requestFrameRedraw();
      return;
  }
  if (std::dynamic_pointer_cast<Commands::UpdateAnnotation>(command)) {
      emit signal_requestFrameRedraw();
      return;
  }
  if (std::dynamic_pointer_cast<Commands::UpdateObject>(command)) {
      emit signal_updateObject(std::dynamic_pointer_cast<Commands::UpdateObject>(command)->getObject());
      return;
  }
  if (std::dynamic_pointer_cast<Commands::CompressObject>(command)) {
      emit signal_removedObject(std::dynamic_pointer_cast<Commands::CompressObject>(command)->getObject());
      emit signal_newObject(std::dynamic_pointer_cast<Commands::CompressObject>(command)->getObject());
      emit signal_requestFrameRedraw();
      return;
  }
  if (std::dynamic_pointer_cast<Commands::CompressSession>(command) ||
      std::dynamic_pointer_cast<Commands::CleanSession>(command) ||
      std::dynamic_pointer_cast<Commands::RemoveAnnotationRange>(command)) {
      emit signal_refreshSession();
      emit signal_requestFrameRedraw();
      SelectionController::instance()->setSelectedObject(nullptr); //TODO
      return;
    }
}

void CommandController::enableBusySpinner(bool enable) {
  static WaitingSpinnerWidget* spinner;
  if (enable) {
    if (spinner == nullptr) {
      if (main_widget != nullptr)
        spinner = new WaitingSpinnerWidget(Qt::ApplicationModal, main_widget, true, true);
      else
        spinner = new WaitingSpinnerWidget(Qt::ApplicationModal);

      spinner->setRoundness(70.0);
      spinner->setMinimumTrailOpacity(25.0);
      spinner->setTrailFadePercentage(70.0);
      spinner->setNumberOfLines(12);
      spinner->setLineLength(11);
      spinner->setLineWidth(6);
      spinner->setInnerRadius(11);
      spinner->setRevolutionsPerSecond(1);
      spinner->setColor(QColor(81, 81, 81));
    }
    spinner->start(); // starts spinning
  } else {
    spinner->stop();
  }
}

<|endoftext|>


<commit_before>#include "pincodequeryui.h"

#include <DuiWidget>
#include <DuiLocale>
#include <DuiTextEdit>
#include <DuiTheme>
#include <DuiSceneManager>
#include <DuiGrid>
#include <DuiGridLayoutPolicy>
#include <DuiButton>
#include <DuiLabel>
#include <DuiTextEdit>

#include <QStringList>
#include <QSizePolicy>
#include <QTimer>
#include <QDebug>

PinCodeQueryUI::PinCodeQueryUI(QStringList emergencyNumbers)
{
    this->emergencyNumbers = emergencyNumbers;
    setFullscreen(true);
    setNavigationBarVisible(false);
    setTitle("PIN code query:");
    createContent();
}

PinCodeQueryUI::~PinCodeQueryUI()
{
}

void PinCodeQueryUI::createContent()
{
    DuiApplicationPage::createContent();
    DuiWidget *panel = centralWidget();

    //create the widgets and numpad.
    createWidgetItems();

    //create mainLayout
    DuiLayout *mainLayout = new DuiLayout(panel);
    //mainLayout->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);

    //create landscapePolicy and portraitPolicy for mainLayout
    landscapePolicy = new DuiGridLayoutPolicy(mainLayout);
    portraitPolicy = new DuiGridLayoutPolicy(mainLayout);

    //attach widget items to landscape and portrait policies
    landscapePolicy->addItemAtPosition(headerLabel, 0, 0, 1, 5);
    landscapePolicy->addItemAtPosition(emergencyCallButton, 1, 0, 1, 4);
    landscapePolicy->addItemAtPosition(entryTextEdit, 2, 0, 1, 3);
    landscapePolicy->addItemAtPosition(backspaceButton, 2, 3, 1, 1);
    landscapePolicy->addItemAtPosition(enterButton, 3, 0, 1, 2);
    landscapePolicy->addItemAtPosition(cancelButton, 3, 2, 1, 2);
    landscapePolicy->addItemAtPosition(numpadLayout, 1, 4, 3, 1);
    portraitPolicy->addItemAtPosition(headerLabel, 0, 0, 1, 4);
    portraitPolicy->addItemAtPosition(emergencyCallButton, 1, 0, 1, 4);
    portraitPolicy->addItemAtPosition(entryTextEdit, 2, 0, 1, 3);
    portraitPolicy->addItemAtPosition(backspaceButton, 2, 3);
    portraitPolicy->addItemAtPosition(numpadLayout, 3, 0, 1, 4);
    portraitPolicy->addItemAtPosition(enterButton, 4, 0, 1, 2);
    portraitPolicy->addItemAtPosition(cancelButton, 4, 2, 1, 2);

    //set column and row sizes
    int fullWidth = DuiSceneManager::instance()->visibleSceneRect().width();
    int fullHeight = DuiSceneManager::instance()->visibleSceneRect().height();
    for(int lsCol=0; lsCol<5; ++lsCol) {
	if(lsCol < 4)
            landscapePolicy->setColumnFixedWidth(lsCol, fullWidth/8);
	else
	    landscapePolicy->setColumnFixedWidth(lsCol, fullWidth/2);
    }
    for(int lsRow=0; lsRow<4;++lsRow) {
	landscapePolicy->setRowFixedHeight(lsRow, fullHeight/4);
    }
    for(int ptCol=0; ptCol<4; ++ptCol) {
	portraitPolicy->setColumnFixedWidth(ptCol, fullHeight/4);
    }
    for(int ptRow=0; ptRow<5; ++ptRow) {
	portraitPolicy->setRowFixedHeight(ptRow, fullWidth/5);
    }

    orientationChanged(DuiSceneManager::instance()->orientation());

//    DuiTheme::loadCSS("pinquery.css");

    // HACK: make all buttons visible :)
    /*
    requestPageMove(QPointF(0, -1), QPointF(0, 1), false);
    restorePageMove();
   */

    // Get informed about orientation changes
    connect(DuiSceneManager::instance(),
            SIGNAL(orientationChanged(const Dui::Orientation &)),
            this, SLOT(orientationChanged(const Dui::Orientation &)));

    backspaceTimer = NULL;
}

DuiButton *PinCodeQueryUI::getEmergencyBtn()
{
    return emergencyCallButton;
}
DuiButton *PinCodeQueryUI::getCancelBtn()
{
    return cancelButton;
}
DuiButton *PinCodeQueryUI::getEnterBtn()
{
    return enterButton;
}
DuiTextEdit *PinCodeQueryUI::getCodeEntry()
{
    return entryTextEdit;
}
void PinCodeQueryUI::setHeader(QString header)
{
    headerLabel->setText(header);
}

void PinCodeQueryUI::createWidgetItems()
{
    emergencyCallButton = new DuiButton(QString(trid("qtn_cell_emergency_call", "Emergency call")), 0 );
    emergencyCallButton->setObjectName("emergencyCallButton");
    connect(emergencyCallButton, SIGNAL(released()), this, SLOT(buttonReleased()));
    qDebug() << "hiding emergenceCall button" ;
    emergencyCallButton->setVisible(false);

    entryTextEdit = new DuiTextEdit(DuiTextEditModel::SingleLine, "", 0);
    entryTextEdit->setObjectName("codeEntry");
    entryTextEdit->setMaskedInput(true);

    enterButton = new DuiButton(QString(trid("qtn_cell_enter", "Enter")), 0);
    enterButton->setObjectName("enterButton");
    connect(enterButton, SIGNAL(released()), this, SLOT(buttonReleased()));

    cancelButton = new DuiButton(QString(trid("qtn_comm_cancel", "Cancel")), 0);
    cancelButton->setObjectName("cancelButton");
    connect(cancelButton, SIGNAL(released()), this, SLOT(buttonReleased()));

    backspaceButton = new DuiButton(0);
    backspaceButton->setObjectName("backspaceButton");
    backspaceButton->setIconID("Icon-back");
    connect(backspaceButton, SIGNAL(released()), this, SLOT(buttonReleased()));
    connect(backspaceButton, SIGNAL(pressed()), this, SLOT(buttonPressed()));

    headerLabel = new DuiLabel(0);
    headerLabel->setAlignment(Qt::AlignCenter);

    createNumpad();
}

void PinCodeQueryUI::createNumpad()
{
    //create numpadLayout and policy for that
    numpadLayout = new DuiLayout(0);
    DuiGridLayoutPolicy *numpadLayoutPolicy = new DuiGridLayoutPolicy(numpadLayout);

    int values[] = {
        1, 2, 3,
        4, 5, 6,
        7, 8, 9,
        0
    };

    int colSpan = 1;
    for (unsigned int i=0; i<sizeof(values)/sizeof(values[0]); ++i) {

	if(values[i] == 0)
	    colSpan = 3;

        QString str1 = QString("qtn_cell_dialer_").append(QString::number(values[i]));
        QString str2 = QString::number(values[i]);
        QString str3 = QString("numpadButton" + str2);
        DuiButton *num = new DuiButton(QString(trid(str1.toLatin1(), str2.toLatin1())), 0);
        num->setObjectName(str3);
        connect(num, SIGNAL(released()), this, SLOT(buttonReleased()));
        numpadLayoutPolicy->addItemAtPosition(num, (i/3), i%3, 1, colSpan);
    }
}

void PinCodeQueryUI::buttonReleased()
{
    DuiButton* button = static_cast<DuiButton*>(this->sender());

    //Check if the button was a numpad button
    if(button->objectName().left(button->objectName().length()-1) == "numpadButton") {
        entryTextEdit->insert(button->objectName().right(1));
        qDebug() << "text now: " << entryTextEdit->text();
        checkEntry(); //Check the current entry
    }

    //Check if the button was backspace
    else if(button->objectName() == QString("backspaceButton")) {
        if(backspaceTimer != NULL) {
            //we stop timing the press event
            backspaceTimer->stop();
            delete backspaceTimer;
            backspaceTimer = NULL;
        }
        entryTextEdit->setText(entryTextEdit->text().left(entryTextEdit->text().length()-1));
        checkEntry(); //Check the current entry
    }
}

void PinCodeQueryUI::buttonPressed()
{
    DuiButton* button = static_cast<DuiButton*>(this->sender());
    //Check if the button was backspace
    if(button->objectName() == QString("backspaceButton")) {
        //we check if the user holds the button down for 1 second or longer
        backspaceTimer = new QTimer(0);
        connect(backspaceTimer, SIGNAL(timeout()), this, SLOT(removeText()));
        backspaceTimer->start(1000);
    }
}

void PinCodeQueryUI::removeText()
{
    if(backspaceTimer != NULL) {
        backspaceTimer->stop();
        delete backspaceTimer;
        backspaceTimer = NULL;
    }
    entryTextEdit->setText("");
}

void PinCodeQueryUI::checkEntry()
{
    if(emergencyCallButton == NULL)
        return;

    QString pinCode = entryTextEdit->text();

    //check if the entered opin code is an emergency call phone number
    if( emergencyNumbers.contains(pinCode) ) {
        emergencyCallButton->setVisible(true);
        entryTextEdit->setMaskedInput(false);
    }
    else if(emergencyCallButton->isVisible()) {
        emergencyCallButton->setVisible(false);
        entryTextEdit->setMaskedInput(true);
    }

}

void PinCodeQueryUI::orientationChanged(const Dui::Orientation &orientation)
{
     qDebug() << "OrientationChanged" ;
    if (orientation == Dui::Portrait) {
        portraitPolicy->activate();
    } else {
        landscapePolicy->activate();
    }
}

<commit_msg>Temporary fix for<commit_after>#include "pincodequeryui.h"

#include <DuiWidget>
#include <DuiLocale>
#include <DuiTextEdit>
#include <DuiTheme>
#include <DuiSceneManager>
#include <DuiGrid>
#include <DuiGridLayoutPolicy>
#include <DuiButton>
#include <DuiLabel>
#include <DuiTextEdit>

#include <QStringList>
#include <QSizePolicy>
#include <QTimer>
#include <QDebug>

PinCodeQueryUI::PinCodeQueryUI(QStringList emergencyNumbers)
{
    this->emergencyNumbers = emergencyNumbers;
    setFullscreen(true);
    setNavigationBarVisible(false);
    setTitle("PIN code query:");
    createContent();
}

PinCodeQueryUI::~PinCodeQueryUI()
{
}

void PinCodeQueryUI::createContent()
{
    DuiApplicationPage::createContent();
    DuiWidget *panel = centralWidget();

    //create the widgets and numpad.
    createWidgetItems();

    //create mainLayout
    DuiLayout *mainLayout = new DuiLayout(panel);
    //mainLayout->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Maximum);

    //create landscapePolicy and portraitPolicy for mainLayout
    landscapePolicy = new DuiGridLayoutPolicy(mainLayout);
    portraitPolicy = new DuiGridLayoutPolicy(mainLayout);

    //attach widget items to landscape and portrait policies
    landscapePolicy->addItemAtPosition(headerLabel, 0, 0, 1, 5);
    landscapePolicy->addItemAtPosition(emergencyCallButton, 1, 0, 1, 4);
    landscapePolicy->addItemAtPosition(entryTextEdit, 2, 0, 1, 3);
    landscapePolicy->addItemAtPosition(backspaceButton, 2, 3, 1, 1);
    landscapePolicy->addItemAtPosition(enterButton, 3, 0, 1, 2);
    landscapePolicy->addItemAtPosition(cancelButton, 3, 2, 1, 2);
    landscapePolicy->addItemAtPosition(numpadLayout, 1, 4, 3, 1);
    portraitPolicy->addItemAtPosition(headerLabel, 0, 0, 1, 4);
    portraitPolicy->addItemAtPosition(emergencyCallButton, 1, 0, 1, 4);
    portraitPolicy->addItemAtPosition(entryTextEdit, 2, 0, 1, 3);
    portraitPolicy->addItemAtPosition(backspaceButton, 2, 3);
    portraitPolicy->addItemAtPosition(numpadLayout, 3, 0, 1, 4);
    portraitPolicy->addItemAtPosition(enterButton, 4, 0, 1, 2);
    portraitPolicy->addItemAtPosition(cancelButton, 4, 2, 1, 2);

    //set column and row sizes
    int fullWidth = DuiSceneManager::instance()->visibleSceneRect().width();
    int fullHeight = DuiSceneManager::instance()->visibleSceneRect().height();
    for(int lsCol=0; lsCol<5; ++lsCol) {
	if(lsCol < 4)
            landscapePolicy->setColumnFixedWidth(lsCol, fullWidth/8);
	else
	    landscapePolicy->setColumnFixedWidth(lsCol, fullWidth/2);
    }
    for(int lsRow=0; lsRow<4;++lsRow) {
	landscapePolicy->setRowFixedHeight(lsRow, fullHeight/4);
    }
    for(int ptCol=0; ptCol<4; ++ptCol) {
	portraitPolicy->setColumnFixedWidth(ptCol, fullHeight/4);
    }
    for(int ptRow=0; ptRow<5; ++ptRow) {
	portraitPolicy->setRowFixedHeight(ptRow, fullWidth/5);
    }

    orientationChanged(DuiSceneManager::instance()->orientation());

//    DuiTheme::loadCSS("pinquery.css");

    // HACK: make all buttons visible :)
    /*
    requestPageMove(QPointF(0, -1), QPointF(0, 1), false);
    restorePageMove();
   */

    // Get informed about orientation changes
    connect(DuiSceneManager::instance(),
            SIGNAL(orientationChanged(const Dui::Orientation &)),
            this, SLOT(orientationChanged(const Dui::Orientation &)));

    backspaceTimer = NULL;
}

DuiButton *PinCodeQueryUI::getEmergencyBtn()
{
    return emergencyCallButton;
}
DuiButton *PinCodeQueryUI::getCancelBtn()
{
    return cancelButton;
}
DuiButton *PinCodeQueryUI::getEnterBtn()
{
    return enterButton;
}
DuiTextEdit *PinCodeQueryUI::getCodeEntry()
{
    return entryTextEdit;
}
void PinCodeQueryUI::setHeader(QString header)
{
    headerLabel->setText(header);
}

void PinCodeQueryUI::createWidgetItems()
{
    emergencyCallButton = new DuiButton(QString(trid("qtn_cell_emergency_call", "Emergency call")), 0 );
    emergencyCallButton->setObjectName("emergencyCallButton");
    connect(emergencyCallButton, SIGNAL(released()), this, SLOT(buttonReleased()));
    qDebug() << "hiding emergenceCall button" ;
    emergencyCallButton->setVisible(false);

    entryTextEdit = new DuiTextEdit(DuiTextEditModel::SingleLine, "", 0);
    entryTextEdit->setObjectName("codeEntry");
    entryTextEdit->setMaskedInput(true);

    enterButton = new DuiButton(QString(trid("qtn_cell_enter", "Enter")), 0);
    enterButton->setObjectName("enterButton");
    connect(enterButton, SIGNAL(released()), this, SLOT(buttonReleased()));

    cancelButton = new DuiButton(QString(trid("qtn_comm_cancel", "Cancel")), 0);
    cancelButton->setObjectName("cancelButton");
    connect(cancelButton, SIGNAL(released()), this, SLOT(buttonReleased()));

    backspaceButton = new DuiButton(0);
    backspaceButton->setObjectName("backspaceButton");
    backspaceButton->setIconID("Icon-back");
    connect(backspaceButton, SIGNAL(released()), this, SLOT(buttonReleased()));
    connect(backspaceButton, SIGNAL(pressed()), this, SLOT(buttonPressed()));

    headerLabel = new DuiLabel(0);
    headerLabel->setAlignment(Qt::AlignCenter);

    createNumpad();
}

void PinCodeQueryUI::createNumpad()
{
    //create numpadLayout and policy for that
    numpadLayout = new DuiLayout(0);
    DuiGridLayoutPolicy *numpadLayoutPolicy = new DuiGridLayoutPolicy(numpadLayout);

    int values[] = {
        1, 2, 3,
        4, 5, 6,
        7, 8, 9,
        0
    };

    int colSpan = 1;
    for (unsigned int i=0; i<sizeof(values)/sizeof(values[0]); ++i) {

	if(values[i] == 0)
	    colSpan = 3;

        QString str1 = QString("qtn_cell_dialer_").append(QString::number(values[i]));
        QString str2 = QString::number(values[i]);
        QString str3 = QString("numpadButton" + str2);
        DuiButton *num = new DuiButton(QString(trid(str1.toLatin1(), str2.toLatin1())), 0);
        num->setObjectName(str3);
        connect(num, SIGNAL(released()), this, SLOT(buttonReleased()));
        numpadLayoutPolicy->addItemAtPosition(num, (i/3), i%3, 1, colSpan);
    }
}

void PinCodeQueryUI::buttonReleased()
{
    DuiButton* button = static_cast<DuiButton*>(this->sender());

    //Check if the button was a numpad button
    if(button->objectName().left(button->objectName().length()-1) == "numpadButton") {
        entryTextEdit->insert(button->objectName().right(1));
        qDebug() << "text now: " << entryTextEdit->text();
        checkEntry(); //Check the current entry
    }

    //Check if the button was backspace
    else if(button->objectName() == QString("backspaceButton")) {
        if(backspaceTimer != NULL) {
            //we stop timing the press event
            backspaceTimer->stop();
            delete backspaceTimer;
            backspaceTimer = NULL;
        }
        entryTextEdit->setText(entryTextEdit->text().left(entryTextEdit->text().length()-1));
        checkEntry(); //Check the current entry
    }
}

void PinCodeQueryUI::buttonPressed()
{
    DuiButton* button = static_cast<DuiButton*>(this->sender());
    //Check if the button was backspace
    if(button->objectName() == QString("backspaceButton")) {
        //we check if the user holds the button down for 1 second or longer
        backspaceTimer = new QTimer(0);
        connect(backspaceTimer, SIGNAL(timeout()), this, SLOT(removeText()));
        backspaceTimer->start(1000);
    }
}

void PinCodeQueryUI::removeText()
{
    if(backspaceTimer != NULL) {
        backspaceTimer->stop();
        delete backspaceTimer;
        backspaceTimer = NULL;
    }
    entryTextEdit->setText("");
}

void PinCodeQueryUI::checkEntry()
{
    if(emergencyCallButton == NULL)
        return;

    QString pinCode = entryTextEdit->text();

    //check if the entered opin code is an emergency call phone number
    if( emergencyNumbers.contains(pinCode) ) {
        emergencyCallButton->setVisible(true);
/*
        (2.9.2009 / tt) temporary fix for

        Program received signal SIGSEGV, Segmentation fault.
        0xb7288c4a in ?? () from /usr/lib/libQtGui.so.4
        (gdb) bt
        #0  0xb7288c4a in ?? () from /usr/lib/libQtGui.so.4
        #1  0xbff1e228 in ?? ()
        #2  0xb727bedc in QTextDocument::docHandle () from /usr/lib/libQtGui.so.4
*/
        //entryTextEdit->setMaskedInput(false);
    }
    else if(emergencyCallButton->isVisible()) {
        emergencyCallButton->setVisible(false);
        entryTextEdit->setMaskedInput(true);
    }

}

void PinCodeQueryUI::orientationChanged(const Dui::Orientation &orientation)
{
     qDebug() << "OrientationChanged" ;
    if (orientation == Dui::Portrait) {
        portraitPolicy->activate();
    } else {
        landscapePolicy->activate();
    }
}

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2007, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
 * All rights reserved.
 *
 * This library/application is free software; you can redistribute and/or modify it under the terms of
 * the license that is included with this library/application in the file license.txt.
 */

#ifndef _set_wrapper_H
#define _set_wrapper_H

//---- baseclass include -------------------------------------------------
#include <loki/Visitor.h>

#include "STLStorage.h"
#include <set>

#include "DummyMutex.h"

//---- forward declaration -----------------------------------------------
class Anything;
class LockUnlockEntry;

// disable tracing if requested, even if in DEBUG mode, eg. performance tests
#define WD_DISABLE_TRACE
#if !defined(DEBUG) || defined(WD_DISABLE_TRACE)
#define swStatTrace(trigger, msg, allocator)
#define swStartTrace(trigger)
#define swStartTrace1(trigger, msg)
#define swTrace(msg);
#else
#define swStatTrace(trigger, msg, allocator) 	StatTrace(trigger, msg, allocator)
#define swStartTrace(trigger)					StartTrace(trigger)
#define swStartTrace1(trigger, msg)				StartTrace1(trigger, msg)
#define swTrace(msg)							Trace(msg);
#endif

//---- set_wrapper ----------------------------------------------------------
//! single line description of the class
/*!
further explanation of the purpose of the class
this may contain HTML-Tags
*/
template <
typename T,
		 class MutexPolicy = DummyMutex,
		 template < typename > class AllocType = DefaultAllocatorGlobalType
		 >
class set_wrapper : public Loki::BaseVisitable< Anything >
{
	set_wrapper(const set_wrapper &);

public:
	typedef std::less< T > CompareType;
	typedef T ItemType;
	typedef AllocType< ItemType > allocator_type;
	typedef std::set< T, CompareType, allocator_type > Type;
	typedef Type &TypeRef;
	typedef typename Type::size_type size_type;
	typedef std::pair< typename Type::iterator, bool > InsertResultType;
	typedef typename Type::iterator IteratorType;
	typedef typename Type::const_iterator ConstIteratorType;

	LOKI_DEFINE_VISITABLE()

	set_wrapper( const char *pName = "set_wrapper_lock" )
		: fpList( NULL )
		, fLock( pName, Storage::Global() )
	{}
	~set_wrapper() {
		LockUnlockEntry aGuard( fLock );
		if ( IntHasList() ) {
			IntGetListPtr()->clear();
		}
		delete fpList;
		fpList = NULL;
	}

	bool AddItem(const ItemType &aItem) {
		// success means it was a new entry, otherwise there is already an item present
		LockUnlockEntry aGuard( fLock );
		return IntAddItem( aItem );
	}

	bool DeleteItem(const ItemType &aItem) {
		swStartTrace(set_wrapper.DeleteItem);
		LockUnlockEntry aGuard( fLock );
		return IntDeleteItem( aItem );
	}

	bool DeleteItem( const ConstIteratorType &aItemPos ) {
		swStartTrace(set_wrapper.DeleteItem);
		LockUnlockEntry aGuard( fLock );
		return IntDeleteItem( aItemPos );
	}

	bool ReplaceItem(const ItemType &aItem) {
		swStartTrace(set_wrapper.ReplaceItem);
		LockUnlockEntry aGuard( fLock );
		IntDeleteItem(aItem);
		return IntAddItem(aItem);
	}

	/*! this is the exact match version of find
		\param
		\return true in case we found the item, rItemPos will then be the iterator pointing to the item */
	bool FindItem(const ItemType &aItem, ConstIteratorType &rItemPos) const {
		swStartTrace(set_wrapper.FindItem);
		bool bFound(false);
		if ( HasList() ) {
			LockUnlockEntry aGuard( *const_cast<MutexPolicy *>(&fLock) );
			rItemPos = IntGetConstListPtr()->find( aItem );
			bFound = ( rItemPos != IntGetConstListPtr()->end() );
		}
		return bFound;
	}

	/*! Find range of items within given boundaries
		\param aItemMin minimum item to find
		\param aItemMax maximum item to find
		\param rItemsBegin iterator position pointing to first element in range
		\param rItemsEnd iterator position pointing to element after last element in range
		\return true in case the range is not empty */
	bool FindItemRange(const ItemType &aItemMin, const ItemType &aItemMax, ConstIteratorType &rItemsBegin, ConstIteratorType &rItemsEnd) const {
		swStartTrace1(set_wrapper.FindItemRange, "find items for range [" << aItemMin.AsString() << "," << aItemMax.AsString() << "]");
		bool bFound(false);
		if ( HasList() ) {
			LockUnlockEntry aGuard( *const_cast<MutexPolicy *>(&fLock) );
			bFound = IntFindItemRange( aItemMin, aItemMax, rItemsBegin, rItemsEnd );
		}
		return bFound;
	}

	/*! Reduce list of items to given boundaries
		\param aItemMin minimum item to find
		\param aItemMax maximum item to find
		\return true in case we reduced the list */
	bool ReduceToRange(const ItemType &aItemMin, const ItemType &aItemMax) {
		swStartTrace1(set_wrapper.ReduceToRange, "reduce items to range [" << aItemMin.AsString() << "," << aItemMax.AsString() << "]");
		bool bModified(false);
		if ( HasList() ) {
			LockUnlockEntry aGuard( fLock );
			bModified = IntReduceToRange( aItemMin, aItemMax );
		}
		return bModified;
	}

	/*! Return iterators spanning all elements
		\param rItemsBegin beginning position of range
		\param rItemsEnd end position of range
		\return true in case the range is not empty */
	bool FullRange(ConstIteratorType &rItemsBegin, ConstIteratorType &rItemsEnd) const {
		swStartTrace(set_wrapper.FullRange);
		bool bFound(false);
		if ( HasList() ) {
			LockUnlockEntry aGuard( *const_cast<MutexPolicy *>(&fLock) );
			rItemsBegin = IntGetConstListPtr()->begin();
			rItemsEnd = IntGetConstListPtr()->end();
			bFound = ( rItemsBegin != rItemsEnd );
		}
		return bFound;
	}

	bool DeleteItemRange(const IteratorType &rItemsBegin, const IteratorType &rItemsEnd) {
		swStartTrace1(set_wrapper.DeleteItemRange, "[" << ( ( rItemsBegin != IntGetConstListPtr()->end() ) ? (*rItemsBegin).AsString() : "<end>" ) << "," << ( ( rItemsEnd != IntGetConstListPtr()->end() ) ? (*rItemsEnd).AsString() : "<end>" ) << ")");
		bool bRet(false);
		if ( HasList() ) {
			LockUnlockEntry aGuard( fLock );
			IntGetCreateListPtr()->erase(rItemsBegin, rItemsEnd);
			bRet = true;
		}
		return bRet;
	}

	bool DeleteItemRange(const ItemType &aItemMin, const ItemType &aItemMax) {
		swStartTrace1(set_wrapper.DeleteItemRange, "deleting items for range [" << aItemMin.AsString() << "," << aItemMax.AsString() << "]");
		bool bRet(false);
		if ( HasList() ) {
			LockUnlockEntry aGuard( fLock );
			IteratorType rItemsBegin, rItemsEnd;
			if ( IntFindItemRange(aItemMin, aItemMax, rItemsBegin, rItemsEnd) ) {
				IntGetCreateListPtr()->erase(rItemsBegin, rItemsEnd);
				bRet = true;
			}
		}
		return bRet;
	}

	void Clear() {
		LockUnlockEntry aGuard( *const_cast<MutexPolicy *>(&fLock) );
		if ( IntHasList() ) {
			IntGetListPtr()->clear();
		}
	}

	size_type Size() const {
		LockUnlockEntry aGuard( *const_cast<MutexPolicy *>(&fLock) );
		size_type sz(0);
		if ( IntHasList() ) {
			sz = IntGetConstListPtr()->size();
		}
		return sz;
	}

	bool HasList() const {
		LockUnlockEntry aGuard( *const_cast<MutexPolicy *>(&fLock) );
		return IntHasList();
	}

	bool IsEnd(const IteratorType &aIter) const {
		LockUnlockEntry aGuard( *const_cast<MutexPolicy *>(&fLock) );
		return ( IntHasList() ? ( aIter == IntGetConstListPtr()->end() ) : true );
	}

	const Type *GetConstListPtr() const {
		LockUnlockEntry aGuard( *const_cast<MutexPolicy *>(&fLock) );
		return IntGetConstListPtr();
	}

	set_wrapper &operator=(const set_wrapper &other) {
		return Assign( other );
	}
	template < class M, template < class > class A >
	set_wrapper &operator=(const set_wrapper<T, M, A>& other) {
		return Assign( other );
	}

	template < class M, template < class > class A >
	set_wrapper &Assign(const set_wrapper<T, M, A>& other) {
		if ( other.HasList() ) {
			LockUnlockEntry aGuard( fLock );
			CopyItems(IntGetCreateListPtr(), other.GetConstListPtr());
		}
		return (*this);
	}

	Type *GetCreateListPtr() {
		LockUnlockEntry aGuard( fLock );
		return IntGetCreateListPtr();
	}

protected:
	bool IntHasList() const {
		const Type *pList( fpList );
		swStatTrace(set_wrapper.IntHasList, "ptr is:" << (long)pList, Storage::Current());
		return ( pList != NULL );
	}

	Type *IntGetListPtr() {
		Type *pList( fpList );
		swStatTrace(set_wrapper.IntGetListPtr, "ptr is:" << (long)pList, Storage::Current());
		return pList;
	}

	const Type *IntGetConstListPtr() const {
		const Type *pList( fpList );
		swStatTrace(set_wrapper.IntGetConstListPtr, "ptr is:" << (long)pList, Storage::Current());
		return pList;
	}

	Type *IntGetCreateListPtr() {
		swStartTrace(set_wrapper.IntGetCreateListPtr);
		if ( !IntHasList() ) {
			fpList = new Type();
		}
		Type *pList( fpList );
		swTrace("ptr is:" << (long)pList);
		return pList;
	}

	/*! Find range of items within given boundaries
		\param aItemMin minimum item to find
		\param aItemMax maximum item to find
		\param rItemsBegin iterator position pointing to first element in range
		\param rItemsEnd iterator position pointing to element after last element in range
		\return true in case the range is not empty */
	bool IntFindItemRange(const ItemType &aItemMin, const ItemType &aItemMax, ConstIteratorType &rItemsBegin, ConstIteratorType &rItemsEnd) const {
		swStartTrace1(set_wrapper.IntFindItemRange, "find items for range [" << aItemMin.AsString() << "," << aItemMax.AsString() << "]");
		bool bFound(false);
		if ( IntHasList() ) {
			ConstIteratorType aEnd( IntGetConstListPtr()->end() );
			rItemsBegin = IntGetConstListPtr()->lower_bound( aItemMin );
			rItemsEnd = IntGetConstListPtr()->upper_bound( aItemMax );
			swTrace("[" << ( ( rItemsBegin != aEnd ) ? (*rItemsBegin).AsString() : "<end>" ) << "," << ( ( rItemsEnd != aEnd ) ? (*rItemsEnd).AsString() : "<end>" ) << ")");
			if ( ( rItemsBegin != aEnd || rItemsEnd != aEnd ) ) {
				// check if values are within range
				// -> begin value must at least be lower or equal the given aItemMax
				bFound = ( *rItemsBegin < aItemMax || !( aItemMax < *rItemsBegin ) );
			}
		}
		return bFound;
	}

	/*! Reduce list of items to given boundaries
		\param aItemMin minimum item to keep
		\param aItemMax maximum item to keep
		\return true in case we reduced the list */
	bool IntReduceToRange(const ItemType &aItemMin, const ItemType &aItemMax) {
		swStartTrace1(set_wrapper.IntReduceToRange, "reduce items to range [" << aItemMin.AsString() << "," << aItemMax.AsString() << "]");
		bool bModified( false );
		if ( IntHasList() ) {
			IteratorType aEnd( IntGetListPtr()->end() ), aBoundPos;
			aBoundPos = IntGetListPtr()->upper_bound( aItemMin );
			if ( ( aBoundPos != aEnd ) && ( aBoundPos != IntGetListPtr()->begin() ) ) {
				swTrace("removing [" << IntGetListPtr()->begin()->AsString() << "," << ( ( aBoundPos != aEnd ) ? aBoundPos->AsString() : "<end>" ) << ")");
				IntGetListPtr()->erase( IntGetListPtr()->begin(), aBoundPos );
				bModified = true;
			}
			aBoundPos = IntGetListPtr()->upper_bound( aItemMax );
			if ( aBoundPos != aEnd ) {
				swTrace("removing [" << aBoundPos->AsString() << ",<end>)");
				IntGetListPtr()->erase( aBoundPos, IntGetListPtr()->end() );
				bModified = true;
			}
		}
		return bModified;
	}

	bool IntAddItem(const ItemType &aItem) {
		InsertResultType aRetCode( IntGetCreateListPtr()->insert(aItem) );
		swStatTrace(set_wrapper.IntAddItem, "Item [" << aItem.AsString() << "] was " << (aRetCode.second ? "" : "not " ) << "successful", Storage::Current());
		// success means it was a new entry, otherwise there is already an item present
		return aRetCode.second;
	}

	bool IntDeleteItem(const ItemType &aItem) {
		swStartTrace(set_wrapper.IntDeleteItem);
		bool bRet(false);
		if ( IntHasList() ) {
			size_type aRetCode( IntGetCreateListPtr()->erase( aItem ) );
			// number of elements == 1 means success
			bRet = ( aRetCode == 1 );
		}
		return bRet;
	}

	bool IntDeleteItem(const ConstIteratorType &aItemPos) {
		swStartTrace(set_wrapper.IntDeleteItem);
		bool bRet(false);
		if ( IntHasList() ) {
			IntGetCreateListPtr()->erase( aItemPos );
			bRet = true;
		}
		return bRet;
	}

private:
	Type *fpList;
	MutexPolicy fLock;
};

template < class AL, class AR >
inline void CopyItems(AL *pThisList, const AR *pOtherList)
{
//	pThisList->reserve(pOtherList->size());
	std::copy(pOtherList->begin(), pOtherList->end(), std::inserter(*pThisList, pThisList->begin()));
}

#endif
<commit_msg>added function to get FullRange using reverse iterators<commit_after>/*
 * Copyright (c) 2007, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland
 * All rights reserved.
 *
 * This library/application is free software; you can redistribute and/or modify it under the terms of
 * the license that is included with this library/application in the file license.txt.
 */

#ifndef _set_wrapper_H
#define _set_wrapper_H

//---- baseclass include -------------------------------------------------
#include <loki/Visitor.h>

#include "STLStorage.h"
#include <set>

#include "DummyMutex.h"

//---- forward declaration -----------------------------------------------
class Anything;
class LockUnlockEntry;

// disable tracing if requested, even if in DEBUG mode, eg. performance tests
#define WD_DISABLE_TRACE
#if !defined(DEBUG) || defined(WD_DISABLE_TRACE)
#define swStatTrace(trigger, msg, allocator)
#define swStartTrace(trigger)
#define swStartTrace1(trigger, msg)
#define swTrace(msg);
#else
#define swStatTrace(trigger, msg, allocator) 	StatTrace(trigger, msg, allocator)
#define swStartTrace(trigger)					StartTrace(trigger)
#define swStartTrace1(trigger, msg)				StartTrace1(trigger, msg)
#define swTrace(msg)							Trace(msg);
#endif

//---- set_wrapper ----------------------------------------------------------
//! single line description of the class
/*!
further explanation of the purpose of the class
this may contain HTML-Tags
*/
template <
typename T,
		 class MutexPolicy = DummyMutex,
		 template < typename > class AllocType = DefaultAllocatorGlobalType
		 >
class set_wrapper : public Loki::BaseVisitable< Anything >
{
	set_wrapper(const set_wrapper &);

public:
	typedef std::less< T > CompareType;
	typedef T ItemType;
	typedef AllocType< ItemType > allocator_type;
	typedef std::set< T, CompareType, allocator_type > Type;
	typedef Type &TypeRef;
	typedef typename Type::size_type size_type;
	typedef std::pair< typename Type::iterator, bool > InsertResultType;
	typedef typename Type::iterator IteratorType;
	typedef typename Type::const_iterator ConstIteratorType;
	typedef typename Type::const_reverse_iterator ConstReverseIteratorType;

	LOKI_DEFINE_VISITABLE()

	set_wrapper( const char *pName = "set_wrapper_lock" )
		: fpList( NULL )
		, fLock( pName, Storage::Global() )
	{}
	~set_wrapper() {
		LockUnlockEntry aGuard( fLock );
		if ( IntHasList() ) {
			IntGetListPtr()->clear();
		}
		delete fpList;
		fpList = NULL;
	}

	bool AddItem(const ItemType &aItem) {
		// success means it was a new entry, otherwise there is already an item present
		LockUnlockEntry aGuard( fLock );
		return IntAddItem( aItem );
	}

	bool DeleteItem(const ItemType &aItem) {
		swStartTrace(set_wrapper.DeleteItem);
		LockUnlockEntry aGuard( fLock );
		return IntDeleteItem( aItem );
	}

	bool DeleteItem( const ConstIteratorType &aItemPos ) {
		swStartTrace(set_wrapper.DeleteItem);
		LockUnlockEntry aGuard( fLock );
		return IntDeleteItem( aItemPos );
	}

	bool ReplaceItem(const ItemType &aItem) {
		swStartTrace(set_wrapper.ReplaceItem);
		LockUnlockEntry aGuard( fLock );
		IntDeleteItem(aItem);
		return IntAddItem(aItem);
	}

	/*! this is the exact match version of find
		\param
		\return true in case we found the item, rItemPos will then be the iterator pointing to the item */
	bool FindItem(const ItemType &aItem, ConstIteratorType &rItemPos) const {
		swStartTrace(set_wrapper.FindItem);
		bool bFound(false);
		if ( HasList() ) {
			LockUnlockEntry aGuard( *const_cast<MutexPolicy *>(&fLock) );
			rItemPos = IntGetConstListPtr()->find( aItem );
			bFound = ( rItemPos != IntGetConstListPtr()->end() );
		}
		return bFound;
	}

	/*! Find range of items within given boundaries
		\param aItemMin minimum item to find
		\param aItemMax maximum item to find
		\param rItemsBegin iterator position pointing to first element in range
		\param rItemsEnd iterator position pointing to element after last element in range
		\return true in case the range is not empty */
	bool FindItemRange(const ItemType &aItemMin, const ItemType &aItemMax, ConstIteratorType &rItemsBegin, ConstIteratorType &rItemsEnd) const {
		swStartTrace1(set_wrapper.FindItemRange, "find items for range [" << aItemMin.AsString() << "," << aItemMax.AsString() << "]");
		bool bFound(false);
		if ( HasList() ) {
			LockUnlockEntry aGuard( *const_cast<MutexPolicy *>(&fLock) );
			bFound = IntFindItemRange( aItemMin, aItemMax, rItemsBegin, rItemsEnd );
		}
		return bFound;
	}

	/*! Reduce list of items to given boundaries
		\param aItemMin minimum item to find
		\param aItemMax maximum item to find
		\return true in case we reduced the list */
	bool ReduceToRange(const ItemType &aItemMin, const ItemType &aItemMax) {
		swStartTrace1(set_wrapper.ReduceToRange, "reduce items to range [" << aItemMin.AsString() << "," << aItemMax.AsString() << "]");
		bool bModified(false);
		if ( HasList() ) {
			LockUnlockEntry aGuard( fLock );
			bModified = IntReduceToRange( aItemMin, aItemMax );
		}
		return bModified;
	}

	/*! Return iterators spanning all elements
		\param rItemsBegin beginning position of range
		\param rItemsEnd end position of range
		\return true in case the range is not empty */
	bool FullRange(ConstIteratorType &rItemsBegin, ConstIteratorType &rItemsEnd) const {
		swStartTrace(set_wrapper.FullRange);
		bool bFound(false);
		if ( HasList() ) {
			LockUnlockEntry aGuard( *const_cast<MutexPolicy *>(&fLock) );
			rItemsBegin = IntGetConstListPtr()->begin();
			rItemsEnd = IntGetConstListPtr()->end();
			bFound = ( rItemsBegin != rItemsEnd );
		}
		return bFound;
	}

	/*! Return reverse_iterators spanning all elements
		\param rItemsBegin r-beginning position of range
		\param rItemsEnd r-end position of range
		\return true in case the range is not empty */
	bool FullReverseRange(ConstReverseIteratorType &rItemsBegin, ConstReverseIteratorType &rItemsEnd) const {
		swStartTrace(set_wrapper.FullReverseRange);
		bool bFound(false);
		if ( HasList() ) {
			LockUnlockEntry aGuard( *const_cast<MutexPolicy *>(&fLock) );
			rItemsBegin = IntGetConstListPtr()->rbegin();
			rItemsEnd = IntGetConstListPtr()->rend();
			bFound = ( rItemsBegin != rItemsEnd );
		}
		return bFound;
	}

	bool DeleteItemRange(const IteratorType &rItemsBegin, const IteratorType &rItemsEnd) {
		swStartTrace1(set_wrapper.DeleteItemRange, "[" << ( ( rItemsBegin != IntGetConstListPtr()->end() ) ? (*rItemsBegin).AsString() : "<end>" ) << "," << ( ( rItemsEnd != IntGetConstListPtr()->end() ) ? (*rItemsEnd).AsString() : "<end>" ) << ")");
		bool bRet(false);
		if ( HasList() ) {
			LockUnlockEntry aGuard( fLock );
			IntGetCreateListPtr()->erase(rItemsBegin, rItemsEnd);
			bRet = true;
		}
		return bRet;
	}

	bool DeleteItemRange(const ItemType &aItemMin, const ItemType &aItemMax) {
		swStartTrace1(set_wrapper.DeleteItemRange, "deleting items for range [" << aItemMin.AsString() << "," << aItemMax.AsString() << "]");
		bool bRet(false);
		if ( HasList() ) {
			LockUnlockEntry aGuard( fLock );
			IteratorType rItemsBegin, rItemsEnd;
			if ( IntFindItemRange(aItemMin, aItemMax, rItemsBegin, rItemsEnd) ) {
				IntGetCreateListPtr()->erase(rItemsBegin, rItemsEnd);
				bRet = true;
			}
		}
		return bRet;
	}

	void Clear() {
		LockUnlockEntry aGuard( *const_cast<MutexPolicy *>(&fLock) );
		if ( IntHasList() ) {
			IntGetListPtr()->clear();
		}
	}

	size_type Size() const {
		LockUnlockEntry aGuard( *const_cast<MutexPolicy *>(&fLock) );
		size_type sz(0);
		if ( IntHasList() ) {
			sz = IntGetConstListPtr()->size();
		}
		return sz;
	}

	bool HasList() const {
		LockUnlockEntry aGuard( *const_cast<MutexPolicy *>(&fLock) );
		return IntHasList();
	}

	bool IsEnd(const IteratorType &aIter) const {
		LockUnlockEntry aGuard( *const_cast<MutexPolicy *>(&fLock) );
		return ( IntHasList() ? ( aIter == IntGetConstListPtr()->end() ) : true );
	}

	const Type *GetConstListPtr() const {
		LockUnlockEntry aGuard( *const_cast<MutexPolicy *>(&fLock) );
		return IntGetConstListPtr();
	}

	set_wrapper &operator=(const set_wrapper &other) {
		return Assign( other );
	}
	template < class M, template < class > class A >
	set_wrapper &operator=(const set_wrapper<T, M, A>& other) {
		return Assign( other );
	}

	template < class M, template < class > class A >
	set_wrapper &Assign(const set_wrapper<T, M, A>& other) {
		if ( other.HasList() ) {
			LockUnlockEntry aGuard( fLock );
			CopyItems(IntGetCreateListPtr(), other.GetConstListPtr());
		}
		return (*this);
	}

	Type *GetCreateListPtr() {
		LockUnlockEntry aGuard( fLock );
		return IntGetCreateListPtr();
	}

protected:
	bool IntHasList() const {
		const Type *pList( fpList );
		swStatTrace(set_wrapper.IntHasList, "ptr is:" << (long)pList, Storage::Current());
		return ( pList != NULL );
	}

	Type *IntGetListPtr() {
		Type *pList( fpList );
		swStatTrace(set_wrapper.IntGetListPtr, "ptr is:" << (long)pList, Storage::Current());
		return pList;
	}

	const Type *IntGetConstListPtr() const {
		const Type *pList( fpList );
		swStatTrace(set_wrapper.IntGetConstListPtr, "ptr is:" << (long)pList, Storage::Current());
		return pList;
	}

	Type *IntGetCreateListPtr() {
		swStartTrace(set_wrapper.IntGetCreateListPtr);
		if ( !IntHasList() ) {
			fpList = new Type();
		}
		Type *pList( fpList );
		swTrace("ptr is:" << (long)pList);
		return pList;
	}

	/*! Find range of items within given boundaries
		\param aItemMin minimum item to find
		\param aItemMax maximum item to find
		\param rItemsBegin iterator position pointing to first element in range
		\param rItemsEnd iterator position pointing to element after last element in range
		\return true in case the range is not empty */
	bool IntFindItemRange(const ItemType &aItemMin, const ItemType &aItemMax, ConstIteratorType &rItemsBegin, ConstIteratorType &rItemsEnd) const {
		swStartTrace1(set_wrapper.IntFindItemRange, "find items for range [" << aItemMin.AsString() << "," << aItemMax.AsString() << "]");
		bool bFound(false);
		if ( IntHasList() ) {
			ConstIteratorType aEnd( IntGetConstListPtr()->end() );
			rItemsBegin = IntGetConstListPtr()->lower_bound( aItemMin );
			rItemsEnd = IntGetConstListPtr()->upper_bound( aItemMax );
			swTrace("[" << ( ( rItemsBegin != aEnd ) ? (*rItemsBegin).AsString() : "<end>" ) << "," << ( ( rItemsEnd != aEnd ) ? (*rItemsEnd).AsString() : "<end>" ) << ")");
			if ( ( rItemsBegin != aEnd || rItemsEnd != aEnd ) ) {
				// check if values are within range
				// -> begin value must at least be lower or equal the given aItemMax
				bFound = ( *rItemsBegin < aItemMax || !( aItemMax < *rItemsBegin ) );
			}
		}
		return bFound;
	}

	/*! Reduce list of items to given boundaries
		\param aItemMin minimum item to keep
		\param aItemMax maximum item to keep
		\return true in case we reduced the list */
	bool IntReduceToRange(const ItemType &aItemMin, const ItemType &aItemMax) {
		swStartTrace1(set_wrapper.IntReduceToRange, "reduce items to range [" << aItemMin.AsString() << "," << aItemMax.AsString() << "]");
		bool bModified( false );
		if ( IntHasList() ) {
			IteratorType aEnd( IntGetListPtr()->end() ), aBoundPos;
			aBoundPos = IntGetListPtr()->upper_bound( aItemMin );
			if ( ( aBoundPos != aEnd ) && ( aBoundPos != IntGetListPtr()->begin() ) ) {
				swTrace("removing [" << IntGetListPtr()->begin()->AsString() << "," << ( ( aBoundPos != aEnd ) ? aBoundPos->AsString() : "<end>" ) << ")");
				IntGetListPtr()->erase( IntGetListPtr()->begin(), aBoundPos );
				bModified = true;
			}
			aBoundPos = IntGetListPtr()->upper_bound( aItemMax );
			if ( aBoundPos != aEnd ) {
				swTrace("removing [" << aBoundPos->AsString() << ",<end>)");
				IntGetListPtr()->erase( aBoundPos, IntGetListPtr()->end() );
				bModified = true;
			}
		}
		return bModified;
	}

	bool IntAddItem(const ItemType &aItem) {
		InsertResultType aRetCode( IntGetCreateListPtr()->insert(aItem) );
		swStatTrace(set_wrapper.IntAddItem, "Item [" << aItem.AsString() << "] was " << (aRetCode.second ? "" : "not " ) << "successful", Storage::Current());
		// success means it was a new entry, otherwise there is already an item present
		return aRetCode.second;
	}

	bool IntDeleteItem(const ItemType &aItem) {
		swStartTrace(set_wrapper.IntDeleteItem);
		bool bRet(false);
		if ( IntHasList() ) {
			size_type aRetCode( IntGetCreateListPtr()->erase( aItem ) );
			// number of elements == 1 means success
			bRet = ( aRetCode == 1 );
		}
		return bRet;
	}

	bool IntDeleteItem(const ConstIteratorType &aItemPos) {
		swStartTrace(set_wrapper.IntDeleteItem);
		bool bRet(false);
		if ( IntHasList() ) {
			IntGetCreateListPtr()->erase( aItemPos );
			bRet = true;
		}
		return bRet;
	}

private:
	Type *fpList;
	MutexPolicy fLock;
};

template < class AL, class AR >
inline void CopyItems(AL *pThisList, const AR *pOtherList)
{
//	pThisList->reserve(pOtherList->size());
	std::copy(pOtherList->begin(), pOtherList->end(), std::inserter(*pThisList, pThisList->begin()));
}

#endif
<|endoftext|>


<commit_before>#include <iostream>

#include "commandline.h"

int main(int argc, const char * argv[])
{
	std::cout << "Hi, I'm the traffic service" << std::endl;

	traffic::Commandline cmd;
	if (! cmd.parse(argc, argv)) {
		return 1;
	}

	return 0;
}

<commit_msg>Plug the commandline and the server together<commit_after>#include <iostream>
#include <string>

#include "commandline.h"
#include "traffic_server.h"

int main(int argc, const char * argv[])
{
	std::cout << "Hi, I'm the traffic service" << std::endl;

	traffic::Commandline cmd;
	if (! cmd.parse(argc, argv)) {
		return 1;
	}

	traffic::TrafficServer server;

	for (std::string const &address : cmd.addresses()) {
		server.bind("tcp://" + address);
	}

	server.run();

	return 0;
}

<|endoftext|>