<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the S60 port of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used 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.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qmenu.h"
#include "qapplication.h"
#include "qevent.h"
#include "qstyle.h"
#include "qdebug.h"
#include "qwidgetaction.h"
#include <private/qapplication_p.h>
#include <private/qmenu_p.h>
#include <private/qmenubar_p.h>
#include <qt_s60_p.h>
#include <QtCore/qlibrary.h>

#ifdef Q_WS_S60
#include <eikmenub.h>
#include <eikmenup.h>
#include <eikaufty.h>
#include <eikbtgpc.h>
#include <avkon.rsg>
#endif

#if !defined(QT_NO_MENUBAR) && defined(Q_WS_S60)

QT_BEGIN_NAMESPACE

typedef QMultiHash<QWidget *, QMenuBarPrivate *> MenuBarHash;
Q_GLOBAL_STATIC(MenuBarHash, menubars)

#define QT_FIRST_MENU_ITEM 32000

struct SymbianMenuItem
{
    int id;
    CEikMenuPaneItem::SData menuItemData;
    QList<SymbianMenuItem*> children;
    QAction* action;
};

static QList<SymbianMenuItem*> symbianMenus;
static QList<QMenuBar*> nativeMenuBars;
static uint qt_symbian_menu_static_cmd_id = QT_FIRST_MENU_ITEM;
static QPointer<QWidget> widgetWithContextMenu;
static QList<QAction*> contextMenuActionList;
static QAction contextAction(0);
static int contexMenuCommand=0;

bool menuExists()
{
    QWidget *w = qApp->activeWindow();
    QMenuBarPrivate *mb = menubars()->value(w);
    if ((!mb) && !menubars()->count())
        return false;
    return true;
}

static bool hasContextMenu(QWidget* widget)
{
    if (!widget)
        return false;
    const Qt::ContextMenuPolicy policy = widget->contextMenuPolicy();
    if (policy != Qt::NoContextMenu && policy != Qt::PreventContextMenu ) {
        return true;
    }
    return false;
}

static SymbianMenuItem* qt_symbian_find_menu(int id, const QList<SymbianMenuItem*> &parent)
{
    int index=0;
    while (index < parent.count()) {
        SymbianMenuItem* temp = parent[index];
        if (temp->menuItemData.iCascadeId == id)
           return temp;
        else if (temp->menuItemData.iCascadeId != 0) {
            SymbianMenuItem* result = qt_symbian_find_menu( id, temp->children);
            if (result)
                return result;
        }
        index++;
    }
    return 0;
}

static SymbianMenuItem* qt_symbian_find_menu_item(int id, const QList<SymbianMenuItem*> &parent)
{
    int index=0;
    while (index < parent.count()) {
        SymbianMenuItem* temp = parent[index];
        if (temp->menuItemData.iCascadeId != 0) {
            SymbianMenuItem* result = qt_symbian_find_menu_item( id, temp->children);
            if (result)
                return result;
        }
        else if (temp->menuItemData.iCommandId == id)
            return temp;
        index++;

    }
    return 0;
}

static void qt_symbian_insert_action(QSymbianMenuAction* action, QList<SymbianMenuItem*>* parent)
{
    if (action->action->isVisible()) {
        if (action->action->isSeparator())
            return;

        const int underlineShortCut = QApplication::style()->styleHint(QStyle::SH_UnderlineShortcut);
        QString iconText = action->action->iconText();
        TPtrC menuItemText = qt_QString2TPtrC( underlineShortCut ? action->action->text() : iconText);
        if (action->action->menu()) {
            SymbianMenuItem* menuItem = new SymbianMenuItem();
            menuItem->menuItemData.iCascadeId = action->command;
            menuItem->menuItemData.iCommandId = action->command;
            menuItem->menuItemData.iFlags = 0;
            menuItem->menuItemData.iText = menuItemText;
            menuItem->action = action->action;
            if (action->action->menu()->actions().size() == 0 || !action->action->isEnabled() )
                menuItem->menuItemData.iFlags |= EEikMenuItemDimmed;
            parent->append(menuItem);

            if (action->action->menu()->actions().size() > 0) {
                for (int c2= 0; c2 < action->action->menu()->actions().size(); ++c2) {
                    QSymbianMenuAction *symbianAction2 = new QSymbianMenuAction;
                    symbianAction2->action = action->action->menu()->actions().at(c2);
                    QMenu * menu = symbianAction2->action->menu();
                    symbianAction2->command = qt_symbian_menu_static_cmd_id++;
                    qt_symbian_insert_action(symbianAction2, &(menuItem->children));
                }
            }

        } else {
            SymbianMenuItem* menuItem = new SymbianMenuItem();
            menuItem->menuItemData.iCascadeId = 0;
            menuItem->menuItemData.iCommandId = action->command;
            menuItem->menuItemData.iFlags = 0;
            menuItem->menuItemData.iText = menuItemText;
            menuItem->action = action->action;
            if (!action->action->isEnabled()){
                menuItem->menuItemData.iFlags += EEikMenuItemDimmed;
            }

            if (action->action->isCheckable()) {
                if (action->action->isChecked())
                    menuItem->menuItemData.iFlags += EEikMenuItemCheckBox | EEikMenuItemSymbolOn;
                else
                    menuItem->menuItemData.iFlags += EEikMenuItemCheckBox;
            }
            parent->append(menuItem);
        }
    }
}

void deleteAll(QList<SymbianMenuItem*> *items)
{
    while (!items->isEmpty()) {
        SymbianMenuItem* temp = items->takeFirst();
        deleteAll(&temp->children);
        delete temp;
    }
}

static void rebuildMenu()
{
    widgetWithContextMenu = 0;
    QMenuBarPrivate *mb = 0;
    QWidget *w = qApp->activeWindow();
    QWidget* focusWidget = QApplication::focusWidget();
    if (focusWidget) {
        if (hasContextMenu(focusWidget))
            widgetWithContextMenu = focusWidget;
    }

    if (w) {
        mb = menubars()->value(w);
        qt_symbian_menu_static_cmd_id = QT_FIRST_MENU_ITEM;
        deleteAll( &symbianMenus );
        if (!mb)
            return;
        mb->symbian_menubar->rebuild();
    }
}

#ifdef Q_WS_S60
void qt_symbian_show_toplevel( CEikMenuPane* menuPane)
{
    if (!menuExists())
        return;
    rebuildMenu();
    for (int i = 0; i < symbianMenus.count(); ++i)
        QT_TRAP_THROWING(menuPane->AddMenuItemL(symbianMenus.at(i)->menuItemData));
}

void qt_symbian_show_submenu( CEikMenuPane* menuPane, int id)
{
    SymbianMenuItem* menu = qt_symbian_find_menu(id, symbianMenus);
    if (menu) {
        for (int i = 0; i < menu->children.count(); ++i)
            QT_TRAP_THROWING(menuPane->AddMenuItemL(menu->children.at(i)->menuItemData));
    }
}
#endif // Q_WS_S60

void QMenuBarPrivate::symbianCommands(int command)
{
    if (command == contexMenuCommand && !widgetWithContextMenu.isNull()) {
        QContextMenuEvent* event = new QContextMenuEvent(QContextMenuEvent::Keyboard, QPoint(0,0));
        QCoreApplication::postEvent(widgetWithContextMenu, event);
    }

    int size = nativeMenuBars.size();
    for (int i = 0; i < nativeMenuBars.size(); ++i) {
        SymbianMenuItem* menu = qt_symbian_find_menu_item(command, symbianMenus);
        if (!menu)
            continue;

        emit nativeMenuBars.at(i)->triggered(menu->action);
        menu->action->activate(QAction::Trigger);
        break;
    }
}

void QMenuBarPrivate::symbianCreateMenuBar(QWidget *parent)
{
    Q_Q(QMenuBar);
    if (parent && parent->isWindow()){
        menubars()->insert(q->window(), this);
        symbian_menubar = new QSymbianMenuBarPrivate(this);
        nativeMenuBars.append(q);
    }
}

void QMenuBarPrivate::symbianDestroyMenuBar()
{
    Q_Q(QMenuBar);
    int index = nativeMenuBars.indexOf(q);
    nativeMenuBars.removeAt(index);
    menubars()->remove(q->window(), this);
    rebuildMenu();
    if (symbian_menubar)
        delete symbian_menubar;
    symbian_menubar = 0;
}

QMenuBarPrivate::QSymbianMenuBarPrivate::QSymbianMenuBarPrivate(QMenuBarPrivate *menubar)
{
    d = menubar;
}

QMenuBarPrivate::QSymbianMenuBarPrivate::~QSymbianMenuBarPrivate()
{
    deleteAll( &symbianMenus );
    symbianMenus.clear();
    d = 0;
    rebuild();
}

QMenuPrivate::QSymbianMenuPrivate::QSymbianMenuPrivate()
{
}

QMenuPrivate::QSymbianMenuPrivate::~QSymbianMenuPrivate()
{

}

void QMenuPrivate::QSymbianMenuPrivate::addAction(QAction *a, QSymbianMenuAction *before)
{
    QSymbianMenuAction *action = new QSymbianMenuAction;
    action->action = a;
    action->command = qt_symbian_menu_static_cmd_id++;
    addAction(action, before);
}

void QMenuPrivate::QSymbianMenuPrivate::addAction(QSymbianMenuAction *action, QSymbianMenuAction *before)
{
    if (!action)
        return;
    int before_index = actionItems.indexOf(before);
    if (before_index < 0) {
        before = 0;
        before_index = actionItems.size();
    }
    actionItems.insert(before_index, action);
}

void QMenuPrivate::QSymbianMenuPrivate::syncAction(QSymbianMenuAction *)
{
    rebuild();
}

void QMenuPrivate::QSymbianMenuPrivate::removeAction(QSymbianMenuAction *action)
{
    actionItems.removeAll(action);
    delete action;
    action = 0;
    rebuild();
}

void QMenuPrivate::QSymbianMenuPrivate::rebuild(bool)
{
}

void QMenuBarPrivate::QSymbianMenuBarPrivate::addAction(QAction *a, QSymbianMenuAction *before)
{
    QSymbianMenuAction *action = new QSymbianMenuAction;
    action->action = a;
    action->command = qt_symbian_menu_static_cmd_id++;
    addAction(action, before);
}

void QMenuBarPrivate::QSymbianMenuBarPrivate::addAction(QSymbianMenuAction *action, QSymbianMenuAction *before)
{
    if (!action)
        return;
    int before_index = actionItems.indexOf(before);
    if (before_index < 0) {
        before = 0;
        before_index = actionItems.size();
    }
    actionItems.insert(before_index, action);
}

void QMenuBarPrivate::QSymbianMenuBarPrivate::syncAction(QSymbianMenuAction*)
{
    rebuild();
}

void QMenuBarPrivate::QSymbianMenuBarPrivate::removeAction(QSymbianMenuAction *action)
{
    actionItems.removeAll(action);
    delete action;
    rebuild();
}

void QMenuBarPrivate::QSymbianMenuBarPrivate::insertNativeMenuItems(const QList<QAction*> &actions)
{
    for (int i = 0; i <actions.size(); ++i) {
        QSymbianMenuAction *symbianActionTopLevel = new QSymbianMenuAction;
        symbianActionTopLevel->action = actions.at(i);
        symbianActionTopLevel->parent = 0;
        symbianActionTopLevel->command = qt_symbian_menu_static_cmd_id++;
        qt_symbian_insert_action(symbianActionTopLevel, &symbianMenus);
    }
}

void QMenuBarPrivate::QSymbianMenuBarPrivate::rebuild()
{
    contexMenuCommand = 0;
    qt_symbian_menu_static_cmd_id = QT_FIRST_MENU_ITEM;
    deleteAll( &symbianMenus );
    if (d)
        insertNativeMenuItems(d->actions);

    contextMenuActionList.clear();
    if (widgetWithContextMenu) {
        contexMenuCommand = qt_symbian_menu_static_cmd_id;
        contextAction.setText(QMenuBar::tr("Actions"));
        contextMenuActionList.append(&contextAction);
        insertNativeMenuItems(contextMenuActionList);
    }
}
QT_END_NAMESPACE

#endif //QT_NO_MENUBAR
<commit_msg>Added some comments. (cherry picked from commit 4754ebccb9848bff1cb11caab61f58ac2f441b3c)<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the S60 port of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used 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.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qmenu.h"
#include "qapplication.h"
#include "qevent.h"
#include "qstyle.h"
#include "qdebug.h"
#include "qwidgetaction.h"
#include <private/qapplication_p.h>
#include <private/qmenu_p.h>
#include <private/qmenubar_p.h>
#include <qt_s60_p.h>
#include <QtCore/qlibrary.h>

#ifdef Q_WS_S60
#include <eikmenub.h>
#include <eikmenup.h>
#include <eikaufty.h>
#include <eikbtgpc.h>
#include <avkon.rsg>
#endif

#if !defined(QT_NO_MENUBAR) && defined(Q_WS_S60)

QT_BEGIN_NAMESPACE

typedef QMultiHash<QWidget *, QMenuBarPrivate *> MenuBarHash;
Q_GLOBAL_STATIC(MenuBarHash, menubars)

#define QT_FIRST_MENU_ITEM 32000

struct SymbianMenuItem
{
    int id;
    CEikMenuPaneItem::SData menuItemData;
    QList<SymbianMenuItem*> children;
    QAction* action;
};

static QList<SymbianMenuItem*> symbianMenus;
static QList<QMenuBar*> nativeMenuBars;
static uint qt_symbian_menu_static_cmd_id = QT_FIRST_MENU_ITEM;
static QPointer<QWidget> widgetWithContextMenu;
static QList<QAction*> contextMenuActionList;
static QAction contextAction(0);
static int contexMenuCommand=0;

bool menuExists()
{
    QWidget *w = qApp->activeWindow();
    QMenuBarPrivate *mb = menubars()->value(w);
    if ((!mb) && !menubars()->count())
        return false;
    return true;
}

static bool hasContextMenu(QWidget* widget)
{
    if (!widget)
        return false;
    const Qt::ContextMenuPolicy policy = widget->contextMenuPolicy();
    if (policy != Qt::NoContextMenu && policy != Qt::PreventContextMenu ) {
        return true;
    }
    return false;
}

static SymbianMenuItem* qt_symbian_find_menu(int id, const QList<SymbianMenuItem*> &parent)
{
    int index=0;
    while (index < parent.count()) {
        SymbianMenuItem* temp = parent[index];
        if (temp->menuItemData.iCascadeId == id)
           return temp;
        else if (temp->menuItemData.iCascadeId != 0) {
            SymbianMenuItem* result = qt_symbian_find_menu( id, temp->children);
            if (result)
                return result;
        }
        index++;
    }
    return 0;
}

static SymbianMenuItem* qt_symbian_find_menu_item(int id, const QList<SymbianMenuItem*> &parent)
{
    int index=0;
    while (index < parent.count()) {
        SymbianMenuItem* temp = parent[index];
        if (temp->menuItemData.iCascadeId != 0) {
            SymbianMenuItem* result = qt_symbian_find_menu_item( id, temp->children);
            if (result)
                return result;
        }
        else if (temp->menuItemData.iCommandId == id)
            return temp;
        index++;

    }
    return 0;
}

static void qt_symbian_insert_action(QSymbianMenuAction* action, QList<SymbianMenuItem*>* parent)
{
    if (action->action->isVisible()) {
        if (action->action->isSeparator())
            return;

        const int underlineShortCut = QApplication::style()->styleHint(QStyle::SH_UnderlineShortcut);
        QString iconText = action->action->iconText();
        TPtrC menuItemText = qt_QString2TPtrC( underlineShortCut ? action->action->text() : iconText);
        if (action->action->menu()) {
            SymbianMenuItem* menuItem = new SymbianMenuItem();
            menuItem->menuItemData.iCascadeId = action->command;
            menuItem->menuItemData.iCommandId = action->command;
            menuItem->menuItemData.iFlags = 0;
            menuItem->menuItemData.iText = menuItemText;
            menuItem->action = action->action;
            if (action->action->menu()->actions().size() == 0 || !action->action->isEnabled() )
                menuItem->menuItemData.iFlags |= EEikMenuItemDimmed;
            parent->append(menuItem);

            if (action->action->menu()->actions().size() > 0) {
                for (int c2= 0; c2 < action->action->menu()->actions().size(); ++c2) {
                    QSymbianMenuAction *symbianAction2 = new QSymbianMenuAction;
                    symbianAction2->action = action->action->menu()->actions().at(c2);
                    QMenu * menu = symbianAction2->action->menu();
                    symbianAction2->command = qt_symbian_menu_static_cmd_id++;
                    qt_symbian_insert_action(symbianAction2, &(menuItem->children));
                }
            }

        } else {
            SymbianMenuItem* menuItem = new SymbianMenuItem();
            menuItem->menuItemData.iCascadeId = 0;
            menuItem->menuItemData.iCommandId = action->command;
            menuItem->menuItemData.iFlags = 0;
            menuItem->menuItemData.iText = menuItemText;
            menuItem->action = action->action;
            if (!action->action->isEnabled()){
                menuItem->menuItemData.iFlags += EEikMenuItemDimmed;
            }

            if (action->action->isCheckable()) {
                if (action->action->isChecked())
                    menuItem->menuItemData.iFlags += EEikMenuItemCheckBox | EEikMenuItemSymbolOn;
                else
                    menuItem->menuItemData.iFlags += EEikMenuItemCheckBox;
            }
            parent->append(menuItem);
        }
    }
}

void deleteAll(QList<SymbianMenuItem*> *items)
{
    while (!items->isEmpty()) {
        SymbianMenuItem* temp = items->takeFirst();
        deleteAll(&temp->children);
        delete temp;
    }
}

static void rebuildMenu()
{
    widgetWithContextMenu = 0;
    QMenuBarPrivate *mb = 0;
    QWidget *w = qApp->activeWindow();
    QWidget* focusWidget = QApplication::focusWidget();
    if (focusWidget) {
        if (hasContextMenu(focusWidget))
            widgetWithContextMenu = focusWidget;
    }

    if (w) {
        mb = menubars()->value(w);
        qt_symbian_menu_static_cmd_id = QT_FIRST_MENU_ITEM;
        deleteAll( &symbianMenus );
        if (!mb)
            return;
        mb->symbian_menubar->rebuild();
    }
}

#ifdef Q_WS_S60
void qt_symbian_show_toplevel( CEikMenuPane* menuPane)
{
    if (!menuExists())
        return;
    rebuildMenu();
    for (int i = 0; i < symbianMenus.count(); ++i)
        QT_TRAP_THROWING(menuPane->AddMenuItemL(symbianMenus.at(i)->menuItemData));
}

void qt_symbian_show_submenu( CEikMenuPane* menuPane, int id)
{
    SymbianMenuItem* menu = qt_symbian_find_menu(id, symbianMenus);
    if (menu) {
        for (int i = 0; i < menu->children.count(); ++i)
            QT_TRAP_THROWING(menuPane->AddMenuItemL(menu->children.at(i)->menuItemData));
    }
}
#endif // Q_WS_S60

void QMenuBarPrivate::symbianCommands(int command)
{
    if (command == contexMenuCommand && !widgetWithContextMenu.isNull()) {
        QContextMenuEvent* event = new QContextMenuEvent(QContextMenuEvent::Keyboard, QPoint(0,0));
        QCoreApplication::postEvent(widgetWithContextMenu, event);
    }

    int size = nativeMenuBars.size();
    for (int i = 0; i < nativeMenuBars.size(); ++i) {
        SymbianMenuItem* menu = qt_symbian_find_menu_item(command, symbianMenus);
        if (!menu)
            continue;

        emit nativeMenuBars.at(i)->triggered(menu->action);
        menu->action->activate(QAction::Trigger);
        break;
    }
}

void QMenuBarPrivate::symbianCreateMenuBar(QWidget *parent)
{
    Q_Q(QMenuBar);
    if (parent && parent->isWindow()){
        menubars()->insert(q->window(), this);
        symbian_menubar = new QSymbianMenuBarPrivate(this);
        nativeMenuBars.append(q);
    }
}

void QMenuBarPrivate::symbianDestroyMenuBar()
{
    Q_Q(QMenuBar);
    int index = nativeMenuBars.indexOf(q);
    nativeMenuBars.removeAt(index);
    menubars()->remove(q->window(), this);
    rebuildMenu();
    if (symbian_menubar)
        delete symbian_menubar;
    symbian_menubar = 0;
}

QMenuBarPrivate::QSymbianMenuBarPrivate::QSymbianMenuBarPrivate(QMenuBarPrivate *menubar)
{
    d = menubar;
}

QMenuBarPrivate::QSymbianMenuBarPrivate::~QSymbianMenuBarPrivate()
{
    deleteAll( &symbianMenus );
    symbianMenus.clear();
    d = 0;
    rebuild();
}

QMenuPrivate::QSymbianMenuPrivate::QSymbianMenuPrivate()
{
}

QMenuPrivate::QSymbianMenuPrivate::~QSymbianMenuPrivate()
{

}

void QMenuPrivate::QSymbianMenuPrivate::addAction(QAction *a, QSymbianMenuAction *before)
{
    QSymbianMenuAction *action = new QSymbianMenuAction;
    action->action = a;
    action->command = qt_symbian_menu_static_cmd_id++;
    addAction(action, before);
}

void QMenuPrivate::QSymbianMenuPrivate::addAction(QSymbianMenuAction *action, QSymbianMenuAction *before)
{
    if (!action)
        return;
    int before_index = actionItems.indexOf(before);
    if (before_index < 0) {
        before = 0;
        before_index = actionItems.size();
    }
    actionItems.insert(before_index, action);
}

void QMenuPrivate::QSymbianMenuPrivate::syncAction(QSymbianMenuAction *)
{
    rebuild();
}

void QMenuPrivate::QSymbianMenuPrivate::removeAction(QSymbianMenuAction *action)
{
    actionItems.removeAll(action);
    delete action;
    action = 0;
    rebuild();
}

void QMenuPrivate::QSymbianMenuPrivate::rebuild(bool)
{
}

void QMenuBarPrivate::QSymbianMenuBarPrivate::addAction(QAction *a, QSymbianMenuAction *before)
{
    QSymbianMenuAction *action = new QSymbianMenuAction;
    action->action = a;
    action->command = qt_symbian_menu_static_cmd_id++;
    addAction(action, before);
}

void QMenuBarPrivate::QSymbianMenuBarPrivate::addAction(QSymbianMenuAction *action, QSymbianMenuAction *before)
{
    if (!action)
        return;
    int before_index = actionItems.indexOf(before);
    if (before_index < 0) {
        before = 0;
        before_index = actionItems.size();
    }
    actionItems.insert(before_index, action);
}

void QMenuBarPrivate::QSymbianMenuBarPrivate::syncAction(QSymbianMenuAction*)
{
    rebuild();
}

void QMenuBarPrivate::QSymbianMenuBarPrivate::removeAction(QSymbianMenuAction *action)
{
    actionItems.removeAll(action);
    delete action;
    rebuild();
}

void QMenuBarPrivate::QSymbianMenuBarPrivate::insertNativeMenuItems(const QList<QAction*> &actions)
{
    for (int i = 0; i <actions.size(); ++i) {
        QSymbianMenuAction *symbianActionTopLevel = new QSymbianMenuAction;
        symbianActionTopLevel->action = actions.at(i);
        symbianActionTopLevel->parent = 0;
        symbianActionTopLevel->command = qt_symbian_menu_static_cmd_id++;
        qt_symbian_insert_action(symbianActionTopLevel, &symbianMenus);
    }
}

void QMenuBarPrivate::QSymbianMenuBarPrivate::rebuild()
{
    contexMenuCommand = 0;
    qt_symbian_menu_static_cmd_id = QT_FIRST_MENU_ITEM;
    deleteAll( &symbianMenus );
    if (d)
        insertNativeMenuItems(d->actions);

    contextMenuActionList.clear();
    if (widgetWithContextMenu) {
        contexMenuCommand = qt_symbian_menu_static_cmd_id; // Increased inside insertNativeMenuItems
        contextAction.setText(QMenuBar::tr("Actions"));
        contextMenuActionList.append(&contextAction);
        insertNativeMenuItems(contextMenuActionList);
    }
}
QT_END_NAMESPACE

#endif //QT_NO_MENUBAR
<|endoftext|>


<commit_before>#ifndef MRR_PIPE_HXX_
#define MRR_PIPE_HXX_

#include <array>

#include "file_descriptor.hxx"

//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

namespace mrr {
namespace posix {

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

struct pipe
{
  using fd_type = file_descriptor::fd_type;

private:
  void init()
  {
    int fd_[2];
    ::pipe(fd_);
    read = fd_[0];
    write = fd_[1];
  }

public:
  pipe()
  {
    init();
  }

  pipe(pipe&& p)
    : read(p.read.fd), write(p.write.fd)
  {
    p.read.fd = -1;
    p.write.fd = -1;
  }

  pipe& operator =(pipe&& p)
  {
    read = p.read.fd;
    write = p.read.fd;
    p.read.fd = -1;
    p.write.fd = -1;
  }

  pipe(pipe const&) = delete;
  pipe& operator =(pipe const&) = delete;

  ~pipe()
  {
    this->close();
  }

  void close()
  {
    read.close();
    write.close();
  }

  void close_read_end()
  {
    read.close();
  }

  void close_write_end()
  {
    write.close();
  }

  void create()
  {
    this->close();
    init();
  }

  file_descriptor& read_end()
  {
    return read;
  }

  file_descriptor& write_end()
  {
    return write;

  } // file_descriptor& write_end()

private:
  file_descriptor read;
  file_descriptor write;
};

pipe make_pipe()
{
  return pipe();
}

//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

} // namespace posix
} // namespace mrr

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

#endif // #ifndef MRR_PIPE_HXX_
<commit_msg>Fixed move assignment in pipe, forgot to return *this<commit_after>#ifndef MRR_PIPE_HXX_
#define MRR_PIPE_HXX_

#include <array>

#include "file_descriptor.hxx"

//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

namespace mrr {
namespace posix {

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

struct pipe
{
  using fd_type = file_descriptor::fd_type;

private:
  void init()
  {
    int fd_[2];
    ::pipe(fd_);
    read = fd_[0];
    write = fd_[1];
  }

public:
  pipe()
  {
    init();
  }

  pipe(pipe&& p)
    : read(p.read.fd), write(p.write.fd)
  {
    p.read.fd = -1;
    p.write.fd = -1;
  }

  pipe& operator =(pipe&& p)
  {
    read = p.read.fd;
    write = p.read.fd;
    p.read.fd = -1;
    p.write.fd = -1;
    return *this;
  }

  pipe(pipe const&) = delete;
  pipe& operator =(pipe const&) = delete;

  ~pipe()
  {
    this->close();
  }

  void close()
  {
    read.close();
    write.close();
  }

  void close_read_end()
  {
    read.close();
  }

  void close_write_end()
  {
    write.close();
  }

  void create()
  {
    this->close();
    init();
  }

  file_descriptor& read_end()
  {
    return read;
  }

  file_descriptor& write_end()
  {
    return write;

  } // file_descriptor& write_end()

private:
  file_descriptor read;
  file_descriptor write;
};

pipe make_pipe()
{
  return pipe();
}

//m=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

} // namespace posix
} // namespace mrr

//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-

#endif // #ifndef MRR_PIPE_HXX_
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2007  Justin Karneges
 *
 * This 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
 *
 */

#include "irisnetplugin.h"

#include <QtCore>
#include "netnames.h"
#include "qdnssd.h"

class AppleNameProvider;

static QString nameToString(const QByteArray &in)
{
	QStringList parts;
	int at = 0;
	while(at < in.size())
	{
		int len = in[at++];
		parts += QString::fromUtf8(in.mid(at, len));
		at += len;
	}
	return parts.join(".");
}

static XMPP::NameRecord importQDnsSdRecord(const QDnsSd::Record &in)
{
	XMPP::NameRecord out;
	switch(in.rrtype)
	{
		case 1: // A
		{
			quint32 *p = (quint32 *)in.rdata.data();
			out.setAddress(QHostAddress(ntohl(*p)));
		}
		break;

		case 28: // AAAA
		{
			out.setAddress(QHostAddress((quint8 *)in.rdata.data()));
		}
		break;

		case 12: // PTR
		{
			out.setPtr(nameToString(in.rdata));
		}
		break;

		case 10: // NULL
		{
			out.setNull(in.rdata);
		}
		break;

		case 16: // TXT
		{
			QList<QByteArray> txtEntries = QDnsSd::parseTxtRecord(in.rdata);
			if(txtEntries.isEmpty())
				return out;
			out.setTxt(txtEntries);
		}
		break;

		default: // unsupported
		{
			return out;
		}
	}

	out.setOwner(in.name);
	out.setTTL(in.ttl);
	return out;
}

//----------------------------------------------------------------------------
// AppleProvider
//----------------------------------------------------------------------------
class AppleProvider : public XMPP::IrisNetProvider
{
	Q_OBJECT
	Q_INTERFACES(XMPP::IrisNetProvider);
public:
	QDnsSd dns;
	QHash<int,AppleNameProvider*> nameProviderById;

	AppleProvider() :
		dns(this)
	{
		connect(&dns, SIGNAL(queryResult(int, const QDnsSd::QueryResult &)), SLOT(dns_queryResult(int, const QDnsSd::QueryResult &)));
	}

	virtual XMPP::NameProvider *createNameProviderInternet();
	virtual XMPP::NameProvider *createNameProviderLocal();

	int query(AppleNameProvider *p, const QByteArray &name, int qType);
	void stop(int id);

private slots:
	void dns_queryResult(int id, const QDnsSd::QueryResult &result);
};

//----------------------------------------------------------------------------
// AppleNameProvider
//----------------------------------------------------------------------------
class AppleNameProvider : public XMPP::NameProvider
{
	Q_OBJECT
public:
	AppleProvider *global;

	AppleNameProvider(AppleProvider *parent) :
		NameProvider(parent),
		global(parent)
	{
	}

	bool supportsSingle() const
	{
		return false;
	}

	bool supportsLongLived() const
	{
		return true;
	}

	virtual int resolve_start(const QByteArray &name, int qType, bool longLived)
	{
		Q_UNUSED(longLived); // query is always long lived
		return global->dns.query(name, qType);
	}

	virtual void resolve_stop(int id)
	{
		global->dns.stop(id);
	}

	// called by AppleProvider

	void dns_queryResult(int id, const QDnsSd::QueryResult &result)
	{
		if(!result.success)
		{
			emit resolve_error(id, XMPP::NameResolver::ErrorGeneric);
			return;
		}

		QList<XMPP::NameRecord> results;
		foreach(const QDnsSd::Record &rec, result.records)
		{
			XMPP::NameRecord nr = importQDnsSdRecord(rec);

			// unsupported type
			if(nr.isNull())
				continue;

			// if removed, ensure ttl is 0
			if(!rec.added)
				nr.setTtl(0);

			results += nr;
		}

		emit resolve_resultsReady(id, results);
	}
};

// AppleProvider
XMPP::NameProvider *AppleProvider::createNameProviderInternet()
{
	return new AppleNameProvider(this);
}

XMPP::NameProvider *AppleProvider::createNameProviderLocal()
{
	return new AppleNameProvider(this);
}

int AppleProvider::query(AppleNameProvider *p, const QByteArray &name, int qType)
{
	int id = dns.query(name, qType);
	nameProviderById[id] = p;
	return id;
}

void AppleProvider::stop(int id)
{
	nameProviderById.remove(id);
}

void AppleProvider::dns_queryResult(int id, const QDnsSd::QueryResult &result)
{
	nameProviderById[id]->dns_queryResult(id, result);
}

#include "appledns.moc"

#ifdef APPLEDNS_STATIC
IrisNetProvider *irisnet_createAppleProvider()
{
        return new AppleProvider;
}
#else
Q_EXPORT_PLUGIN2(appledns, AppleProvider)
#endif
<commit_msg>fixes...<commit_after>/*
 * Copyright (C) 2007  Justin Karneges
 *
 * This 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
 *
 */

#include "irisnetplugin.h"

#include <QtCore>
#include "netnames.h"
#include "qdnssd.h"

class AppleNameProvider;

static QByteArray nameToDottedString(const QByteArray &in)
{
	QByteArray out;
	int at = 0;
	while(at < in.size())
	{
		int len = in[at++];
		if(len > 0)
			out += in.mid(at, len);
		out += '.';
		at += len;
	}
	return out;
}

static XMPP::NameRecord importQDnsSdRecord(const QDnsSd::Record &in)
{
	XMPP::NameRecord out;
	switch(in.rrtype)
	{
		case 1: // A
		{
			quint32 *p = (quint32 *)in.rdata.data();
			out.setAddress(QHostAddress(ntohl(*p)));
		}
		break;

		case 28: // AAAA
		{
			out.setAddress(QHostAddress((quint8 *)in.rdata.data()));
		}
		break;

		case 12: // PTR
		{
			out.setPtr(nameToDottedString(in.rdata));
		}
		break;

		case 10: // NULL
		{
			out.setNull(in.rdata);
		}
		break;

		case 16: // TXT
		{
			QList<QByteArray> txtEntries = QDnsSd::parseTxtRecord(in.rdata);
			if(txtEntries.isEmpty())
				return out;
			out.setTxt(txtEntries);
		}
		break;

		default: // unsupported
		{
			return out;
		}
	}

	out.setOwner(in.name);
	out.setTtl(in.ttl);
	return out;
}

//----------------------------------------------------------------------------
// AppleProvider
//----------------------------------------------------------------------------
class AppleProvider : public XMPP::IrisNetProvider
{
	Q_OBJECT
	Q_INTERFACES(XMPP::IrisNetProvider);
public:
	QDnsSd dns;
	QHash<int,AppleNameProvider*> nameProviderById;

	AppleProvider() :
		dns(this)
	{
		connect(&dns, SIGNAL(queryResult(int, const QDnsSd::QueryResult &)), SLOT(dns_queryResult(int, const QDnsSd::QueryResult &)));
	}

	virtual XMPP::NameProvider *createNameProviderInternet();
	virtual XMPP::NameProvider *createNameProviderLocal();

	int query(AppleNameProvider *p, const QByteArray &name, int qType);
	void stop(int id);

private slots:
	void dns_queryResult(int id, const QDnsSd::QueryResult &result);
};

//----------------------------------------------------------------------------
// AppleNameProvider
//----------------------------------------------------------------------------
class AppleNameProvider : public XMPP::NameProvider
{
	Q_OBJECT
public:
	AppleProvider *global;

	AppleNameProvider(AppleProvider *parent) :
		NameProvider(parent),
		global(parent)
	{
	}

	bool supportsSingle() const
	{
		return false;
	}

	bool supportsLongLived() const
	{
		return true;
	}

	virtual int resolve_start(const QByteArray &name, int qType, bool longLived)
	{
		Q_UNUSED(longLived); // query is always long lived
		return global->dns.query(name, qType);
	}

	virtual void resolve_stop(int id)
	{
		global->dns.stop(id);
	}

	// called by AppleProvider

	void dns_queryResult(int id, const QDnsSd::QueryResult &result)
	{
		if(!result.success)
		{
			emit resolve_error(id, XMPP::NameResolver::ErrorGeneric);
			return;
		}

		QList<XMPP::NameRecord> results;
		foreach(const QDnsSd::Record &rec, result.records)
		{
			XMPP::NameRecord nr = importQDnsSdRecord(rec);

			// unsupported type
			if(nr.isNull())
				continue;

			// if removed, ensure ttl is 0
			if(!rec.added)
				nr.setTtl(0);

			results += nr;
		}

		emit resolve_resultsReady(id, results);
	}
};

// AppleProvider
XMPP::NameProvider *AppleProvider::createNameProviderInternet()
{
	return new AppleNameProvider(this);
}

XMPP::NameProvider *AppleProvider::createNameProviderLocal()
{
	return new AppleNameProvider(this);
}

int AppleProvider::query(AppleNameProvider *p, const QByteArray &name, int qType)
{
	int id = dns.query(name, qType);
	nameProviderById[id] = p;
	return id;
}

void AppleProvider::stop(int id)
{
	nameProviderById.remove(id);
}

void AppleProvider::dns_queryResult(int id, const QDnsSd::QueryResult &result)
{
	nameProviderById[id]->dns_queryResult(id, result);
}

#include "appledns.moc"

#ifdef APPLEDNS_STATIC
IrisNetProvider *irisnet_createAppleProvider()
{
        return new AppleProvider;
}
#else
Q_EXPORT_PLUGIN2(appledns, AppleProvider)
#endif
<|endoftext|>


<commit_before>#include <v8.h>
#include <node.h>
#include <glib.h>
#include <dbus/dbus.h>
#include <dbus/dbus-glib.h>
#include <dbus/dbus-glib-lowlevel.h>
#include <string>
#include <list>
#include <map>
#include <iostream>

#include "common.h"
#include "dbus.h"
#include "dbus_introspect.h"
#include "dbus_register.h"

using namespace v8;
using namespace dbus_library;

DBusObjectPathVTable vtable = CreateVTable();
char *currentName = NULL;

bool
AppendDictValue(DBusMessageIter *iter, Local<Value> value)
{
	DBusMessageIter value_iter;
	const char *signature;

	if (value->IsBoolean()) {
		signature = DBUS_TYPE_BOOLEAN_AS_STRING;
		dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, signature, &value_iter);

	} else if (value->IsString()) {
		signature = DBUS_TYPE_STRING_AS_STRING;
		dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, signature, &value_iter);

	} else if (value->IsInt32()) {
		signature = DBUS_TYPE_INT32_AS_STRING;
		dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, signature, &value_iter);

	} else if (value->IsUint32()) {
		signature = DBUS_TYPE_UINT32_AS_STRING;
		dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, signature, &value_iter);

	} else if (value->IsNumber()) {
		signature = DBUS_TYPE_DOUBLE_AS_STRING;
		dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, signature, &value_iter);

	} else if (value->IsArray()) {
		dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT,
			DBUS_TYPE_ARRAY_AS_STRING DBUS_TYPE_VARIANT_AS_STRING,
			&value_iter);

	} else if (value->IsObject()) {
		dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT,
			DBUS_TYPE_ARRAY_AS_STRING
			DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
			DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
			DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
			&value_iter);
	}

	EncodeReplyValue(value, &value_iter);

	dbus_message_iter_close_container(iter, &value_iter);

	return TRUE;
}

bool
AppendDictEntry(DBusMessageIter *iter, Local<Value> key, Local<Value> value)
{

	DBusMessageIter dict_iter;

	/* Get key */
	String::Utf8Value key_name_val(key->ToString());
	char *key_str = *key_name_val;

	dbus_message_iter_open_container(iter, DBUS_TYPE_DICT_ENTRY, NULL, &dict_iter);

	/* Key */
	dbus_message_iter_append_basic(&dict_iter, DBUS_TYPE_STRING, &key_str);

	/* Value */
	AppendDictValue(&dict_iter, value);

	dbus_message_iter_close_container(iter, &dict_iter);

	return TRUE;
}

void
GetSignatureFromValue(Local<Value> value, char *_sign)
{
	char *sign = _sign;

	if (value->IsBoolean()) {
		*sign = DBUS_TYPE_BOOLEAN;
		*(sign + 1) = '\0';
	} else if (value->IsString()) {
		*sign = DBUS_TYPE_STRING;
		*(sign + 1) = '\0';
	} else if (value->IsInt32()) {
		*sign = DBUS_TYPE_INT32;
		*(sign + 1) = '\0';
	} else if (value->IsUint32()) {
		*sign = DBUS_TYPE_UINT32;
		*(sign + 1) = '\0';
	} else if (value->IsNumber()) {
		*sign = DBUS_TYPE_DOUBLE;
		*(sign + 1) = '\0';
	} else if (value->IsArray()) {
		*sign = DBUS_TYPE_ARRAY;
		*(sign + 1) = '\0';
	} else if (value->IsObject()) {
/*
		*sign = (int)DBUS_TYPE_ARRAY_AS_STRING;
		*(sign + 1) = (int)DBUS_TYPE_STRING_AS_STRING;
		*(sign + 2) = '\0';
*/
/*
		*sign = DBUS_TYPE_ARRAY;
		*(sign + 1) = '\0';
*/
		*sign = (int)DBUS_TYPE_ARRAY_AS_STRING;
		*(sign + 1) = (int)DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING;
		*(sign + 2) = (int)DBUS_TYPE_STRING_AS_STRING;
		*(sign + 3) = (int)DBUS_TYPE_VARIANT_AS_STRING;
		*(sign + 4) = (int)DBUS_DICT_ENTRY_END_CHAR_AS_STRING;
		*(sign + 5) = '\0';
	}
}

bool
EncodeReplyValue(Local<Value> value, DBusMessageIter *iter)
{
	if (value->IsBoolean()) {
		dbus_bool_t data = value->BooleanValue();

		if (!dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN, &data)) {
			ERROR("Error append boolean\n");
			return false;
		}

	} else if (value->IsString()) {
		String::Utf8Value data_val(value->ToString());
		char *data = *data_val;

		if (!dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &data)) {
			ERROR("Error append string\n");
			return false;
		}

	} else if (value->IsInt32()) {
		dbus_uint64_t data = value->IntegerValue();

		if (!dbus_message_iter_append_basic(iter, DBUS_TYPE_INT32, &data)) {
			ERROR("Error append numeric\n");
			return false;
		}

	} else if (value->IsUint32()) {
		dbus_uint64_t data = value->IntegerValue();

		if (!dbus_message_iter_append_basic(iter, DBUS_TYPE_UINT32, &data)) {
			ERROR("Error append numeric\n");
			return false;
		}

	} else if (value->IsNumber()) {
		double data = value->NumberValue();

		if (!dbus_message_iter_append_basic(iter, DBUS_TYPE_DOUBLE, &data)) {
			ERROR("Error append double\n");
			return false;
		}

	} else if (value->IsArray()) {
        DBusMessageIter subIter;

		/* Create a new container */
		dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY, DBUS_TYPE_VARIANT_AS_STRING, &subIter);

        Local<Array> arrayData = Local<Array>::Cast(value);
        bool no_error_status = true;
		for (unsigned int i = 0; i < arrayData->Length(); ++i) {
			Local<Value> arrayItem = arrayData->Get(i);
			AppendDictValue(&subIter, arrayItem);
		}

        dbus_message_iter_close_container(iter, &subIter);

	} else if (value->IsObject()) {
        Local<Object> value_object = value->ToObject();
        DBusMessageIter subIter;
		char signature[6];

		/* Create a new container */
		dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
			DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
			DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
			DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
			&subIter);

        Local<Array> prop_names = value_object->GetOwnPropertyNames();
        int len = prop_names->Length();

        bool no_error_status = true;
		for (int i = 0; i < len; ++i) {
			Local<Value> prop_name = prop_names->Get(i);
			Local<Value> valueItem = value_object->Get(prop_name);

			AppendDictEntry(&subIter, prop_name, valueItem);
		}

		dbus_message_iter_close_container(iter, &subIter);
	}

	return true;
}

static void
SendMessageReply(DBusConnection *connection, DBusMessage *message, Local<Value> reply_value)
{
	DBusMessageIter iter;
	DBusMessage *reply;
	dbus_uint32_t serial = 0;

	reply = dbus_message_new_method_return(message);

	dbus_message_iter_init_append(reply, &iter);

	if (!EncodeReplyValue(reply_value, &iter)) {
		ERROR("Failed to encode reply value\n");
	}

	/* Send the reply */
	dbus_connection_send(connection, reply, &serial);
	dbus_connection_flush(connection);

	/* Release */
	dbus_message_unref(reply);
}

static DBusHandlerResult
MessageHandler(DBusConnection *connection, DBusMessage *message, void *user_data)
{
	HandleScope scope;
	Persistent<Function> *f(node::cb_unwrap(user_data));
	Handle<Value> args_value = Undefined();
	Local<Value> return_value;

	args_value = decode_reply_messages(message);

	int argc = 3;
	Local<Value> argv[3] = {
		Local<Value>::New(String::New(dbus_message_get_interface(message))),
		Local<Value>::New(String::New(dbus_message_get_member(message))),
		Local<Value>::New(args_value)
	};

	/*
	 * NOTE: Using JavaScript to handle message is easier for development.
	 * If it has performance concern, we can integrate it into C++ code.
	 */
	return_value = (*f)->Call(*f, argc, argv);

	SendMessageReply(connection, message, return_value);

	return DBUS_HANDLER_RESULT_HANDLED;
}

static void
UnregisterMessageHandler(DBusConnection *connection, void *user_data)
{
	node::cb_destroy(node::cb_unwrap(user_data));
}

static inline DBusObjectPathVTable
CreateVTable()
{
	DBusObjectPathVTable vt;

	vt.message_function = MessageHandler;
	vt.unregister_function = UnregisterMessageHandler;

	return vt;
}

Handle<Value>
RequestName(Arguments const &args)
{
	DBusGConnection *connection;

	if (!args[0]->IsObject()) {
		return ThrowException(Exception::TypeError(
			String::New("first argument must be a object (bus)")
		));
	}

	if (!args[1]->IsString()) {
		return ThrowException(Exception::TypeError(
			String::New("first argument must be a string (Bus Name)")
		));
	}

	connection = (DBusGConnection*) External::Unwrap(args[0]->ToObject()->GetInternalField(0));

	/* Name */
	free(currentName);
	currentName = g_strdup(*String::Utf8Value(args[1]->ToString()));

	/* Request bus name */
	dbus_bus_request_name(dbus_g_connection_get_connection(connection),
		currentName, 0, NULL);
//		*String::Utf8Value(args[1]->ToString()), 0, NULL);
	/* TODO: accept flags */
	/* TODO: check last parameter for error */

	return Undefined();
}

Handle<Value>
RegisterObjectPath(Arguments const &args)
{
	HandleScope scope;

	if (!args[0]->IsObject()) {
		return ThrowException(Exception::TypeError(
			String::New("first argument must be a object (bus)")
		));
	}

	if (!args[1]->IsString()) {
		return ThrowException(Exception::TypeError(
			String::New("second argument must be a string (object path)")
		));
	}

	if (!args[2]->IsFunction()) {
		return ThrowException(Exception::TypeError(
			String::New("third argument must be a function (message handler)")
		));
	}

	DBusGConnection *connection = (DBusGConnection*) External::Unwrap(args[0]->ToObject()->GetInternalField(0));

	/* Register message handler for object */
	dbus_bool_t ret = dbus_connection_register_object_path(dbus_g_connection_get_connection(connection),
		*String::Utf8Value(args[1]->ToString()),
		&vtable,
		node::cb_persist(args[2]));
	if (!ret)
		return ThrowException(Exception::Error(
			String::New("Out of Memory")
		));

	return Undefined();
}
<commit_msg>remove uneccessary code<commit_after>#include <v8.h>
#include <node.h>
#include <glib.h>
#include <dbus/dbus.h>
#include <dbus/dbus-glib.h>
#include <dbus/dbus-glib-lowlevel.h>
#include <string>
#include <list>
#include <map>
#include <iostream>

#include "common.h"
#include "dbus.h"
#include "dbus_introspect.h"
#include "dbus_register.h"

using namespace v8;
using namespace dbus_library;

DBusObjectPathVTable vtable = CreateVTable();
char *currentName = NULL;

bool
AppendDictValue(DBusMessageIter *iter, Local<Value> value)
{
	DBusMessageIter value_iter;
	const char *signature;

	if (value->IsBoolean()) {
		signature = DBUS_TYPE_BOOLEAN_AS_STRING;
		dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, signature, &value_iter);

	} else if (value->IsString()) {
		signature = DBUS_TYPE_STRING_AS_STRING;
		dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, signature, &value_iter);

	} else if (value->IsInt32()) {
		signature = DBUS_TYPE_INT32_AS_STRING;
		dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, signature, &value_iter);

	} else if (value->IsUint32()) {
		signature = DBUS_TYPE_UINT32_AS_STRING;
		dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, signature, &value_iter);

	} else if (value->IsNumber()) {
		signature = DBUS_TYPE_DOUBLE_AS_STRING;
		dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT, signature, &value_iter);

	} else if (value->IsArray()) {
		dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT,
			DBUS_TYPE_ARRAY_AS_STRING DBUS_TYPE_VARIANT_AS_STRING,
			&value_iter);

	} else if (value->IsObject()) {
		dbus_message_iter_open_container(iter, DBUS_TYPE_VARIANT,
			DBUS_TYPE_ARRAY_AS_STRING
			DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
			DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
			DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
			&value_iter);
	}

	EncodeReplyValue(value, &value_iter);

	dbus_message_iter_close_container(iter, &value_iter);

	return TRUE;
}

bool
AppendDictEntry(DBusMessageIter *iter, Local<Value> key, Local<Value> value)
{

	DBusMessageIter dict_iter;

	/* Get key */
	String::Utf8Value key_name_val(key->ToString());
	char *key_str = *key_name_val;

	dbus_message_iter_open_container(iter, DBUS_TYPE_DICT_ENTRY, NULL, &dict_iter);

	/* Key */
	dbus_message_iter_append_basic(&dict_iter, DBUS_TYPE_STRING, &key_str);

	/* Value */
	AppendDictValue(&dict_iter, value);

	dbus_message_iter_close_container(iter, &dict_iter);

	return TRUE;
}

bool
EncodeReplyValue(Local<Value> value, DBusMessageIter *iter)
{
	if (value->IsBoolean()) {
		dbus_bool_t data = value->BooleanValue();

		if (!dbus_message_iter_append_basic(iter, DBUS_TYPE_BOOLEAN, &data)) {
			ERROR("Error append boolean\n");
			return false;
		}

	} else if (value->IsString()) {
		String::Utf8Value data_val(value->ToString());
		char *data = *data_val;

		if (!dbus_message_iter_append_basic(iter, DBUS_TYPE_STRING, &data)) {
			ERROR("Error append string\n");
			return false;
		}

	} else if (value->IsInt32()) {
		dbus_uint64_t data = value->IntegerValue();

		if (!dbus_message_iter_append_basic(iter, DBUS_TYPE_INT32, &data)) {
			ERROR("Error append numeric\n");
			return false;
		}

	} else if (value->IsUint32()) {
		dbus_uint64_t data = value->IntegerValue();

		if (!dbus_message_iter_append_basic(iter, DBUS_TYPE_UINT32, &data)) {
			ERROR("Error append numeric\n");
			return false;
		}

	} else if (value->IsNumber()) {
		double data = value->NumberValue();

		if (!dbus_message_iter_append_basic(iter, DBUS_TYPE_DOUBLE, &data)) {
			ERROR("Error append double\n");
			return false;
		}

	} else if (value->IsArray()) {
        DBusMessageIter subIter;

		/* Create a new container */
		dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY, DBUS_TYPE_VARIANT_AS_STRING, &subIter);

        Local<Array> arrayData = Local<Array>::Cast(value);
		for (unsigned int i = 0; i < arrayData->Length(); ++i) {
			Local<Value> arrayItem = arrayData->Get(i);
			AppendDictValue(&subIter, arrayItem);
		}

        dbus_message_iter_close_container(iter, &subIter);

	} else if (value->IsObject()) {
        Local<Object> value_object = value->ToObject();
        DBusMessageIter subIter;

		/* Create a new container */
		dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
			DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
			DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
			DBUS_DICT_ENTRY_END_CHAR_AS_STRING,
			&subIter);

        Local<Array> prop_names = value_object->GetOwnPropertyNames();
        int len = prop_names->Length();

		for (int i = 0; i < len; ++i) {
			Local<Value> prop_name = prop_names->Get(i);
			Local<Value> valueItem = value_object->Get(prop_name);

			AppendDictEntry(&subIter, prop_name, valueItem);
		}

		dbus_message_iter_close_container(iter, &subIter);
	}

	return true;
}

static void
SendMessageReply(DBusConnection *connection, DBusMessage *message, Local<Value> reply_value)
{
	DBusMessageIter iter;
	DBusMessage *reply;
	dbus_uint32_t serial = 0;

	reply = dbus_message_new_method_return(message);

	dbus_message_iter_init_append(reply, &iter);

	if (!EncodeReplyValue(reply_value, &iter)) {
		ERROR("Failed to encode reply value\n");
	}

	/* Send the reply */
	dbus_connection_send(connection, reply, &serial);
	dbus_connection_flush(connection);

	/* Release */
	dbus_message_unref(reply);
}

static DBusHandlerResult
MessageHandler(DBusConnection *connection, DBusMessage *message, void *user_data)
{
	HandleScope scope;
	Persistent<Function> *f(node::cb_unwrap(user_data));
	Handle<Value> args_value = Undefined();
	Local<Value> return_value;

	args_value = decode_reply_messages(message);

	int argc = 3;
	Local<Value> argv[3] = {
		Local<Value>::New(String::New(dbus_message_get_interface(message))),
		Local<Value>::New(String::New(dbus_message_get_member(message))),
		Local<Value>::New(args_value)
	};

	/*
	 * NOTE: Using JavaScript to handle message is easier for development.
	 * If it has performance concern, we can integrate it into C++ code.
	 */
	return_value = (*f)->Call(*f, argc, argv);

	SendMessageReply(connection, message, return_value);

	return DBUS_HANDLER_RESULT_HANDLED;
}

static void
UnregisterMessageHandler(DBusConnection *connection, void *user_data)
{
	node::cb_destroy(node::cb_unwrap(user_data));
}

static inline DBusObjectPathVTable
CreateVTable()
{
	DBusObjectPathVTable vt;

	vt.message_function = MessageHandler;
	vt.unregister_function = UnregisterMessageHandler;

	return vt;
}

Handle<Value>
RequestName(Arguments const &args)
{
	DBusGConnection *connection;

	if (!args[0]->IsObject()) {
		return ThrowException(Exception::TypeError(
			String::New("first argument must be a object (bus)")
		));
	}

	if (!args[1]->IsString()) {
		return ThrowException(Exception::TypeError(
			String::New("first argument must be a string (Bus Name)")
		));
	}

	connection = (DBusGConnection*) External::Unwrap(args[0]->ToObject()->GetInternalField(0));

	/* Name */
	free(currentName);
	currentName = g_strdup(*String::Utf8Value(args[1]->ToString()));

	/* Request bus name */
	dbus_bus_request_name(dbus_g_connection_get_connection(connection),
		currentName, 0, NULL);
//		*String::Utf8Value(args[1]->ToString()), 0, NULL);
	/* TODO: accept flags */
	/* TODO: check last parameter for error */

	return Undefined();
}

Handle<Value>
RegisterObjectPath(Arguments const &args)
{
	HandleScope scope;

	if (!args[0]->IsObject()) {
		return ThrowException(Exception::TypeError(
			String::New("first argument must be a object (bus)")
		));
	}

	if (!args[1]->IsString()) {
		return ThrowException(Exception::TypeError(
			String::New("second argument must be a string (object path)")
		));
	}

	if (!args[2]->IsFunction()) {
		return ThrowException(Exception::TypeError(
			String::New("third argument must be a function (message handler)")
		));
	}

	DBusGConnection *connection = (DBusGConnection*) External::Unwrap(args[0]->ToObject()->GetInternalField(0));

	/* Register message handler for object */
	dbus_bool_t ret = dbus_connection_register_object_path(dbus_g_connection_get_connection(connection),
		*String::Utf8Value(args[1]->ToString()),
		&vtable,
		node::cb_persist(args[2]));
	if (!ret)
		return ThrowException(Exception::Error(
			String::New("Out of Memory")
		));

	return Undefined();
}
<|endoftext|>


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

/* CPU kernel entry points */

/* On x86-64, we can assume SSE2, so avoid the extra kernel and compile this
 * one with SSE2 intrinsics.
 */
#if defined(__x86_64__) || defined(_M_X64)
#  define __KERNEL_SSE2__
#endif

/* When building kernel for native machine detect kernel features from the flags
 * set by compiler.
 */
#ifdef WITH_KERNEL_NATIVE
#  ifdef __SSE2__
#    ifndef __KERNEL_SSE2__
#      define __KERNEL_SSE2__
#    endif
#  endif
#  ifdef __SSE3__
#    define __KERNEL_SSE3__
#  endif
#  ifdef __SSSE3__
#    define __KERNEL_SSSE3__
#  endif
#  ifdef __SSE4_1__
#    define __KERNEL_SSE41__
#  endif
#  ifdef __AVX__
#    define __KERNEL_AVX__
#  endif
#  ifdef __AVX2__
#    define __KERNEL_AVX2__
#  endif
#endif

/* quiet unused define warnings */
#if defined(__KERNEL_SSE2__)
    /* do nothing */
#endif

#include "kernel.h"
#define KERNEL_ARCH cpu
#include "kernel_cpu_impl.h"

CCL_NAMESPACE_BEGIN

/* Memory Copy */

void kernel_const_copy(KernelGlobals *kg, const char *name, void *host, size_t size)
{
	if(strcmp(name, "__data") == 0)
		memcpy(&kg->__data, host, size);
	else
		assert(0);
}

void kernel_tex_copy(KernelGlobals *kg,
                     const char *name,
                     device_ptr mem,
                     size_t width,
                     size_t height,
                     size_t depth,
                     InterpolationType interpolation,
                     ExtensionType extension)
{
	if(0) {
	}

#define KERNEL_TEX(type, ttype, tname) \
	else if(strcmp(name, #tname) == 0) { \
		kg->tname.data = (type*)mem; \
		kg->tname.width = width; \
	}
#define KERNEL_IMAGE_TEX(type, ttype, tname)
#include "kernel_textures.h"

	else if(strstr(name, "__tex_image_float4")) {
		texture_image_float4 *tex = NULL;
		int id = atoi(name + strlen("__tex_image_float4_"));
		int array_index = id;

		if(array_index >= 0 && array_index < TEX_NUM_FLOAT4_CPU) {
			tex = &kg->texture_float4_images[array_index];
		}

		if(tex) {
			tex->data = (float4*)mem;
			tex->dimensions_set(width, height, depth);
			tex->interpolation = interpolation;
			tex->extension = extension;
		}
	}
	else if(strstr(name, "__tex_image_float")) {
		texture_image_float *tex = NULL;
		int id = atoi(name + strlen("__tex_image_float_"));
		int array_index = id - TEX_START_FLOAT_CPU;

		if(array_index >= 0 && array_index < TEX_NUM_FLOAT_CPU) {
			tex = &kg->texture_float_images[array_index];
		}

		if(tex) {
			tex->data = (float*)mem;
			tex->dimensions_set(width, height, depth);
			tex->interpolation = interpolation;
			tex->extension = extension;
		}
	}
	else if(strstr(name, "__tex_image_byte4")) {
		texture_image_uchar4 *tex = NULL;
		int id = atoi(name + strlen("__tex_image_byte4_"));
		int array_index = id - TEX_START_BYTE4_CPU;

		if(array_index >= 0 && array_index < TEX_NUM_BYTE4_CPU) {
			tex = &kg->texture_byte4_images[array_index];
		}

		if(tex) {
			tex->data = (uchar4*)mem;
			tex->dimensions_set(width, height, depth);
			tex->interpolation = interpolation;
			tex->extension = extension;
		}
	}
	else if(strstr(name, "__tex_image_byte")) {
		texture_image_uchar *tex = NULL;
		int id = atoi(name + strlen("__tex_image_byte_"));
		int array_index = id - TEX_START_BYTE_CPU;

		if(array_index >= 0 && array_index < TEX_NUM_BYTE_CPU) {
			tex = &kg->texture_byte_images[array_index];
		}

		if(tex) {
			tex->data = (uchar*)mem;
			tex->dimensions_set(width, height, depth);
			tex->interpolation = interpolation;
			tex->extension = extension;
		}
	}
	else if(strstr(name, "__tex_image_half4")) {
		texture_image_half4 *tex = NULL;
		int id = atoi(name + strlen("__tex_image_half4_"));
		int array_index = id - TEX_START_HALF4_CPU;

		if(array_index >= 0 && array_index < TEX_NUM_HALF4_CPU) {
			tex = &kg->texture_half4_images[array_index];
		}

		if(tex) {
			tex->data = (half4*)mem;
			tex->dimensions_set(width, height, depth);
			tex->interpolation = interpolation;
			tex->extension = extension;
		}
	}
	else if(strstr(name, "__tex_image_half")) {
		texture_image_half *tex = NULL;
		int id = atoi(name + strlen("__tex_image_half_"));
		int array_index = id - TEX_START_HALF_CPU;

		if(array_index >= 0 && array_index < TEX_NUM_HALF_CPU) {
			tex = &kg->texture_half_images[array_index];
		}

		if(tex) {
			tex->data = (half*)mem;
			tex->dimensions_set(width, height, depth);
			tex->interpolation = interpolation;
			tex->extension = extension;
		}
	}
	else
		assert(0);
}

CCL_NAMESPACE_END
<commit_msg>Fix build error with WITH_CYCLES_NATIVE_ONLY and recent AVX2 changes.<commit_after>/*
 * Copyright 2011-2013 Blender Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* CPU kernel entry points */

/* On x86-64, we can assume SSE2, so avoid the extra kernel and compile this
 * one with SSE2 intrinsics.
 */
#if defined(__x86_64__) || defined(_M_X64)
#  define __KERNEL_SSE2__
#endif

/* When building kernel for native machine detect kernel features from the flags
 * set by compiler.
 */
#ifdef WITH_KERNEL_NATIVE
#  ifdef __SSE2__
#    ifndef __KERNEL_SSE2__
#      define __KERNEL_SSE2__
#    endif
#  endif
#  ifdef __SSE3__
#    define __KERNEL_SSE3__
#  endif
#  ifdef __SSSE3__
#    define __KERNEL_SSSE3__
#  endif
#  ifdef __SSE4_1__
#    define __KERNEL_SSE41__
#  endif
#  ifdef __AVX__
#    define __KERNEL_AVX__
#  endif
#  ifdef __AVX2__
#    define __KERNEL_SSE__
#    define __KERNEL_AVX2__
#  endif
#endif

/* quiet unused define warnings */
#if defined(__KERNEL_SSE2__)
    /* do nothing */
#endif

#include "kernel.h"
#define KERNEL_ARCH cpu
#include "kernel_cpu_impl.h"

CCL_NAMESPACE_BEGIN

/* Memory Copy */

void kernel_const_copy(KernelGlobals *kg, const char *name, void *host, size_t size)
{
	if(strcmp(name, "__data") == 0)
		memcpy(&kg->__data, host, size);
	else
		assert(0);
}

void kernel_tex_copy(KernelGlobals *kg,
                     const char *name,
                     device_ptr mem,
                     size_t width,
                     size_t height,
                     size_t depth,
                     InterpolationType interpolation,
                     ExtensionType extension)
{
	if(0) {
	}

#define KERNEL_TEX(type, ttype, tname) \
	else if(strcmp(name, #tname) == 0) { \
		kg->tname.data = (type*)mem; \
		kg->tname.width = width; \
	}
#define KERNEL_IMAGE_TEX(type, ttype, tname)
#include "kernel_textures.h"

	else if(strstr(name, "__tex_image_float4")) {
		texture_image_float4 *tex = NULL;
		int id = atoi(name + strlen("__tex_image_float4_"));
		int array_index = id;

		if(array_index >= 0 && array_index < TEX_NUM_FLOAT4_CPU) {
			tex = &kg->texture_float4_images[array_index];
		}

		if(tex) {
			tex->data = (float4*)mem;
			tex->dimensions_set(width, height, depth);
			tex->interpolation = interpolation;
			tex->extension = extension;
		}
	}
	else if(strstr(name, "__tex_image_float")) {
		texture_image_float *tex = NULL;
		int id = atoi(name + strlen("__tex_image_float_"));
		int array_index = id - TEX_START_FLOAT_CPU;

		if(array_index >= 0 && array_index < TEX_NUM_FLOAT_CPU) {
			tex = &kg->texture_float_images[array_index];
		}

		if(tex) {
			tex->data = (float*)mem;
			tex->dimensions_set(width, height, depth);
			tex->interpolation = interpolation;
			tex->extension = extension;
		}
	}
	else if(strstr(name, "__tex_image_byte4")) {
		texture_image_uchar4 *tex = NULL;
		int id = atoi(name + strlen("__tex_image_byte4_"));
		int array_index = id - TEX_START_BYTE4_CPU;

		if(array_index >= 0 && array_index < TEX_NUM_BYTE4_CPU) {
			tex = &kg->texture_byte4_images[array_index];
		}

		if(tex) {
			tex->data = (uchar4*)mem;
			tex->dimensions_set(width, height, depth);
			tex->interpolation = interpolation;
			tex->extension = extension;
		}
	}
	else if(strstr(name, "__tex_image_byte")) {
		texture_image_uchar *tex = NULL;
		int id = atoi(name + strlen("__tex_image_byte_"));
		int array_index = id - TEX_START_BYTE_CPU;

		if(array_index >= 0 && array_index < TEX_NUM_BYTE_CPU) {
			tex = &kg->texture_byte_images[array_index];
		}

		if(tex) {
			tex->data = (uchar*)mem;
			tex->dimensions_set(width, height, depth);
			tex->interpolation = interpolation;
			tex->extension = extension;
		}
	}
	else if(strstr(name, "__tex_image_half4")) {
		texture_image_half4 *tex = NULL;
		int id = atoi(name + strlen("__tex_image_half4_"));
		int array_index = id - TEX_START_HALF4_CPU;

		if(array_index >= 0 && array_index < TEX_NUM_HALF4_CPU) {
			tex = &kg->texture_half4_images[array_index];
		}

		if(tex) {
			tex->data = (half4*)mem;
			tex->dimensions_set(width, height, depth);
			tex->interpolation = interpolation;
			tex->extension = extension;
		}
	}
	else if(strstr(name, "__tex_image_half")) {
		texture_image_half *tex = NULL;
		int id = atoi(name + strlen("__tex_image_half_"));
		int array_index = id - TEX_START_HALF_CPU;

		if(array_index >= 0 && array_index < TEX_NUM_HALF_CPU) {
			tex = &kg->texture_half_images[array_index];
		}

		if(tex) {
			tex->data = (half*)mem;
			tex->dimensions_set(width, height, depth);
			tex->interpolation = interpolation;
			tex->extension = extension;
		}
	}
	else
		assert(0);
}

CCL_NAMESPACE_END
<|endoftext|>


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

/******************************************************************************
 * Dependencies
 ******************************************************************************/

#include "fileappender.h"

#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QDebug>
#include <QtCore/QTextStream>
#include <QtCore/QTextCodec>
#include "layout.h"
#include "loggingevent.h"

namespace Log4Qt
{

	/**************************************************************************
	 * Declarations
	 **************************************************************************/

	/**************************************************************************
	 * C helper functions
	 **************************************************************************/

	/**************************************************************************
	 * Class implementation: FileAppender
	 **************************************************************************/

	FileAppender::FileAppender(QObject *pParent) :
			WriterAppender(pParent),
			mAppendFile(false),
			mBufferedIo(true),
			mFileName(),
			mpFile(0),
			mpTextStream(0)
	{
	}

	FileAppender::FileAppender(Layout *pLayout,
														 const QString &rFileName,
														 QObject *pParent) :
			WriterAppender(pLayout, pParent),
			mAppendFile(false),
			mBufferedIo(true),
			mFileName(rFileName),
			mpFile(0),
			mpTextStream(0)
	{
	}

	FileAppender::FileAppender(Layout *pLayout,
														 const QString &rFileName,
														 bool append,
														 QObject *pParent) :
			WriterAppender(pLayout, pParent),
			mAppendFile(append),
			mBufferedIo(true),
			mFileName(rFileName),
			mpFile(0),
			mpTextStream(0)
	{
	}

	FileAppender::FileAppender(Layout *pLayout,
														 const QString &rFileName,
														 bool append,
														 bool buffered,
														 QObject *pParent) :
			WriterAppender(pLayout, pParent),
			mAppendFile(append),
			mBufferedIo(buffered),
			mFileName(rFileName),
			mpFile(0),
			mpTextStream(0)
	{
	}

	FileAppender::~FileAppender()
	{
			close();
	}

	void FileAppender::activateOptions()
	{
			QMutexLocker locker(&mObjectGuard);

				if (mFileName.isEmpty())
				{
						LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Activation of Appender '%1' that requires file and has no file set"),
																						 APPENDER_ACTIVATE_MISSING_FILE_ERROR);
						e << name();
						logger()->error(e);
						return;
				}
			closeFile();
			openFile();
			WriterAppender::activateOptions();
	}

	void FileAppender::close()
	{
			QMutexLocker locker(&mObjectGuard);

			if (isClosed())
					return;

			WriterAppender::close();
			closeFile();
	}

	bool FileAppender::checkEntryConditions() const
	{
			// Q_ASSERT_X(, "FileAppender::checkEntryConditions()", "Lock must be held by caller")

			if (!mpFile || !mpTextStream)
			{
					LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Use of appender '%1' without open file"),
																						 APPENDER_NO_OPEN_FILE_ERROR);
					e << name();
					logger()->error(e);
					return false;
			}

			return WriterAppender::checkEntryConditions();
	}

	void FileAppender::closeFile()
	{
			// Q_ASSERT_X(, "FileAppender::closeFile()", "Lock must be held by caller")

			if (mpFile)
					logger()->debug("Closing file '%1' for appender '%2'", mpFile->fileName(), name());

			setWriter(0);
			delete mpTextStream;
			mpTextStream = 0;
			delete mpFile;
			mpFile = 0;
	}

#ifndef QT_NO_DEBUG_STREAM
	QDebug FileAppender::debug(QDebug &rDebug) const
	{
			QString layout_name;
			if (layout())
					layout_name = layout()->name();
			QString codec_name;
			if (encoding())
					codec_name = QLatin1String(encoding()->name());

			rDebug.nospace() << "FileAppender("
					<< "name:" << name() << " "
					<< "appendfile:" << appendFile() << " "
					<< "bufferedio:" << bufferedIo() << " "
					<< "encoding:" << codec_name << " "
					<< "file:" << file() << " "
					<< "filter:" << firstFilter() << " "
					<< "immediateflush:" << immediateFlush() << " "
					<< "isactive:" << isActive() << " "
					<< "isclosed:" << isClosed() << " "
					<< "layout:" << layout_name << " "
					<< "referencecount:" << referenceCount() << " "
					<< "threshold:" << threshold().toString() << " "
					<< "writer:" << writer()
					<< ")";
			return rDebug.space();
	}
#endif // QT_NO_DEBUG_STREAM

		bool FileAppender::handleIoErrors() const
	{
			// Q_ASSERT_X(, "FileAppender::handleIoErrors()", "Lock must be held by caller")

			if (mpFile->error() == QFile::NoError)
					return false;

			LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to write to file '%1' for appender '%2'"),
																				 APPENDER_WRITING_FILE_ERROR);
			e << mFileName << name();
			e.addCausingError(LogError(mpFile->errorString(), mpFile->error()));
			logger()->error(e);
			return true;
	}

	void FileAppender::openFile()
	{
			Q_ASSERT_X(mpFile == 0 && mpTextStream == 0, "FileAppender::openFile()", "Opening file without closing previous file");

			QFileInfo file_info(mFileName);
			QDir parent_dir = file_info.dir();
			if (!parent_dir.exists())
			{
					logger()->trace("Creating missing parent directory for file %1", mFileName);
					QString name = parent_dir.dirName();
					parent_dir.cdUp();
					parent_dir.mkdir(name);
			}

			mpFile = new QFile(mFileName);
			QFile::OpenMode mode = QIODevice::WriteOnly | QIODevice::Text;
			if (mAppendFile)
					mode |= QIODevice::Append;
			else
					mode |= QIODevice::Truncate;
			if (!mBufferedIo)
					mode |= QIODevice::Unbuffered;
			if (!mpFile->open(mode))
			{
					LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to open file '%1' for appender '%2'"),
																						 APPENDER_OPENING_FILE_ERROR);
					e << mFileName << name();
					e.addCausingError(LogError(mpFile->errorString(), mpFile->error()));
					logger()->error(e);
					return;
			}
			mpTextStream = new QTextStream(mpFile);
			setWriter(mpTextStream);
			logger()->debug("Opened file '%1' for appender '%2'", mpFile->fileName(), name());
	}

		bool FileAppender::removeFile(QFile &rFile) const
	{
				if (rFile.remove())
					return true;

			LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to remove file '%1' for appender '%2'"),
																				 APPENDER_REMOVE_FILE_ERROR);
				e << rFile.fileName() << name();
				e.addCausingError(LogError(rFile.errorString(), rFile.error()));
				logger()->error(e);
				return false;
		}

		bool FileAppender::renameFile(QFile &rFile,
																	const QString &rFileName) const
	{
				logger()->debug("Renaming file '%1' to '%2'", rFile.fileName(), rFileName);
				if (rFile.rename(rFileName))
					return true;

				LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to rename file '%1' to '%2' for appender '%3'"),
																				 APPENDER_RENAMING_FILE_ERROR);
				e << rFile.fileName() << rFileName << name();
				e.addCausingError(LogError(rFile.errorString(), rFile.error()));
				logger()->error(e);
				return false;
		}

		/**************************************************************************
	 * Implementation: Operators, Helper
	 **************************************************************************/

} // namespace Log4Qt
<commit_msg>[WIN] Added resolution of environment variables included in file paths<commit_after>/******************************************************************************
 *
 * package:
 * file:        fileappender.cpp
 * created:     September 2007
 * author:      Martin Heinrich
 *
 *
 * Copyright 2007 Martin Heinrich
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ******************************************************************************/

/******************************************************************************
 * Dependencies
 ******************************************************************************/

#include "fileappender.h"

#include <QtCore/QDir>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QDebug>
#include <QtCore/QTextStream>
#include <QtCore/QTextCodec>
#include "layout.h"
#include "loggingevent.h"

// if we are in WIN*
#if defined(__WIN32__) || defined(WIN) || defined(WIN32) || defined(Q_OS_WIN32)
#include <windows.h>
#endif

namespace Log4Qt
{

	/**************************************************************************
	 * Declarations
	 **************************************************************************/

	/**************************************************************************
	 * C helper functions
	 **************************************************************************/

	/**************************************************************************
	 * Class implementation: FileAppender
	 **************************************************************************/

	FileAppender::FileAppender(QObject *pParent) :
			WriterAppender(pParent),
			mAppendFile(false),
			mBufferedIo(true),
			mFileName(),
			mpFile(0),
			mpTextStream(0)
	{
	}

	FileAppender::FileAppender(Layout *pLayout,
														 const QString &rFileName,
														 QObject *pParent) :
			WriterAppender(pLayout, pParent),
			mAppendFile(false),
			mBufferedIo(true),
			mFileName(rFileName),
			mpFile(0),
			mpTextStream(0)
	{
	}

	FileAppender::FileAppender(Layout *pLayout,
														 const QString &rFileName,
														 bool append,
														 QObject *pParent) :
			WriterAppender(pLayout, pParent),
			mAppendFile(append),
			mBufferedIo(true),
			mFileName(rFileName),
			mpFile(0),
			mpTextStream(0)
	{
	}

	FileAppender::FileAppender(Layout *pLayout,
														 const QString &rFileName,
														 bool append,
														 bool buffered,
														 QObject *pParent) :
			WriterAppender(pLayout, pParent),
			mAppendFile(append),
			mBufferedIo(buffered),
			mFileName(rFileName),
			mpFile(0),
			mpTextStream(0)
	{
	}

	FileAppender::~FileAppender()
	{
			close();
	}

	void FileAppender::activateOptions()
	{
			QMutexLocker locker(&mObjectGuard);

				if (mFileName.isEmpty())
				{
						LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Activation of Appender '%1' that requires file and has no file set"),
																						 APPENDER_ACTIVATE_MISSING_FILE_ERROR);
						e << name();
						logger()->error(e);
						return;
				}
			closeFile();
			openFile();
			WriterAppender::activateOptions();
	}

	void FileAppender::close()
	{
			QMutexLocker locker(&mObjectGuard);

			if (isClosed())
					return;

			WriterAppender::close();
			closeFile();
	}

	bool FileAppender::checkEntryConditions() const
	{
			// Q_ASSERT_X(, "FileAppender::checkEntryConditions()", "Lock must be held by caller")

			if (!mpFile || !mpTextStream)
			{
					LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Use of appender '%1' without open file"),
																						 APPENDER_NO_OPEN_FILE_ERROR);
					e << name();
					logger()->error(e);
					return false;
			}

			return WriterAppender::checkEntryConditions();
	}

	void FileAppender::closeFile()
	{
			// Q_ASSERT_X(, "FileAppender::closeFile()", "Lock must be held by caller")

			if (mpFile)
					logger()->debug("Closing file '%1' for appender '%2'", mpFile->fileName(), name());

			setWriter(0);
			delete mpTextStream;
			mpTextStream = 0;
			delete mpFile;
			mpFile = 0;
	}

#ifndef QT_NO_DEBUG_STREAM
	QDebug FileAppender::debug(QDebug &rDebug) const
	{
			QString layout_name;
			if (layout())
					layout_name = layout()->name();
			QString codec_name;
			if (encoding())
					codec_name = QLatin1String(encoding()->name());

			rDebug.nospace() << "FileAppender("
					<< "name:" << name() << " "
					<< "appendfile:" << appendFile() << " "
					<< "bufferedio:" << bufferedIo() << " "
					<< "encoding:" << codec_name << " "
					<< "file:" << file() << " "
					<< "filter:" << firstFilter() << " "
					<< "immediateflush:" << immediateFlush() << " "
					<< "isactive:" << isActive() << " "
					<< "isclosed:" << isClosed() << " "
					<< "layout:" << layout_name << " "
					<< "referencecount:" << referenceCount() << " "
					<< "threshold:" << threshold().toString() << " "
					<< "writer:" << writer()
					<< ")";
			return rDebug.space();
	}
#endif // QT_NO_DEBUG_STREAM

		bool FileAppender::handleIoErrors() const
	{
			// Q_ASSERT_X(, "FileAppender::handleIoErrors()", "Lock must be held by caller")

			if (mpFile->error() == QFile::NoError)
					return false;

			LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to write to file '%1' for appender '%2'"),
																				 APPENDER_WRITING_FILE_ERROR);
			e << mFileName << name();
			e.addCausingError(LogError(mpFile->errorString(), mpFile->error()));
			logger()->error(e);
			return true;
	}

	void FileAppender::openFile()
	{
			Q_ASSERT_X(mpFile == 0 && mpTextStream == 0, "FileAppender::openFile()", "Opening file without closing previous file");

			QFileInfo file_info(mFileName);
			QDir parent_dir = file_info.dir();
			if (!parent_dir.exists())
			{
					logger()->trace("Creating missing parent directory for file %1", mFileName);
					QString name = parent_dir.dirName();
					parent_dir.cdUp();
					parent_dir.mkdir(name);
			}

#if defined(__WIN32__) || defined(WIN) || defined(WIN32) || defined(Q_OS_WIN32)
                        // Let windows resolve any environment variables included in the file path
                        wchar_t buffer[MAX_PATH];
                        if (ExpandEnvironmentStringsW((wchar_t*)mFileName.utf16(), buffer, MAX_PATH)) {
                            mFileName = QString::fromWCharArray(buffer);
                        }
#endif

			mpFile = new QFile(mFileName);
			QFile::OpenMode mode = QIODevice::WriteOnly | QIODevice::Text;
			if (mAppendFile)
					mode |= QIODevice::Append;
			else
					mode |= QIODevice::Truncate;
			if (!mBufferedIo)
					mode |= QIODevice::Unbuffered;
			if (!mpFile->open(mode))
			{
					LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to open file '%1' for appender '%2'"),
																						 APPENDER_OPENING_FILE_ERROR);
					e << mFileName << name();
					e.addCausingError(LogError(mpFile->errorString(), mpFile->error()));
					logger()->error(e);
					return;
			}
			mpTextStream = new QTextStream(mpFile);
			setWriter(mpTextStream);
			logger()->debug("Opened file '%1' for appender '%2'", mpFile->fileName(), name());
	}

		bool FileAppender::removeFile(QFile &rFile) const
	{
				if (rFile.remove())
					return true;

			LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to remove file '%1' for appender '%2'"),
																				 APPENDER_REMOVE_FILE_ERROR);
				e << rFile.fileName() << name();
				e.addCausingError(LogError(rFile.errorString(), rFile.error()));
				logger()->error(e);
				return false;
		}

		bool FileAppender::renameFile(QFile &rFile,
																	const QString &rFileName) const
	{
				logger()->debug("Renaming file '%1' to '%2'", rFile.fileName(), rFileName);
				if (rFile.rename(rFileName))
					return true;

				LogError e = LOG4QT_QCLASS_ERROR(QT_TR_NOOP("Unable to rename file '%1' to '%2' for appender '%3'"),
																				 APPENDER_RENAMING_FILE_ERROR);
				e << rFile.fileName() << rFileName << name();
				e.addCausingError(LogError(rFile.errorString(), rFile.error()));
				logger()->error(e);
				return false;
		}

		/**************************************************************************
	 * Implementation: Operators, Helper
	 **************************************************************************/

} // namespace Log4Qt
<|endoftext|>


<commit_before>#include <map>
#include <iostream>
#include <stdlib.h>
using namespace std;

float deadwood_calc(float biome_data, float elevation_data, float precip_data, float agb_data)
{
	float deadwood;
	if (elevation_data == -32768)
	{
		deadwood = 0;
	}
	else
	{
	if (biome_data == 1 && elevation_data < 2000 && precip_data< 1000) {
		deadwood = agb_data * .02 * .47;}

	else if (biome_data == 1 && elevation_data < 2000 && precip_data< 1600 && precip_data > 1000) {
		deadwood = agb_data * .01 * .47;}

	else if (biome_data == 1 && elevation_data< 2000 && precip_data > 1600) {
		deadwood = agb_data * .06 * .47;}

	else if (biome_data == 1 && elevation_data> 2000) {
		deadwood = agb_data * .07 * .47;}

	else if ((biome_data == 2) || (biome_data == 3)) {
		deadwood = agb_data * .08 * .47;}

	else {
		deadwood = 0;}
	}
	return deadwood;
}

float litter_calc(float biome_data, float elevation_data, float precip_data, float agb_data)
{
	float litter;
        if (elevation_data == -32768)
        {
                litter = 0;
        }
        else
        {

	if (biome_data== 1 && elevation_data < 2000 && precip_data < 1000)
	{
		litter = agb_data * .04 * .37;
	}

	else if (biome_data == 1 && elevation_data < 2000 && precip_data < 1600 && precip_data > 1000)
	{
		litter = agb_data * .01 * .37;
	}

	else if (biome_data == 1 && elevation_data < 2000 && precip_data > 1600)
	{
		litter = agb_data * .01 * .37;
	}

	else if (biome_data == 1 && elevation_data > 2000)
	{
		litter = agb_data * .01 * .37;
	}

	else if ((biome_data == 2) || (biome_data == 3))
	{
		litter = agb_data * .04 * .37;
	}

	else
	{
		litter = 0;
	}
}

	return litter;
}
<commit_msg>if deadwood is on no data elevation and in boreal, calc values<commit_after>#include <map>
#include <iostream>
#include <stdlib.h>
using namespace std;

float deadwood_calc(float biome_data, float elevation_data, float precip_data, float agb_data)
{
	float deadwood;
	if (elevation_data == -32768 && biome_data ==2)
	{
		deadwood = agb_data * .08 * .47;
	}
	else
	{
	if (biome_data == 1 && elevation_data < 2000 && precip_data< 1000) {
		deadwood = agb_data * .02 * .47;}

	else if (biome_data == 1 && elevation_data < 2000 && precip_data< 1600 && precip_data > 1000) {
		deadwood = agb_data * .01 * .47;}

	else if (biome_data == 1 && elevation_data< 2000 && precip_data > 1600) {
		deadwood = agb_data * .06 * .47;}

	else if (biome_data == 1 && elevation_data> 2000) {
		deadwood = agb_data * .07 * .47;}

	else if ((biome_data == 2) || (biome_data == 3)) {
		deadwood = agb_data * .08 * .47;}

	else {
		deadwood = 0;}
	}
	return deadwood;
}

float litter_calc(float biome_data, float elevation_data, float precip_data, float agb_data)
{
	float litter;
        if (elevation_data == -32768)
        {
                litter = 0;
        }
        else
        {

	if (biome_data== 1 && elevation_data < 2000 && precip_data < 1000)
	{
		litter = agb_data * .04 * .37;
	}

	else if (biome_data == 1 && elevation_data < 2000 && precip_data < 1600 && precip_data > 1000)
	{
		litter = agb_data * .01 * .37;
	}

	else if (biome_data == 1 && elevation_data < 2000 && precip_data > 1600)
	{
		litter = agb_data * .01 * .37;
	}

	else if (biome_data == 1 && elevation_data > 2000)
	{
		litter = agb_data * .01 * .37;
	}

	else if ((biome_data == 2) || (biome_data == 3))
	{
		litter = agb_data * .04 * .37;
	}

	else
	{
		litter = 0;
	}
}

	return litter;
}
<|endoftext|>


<commit_before>/*
    knstringfilter.cpp

    KNode, the KDE newsreader
    Copyright (c) 1999-2000 the KNode authors.
    See file AUTHORS for details

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software Foundation,
    Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, US
*/

#include <qlayout.h>
#include <qregexp.h>
#include <qcheckbox.h>
#include <qcombobox.h>
#include <qlineedit.h>

#include <klocale.h>
#include <ksimpleconfig.h>

#include "kngroup.h"
#include "knnntpaccount.h"
#include "knglobals.h"
#include "knconfigmanager.h"
#include "knstringfilter.h"

KNStringFilter& KNStringFilter::operator=(const KNStringFilter &sf)
{
  con=sf.con;
  data=sf.data.copy();
  regExp=sf.regExp;

  return (*this);
}

bool KNStringFilter::doFilter(const QString &s)
{
  bool ret=true;

  if(!expanded.isEmpty()) {
    if(regExp) ret=(s.contains(QRegExp(expanded)) > 0);
    else ret=(s.find(expanded,0,false)!=-1);

    if(!con) ret=!ret;
  }

  return ret;
}

// replace placeholders
void KNStringFilter::expand(KNGroup *g)
{
  KNConfig::Identity  *id=0,
                      *defId=knGlobals.cfgManager->identity(),
                      *grpId=g->identity(),
                      *accId=g->account()->identity();

  expanded = data;

  if ((grpId) && grpId->hasName())
    id=grpId;
  else
    id= ((accId) && accId->hasName())? accId:defId;
  expanded.replace(QRegExp("%MYNAME"), id->name());

  if ((grpId) && grpId->hasEmail())
    id=grpId;
  else
    id= ((accId) && accId->hasEmail())? accId:defId;
  expanded.replace(QRegExp("%MYEMAIL"), id->email());
}

void KNStringFilter::load(KSimpleConfig *conf)
{
  con=conf->readBoolEntry("contains", true);
  data=conf->readEntry("Data");
  regExp=conf->readBoolEntry("regX", false);
}

void KNStringFilter::save(KSimpleConfig *conf)
{
  conf->writeEntry("contains", con);
  conf->writeEntry("Data", data);
  conf->writeEntry("regX", regExp);
}

//===============================================================================

KNStringFilterWidget::KNStringFilterWidget(const QString& title, QWidget *parent)
  : QGroupBox(title, parent)
{
   fType=new QComboBox(this);
  fType->insertItem(i18n("does contain"));
  fType->insertItem(i18n("does NOT contain"));

  fString=new QLineEdit(this);

  regExp=new QCheckBox(i18n("regular expression"), this);

  QGridLayout *topL=new QGridLayout(this, 3,3, 8,5 );
  topL->addRowSpacing(0, fontMetrics().lineSpacing()-4);
  topL->addWidget(fType, 1,0);
  topL->addColSpacing(1, 10);
  topL->addWidget(regExp, 1,1);
  topL->addMultiCellWidget(fString, 2,2, 0,2);
  topL->setColStretch(2,1);
}

KNStringFilterWidget::~KNStringFilterWidget()
{
}

KNStringFilter KNStringFilterWidget::filter()
{
  KNStringFilter ret;
  ret.con=(fType->currentItem()==0);
  ret.data=fString->text().local8Bit();
  ret.regExp=regExp->isChecked();

  return ret;
}

void KNStringFilterWidget::setFilter(KNStringFilter &f)
{
  if(f.con) fType->setCurrentItem(0);
  else fType->setCurrentItem(1);
  fString->setText(f.data);
  regExp->setChecked(f.regExp);
}

void KNStringFilterWidget::clear()
{
  fString->clear();
  fType->setCurrentItem(0);
  regExp->setChecked(false);
}

void KNStringFilterWidget::setStartFocus()
{
  fString->setFocus();
}

// -----------------------------------------------------------------------------+

#include "knstringfilter.moc"

<commit_msg>tiny charset fix<commit_after>/*
    knstringfilter.cpp

    KNode, the KDE newsreader
    Copyright (c) 1999-2000 the KNode authors.
    See file AUTHORS for details

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software Foundation,
    Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, US
*/

#include <qlayout.h>
#include <qregexp.h>
#include <qcheckbox.h>
#include <qcombobox.h>
#include <qlineedit.h>

#include <klocale.h>
#include <ksimpleconfig.h>

#include "kngroup.h"
#include "knnntpaccount.h"
#include "knglobals.h"
#include "knconfigmanager.h"
#include "knstringfilter.h"

KNStringFilter& KNStringFilter::operator=(const KNStringFilter &sf)
{
  con=sf.con;
  data=sf.data.copy();
  regExp=sf.regExp;

  return (*this);
}

bool KNStringFilter::doFilter(const QString &s)
{
  bool ret=true;

  if(!expanded.isEmpty()) {
    if(regExp) ret=(s.contains(QRegExp(expanded)) > 0);
    else ret=(s.find(expanded,0,false)!=-1);

    if(!con) ret=!ret;
  }

  return ret;
}

// replace placeholders
void KNStringFilter::expand(KNGroup *g)
{
  KNConfig::Identity  *id=0,
                      *defId=knGlobals.cfgManager->identity(),
                      *grpId=g->identity(),
                      *accId=g->account()->identity();

  expanded = data;

  if ((grpId) && grpId->hasName())
    id=grpId;
  else
    id= ((accId) && accId->hasName())? accId:defId;
  expanded.replace(QRegExp("%MYNAME"), id->name());

  if ((grpId) && grpId->hasEmail())
    id=grpId;
  else
    id= ((accId) && accId->hasEmail())? accId:defId;
  expanded.replace(QRegExp("%MYEMAIL"), id->email());
}

void KNStringFilter::load(KSimpleConfig *conf)
{
  con=conf->readBoolEntry("contains", true);
  data=conf->readEntry("Data");
  regExp=conf->readBoolEntry("regX", false);
}

void KNStringFilter::save(KSimpleConfig *conf)
{
  conf->writeEntry("contains", con);
  conf->writeEntry("Data", data);
  conf->writeEntry("regX", regExp);
}

//===============================================================================

KNStringFilterWidget::KNStringFilterWidget(const QString& title, QWidget *parent)
  : QGroupBox(title, parent)
{
  fType=new QComboBox(this);
  fType->insertItem(i18n("does contain"));
  fType->insertItem(i18n("does NOT contain"));

  fString=new QLineEdit(this);

  regExp=new QCheckBox(i18n("regular expression"), this);

  QGridLayout *topL=new QGridLayout(this, 3,3, 8,5 );
  topL->addRowSpacing(0, fontMetrics().lineSpacing()-4);
  topL->addWidget(fType, 1,0);
  topL->addColSpacing(1, 10);
  topL->addWidget(regExp, 1,1);
  topL->addMultiCellWidget(fString, 2,2, 0,2);
  topL->setColStretch(2,1);
}

KNStringFilterWidget::~KNStringFilterWidget()
{
}

KNStringFilter KNStringFilterWidget::filter()
{
  KNStringFilter ret;
  ret.con=(fType->currentItem()==0);
  ret.data=fString->text();
  ret.regExp=regExp->isChecked();

  return ret;
}

void KNStringFilterWidget::setFilter(KNStringFilter &f)
{
  if(f.con) fType->setCurrentItem(0);
  else fType->setCurrentItem(1);
  fString->setText(f.data);
  regExp->setChecked(f.regExp);
}

void KNStringFilterWidget::clear()
{
  fString->clear();
  fType->setCurrentItem(0);
  regExp->setChecked(false);
}

void KNStringFilterWidget::setStartFocus()
{
  fString->setFocus();
}

// -----------------------------------------------------------------------------+

#include "knstringfilter.moc"

<|endoftext|>