<commit_before>/* * This file is part of meego-im-framework *
 *
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 * Contact: Nokia Corporation (directui@nokia.com)
 *
 * If you have questions regarding the use of this file, please contact
 * Nokia at directui@nokia.com.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "glibdbusimserverproxy.h"
#include "minputcontext.h"
#include "mdbusglibinputcontextadaptor.h"

#include <QPoint>
#include <QRect>
#include <QString>
#include <QDataStream>
#include <QVariant>
#include <QTimer>
#include <QDateTime>
#include <QDebug>

#include <unistd.h>
#include <sys/types.h>

namespace
{
    const char * const DBusPath("/com/meego/inputmethod/uiserver1");
    const char * const DBusInterface("com.meego.inputmethod.uiserver1");
    const char * const SocketPath = "unix:path=/tmp/meego-im-uiserver/imserver_dbus";
    const int ConnectionRetryInterval(6*1000); // in ms
    const QString icAdaptorPath("/com/meego/inputmethod/inputcontext");

    Maliit::DBusGLib::ConnectionRef toRef(DBusGConnection *connection)
    {
        if (!connection)
            return Maliit::DBusGLib::ConnectionRef();

        return Maliit::DBusGLib::ConnectionRef(connection,
                                               dbus_g_connection_unref);
    }

    bool encodeVariant(GValue *dest, const QVariant &source)
    {
        switch (source.type()) {
        case QVariant::Bool:
            g_value_init(dest, G_TYPE_BOOLEAN);
            g_value_set_boolean(dest, source.toBool());
            return true;
        case QVariant::Int:
            g_value_init(dest, G_TYPE_INT);
            g_value_set_int(dest, source.toInt());
            return true;
        case QVariant::UInt:
            g_value_init(dest, G_TYPE_UINT);
            g_value_set_uint(dest, source.toUInt());
            return true;
        case QVariant::LongLong:
            g_value_init(dest, G_TYPE_INT64);
            g_value_set_int64(dest, source.toLongLong());
            return true;
        case QVariant::ULongLong:
            g_value_init(dest, G_TYPE_UINT64);
            g_value_set_uint64(dest, source.toULongLong());
            return true;
        case QVariant::Double:
            g_value_init(dest, G_TYPE_DOUBLE);
            g_value_set_double(dest, source.toDouble());
            return true;
        case QVariant::String:
            g_value_init(dest, G_TYPE_STRING);
            // string is copied by g_value_set_string
            g_value_set_string(dest, source.toString().toUtf8().constData());
            return true;
        case QVariant::Rect:
            {
                // QRect is encoded as (iiii).
                // This is compatible with QDBusArgument encoding. see more in decoder
                GType structType = dbus_g_type_get_struct("GValueArray",
                                                          G_TYPE_INT, G_TYPE_INT,
                                                          G_TYPE_INT, G_TYPE_INT,
                                                          G_TYPE_INVALID);
                g_value_init(dest, structType);
                GValueArray *array = (GValueArray*)dbus_g_type_specialized_construct(structType);
                if (!array) {
                    qWarning() << Q_FUNC_INFO << "failed to initialize Rect instance";
                }
                g_value_take_boxed(dest, array);
                QRect rect = source.toRect();
                if (!dbus_g_type_struct_set(dest,
                                        0, rect.left(),
                                        1, rect.top(),
                                        2, rect.width(),
                                        3, rect.height(),
                                        G_MAXUINT)) {
                    g_value_unset(dest);
                    qWarning() << Q_FUNC_INFO << "failed to fill Rect instance";
                    return false;
                }
                return true;
            }
        case QMetaType::ULong:
            g_value_init(dest, G_TYPE_ULONG);
            g_value_set_ulong(dest, source.value<ulong>());
            return true;
        default:
            qWarning() << Q_FUNC_INFO << "unsupported data:" << source.type() << source;
            return false;
        }
    }

    void destroyGValue(GValue *value)
    {
        g_value_unset(value);
        g_free(value);
    }

    GHashTable *encodeVariantMap(const QMap<QString, QVariant> &source)
    {
        GHashTable* result = g_hash_table_new_full(&g_str_hash, &g_str_equal,
                                                   &g_free, GDestroyNotify(&destroyGValue));
        Q_FOREACH (QString key, source.keys()) {
            GValue *valueVariant = g_new0(GValue, 1);
            if (!encodeVariant(valueVariant, source[key])) {
                g_free(valueVariant);
                g_hash_table_unref(result);
                return 0;
            }
            g_hash_table_insert(result, g_strdup(key.toUtf8().constData()), valueVariant);
        }
        return result;
    }
}

GlibDBusIMServerProxy::GlibDBusIMServerProxy(QObject *parent)
    : glibObjectProxy(NULL),
      connection(),
      active(true)
{
    Q_UNUSED(parent);

    g_type_init();

    MDBusGlibInputContextAdaptor *adaptor = M_DBUS_GLIB_INPUT_CONTEXT_ADAPTOR(
            g_object_new(M_TYPE_DBUS_GLIB_INPUT_CONTEXT_ADAPTOR, NULL));
    adaptor->imServerConnection = this;

    inputContextAdaptor = G_OBJECT(adaptor);

    dbus_g_thread_init();

    connectToDBus();
}

GlibDBusIMServerProxy::~GlibDBusIMServerProxy()
{
    active = false;

    Q_FOREACH (DBusGProxyCall *callId, pendingResetCalls) {
        dbus_g_proxy_cancel_call(glibObjectProxy, callId);
    }
}

// Auxiliary connection handling.............................................

void GlibDBusIMServerProxy::onDisconnectionTrampoline(DBusGProxy */*proxy*/, gpointer userData)
{
    if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__;
    static_cast<GlibDBusIMServerProxy *>(userData)->onDisconnection();
}

void GlibDBusIMServerProxy::connectToDBus()
{
    if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__;

    GError *error = NULL;

    connection = toRef(dbus_g_connection_open(SocketPath, &error));
    if (!connection) {
        if (error) {
            qWarning("MInputContext: unable to create D-Bus connection: %s", error->message);
            g_error_free(error);
        }
        QTimer::singleShot(ConnectionRetryInterval, this, SLOT(connectToDBus()));
        return;
    }

    glibObjectProxy = dbus_g_proxy_new_for_peer(connection.get(), DBusPath, DBusInterface);
    if (!glibObjectProxy) {
        qWarning("MInputContext: unable to find the D-Bus service.");
        connection.reset();
        QTimer::singleShot(ConnectionRetryInterval, this, SLOT(connectToDBus()));
        return;
    }
    g_signal_connect(G_OBJECT(glibObjectProxy), "destroy", G_CALLBACK(onDisconnectionTrampoline),
                     this);

    dbus_g_connection_register_g_object(connection.get(), icAdaptorPath.toAscii().data(), inputContextAdaptor);

    Q_EMIT connected();
}

void GlibDBusIMServerProxy::onDisconnection()
{
    if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__;

    glibObjectProxy = 0;
    connection.reset();
    Q_EMIT disconnected();

    if (active) {
        QTimer::singleShot(ConnectionRetryInterval, this, SLOT(connectToDBus()));
    }
}

void GlibDBusIMServerProxy::resetNotifyTrampoline(DBusGProxy *proxy, DBusGProxyCall *callId,
                                                  gpointer userData)
{
    static_cast<GlibDBusIMServerProxy *>(userData)->resetNotify(proxy, callId);
}

void GlibDBusIMServerProxy::resetNotify(DBusGProxy *proxy, DBusGProxyCall *callId)
{
    if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__;

    dbus_g_proxy_end_call(proxy, callId, 0, G_TYPE_INVALID);
    pendingResetCalls.remove(callId);
}

// Remote methods............................................................

void GlibDBusIMServerProxy::activateContext()
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "activateContext",
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::showInputMethod()
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "showInputMethod",
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::hideInputMethod()
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "hideInputMethod",
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::mouseClickedOnPreedit(const QPoint &pos, const QRect &preeditRect)
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "mouseClickedOnPreedit",
                               G_TYPE_INT, pos.x(),
                               G_TYPE_INT, pos.y(),
                               G_TYPE_INT, preeditRect.x(),
                               G_TYPE_INT, preeditRect.y(),
                               G_TYPE_INT, preeditRect.width(),
                               G_TYPE_INT, preeditRect.height(),
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::setPreedit(const QString &text, int cursorPos)
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "setPreedit",
                               G_TYPE_STRING, text.toUtf8().data(),
                               G_TYPE_INT, cursorPos,
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::updateWidgetInformation(const QMap<QString, QVariant> &stateInformation,
                                                    bool focusChanged)
{
    if (!glibObjectProxy) {
        return;
    }
    GHashTable *encodedState = encodeVariantMap(stateInformation);
    if (encodedState == 0)
        return;

    GType encodedStateType = dbus_g_type_get_map("GHashTable", G_TYPE_STRING, G_TYPE_VALUE);
    dbus_g_proxy_call_no_reply(glibObjectProxy, "updateWidgetInformation",
                               encodedStateType, encodedState,
                               G_TYPE_BOOLEAN, focusChanged,
                               G_TYPE_INVALID);
    g_hash_table_unref(encodedState);
}

void GlibDBusIMServerProxy::reset(bool requireSynchronization)
{
    if (!glibObjectProxy) {
        return;
    }

    if (requireSynchronization) {
        DBusGProxyCall *resetCall = dbus_g_proxy_begin_call(glibObjectProxy, "reset",
                                                            resetNotifyTrampoline, this,
                                                            0, G_TYPE_INVALID);
        pendingResetCalls.insert(resetCall);
    } else {
        dbus_g_proxy_call_no_reply(glibObjectProxy, "reset",
                                   G_TYPE_INVALID);
    }
}

bool GlibDBusIMServerProxy::pendingResets()
{
    return (pendingResetCalls.size() > 0);
}

void GlibDBusIMServerProxy::appOrientationAboutToChange(int angle)
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "appOrientationAboutToChange",
                               G_TYPE_INT, angle,
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::appOrientationChanged(int angle)
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "appOrientationChanged",
                               G_TYPE_INT, angle,
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::setCopyPasteState(bool copyAvailable, bool pasteAvailable)
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "setCopyPasteState",
                               G_TYPE_BOOLEAN, copyAvailable,
                               G_TYPE_BOOLEAN, pasteAvailable,
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::processKeyEvent(QEvent::Type keyType, Qt::Key keyCode,
                                            Qt::KeyboardModifiers modifiers,
                                            const QString &text, bool autoRepeat, int count,
                                            quint32 nativeScanCode, quint32 nativeModifiers,
                                            unsigned long time)
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "processKeyEvent",
                               G_TYPE_INT, static_cast<int>(keyType),
                               G_TYPE_INT, static_cast<int>(keyCode),
                               G_TYPE_INT, static_cast<int>(modifiers),
                               G_TYPE_STRING, text.toUtf8().data(),
                               G_TYPE_BOOLEAN, autoRepeat, G_TYPE_INT, count,
                               G_TYPE_UINT, nativeScanCode, G_TYPE_UINT, nativeModifiers,
                               G_TYPE_ULONG, time,
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::registerAttributeExtension(int id, const QString &fileName)
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "registerAttributeExtension",
                               G_TYPE_INT, id,
                               G_TYPE_STRING, fileName.toUtf8().data(),
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::unregisterAttributeExtension(int id)
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "unregisterAttributeExtension",
                               G_TYPE_INT, id,
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::setExtendedAttribute(int id, const QString &target, const QString &targetItem,
                                                 const QString &attribute, const QVariant &value)
{
    if (!glibObjectProxy) {
        return;
    }
    GValue valueData = {0, {{0}, {0}}};
    if (!encodeVariant(&valueData, value)) {
        return;
    }

    dbus_g_proxy_call_no_reply(glibObjectProxy, "setExtendedAttribute",
                               G_TYPE_INT, id,
                               G_TYPE_STRING, target.toUtf8().data(),
                               G_TYPE_STRING, targetItem.toUtf8().data(),
                               G_TYPE_STRING, attribute.toUtf8().data(),
                               G_TYPE_VALUE, &valueData,
                               G_TYPE_INVALID);
    g_value_unset(&valueData);
}
<commit_msg>Changes: Use QMetaType::Type instead of QVariant::Type.<commit_after>/* * This file is part of meego-im-framework *
 *
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 * All rights reserved.
 * Contact: Nokia Corporation (directui@nokia.com)
 *
 * If you have questions regarding the use of this file, please contact
 * Nokia at directui@nokia.com.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation
 * and appearing in the file LICENSE.LGPL included in the packaging
 * of this file.
 */

#include "glibdbusimserverproxy.h"
#include "minputcontext.h"
#include "mdbusglibinputcontextadaptor.h"

#include <QPoint>
#include <QRect>
#include <QString>
#include <QDataStream>
#include <QVariant>
#include <QTimer>
#include <QDateTime>
#include <QDebug>

#include <unistd.h>
#include <sys/types.h>

namespace
{
    const char * const DBusPath("/com/meego/inputmethod/uiserver1");
    const char * const DBusInterface("com.meego.inputmethod.uiserver1");
    const char * const SocketPath = "unix:path=/tmp/meego-im-uiserver/imserver_dbus";
    const int ConnectionRetryInterval(6*1000); // in ms
    const QString icAdaptorPath("/com/meego/inputmethod/inputcontext");

    Maliit::DBusGLib::ConnectionRef toRef(DBusGConnection *connection)
    {
        if (!connection)
            return Maliit::DBusGLib::ConnectionRef();

        return Maliit::DBusGLib::ConnectionRef(connection,
                                               dbus_g_connection_unref);
    }

    bool encodeVariant(GValue *dest, const QVariant &source)
    {
        switch (static_cast<QMetaType::Type>(source.type())) {
        case QMetaType::Bool:
            g_value_init(dest, G_TYPE_BOOLEAN);
            g_value_set_boolean(dest, source.toBool());
            return true;
        case QMetaType::Int:
            g_value_init(dest, G_TYPE_INT);
            g_value_set_int(dest, source.toInt());
            return true;
        case QMetaType::UInt:
            g_value_init(dest, G_TYPE_UINT);
            g_value_set_uint(dest, source.toUInt());
            return true;
        case QMetaType::LongLong:
            g_value_init(dest, G_TYPE_INT64);
            g_value_set_int64(dest, source.toLongLong());
            return true;
        case QMetaType::ULongLong:
            g_value_init(dest, G_TYPE_UINT64);
            g_value_set_uint64(dest, source.toULongLong());
            return true;
        case QMetaType::Double:
            g_value_init(dest, G_TYPE_DOUBLE);
            g_value_set_double(dest, source.toDouble());
            return true;
        case QMetaType::QString:
            g_value_init(dest, G_TYPE_STRING);
            // string is copied by g_value_set_string
            g_value_set_string(dest, source.toString().toUtf8().constData());
            return true;
        case QMetaType::QRect:
            {
                // QRect is encoded as (iiii).
                // This is compatible with QDBusArgument encoding. see more in decoder
                GType structType = dbus_g_type_get_struct("GValueArray",
                                                          G_TYPE_INT, G_TYPE_INT,
                                                          G_TYPE_INT, G_TYPE_INT,
                                                          G_TYPE_INVALID);
                g_value_init(dest, structType);
                GValueArray *array = (GValueArray*)dbus_g_type_specialized_construct(structType);
                if (!array) {
                    qWarning() << Q_FUNC_INFO << "failed to initialize Rect instance";
                }
                g_value_take_boxed(dest, array);
                QRect rect = source.toRect();
                if (!dbus_g_type_struct_set(dest,
                                        0, rect.left(),
                                        1, rect.top(),
                                        2, rect.width(),
                                        3, rect.height(),
                                        G_MAXUINT)) {
                    g_value_unset(dest);
                    qWarning() << Q_FUNC_INFO << "failed to fill Rect instance";
                    return false;
                }
                return true;
            }
        case QMetaType::ULong:
            g_value_init(dest, G_TYPE_ULONG);
            g_value_set_ulong(dest, source.value<ulong>());
            return true;
        default:
            qWarning() << Q_FUNC_INFO << "unsupported data:" << source.type() << source;
            return false;
        }
    }

    void destroyGValue(GValue *value)
    {
        g_value_unset(value);
        g_free(value);
    }

    GHashTable *encodeVariantMap(const QMap<QString, QVariant> &source)
    {
        GHashTable* result = g_hash_table_new_full(&g_str_hash, &g_str_equal,
                                                   &g_free, GDestroyNotify(&destroyGValue));
        Q_FOREACH (QString key, source.keys()) {
            GValue *valueVariant = g_new0(GValue, 1);
            if (!encodeVariant(valueVariant, source[key])) {
                g_free(valueVariant);
                g_hash_table_unref(result);
                return 0;
            }
            g_hash_table_insert(result, g_strdup(key.toUtf8().constData()), valueVariant);
        }
        return result;
    }
}

GlibDBusIMServerProxy::GlibDBusIMServerProxy(QObject *parent)
    : glibObjectProxy(NULL),
      connection(),
      active(true)
{
    Q_UNUSED(parent);

    g_type_init();

    MDBusGlibInputContextAdaptor *adaptor = M_DBUS_GLIB_INPUT_CONTEXT_ADAPTOR(
            g_object_new(M_TYPE_DBUS_GLIB_INPUT_CONTEXT_ADAPTOR, NULL));
    adaptor->imServerConnection = this;

    inputContextAdaptor = G_OBJECT(adaptor);

    dbus_g_thread_init();

    connectToDBus();
}

GlibDBusIMServerProxy::~GlibDBusIMServerProxy()
{
    active = false;

    Q_FOREACH (DBusGProxyCall *callId, pendingResetCalls) {
        dbus_g_proxy_cancel_call(glibObjectProxy, callId);
    }
}

// Auxiliary connection handling.............................................

void GlibDBusIMServerProxy::onDisconnectionTrampoline(DBusGProxy */*proxy*/, gpointer userData)
{
    if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__;
    static_cast<GlibDBusIMServerProxy *>(userData)->onDisconnection();
}

void GlibDBusIMServerProxy::connectToDBus()
{
    if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__;

    GError *error = NULL;

    connection = toRef(dbus_g_connection_open(SocketPath, &error));
    if (!connection) {
        if (error) {
            qWarning("MInputContext: unable to create D-Bus connection: %s", error->message);
            g_error_free(error);
        }
        QTimer::singleShot(ConnectionRetryInterval, this, SLOT(connectToDBus()));
        return;
    }

    glibObjectProxy = dbus_g_proxy_new_for_peer(connection.get(), DBusPath, DBusInterface);
    if (!glibObjectProxy) {
        qWarning("MInputContext: unable to find the D-Bus service.");
        connection.reset();
        QTimer::singleShot(ConnectionRetryInterval, this, SLOT(connectToDBus()));
        return;
    }
    g_signal_connect(G_OBJECT(glibObjectProxy), "destroy", G_CALLBACK(onDisconnectionTrampoline),
                     this);

    dbus_g_connection_register_g_object(connection.get(), icAdaptorPath.toAscii().data(), inputContextAdaptor);

    Q_EMIT connected();
}

void GlibDBusIMServerProxy::onDisconnection()
{
    if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__;

    glibObjectProxy = 0;
    connection.reset();
    Q_EMIT disconnected();

    if (active) {
        QTimer::singleShot(ConnectionRetryInterval, this, SLOT(connectToDBus()));
    }
}

void GlibDBusIMServerProxy::resetNotifyTrampoline(DBusGProxy *proxy, DBusGProxyCall *callId,
                                                  gpointer userData)
{
    static_cast<GlibDBusIMServerProxy *>(userData)->resetNotify(proxy, callId);
}

void GlibDBusIMServerProxy::resetNotify(DBusGProxy *proxy, DBusGProxyCall *callId)
{
    if (MInputContext::debug) qDebug() << "MInputContext" << __PRETTY_FUNCTION__;

    dbus_g_proxy_end_call(proxy, callId, 0, G_TYPE_INVALID);
    pendingResetCalls.remove(callId);
}

// Remote methods............................................................

void GlibDBusIMServerProxy::activateContext()
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "activateContext",
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::showInputMethod()
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "showInputMethod",
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::hideInputMethod()
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "hideInputMethod",
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::mouseClickedOnPreedit(const QPoint &pos, const QRect &preeditRect)
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "mouseClickedOnPreedit",
                               G_TYPE_INT, pos.x(),
                               G_TYPE_INT, pos.y(),
                               G_TYPE_INT, preeditRect.x(),
                               G_TYPE_INT, preeditRect.y(),
                               G_TYPE_INT, preeditRect.width(),
                               G_TYPE_INT, preeditRect.height(),
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::setPreedit(const QString &text, int cursorPos)
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "setPreedit",
                               G_TYPE_STRING, text.toUtf8().data(),
                               G_TYPE_INT, cursorPos,
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::updateWidgetInformation(const QMap<QString, QVariant> &stateInformation,
                                                    bool focusChanged)
{
    if (!glibObjectProxy) {
        return;
    }
    GHashTable *encodedState = encodeVariantMap(stateInformation);
    if (encodedState == 0)
        return;

    GType encodedStateType = dbus_g_type_get_map("GHashTable", G_TYPE_STRING, G_TYPE_VALUE);
    dbus_g_proxy_call_no_reply(glibObjectProxy, "updateWidgetInformation",
                               encodedStateType, encodedState,
                               G_TYPE_BOOLEAN, focusChanged,
                               G_TYPE_INVALID);
    g_hash_table_unref(encodedState);
}

void GlibDBusIMServerProxy::reset(bool requireSynchronization)
{
    if (!glibObjectProxy) {
        return;
    }

    if (requireSynchronization) {
        DBusGProxyCall *resetCall = dbus_g_proxy_begin_call(glibObjectProxy, "reset",
                                                            resetNotifyTrampoline, this,
                                                            0, G_TYPE_INVALID);
        pendingResetCalls.insert(resetCall);
    } else {
        dbus_g_proxy_call_no_reply(glibObjectProxy, "reset",
                                   G_TYPE_INVALID);
    }
}

bool GlibDBusIMServerProxy::pendingResets()
{
    return (pendingResetCalls.size() > 0);
}

void GlibDBusIMServerProxy::appOrientationAboutToChange(int angle)
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "appOrientationAboutToChange",
                               G_TYPE_INT, angle,
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::appOrientationChanged(int angle)
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "appOrientationChanged",
                               G_TYPE_INT, angle,
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::setCopyPasteState(bool copyAvailable, bool pasteAvailable)
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "setCopyPasteState",
                               G_TYPE_BOOLEAN, copyAvailable,
                               G_TYPE_BOOLEAN, pasteAvailable,
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::processKeyEvent(QEvent::Type keyType, Qt::Key keyCode,
                                            Qt::KeyboardModifiers modifiers,
                                            const QString &text, bool autoRepeat, int count,
                                            quint32 nativeScanCode, quint32 nativeModifiers,
                                            unsigned long time)
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "processKeyEvent",
                               G_TYPE_INT, static_cast<int>(keyType),
                               G_TYPE_INT, static_cast<int>(keyCode),
                               G_TYPE_INT, static_cast<int>(modifiers),
                               G_TYPE_STRING, text.toUtf8().data(),
                               G_TYPE_BOOLEAN, autoRepeat, G_TYPE_INT, count,
                               G_TYPE_UINT, nativeScanCode, G_TYPE_UINT, nativeModifiers,
                               G_TYPE_ULONG, time,
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::registerAttributeExtension(int id, const QString &fileName)
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "registerAttributeExtension",
                               G_TYPE_INT, id,
                               G_TYPE_STRING, fileName.toUtf8().data(),
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::unregisterAttributeExtension(int id)
{
    if (!glibObjectProxy) {
        return;
    }
    dbus_g_proxy_call_no_reply(glibObjectProxy, "unregisterAttributeExtension",
                               G_TYPE_INT, id,
                               G_TYPE_INVALID);
}

void GlibDBusIMServerProxy::setExtendedAttribute(int id, const QString &target, const QString &targetItem,
                                                 const QString &attribute, const QVariant &value)
{
    if (!glibObjectProxy) {
        return;
    }
    GValue valueData = {0, {{0}, {0}}};
    if (!encodeVariant(&valueData, value)) {
        return;
    }

    dbus_g_proxy_call_no_reply(glibObjectProxy, "setExtendedAttribute",
                               G_TYPE_INT, id,
                               G_TYPE_STRING, target.toUtf8().data(),
                               G_TYPE_STRING, targetItem.toUtf8().data(),
                               G_TYPE_STRING, attribute.toUtf8().data(),
                               G_TYPE_VALUE, &valueData,
                               G_TYPE_INVALID);
    g_value_unset(&valueData);
}
<|endoftext|>


<commit_before>#include "rubymotion.h"
#include "motion-game.h"

/// @class Point < Object
/// A point represents a location in a two-dimensional coordinate system using
/// +x+ and +y+ variables.
///
/// When calling a method that expects a +Point+ object, a 2-element +Array+
/// can be passed instead, as a convenience shortcut. For example,
///   node.location = [10, 20]
/// is the same as
///   point = MG::Point.new
///   point.x = 10
///   point.y = 20
///   node.location = point

VALUE rb_cPoint = Qnil;

extern "C"
VALUE
rb_ccvec2_to_obj(cocos2d::Vec2 _vec2)
{
    cocos2d::Vec2 *vec2 = new cocos2d::Vec2(_vec2);
    // cocos2d::Vec2 does not inherite cocos2d::Ref.
    return rb_class_wrap_new(vec2, rb_cPoint);
}

static VALUE
point_alloc(VALUE rcv, SEL sel)
{
    return rb_ccvec2_to_obj(cocos2d::Vec2());
}

/// @property #x
/// @return [Float] the x coordinate of the point.

static VALUE
point_x(VALUE rcv, SEL sel)
{
    return DBL2NUM(VEC2(rcv)->x);
}

static VALUE
point_x_set(VALUE rcv, SEL sel, VALUE x)
{
    VEC2(rcv)->x = NUM2DBL(x);
    return x;
}

/// @property #y
/// @return [Float] the y coordinate of the point.

static VALUE
point_y(VALUE rcv, SEL sel)
{
    return DBL2NUM(VEC2(rcv)->y);
}

static VALUE
point_y_set(VALUE rcv, SEL sel, VALUE y)
{
    VEC2(rcv)->y = NUM2DBL(y);
    return y;
}

/// @group Helpers

/// @method #+(point)
/// Adds the coordinates of the receiver with the coordinates of the given
/// point object.
/// @param point [Point]
/// @return [Point] A new Point object.

static VALUE
point_plus(VALUE rcv, SEL sel, VALUE obj)
{
    return rb_ccvec2_to_obj(*VEC2(rcv) + rb_any_to_ccvec2(obj));
}

/// @method #-(point)
/// Substracts the coordinates of the receiver with the coordinates of the given
/// point object.
/// @param point [Point]
/// @return [Point] A new Point object.

static VALUE
point_minus(VALUE rcv, SEL sel, VALUE obj)
{
    return rb_ccvec2_to_obj(*VEC2(rcv) - rb_any_to_ccvec2(obj));
}

static VALUE
point_inspect(VALUE rcv, SEL sel)
{
    auto vec = VEC2(rcv);
    char buf[100];
    snprintf(buf, sizeof buf, "[%f, %f]", vec->x, vec->y);
    return RSTRING_NEW(buf);
}

/// @class Size < Object
/// A size represents the dimensions of width and height of an object.
///
/// When calling a method that expects a +Size+ object, a 2-element +Array+
/// can be passed instead, as a convenience shortcut. For example,
///   node.size = [200, 400]
/// is the same as
///   size = MG::Size.new
///   size.x = 200
///   size.y = 400
///   node.size = size

VALUE rb_cSize = Qnil;

extern "C"
VALUE
rb_ccsize_to_obj(cocos2d::Size _size)
{
    cocos2d::Size *size = new cocos2d::Size(_size);
    // cocos2d::Size does not inherite cocos2d::Ref.
    return rb_class_wrap_new(size, rb_cSize);
}

static VALUE
size_alloc(VALUE rcv, SEL sel)
{
    return rb_ccsize_to_obj(cocos2d::Size());
}

/// @property #width
/// @return [Float] the size width.

static VALUE
size_width(VALUE rcv, SEL sel)
{
    return DBL2NUM(SIZE(rcv)->width);
}

static VALUE
size_width_set(VALUE rcv, SEL sel, VALUE obj)
{
    SIZE(rcv)->width = NUM2DBL(obj);
    return obj;
}

/// @property #height
/// @return [Float] the size height.

static VALUE
size_height(VALUE rcv, SEL sel)
{
    return DBL2NUM(SIZE(rcv)->height);
}

static VALUE
size_height_set(VALUE rcv, SEL sel, VALUE obj)
{
    SIZE(rcv)->height = NUM2DBL(obj);
    return obj;
}

/// @group Helpers

/// @method #+(size)
/// Adds the dimensions of the receiver with the dimensions of the given
/// size object.
/// @param size [Size]
/// @return [Size] a new Size object.

static VALUE
size_plus(VALUE rcv, SEL sel, VALUE obj)
{
    return rb_ccsize_to_obj(*SIZE(rcv) + rb_any_to_ccsize(obj));
}

/// @method #-(size)
/// Substracts the dimensions of the receiver with the dimensions of the given
/// size object.
/// @param size [Size]
/// @return [Size] a new Size object.

static VALUE
size_minus(VALUE rcv, SEL sel, VALUE obj)
{
    return rb_ccsize_to_obj(*SIZE(rcv) - rb_any_to_ccsize(obj));
}

/// @method #/(delta)
/// Divides the dimensions of the receiver with the given number.
/// @param delta [Float] the number to divide the receiver with.
/// @return [Size] a new Size object.

static VALUE
size_div(VALUE rcv, SEL sel, VALUE obj)
{
    return rb_ccsize_to_obj(*SIZE(rcv) / NUM2DBL(obj));
}

/// @method #*(delta)
/// Multiplies the dimensions of the receiver with the given number.
/// @param delta [Float] the number to multiply the receiver with.
/// @return [Size] a new Size object.

static VALUE
size_mul(VALUE rcv, SEL sel, VALUE obj)
{
    return rb_ccsize_to_obj(*SIZE(rcv) * NUM2DBL(obj));
}

static VALUE
size_inspect(VALUE rcv, SEL sel)
{
    auto vec = SIZE(rcv);
    char buf[100];
    snprintf(buf, sizeof buf, "[%f, %f]", vec->width, vec->height);
    return RSTRING_NEW(buf);
}

/// @class Color < Object
/// A color represents the color, and sometimes opacity (alpha) of an object.
///
/// When calling a method that expects a +Color+ object, a 3-element +Array+
/// (red-green-blue) or 4-element +Array+ (red-green-blue-alpha) can be passed
/// instead, as a convenience shortcut. For example,
///   node.color = [0.2, 0.3, 0.4]
/// is the same as
///   color = MG::Color.new
///   color.red = 0.2
///   color.green = 0.3
///   color.blue = 0.4
///   node.color = color
/// Alternatively, a +Symbol+ corresponding to a basic color name can be
/// provided. For example,
///   node.color = :red
/// is the same as
///   color = MG::Color.new
///   color.red = 1.0
///   color.green = color.blue = 0
///   node.color = color
/// Currently, the following symbols are supported: +:white+, +:black+, +:red+,
/// +:green+ and +:blue+.
/// The +MG::Color.new+ constructor will return the black color.

VALUE rb_cColor = Qnil;

extern "C"
VALUE
rb_cccolor4_to_obj(cocos2d::Color4B _color)
{
    cocos2d::Color4B *color = new cocos2d::Color4B(_color);
    // cocos2d::Color4B does not inherite cocos2d::Ref.
    return rb_class_wrap_new(color, rb_cColor);
}

static VALUE
color_alloc(VALUE rcv, SEL sel)
{
    return rb_cccolor4_to_obj(cocos2d::Color4B::BLACK);
}

/// @property #red
/// @return [Float] the red portion of the color, from +0.0+ to +1.0+.

static VALUE
color_red(VALUE rcv, SEL sel)
{
    return BYTE2NUM(COLOR(rcv)->r);
}

static VALUE
color_red_set(VALUE rcv, SEL sel, VALUE val)
{
    COLOR(rcv)->r = NUM2BYTE(val);
    return val;
}

/// @property #green
/// @return [Float] the green portion of the color, from +0.0+ to +1.0+.

static VALUE
color_green(VALUE rcv, SEL sel)
{
    return BYTE2NUM(COLOR(rcv)->g);
}

static VALUE
color_green_set(VALUE rcv, SEL sel, VALUE val)
{
    COLOR(rcv)->g = NUM2BYTE(val);
    return val;
}

/// @property #blue
/// @return [Float] the blue portion of the color, from +0.0+ to +1.0+.

static VALUE
color_blue(VALUE rcv, SEL sel)
{
    return BYTE2NUM(COLOR(rcv)->b);
}

static VALUE
color_blue_set(VALUE rcv, SEL sel, VALUE val)
{
    COLOR(rcv)->b = NUM2BYTE(val);
    return val;
}

/// @property #alpha
/// @return [Float] the alpha portion of the color, from +0.0+ to +1.0+.

static VALUE
color_alpha(VALUE rcv, SEL sel)
{
    return BYTE2NUM(COLOR(rcv)->a);
}

static VALUE
color_alpha_set(VALUE rcv, SEL sel, VALUE val)
{
    COLOR(rcv)->a = NUM2BYTE(val);
    return val;
}

static VALUE
color_inspect(VALUE rcv, SEL sel)
{
    auto color = COLOR(rcv);
    char buf[100];
    snprintf(buf, sizeof buf, "#<Color Red:%d Green:%d Blue:%d Alpha:%d>",
	    color->r, color->g, color->b, color->a);
    return RSTRING_NEW(buf);
}

extern "C"
void
Init_Types(void)
{
    rb_cPoint = rb_define_class_under(rb_mMC, "Point", rb_cObject);

    rb_define_singleton_method(rb_cPoint, "alloc", point_alloc, 0);
    rb_define_method(rb_cPoint, "x", point_x, 0);
    rb_define_method(rb_cPoint, "x=", point_x_set, 1);
    rb_define_method(rb_cPoint, "y", point_y, 0);
    rb_define_method(rb_cPoint, "y=", point_y_set, 1);
    rb_define_method(rb_cPoint, "+", point_plus, 1);
    rb_define_method(rb_cPoint, "-", point_minus, 1);
    rb_define_method(rb_cPoint, "inspect", point_inspect, 0);

    rb_cSize = rb_define_class_under(rb_mMC, "Size", rb_cObject);

    rb_define_singleton_method(rb_cSize, "alloc", size_alloc, 0);
    rb_define_method(rb_cSize, "width", size_width, 0);
    rb_define_method(rb_cSize, "width=", size_width_set, 1);
    rb_define_method(rb_cSize, "height", size_height, 0);
    rb_define_method(rb_cSize, "height=", size_height_set, 1);
    rb_define_method(rb_cSize, "+", size_plus, 1);
    rb_define_method(rb_cSize, "-", size_minus, 1);
    rb_define_method(rb_cSize, "/", size_div, 1);
    rb_define_method(rb_cSize, "*", size_mul, 1);
    rb_define_method(rb_cSize, "inspect", size_inspect, 0);

    rb_cColor = rb_define_class_under(rb_mMC, "Color", rb_cObject);

    rb_define_singleton_method(rb_cColor, "alloc", color_alloc, 0);
    rb_define_method(rb_cColor, "red", color_red, 0);
    rb_define_method(rb_cColor, "red=", color_red_set, 1);
    rb_define_method(rb_cColor, "green", color_green, 0);
    rb_define_method(rb_cColor, "green=", color_green_set, 1);
    rb_define_method(rb_cColor, "blue", color_blue, 0);
    rb_define_method(rb_cColor, "blue=", color_blue_set, 1);
    rb_define_method(rb_cColor, "alpha", color_alpha, 0);
    rb_define_method(rb_cColor, "alpha=", color_alpha_set, 1);
    rb_define_method(rb_cColor, "inspect", color_inspect, 0);
}
<commit_msg>Adds get_distance to Point<commit_after>#include "rubymotion.h"
#include "motion-game.h"

/// @class Point < Object
/// A point represents a location in a two-dimensional coordinate system using
/// +x+ and +y+ variables.
///
/// When calling a method that expects a +Point+ object, a 2-element +Array+
/// can be passed instead, as a convenience shortcut. For example,
///   node.location = [10, 20]
/// is the same as
///   point = MG::Point.new
///   point.x = 10
///   point.y = 20
///   node.location = point

VALUE rb_cPoint = Qnil;

extern "C"
VALUE
rb_ccvec2_to_obj(cocos2d::Vec2 _vec2)
{
    cocos2d::Vec2 *vec2 = new cocos2d::Vec2(_vec2);
    // cocos2d::Vec2 does not inherite cocos2d::Ref.
    return rb_class_wrap_new(vec2, rb_cPoint);
}

static VALUE
point_alloc(VALUE rcv, SEL sel)
{
    return rb_ccvec2_to_obj(cocos2d::Vec2());
}

/// @property #x
/// @return [Float] the x coordinate of the point.

static VALUE
point_x(VALUE rcv, SEL sel)
{
    return DBL2NUM(VEC2(rcv)->x);
}

static VALUE
point_x_set(VALUE rcv, SEL sel, VALUE x)
{
    VEC2(rcv)->x = NUM2DBL(x);
    return x;
}

/// @property #y
/// @return [Float] the y coordinate of the point.

static VALUE
point_y(VALUE rcv, SEL sel)
{
    return DBL2NUM(VEC2(rcv)->y);
}

static VALUE
point_y_set(VALUE rcv, SEL sel, VALUE y)
{
    VEC2(rcv)->y = NUM2DBL(y);
    return y;
}

/// @group Helpers

/// @method #+(point)
/// Adds the coordinates of the receiver with the coordinates of the given
/// point object.
/// @param point [Point]
/// @return [Point] A new Point object.

static VALUE
point_plus(VALUE rcv, SEL sel, VALUE obj)
{
    return rb_ccvec2_to_obj(*VEC2(rcv) + rb_any_to_ccvec2(obj));
}

/// @method #-(point)
/// Substracts the coordinates of the receiver with the coordinates of the given
/// point object.
/// @param point [Point]
/// @return [Point] A new Point object.

static VALUE
point_minus(VALUE rcv, SEL sel, VALUE obj)
{
    return rb_ccvec2_to_obj(*VEC2(rcv) - rb_any_to_ccvec2(obj));
}

/// @method #get_distance(point)
/// Calculates the distance between two points.
/// @param point [Point]
/// @return [Float] the distance.

static VALUE
point_get_distance(VALUE rcv, SEL sel, VALUE obj)
{
    return DBL2NUM(VEC2(rcv)->getDistance(rb_any_to_ccvec2(obj)));
}

static VALUE
point_inspect(VALUE rcv, SEL sel)
{
    auto vec = VEC2(rcv);
    char buf[100];
    snprintf(buf, sizeof buf, "[%f, %f]", vec->x, vec->y);
    return RSTRING_NEW(buf);
}

/// @class Size < Object
/// A size represents the dimensions of width and height of an object.
///
/// When calling a method that expects a +Size+ object, a 2-element +Array+
/// can be passed instead, as a convenience shortcut. For example,
///   node.size = [200, 400]
/// is the same as
///   size = MG::Size.new
///   size.x = 200
///   size.y = 400
///   node.size = size

VALUE rb_cSize = Qnil;

extern "C"
VALUE
rb_ccsize_to_obj(cocos2d::Size _size)
{
    cocos2d::Size *size = new cocos2d::Size(_size);
    // cocos2d::Size does not inherite cocos2d::Ref.
    return rb_class_wrap_new(size, rb_cSize);
}

static VALUE
size_alloc(VALUE rcv, SEL sel)
{
    return rb_ccsize_to_obj(cocos2d::Size());
}

/// @property #width
/// @return [Float] the size width.

static VALUE
size_width(VALUE rcv, SEL sel)
{
    return DBL2NUM(SIZE(rcv)->width);
}

static VALUE
size_width_set(VALUE rcv, SEL sel, VALUE obj)
{
    SIZE(rcv)->width = NUM2DBL(obj);
    return obj;
}

/// @property #height
/// @return [Float] the size height.

static VALUE
size_height(VALUE rcv, SEL sel)
{
    return DBL2NUM(SIZE(rcv)->height);
}

static VALUE
size_height_set(VALUE rcv, SEL sel, VALUE obj)
{
    SIZE(rcv)->height = NUM2DBL(obj);
    return obj;
}

/// @group Helpers

/// @method #+(size)
/// Adds the dimensions of the receiver with the dimensions of the given
/// size object.
/// @param size [Size]
/// @return [Size] a new Size object.

static VALUE
size_plus(VALUE rcv, SEL sel, VALUE obj)
{
    return rb_ccsize_to_obj(*SIZE(rcv) + rb_any_to_ccsize(obj));
}

/// @method #-(size)
/// Substracts the dimensions of the receiver with the dimensions of the given
/// size object.
/// @param size [Size]
/// @return [Size] a new Size object.

static VALUE
size_minus(VALUE rcv, SEL sel, VALUE obj)
{
    return rb_ccsize_to_obj(*SIZE(rcv) - rb_any_to_ccsize(obj));
}

/// @method #/(delta)
/// Divides the dimensions of the receiver with the given number.
/// @param delta [Float] the number to divide the receiver with.
/// @return [Size] a new Size object.

static VALUE
size_div(VALUE rcv, SEL sel, VALUE obj)
{
    return rb_ccsize_to_obj(*SIZE(rcv) / NUM2DBL(obj));
}

/// @method #*(delta)
/// Multiplies the dimensions of the receiver with the given number.
/// @param delta [Float] the number to multiply the receiver with.
/// @return [Size] a new Size object.

static VALUE
size_mul(VALUE rcv, SEL sel, VALUE obj)
{
    return rb_ccsize_to_obj(*SIZE(rcv) * NUM2DBL(obj));
}

static VALUE
size_inspect(VALUE rcv, SEL sel)
{
    auto vec = SIZE(rcv);
    char buf[100];
    snprintf(buf, sizeof buf, "[%f, %f]", vec->width, vec->height);
    return RSTRING_NEW(buf);
}

/// @class Color < Object
/// A color represents the color, and sometimes opacity (alpha) of an object.
///
/// When calling a method that expects a +Color+ object, a 3-element +Array+
/// (red-green-blue) or 4-element +Array+ (red-green-blue-alpha) can be passed
/// instead, as a convenience shortcut. For example,
///   node.color = [0.2, 0.3, 0.4]
/// is the same as
///   color = MG::Color.new
///   color.red = 0.2
///   color.green = 0.3
///   color.blue = 0.4
///   node.color = color
/// Alternatively, a +Symbol+ corresponding to a basic color name can be
/// provided. For example,
///   node.color = :red
/// is the same as
///   color = MG::Color.new
///   color.red = 1.0
///   color.green = color.blue = 0
///   node.color = color
/// Currently, the following symbols are supported: +:white+, +:black+, +:red+,
/// +:green+ and +:blue+.
/// The +MG::Color.new+ constructor will return the black color.

VALUE rb_cColor = Qnil;

extern "C"
VALUE
rb_cccolor4_to_obj(cocos2d::Color4B _color)
{
    cocos2d::Color4B *color = new cocos2d::Color4B(_color);
    // cocos2d::Color4B does not inherite cocos2d::Ref.
    return rb_class_wrap_new(color, rb_cColor);
}

static VALUE
color_alloc(VALUE rcv, SEL sel)
{
    return rb_cccolor4_to_obj(cocos2d::Color4B::BLACK);
}

/// @property #red
/// @return [Float] the red portion of the color, from +0.0+ to +1.0+.

static VALUE
color_red(VALUE rcv, SEL sel)
{
    return BYTE2NUM(COLOR(rcv)->r);
}

static VALUE
color_red_set(VALUE rcv, SEL sel, VALUE val)
{
    COLOR(rcv)->r = NUM2BYTE(val);
    return val;
}

/// @property #green
/// @return [Float] the green portion of the color, from +0.0+ to +1.0+.

static VALUE
color_green(VALUE rcv, SEL sel)
{
    return BYTE2NUM(COLOR(rcv)->g);
}

static VALUE
color_green_set(VALUE rcv, SEL sel, VALUE val)
{
    COLOR(rcv)->g = NUM2BYTE(val);
    return val;
}

/// @property #blue
/// @return [Float] the blue portion of the color, from +0.0+ to +1.0+.

static VALUE
color_blue(VALUE rcv, SEL sel)
{
    return BYTE2NUM(COLOR(rcv)->b);
}

static VALUE
color_blue_set(VALUE rcv, SEL sel, VALUE val)
{
    COLOR(rcv)->b = NUM2BYTE(val);
    return val;
}

/// @property #alpha
/// @return [Float] the alpha portion of the color, from +0.0+ to +1.0+.

static VALUE
color_alpha(VALUE rcv, SEL sel)
{
    return BYTE2NUM(COLOR(rcv)->a);
}

static VALUE
color_alpha_set(VALUE rcv, SEL sel, VALUE val)
{
    COLOR(rcv)->a = NUM2BYTE(val);
    return val;
}

static VALUE
color_inspect(VALUE rcv, SEL sel)
{
    auto color = COLOR(rcv);
    char buf[100];
    snprintf(buf, sizeof buf, "#<Color Red:%d Green:%d Blue:%d Alpha:%d>",
	    color->r, color->g, color->b, color->a);
    return RSTRING_NEW(buf);
}

extern "C"
void
Init_Types(void)
{
    rb_cPoint = rb_define_class_under(rb_mMC, "Point", rb_cObject);

    rb_define_singleton_method(rb_cPoint, "alloc", point_alloc, 0);
    rb_define_method(rb_cPoint, "x", point_x, 0);
    rb_define_method(rb_cPoint, "x=", point_x_set, 1);
    rb_define_method(rb_cPoint, "y", point_y, 0);
    rb_define_method(rb_cPoint, "y=", point_y_set, 1);
    rb_define_method(rb_cPoint, "+", point_plus, 1);
    rb_define_method(rb_cPoint, "-", point_minus, 1);
    rb_define_method(rb_cPoint, "get_distance", point_get_distance, 1);
    rb_define_method(rb_cPoint, "inspect", point_inspect, 0);

    rb_cSize = rb_define_class_under(rb_mMC, "Size", rb_cObject);

    rb_define_singleton_method(rb_cSize, "alloc", size_alloc, 0);
    rb_define_method(rb_cSize, "width", size_width, 0);
    rb_define_method(rb_cSize, "width=", size_width_set, 1);
    rb_define_method(rb_cSize, "height", size_height, 0);
    rb_define_method(rb_cSize, "height=", size_height_set, 1);
    rb_define_method(rb_cSize, "+", size_plus, 1);
    rb_define_method(rb_cSize, "-", size_minus, 1);
    rb_define_method(rb_cSize, "/", size_div, 1);
    rb_define_method(rb_cSize, "*", size_mul, 1);
    rb_define_method(rb_cSize, "inspect", size_inspect, 0);

    rb_cColor = rb_define_class_under(rb_mMC, "Color", rb_cObject);

    rb_define_singleton_method(rb_cColor, "alloc", color_alloc, 0);
    rb_define_method(rb_cColor, "red", color_red, 0);
    rb_define_method(rb_cColor, "red=", color_red_set, 1);
    rb_define_method(rb_cColor, "green", color_green, 0);
    rb_define_method(rb_cColor, "green=", color_green_set, 1);
    rb_define_method(rb_cColor, "blue", color_blue, 0);
    rb_define_method(rb_cColor, "blue=", color_blue_set, 1);
    rb_define_method(rb_cColor, "alpha", color_alpha, 0);
    rb_define_method(rb_cColor, "alpha=", color_alpha_set, 1);
    rb_define_method(rb_cColor, "inspect", color_inspect, 0);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: WinFileOpenImpl.hxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: vg $ $Date: 2005-02-16 15:35:01 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _WINFILEOPENIMPL_HXX_
#define _WINFILEOPENIMPL_HXX_

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _COM_SUN_STAR_UI_DIALOGS_XEXTENDEDFILEPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_FILEPICKEREVENT_HPP_
#include <com/sun/star/ui/dialogs/FilePickerEvent.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERGROUPMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterGroupManager.hpp>
#endif

#ifndef _FILTER_CONTAINER_HXX_
#include "FilterContainer.hxx"
#endif

#ifndef _FILEOPENDLG_HXX_
#include "FileOpenDlg.hxx"
#endif

#ifndef _PREVIEWADAPTER_HXX_
#include "previewadapter.hxx"
#endif

#ifndef _HELPPOPUPWINDOW_HXX_
#include "helppopupwindow.hxx"
#endif

#ifndef _CUSTOMCONTROL_HXX_
#include "customcontrol.hxx"
#endif

#ifndef _CUSTOMCONTROLFACTORY_HXX_
#include "customcontrolfactory.hxx"
#endif

#include <utility>
#include <memory>
#include <vector>

#ifndef _OSL_CONDITN_HXX_
#include <osl/conditn.hxx>
#endif

//------------------------------------------------------------------------
// deklarations
//------------------------------------------------------------------------

// forward declaration
class CFilePicker;
class CFilePickerState;
class CExecuteFilePickerState;
class CNonExecuteFilePickerState;

class CWinFileOpenImpl : public CFileOpenDialog
{
public:
    CWinFileOpenImpl(
        CFilePicker* aFilePicker,
        sal_Bool bFileOpenDialog = sal_True,
        sal_uInt32 dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
        sal_uInt32 dwTemplateId = 0,
        HINSTANCE hInstance = 0 );

    virtual ~CWinFileOpenImpl( );

    //-----------------------------------------------------------------------------------------
    // XExecutableDialog
    //-----------------------------------------------------------------------------------------

    virtual sal_Int16 SAL_CALL execute(  ) throw( ::com::sun::star::uno::RuntimeException );

    //-----------------------------------------------------------------------------------------
    // XFilePicker
    //-----------------------------------------------------------------------------------------

    virtual void SAL_CALL setDefaultName( const ::rtl::OUString& aName )
        throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getFiles(  )
        throw(::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL setDisplayDirectory( const ::rtl::OUString& aDirectory )
        throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );

    virtual ::rtl::OUString SAL_CALL getDisplayDirectory( ) throw ( ::com::sun::star::uno::RuntimeException );

    //-----------------------------------------------------------------------------------------
    // XFilterManager
    //-----------------------------------------------------------------------------------------

    virtual void SAL_CALL appendFilter( const ::rtl::OUString& aTitle, const ::rtl::OUString& aFilter )
        throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL setCurrentFilter( const ::rtl::OUString& aTitle )
        throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );

    virtual ::rtl::OUString  SAL_CALL getCurrentFilter( )
        throw( ::com::sun::star::uno::RuntimeException );

    //-----------------------------------------------------------------------------------------
    // XFilterGroupManager
    //-----------------------------------------------------------------------------------------

    virtual void SAL_CALL appendFilterGroup( const ::rtl::OUString& sGroupTitle, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::StringPair >& aFilters )
        throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    //-----------------------------------------------------------------------------------------
    // XFilePickerControlAccess
    //-----------------------------------------------------------------------------------------

    virtual void SAL_CALL setValue( sal_Int16 aControlId, sal_Int16 aControlAction, const ::com::sun::star::uno::Any& aValue )
        throw( ::com::sun::star::uno::RuntimeException );

    virtual ::com::sun::star::uno::Any SAL_CALL getValue( sal_Int16 aControlId, sal_Int16 aControlAction )
        throw( ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL enableControl( sal_Int16 aControlId, sal_Bool bEnable )
        throw( ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL setLabel( sal_Int16 aControlId, const ::rtl::OUString& aLabel )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::rtl::OUString SAL_CALL getLabel( sal_Int16 aControlId )
        throw ( ::com::sun::star::uno::RuntimeException);

    //------------------------------------------------
    // XFilePreview
    //------------------------------------------------

    virtual ::com::sun::star::uno::Sequence< sal_Int16 > SAL_CALL getSupportedImageFormats(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Int32 SAL_CALL getTargetColorDepth( )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Int32 SAL_CALL getAvailableWidth( )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Int32 SAL_CALL getAvailableHeight( )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL setImage( sal_Int16 aImageFormat, const ::com::sun::star::uno::Any& aImage )
        throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL setShowState( sal_Bool bShowState )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL getShowState( )
        throw (::com::sun::star::uno::RuntimeException);

    //------------------------------------------------
    // XCancelable
    //------------------------------------------------

    virtual void SAL_CALL cancel( );

    //------------------------------------------------
    // Implementation details
    //------------------------------------------------

protected:
    sal_Int16 SAL_CALL getFocused( );

    virtual bool SAL_CALL preModal( );
    virtual void SAL_CALL postModal( sal_Int16 nDialogResult );

    virtual sal_uInt32 SAL_CALL onFileOk();
    virtual void SAL_CALL onSelChanged( HWND hwndListBox );

    // only called back if OFN_EXPLORER is set
    virtual void SAL_CALL onInitDone();
    virtual void SAL_CALL onFolderChanged();
    virtual void SAL_CALL onTypeChanged( sal_uInt32 nFilterIndex );

    // call base class method first when overloading
    virtual void SAL_CALL onInitDialog( HWND hwndDlg, HWND hwndChild );

    virtual sal_uInt32 SAL_CALL onCtrlCommand( HWND hwndDlg, sal_uInt16 ctrlId, sal_uInt16 notifyCode );

    LRESULT SAL_CALL onWMSize(HWND hwnd, WPARAM type, WORD width, WORD height );
    LRESULT SAL_CALL onWMShow(HWND hwnd, BOOL bShow, int fState);
    LRESULT SAL_CALL onWMWindowPosChanged(HWND hwnd);
    LRESULT SAL_CALL onCustomControlHelpRequest(LPHELPINFO lphi);

private:
    inline void SAL_CALL appendFilterGroupSeparator( );

    inline sal_Bool SAL_CALL IsCustomControlHelpRequested(LPHELPINFO lphi) const;

    void EnlargeStdControlLabels() const;

    // initialize all controls from cache
    void SAL_CALL InitControlLabel( HWND hWnd );
    void SAL_CALL InitCustomControlContainer(HWND hCustomControl);

    // save the control state
    void SAL_CALL CacheControlState(HWND hWnd);

    void SAL_CALL SetDefaultExtension();
    void SAL_CALL InitialSetDefaultName();

    static LRESULT CALLBACK SubClassFunc(HWND hWnd, UINT wMessage, WPARAM wParam, LPARAM lParam);

    static BOOL CALLBACK EnumChildWndProc( HWND hWnd, LPARAM lParam );

private:
    std::auto_ptr<CFilterContainer>         m_filterContainer;
    std::auto_ptr<CPreviewAdapter>          m_Preview;
    std::auto_ptr<CCustomControlFactory>    m_CustomControlFactory;
    std::auto_ptr<CCustomControl>           m_CustomControls;
    CFilePicker*                            m_FilePicker;
    WNDPROC                                 m_pfnOldDlgProc;
    rtl::OUString                           m_defaultName;
    sal_Bool                                m_bInitialSelChanged;
    CHelpPopupWindow                        m_HelpPopupWindow;
    CFilePickerState*                       m_FilePickerState;
    CExecuteFilePickerState*                m_ExecuteFilePickerState;
    CNonExecuteFilePickerState*             m_NonExecuteFilePickerState;
};

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.12.50); FILE MERGED 2005/09/05 17:13:29 rt 1.12.50.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: WinFileOpenImpl.hxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 23:40:15 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _WINFILEOPENIMPL_HXX_
#define _WINFILEOPENIMPL_HXX_

//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------

#ifndef _COM_SUN_STAR_UI_DIALOGS_XEXTENDEDFILEPICKER_HPP_
#include <com/sun/star/ui/dialogs/XFilePickerControlAccess.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_FILEPICKEREVENT_HPP_
#include <com/sun/star/ui/dialogs/FilePickerEvent.hpp>
#endif

#ifndef _COM_SUN_STAR_UI_DIALOGS_XFILTERGROUPMANAGER_HPP_
#include <com/sun/star/ui/dialogs/XFilterGroupManager.hpp>
#endif

#ifndef _FILTER_CONTAINER_HXX_
#include "FilterContainer.hxx"
#endif

#ifndef _FILEOPENDLG_HXX_
#include "FileOpenDlg.hxx"
#endif

#ifndef _PREVIEWADAPTER_HXX_
#include "previewadapter.hxx"
#endif

#ifndef _HELPPOPUPWINDOW_HXX_
#include "helppopupwindow.hxx"
#endif

#ifndef _CUSTOMCONTROL_HXX_
#include "customcontrol.hxx"
#endif

#ifndef _CUSTOMCONTROLFACTORY_HXX_
#include "customcontrolfactory.hxx"
#endif

#include <utility>
#include <memory>
#include <vector>

#ifndef _OSL_CONDITN_HXX_
#include <osl/conditn.hxx>
#endif

//------------------------------------------------------------------------
// deklarations
//------------------------------------------------------------------------

// forward declaration
class CFilePicker;
class CFilePickerState;
class CExecuteFilePickerState;
class CNonExecuteFilePickerState;

class CWinFileOpenImpl : public CFileOpenDialog
{
public:
    CWinFileOpenImpl(
        CFilePicker* aFilePicker,
        sal_Bool bFileOpenDialog = sal_True,
        sal_uInt32 dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
        sal_uInt32 dwTemplateId = 0,
        HINSTANCE hInstance = 0 );

    virtual ~CWinFileOpenImpl( );

    //-----------------------------------------------------------------------------------------
    // XExecutableDialog
    //-----------------------------------------------------------------------------------------

    virtual sal_Int16 SAL_CALL execute(  ) throw( ::com::sun::star::uno::RuntimeException );

    //-----------------------------------------------------------------------------------------
    // XFilePicker
    //-----------------------------------------------------------------------------------------

    virtual void SAL_CALL setDefaultName( const ::rtl::OUString& aName )
        throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );

    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getFiles(  )
        throw(::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL setDisplayDirectory( const ::rtl::OUString& aDirectory )
        throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );

    virtual ::rtl::OUString SAL_CALL getDisplayDirectory( ) throw ( ::com::sun::star::uno::RuntimeException );

    //-----------------------------------------------------------------------------------------
    // XFilterManager
    //-----------------------------------------------------------------------------------------

    virtual void SAL_CALL appendFilter( const ::rtl::OUString& aTitle, const ::rtl::OUString& aFilter )
        throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL setCurrentFilter( const ::rtl::OUString& aTitle )
        throw( ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException );

    virtual ::rtl::OUString  SAL_CALL getCurrentFilter( )
        throw( ::com::sun::star::uno::RuntimeException );

    //-----------------------------------------------------------------------------------------
    // XFilterGroupManager
    //-----------------------------------------------------------------------------------------

    virtual void SAL_CALL appendFilterGroup( const ::rtl::OUString& sGroupTitle, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::StringPair >& aFilters )
        throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    //-----------------------------------------------------------------------------------------
    // XFilePickerControlAccess
    //-----------------------------------------------------------------------------------------

    virtual void SAL_CALL setValue( sal_Int16 aControlId, sal_Int16 aControlAction, const ::com::sun::star::uno::Any& aValue )
        throw( ::com::sun::star::uno::RuntimeException );

    virtual ::com::sun::star::uno::Any SAL_CALL getValue( sal_Int16 aControlId, sal_Int16 aControlAction )
        throw( ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL enableControl( sal_Int16 aControlId, sal_Bool bEnable )
        throw( ::com::sun::star::uno::RuntimeException );

    virtual void SAL_CALL setLabel( sal_Int16 aControlId, const ::rtl::OUString& aLabel )
        throw (::com::sun::star::uno::RuntimeException);

    virtual ::rtl::OUString SAL_CALL getLabel( sal_Int16 aControlId )
        throw ( ::com::sun::star::uno::RuntimeException);

    //------------------------------------------------
    // XFilePreview
    //------------------------------------------------

    virtual ::com::sun::star::uno::Sequence< sal_Int16 > SAL_CALL getSupportedImageFormats(  )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Int32 SAL_CALL getTargetColorDepth( )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Int32 SAL_CALL getAvailableWidth( )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Int32 SAL_CALL getAvailableHeight( )
        throw (::com::sun::star::uno::RuntimeException);

    virtual void SAL_CALL setImage( sal_Int16 aImageFormat, const ::com::sun::star::uno::Any& aImage )
        throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL setShowState( sal_Bool bShowState )
        throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Bool SAL_CALL getShowState( )
        throw (::com::sun::star::uno::RuntimeException);

    //------------------------------------------------
    // XCancelable
    //------------------------------------------------

    virtual void SAL_CALL cancel( );

    //------------------------------------------------
    // Implementation details
    //------------------------------------------------

protected:
    sal_Int16 SAL_CALL getFocused( );

    virtual bool SAL_CALL preModal( );
    virtual void SAL_CALL postModal( sal_Int16 nDialogResult );

    virtual sal_uInt32 SAL_CALL onFileOk();
    virtual void SAL_CALL onSelChanged( HWND hwndListBox );

    // only called back if OFN_EXPLORER is set
    virtual void SAL_CALL onInitDone();
    virtual void SAL_CALL onFolderChanged();
    virtual void SAL_CALL onTypeChanged( sal_uInt32 nFilterIndex );

    // call base class method first when overloading
    virtual void SAL_CALL onInitDialog( HWND hwndDlg, HWND hwndChild );

    virtual sal_uInt32 SAL_CALL onCtrlCommand( HWND hwndDlg, sal_uInt16 ctrlId, sal_uInt16 notifyCode );

    LRESULT SAL_CALL onWMSize(HWND hwnd, WPARAM type, WORD width, WORD height );
    LRESULT SAL_CALL onWMShow(HWND hwnd, BOOL bShow, int fState);
    LRESULT SAL_CALL onWMWindowPosChanged(HWND hwnd);
    LRESULT SAL_CALL onCustomControlHelpRequest(LPHELPINFO lphi);

private:
    inline void SAL_CALL appendFilterGroupSeparator( );

    inline sal_Bool SAL_CALL IsCustomControlHelpRequested(LPHELPINFO lphi) const;

    void EnlargeStdControlLabels() const;

    // initialize all controls from cache
    void SAL_CALL InitControlLabel( HWND hWnd );
    void SAL_CALL InitCustomControlContainer(HWND hCustomControl);

    // save the control state
    void SAL_CALL CacheControlState(HWND hWnd);

    void SAL_CALL SetDefaultExtension();
    void SAL_CALL InitialSetDefaultName();

    static LRESULT CALLBACK SubClassFunc(HWND hWnd, UINT wMessage, WPARAM wParam, LPARAM lParam);

    static BOOL CALLBACK EnumChildWndProc( HWND hWnd, LPARAM lParam );

private:
    std::auto_ptr<CFilterContainer>         m_filterContainer;
    std::auto_ptr<CPreviewAdapter>          m_Preview;
    std::auto_ptr<CCustomControlFactory>    m_CustomControlFactory;
    std::auto_ptr<CCustomControl>           m_CustomControls;
    CFilePicker*                            m_FilePicker;
    WNDPROC                                 m_pfnOldDlgProc;
    rtl::OUString                           m_defaultName;
    sal_Bool                                m_bInitialSelChanged;
    CHelpPopupWindow                        m_HelpPopupWindow;
    CFilePickerState*                       m_FilePickerState;
    CExecuteFilePickerState*                m_ExecuteFilePickerState;
    CNonExecuteFilePickerState*             m_NonExecuteFilePickerState;
};

#endif
<|endoftext|>


<commit_before>//===--- USRGeneration.cpp - Routines for USR generation ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/AST/ASTContext.h"
#include "swift/AST/Module.h"
#include "swift/AST/USRGeneration.h"
#include "swift/AST/Mangle.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/AST/ASTContext.h"
#include "clang/Index/USRGeneration.h"
#include "clang/Lex/PreprocessingRecord.h"
#include "clang/Lex/Preprocessor.h"

using namespace swift;
using namespace ide;

static inline StringRef getUSRSpacePrefix() {
  return "s:";
}

bool ide::printDeclUSR(const ValueDecl *D, raw_ostream &OS) {
  using namespace Mangle;

  if (!isa<FuncDecl>(D) && !D->hasName())
    return true; // Ignore.
  if (D->getModuleContext()->isBuiltinModule())
    return true; // Ignore.

  ValueDecl *VD = const_cast<ValueDecl *>(D);

  if (ClangNode ClangN = VD->getClangNode()) {
    llvm::SmallString<128> Buf;
    if (auto ClangD = ClangN.getAsDecl()) {
      bool Ignore = clang::index::generateUSRForDecl(ClangD, Buf);
      if (!Ignore)
        OS << Buf.str();
      return Ignore;
    }

    auto &Importer = *D->getASTContext().getClangModuleLoader();

    auto ClangMacroInfo = ClangN.getAsMacro();
    auto PPRecord = Importer.getClangPreprocessor().getPreprocessingRecord();
    assert(PPRecord && "Clang importer should be created with "
                       "-detailed-preprocessing-record option");
    auto ClangMacroDef = PPRecord->findMacroDefinition(ClangMacroInfo);

    bool Ignore = clang::index::generateUSRForMacro(
        ClangMacroDef, Importer.getClangASTContext().getSourceManager(), Buf);
    if (!Ignore)
      OS << Buf.str();
    return Ignore;
  }

  if (!D->hasType())
    return true;

  // FIXME: mangling 'self' in destructors crashes in mangler.
  if (isa<ParamDecl>(VD) && isa<DestructorDecl>(VD->getDeclContext()))
    return true;

  OS << getUSRSpacePrefix();
  Mangler Mangler;
  if (auto Ctor = dyn_cast<ConstructorDecl>(VD)) {
    Mangler.mangleConstructorEntity(Ctor, /*isAllocating=*/false,
                                    /*uncurryingLevel=*/0);
  } else if (auto Dtor = dyn_cast<DestructorDecl>(VD)) {
    Mangler.mangleDestructorEntity(Dtor, /*isDeallocating=*/false);
  } else if (auto NTD = dyn_cast<NominalTypeDecl>(VD)) {
    Mangler.mangleNominalType(NTD, Mangler::BindGenerics::None);
  } else if (isa<TypeAliasDecl>(VD) || isa<AssociatedTypeDecl>(VD)) {
    Mangler.mangleContextOf(VD, Mangler::BindGenerics::None);
    Mangler.mangleDeclName(VD);
  } else {
    Mangler.mangleEntity(VD, /*uncurryingLevel=*/0);
  }

  Mangler.finalize(OS);
  return false;
}

bool ide::printAccessorUSR(const AbstractStorageDecl *D, AccessorKind AccKind,
                           llvm::raw_ostream &OS) {
  using namespace Mangle;

  // AccKind should always be either IsGetter or IsSetter here, based
  // on whether a reference is a mutating or non-mutating use.  USRs
  // aren't supposed to reflect implementation differences like stored
  // vs. addressed vs. observing.
  //
  // On the other side, the implementation indexer should be
  // registering the getter/setter USRs independently of how they're
  // actually implemented.  So a stored variable should still have
  // getter/setter USRs (pointing to the variable declaration), and an
  // addressed variable should have its "getter" point at the
  // addressor.

  AbstractStorageDecl *SD = const_cast<AbstractStorageDecl*>(D);
  OS << getUSRSpacePrefix();
  Mangler Mangler;
  Mangler.mangleAccessorEntity(AccKind, AddressorKind::NotAddressor, SD);
  Mangler.finalize(OS);
  return false;
}

bool ide::printExtensionUSR(const ExtensionDecl *ED, raw_ostream &OS) {
  if (ED->getExtendedType().isNull())
    return true;

  // We make up a unique usr for each extension by combining the usr of the
  // extended type and the first value member of the extension.
  if (printDeclUSR(ED->getExtendedType()->getAnyNominal(), OS))
    return true;
  for (auto D : ED->getMembers()) {
    if (auto VD = dyn_cast<ValueDecl>(D)) {
      return printDeclUSR(VD, OS);
    }
  }
  return true;
}

<commit_msg>[Serialization] Shorten extension USRs.<commit_after>//===--- USRGeneration.cpp - Routines for USR generation ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/AST/ASTContext.h"
#include "swift/AST/Module.h"
#include "swift/AST/USRGeneration.h"
#include "swift/AST/Mangle.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/AST/ASTContext.h"
#include "clang/Index/USRGeneration.h"
#include "clang/Lex/PreprocessingRecord.h"
#include "clang/Lex/Preprocessor.h"

using namespace swift;
using namespace ide;

static inline StringRef getUSRSpacePrefix() {
  return "s:";
}

bool ide::printDeclUSR(const ValueDecl *D, raw_ostream &OS) {
  using namespace Mangle;

  if (!isa<FuncDecl>(D) && !D->hasName())
    return true; // Ignore.
  if (D->getModuleContext()->isBuiltinModule())
    return true; // Ignore.

  ValueDecl *VD = const_cast<ValueDecl *>(D);

  if (ClangNode ClangN = VD->getClangNode()) {
    llvm::SmallString<128> Buf;
    if (auto ClangD = ClangN.getAsDecl()) {
      bool Ignore = clang::index::generateUSRForDecl(ClangD, Buf);
      if (!Ignore)
        OS << Buf.str();
      return Ignore;
    }

    auto &Importer = *D->getASTContext().getClangModuleLoader();

    auto ClangMacroInfo = ClangN.getAsMacro();
    auto PPRecord = Importer.getClangPreprocessor().getPreprocessingRecord();
    assert(PPRecord && "Clang importer should be created with "
                       "-detailed-preprocessing-record option");
    auto ClangMacroDef = PPRecord->findMacroDefinition(ClangMacroInfo);

    bool Ignore = clang::index::generateUSRForMacro(
        ClangMacroDef, Importer.getClangASTContext().getSourceManager(), Buf);
    if (!Ignore)
      OS << Buf.str();
    return Ignore;
  }

  if (!D->hasType())
    return true;

  // FIXME: mangling 'self' in destructors crashes in mangler.
  if (isa<ParamDecl>(VD) && isa<DestructorDecl>(VD->getDeclContext()))
    return true;

  OS << getUSRSpacePrefix();
  Mangler Mangler;
  if (auto Ctor = dyn_cast<ConstructorDecl>(VD)) {
    Mangler.mangleConstructorEntity(Ctor, /*isAllocating=*/false,
                                    /*uncurryingLevel=*/0);
  } else if (auto Dtor = dyn_cast<DestructorDecl>(VD)) {
    Mangler.mangleDestructorEntity(Dtor, /*isDeallocating=*/false);
  } else if (auto NTD = dyn_cast<NominalTypeDecl>(VD)) {
    Mangler.mangleNominalType(NTD, Mangler::BindGenerics::None);
  } else if (isa<TypeAliasDecl>(VD) || isa<AssociatedTypeDecl>(VD)) {
    Mangler.mangleContextOf(VD, Mangler::BindGenerics::None);
    Mangler.mangleDeclName(VD);
  } else {
    Mangler.mangleEntity(VD, /*uncurryingLevel=*/0);
  }

  Mangler.finalize(OS);
  return false;
}

bool ide::printAccessorUSR(const AbstractStorageDecl *D, AccessorKind AccKind,
                           llvm::raw_ostream &OS) {
  using namespace Mangle;

  // AccKind should always be either IsGetter or IsSetter here, based
  // on whether a reference is a mutating or non-mutating use.  USRs
  // aren't supposed to reflect implementation differences like stored
  // vs. addressed vs. observing.
  //
  // On the other side, the implementation indexer should be
  // registering the getter/setter USRs independently of how they're
  // actually implemented.  So a stored variable should still have
  // getter/setter USRs (pointing to the variable declaration), and an
  // addressed variable should have its "getter" point at the
  // addressor.

  AbstractStorageDecl *SD = const_cast<AbstractStorageDecl*>(D);
  OS << getUSRSpacePrefix();
  Mangler Mangler;
  Mangler.mangleAccessorEntity(AccKind, AddressorKind::NotAddressor, SD);
  Mangler.finalize(OS);
  return false;
}

bool ide::printExtensionUSR(const ExtensionDecl *ED, raw_ostream &OS) {
  if (ED->getExtendedType().isNull())
    return true;

  // We make up a unique usr for each extension by combining a prefix
  // and the USR of the first value member of the extension.
  for (auto D : ED->getMembers()) {
    if (auto VD = dyn_cast<ValueDecl>(D)) {
      OS << "ext:";
      return printDeclUSR(VD, OS);
    }
  }
  return true;
}

<|endoftext|>


<commit_before>#include "Console.h"
#include "App.h"
#include "ModuleInput.h"
#include "imgui.h"

Console::Console(bool start_enabled) : EditorElement(start_enabled)
{
	memset(input_buffer, 0, sizeof(input_buffer));
}

Console::~Console()
{
}

void Console::Draw()
{
	bool ret = true;

	AddLogs();

	if (App->input->GetKey(SDL_SCANCODE_GRAVE) == KEY_DOWN)
	{
		visible = !visible;
		return;
	}

	if (!visible)
		return;

	ImGui::SetNextWindowSize(ImVec2(400, 400), 2);

	if (ImGui::Begin("Console", &visible))
	{
		if (ImGui::SmallButton("Clear"))
			AddLog("Help");

		ImGui::SameLine();

		if (ImGui::SmallButton("Help"))
			AddLog("Help");

		ImGui::Separator();

		// Scrollable
		ImGui::BeginChild("ScrollingRegion", ImVec2(0, -ImGui::GetItemsLineHeightWithSpacing()), false, ImGuiWindowFlags_HorizontalScrollbar);
		ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 1));

		// Scrollable texts
		for (list<console_text>::iterator it = console_items.begin(); it != console_items.end(); it++)
		{
			ImVec4 col = GetColorByTextType((*it).type);
			ImGui::PushStyleColor(ImGuiCol_Text, col);
			ImGui::TextUnformatted((*it).txt.c_str());
			ImGui::PopStyleColor();
		}

		// Scroll to bottom
		if (scroll_bottom)
		{
			ImGui::SetScrollHere();
			scroll_bottom = false;
		}

		ImGui::PopStyleVar();
		ImGui::EndChild();

		ImGui::Separator();

		// Text input
		if (ImGui::InputText("", input_buffer, 254, ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_CallbackCompletion
			| ImGuiInputTextFlags_CallbackHistory, &TextChangeCallback, (void*)this))
		{
			send_text_input = true;
		}

		// Keep focus on text input
		if (ImGui::IsItemHovered() || (ImGui::IsRootWindowOrAnyChildFocused() && !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0)))
			ImGui::SetKeyboardFocusHere(-1);

		// Submit button
		ImGui::SameLine();
		if (ImGui::Button("Submit", { 100, 23 }))
		{
			send_text_input = true;
		}

		// Input text
		if (send_text_input)
		{
			if (input_buffer != "")
				CommandInput(input_buffer);

			strcpy(input_buffer, "");

			send_text_input = false;
		}
	}
	ImGui::End();
}

void Console::AddLog(const char * txt, console_text_type type)
{
	console_text ct;
	ct.txt = txt;
	ct.type = type;

	console_items.push_back(ct);

	if (console_items.size() > MAX_LINES) {
		console_items.pop_front();
	}

	ScrollBottom();
}

void Console::Clear()
{
	console_items.clear();
}

void Console::ScrollBottom()
{
	scroll_bottom = true;
}

void Console::CommandInput(const char * txt)
{
	AddLog(txt);
}

ImColor Console::GetColorByTextType(console_text_type type)
{
	ImColor ret(255, 255, 255, 255);

	switch (type)
	{
	case console_text_type::console_text_type_default:
		ret = { 255, 255, 255, 255 };
		break;

	case console_text_type::console_text_type_info:
		ret = { 255, 255, 255, 255 };
		break;

	case console_text_type::console_text_type_error:
		ret = { 255, 255, 255, 255 };
		break;

	case console_text_type::console_text_type_succes:
		ret = { 255, 255, 255, 255 };
		break;

	case console_text_type::console_text_type_warning:
		ret = { 255, 255, 255, 255 };
		break;
	default:
		break;
	}

	return ret;
}

void Console::AddLogs()
{
	for (list<string>::iterator it = App->logs.begin(); it != App->logs.end(); it++)
	{
		AddLog((*it).c_str());
	}

	App->logs.clear();
}

static int TextChangeCallback(ImGuiTextEditCallbackData * data)
{
	int i = 0;
	return 1;
}<commit_msg>Clear now works as intended (just the button)<commit_after>#include "Console.h"
#include "App.h"
#include "ModuleInput.h"
#include "imgui.h"

Console::Console(bool start_enabled) : EditorElement(start_enabled)
{
	memset(input_buffer, 0, sizeof(input_buffer));
}

Console::~Console()
{
}

void Console::Draw()
{
	bool ret = true;

	AddLogs();

	if (App->input->GetKey(SDL_SCANCODE_GRAVE) == KEY_DOWN)
	{
		visible = !visible;
		return;
	}

	if (!visible)
		return;

	ImGui::SetNextWindowSize(ImVec2(400, 400), 2);

	if (ImGui::Begin("Console", &visible))
	{
		if (ImGui::SmallButton("Clear"))
			CommandInput(".Clear");

		ImGui::SameLine();

		if (ImGui::SmallButton("Help"))
			AddLog("Help");

		ImGui::Separator();

		// Scrollable
		ImGui::BeginChild("ScrollingRegion", ImVec2(0, -ImGui::GetItemsLineHeightWithSpacing()), false, ImGuiWindowFlags_HorizontalScrollbar);
		ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4, 1));

		// Scrollable texts
		for (list<console_text>::iterator it = console_items.begin(); it != console_items.end(); it++)
		{
			ImVec4 col = GetColorByTextType((*it).type);
			ImGui::PushStyleColor(ImGuiCol_Text, col);
			ImGui::TextUnformatted((*it).txt.c_str());
			ImGui::PopStyleColor();
		}

		// Scroll to bottom
		if (scroll_bottom)
		{
			ImGui::SetScrollHere();
			scroll_bottom = false;
		}

		ImGui::PopStyleVar();
		ImGui::EndChild();

		ImGui::Separator();

		// Text input
		if (ImGui::InputText("", input_buffer, 254, ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_CallbackCompletion
			| ImGuiInputTextFlags_CallbackHistory, &TextChangeCallback, (void*)this))
		{
			send_text_input = true;
		}

		// Keep focus on text input
		if (ImGui::IsItemHovered() || (ImGui::IsRootWindowOrAnyChildFocused() && !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0)))
			ImGui::SetKeyboardFocusHere(-1);

		// Submit button
		ImGui::SameLine();
		if (ImGui::Button("Submit", { 100, 23 }))
		{
			send_text_input = true;
		}

		// Input text
		if (send_text_input)
		{
			if (input_buffer != "")
				CommandInput(input_buffer);

			strcpy(input_buffer, "");

			send_text_input = false;
		}
	}
	ImGui::End();
}

void Console::AddLog(const char * txt, console_text_type type)
{
	console_text ct;
	ct.txt = txt;
	ct.type = type;

	console_items.push_back(ct);

	if (console_items.size() > MAX_LINES) {
		console_items.pop_front();
	}

	ScrollBottom();
}

void Console::Clear()
{
	console_items.clear();
}

void Console::ScrollBottom()
{
	scroll_bottom = true;
}

void Console::CommandInput(const char * txt)
{
	if (txt == ".Clear") {
		for (std::list<console_text>::iterator it = console_items.begin(); it != console_items.end();)
		{
			it = console_items.erase(it);
		}
		console_items.clear();
	}
}

ImColor Console::GetColorByTextType(console_text_type type)
{
	ImColor ret(255, 255, 255, 255);

	switch (type)
	{
	case console_text_type::console_text_type_default:
		ret = { 255, 255, 255, 255 };
		break;

	case console_text_type::console_text_type_info:
		ret = { 255, 255, 255, 255 };
		break;

	case console_text_type::console_text_type_error:
		ret = { 255, 255, 255, 255 };
		break;

	case console_text_type::console_text_type_succes:
		ret = { 255, 255, 255, 255 };
		break;

	case console_text_type::console_text_type_warning:
		ret = { 255, 255, 255, 255 };
		break;
	default:
		break;
	}

	return ret;
}

void Console::AddLogs()
{
	for (list<string>::iterator it = App->logs.begin(); it != App->logs.end(); it++)
	{
		AddLog((*it).c_str());
	}

	App->logs.clear();
}

static int TextChangeCallback(ImGuiTextEditCallbackData * data)
{
	int i = 0;
	return 1;
}<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright UMC Utrecht and contributors
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/
#ifndef itkRecursiveBSplineInterpolationWeightFunction_hxx
#define itkRecursiveBSplineInterpolationWeightFunction_hxx

#include "itkRecursiveBSplineInterpolationWeightFunction.h"

#include "itkImage.h"
#include "itkMatrix.h"
#include "itkMath.h"
#include "itkImageRegionConstIteratorWithIndex.h"

namespace itk
{

/**
 * ********************* Constructor ****************************
 */

template <typename TCoordRep, unsigned int VSpaceDimension, unsigned int VSplineOrder>
RecursiveBSplineInterpolationWeightFunction<TCoordRep, VSpaceDimension, VSplineOrder>::
  RecursiveBSplineInterpolationWeightFunction()
{
  // Initialize support region is a hypercube of length SplineOrder + 1
  this->m_SupportSize.Fill(SplineOrder + 1);

  this->m_NumberOfWeights = 1;
  for (unsigned int i = 0; i < SpaceDimension; ++i)
  {
    this->m_NumberOfWeights *= this->m_SupportSize[i];
  }

} // end Constructor

/**
 * ********************* PrintSelf ****************************
 */

template <typename TCoordRep, unsigned int VSpaceDimension, unsigned int VSplineOrder>
void
RecursiveBSplineInterpolationWeightFunction<TCoordRep, VSpaceDimension, VSplineOrder>::PrintSelf(std::ostream & os,
                                                                                Indent indent) const
{
  Superclass::PrintSelf(os, indent);

  os << indent << "NumberOfWeights: " << m_NumberOfWeights << std::endl;
  os << indent << "SupportSize: " << m_SupportSize << std::endl;
} // end PrintSelf()

/**
 * ********************* Evaluate ****************************
 */

template <typename TCoordRep, unsigned int VSpaceDimension, unsigned int VSplineOrder>
auto
RecursiveBSplineInterpolationWeightFunction<TCoordRep, VSpaceDimension, VSplineOrder>::Evaluate(
  const ContinuousIndexType & index) const -> WeightsType
{
  WeightsType weights;
  IndexType   startIndex;

  this->Evaluate(index, weights, startIndex);

  return weights;
} // end Evaluate()

/**
 * ********************* Evaluate ****************************
 */

template <typename TCoordRep, unsigned int VSpaceDimension, unsigned int VSplineOrder>
auto
RecursiveBSplineInterpolationWeightFunction<TCoordRep, VSpaceDimension, VSplineOrder>::Evaluate(
  const ContinuousIndexType & cindex,
  IndexType &                 startIndex) const -> WeightsType
{
  WeightsType weights;

  typename WeightsType::ValueType * weightsPtr = &weights[0];
  for (unsigned int i = 0; i < SpaceDimension; ++i)
  {
    startIndex[i] = Math::Floor<IndexValueType>(cindex[i] + 0.5 - SplineOrder / 2.0);
    double x = cindex[i] - static_cast<double>(startIndex[i]);
    KernelType::FastEvaluate(x, weightsPtr);
    weightsPtr += SplineOrder + 1;
  }

  return weights;

} // end Evaluate()

template <typename TCoordRep, unsigned int VSpaceDimension, unsigned int VSplineOrder>
void
RecursiveBSplineInterpolationWeightFunction<TCoordRep, VSpaceDimension, VSplineOrder>::Evaluate(
  const ContinuousIndexType & cindex,
  WeightsType &               weights,
  IndexType &                 startIndex) const
{
  weights = this->Evaluate(cindex, startIndex);

} // end Evaluate()

/**
 * ********************* EvaluateDerivative ****************************
 */

template <typename TCoordRep, unsigned int VSpaceDimension, unsigned int VSplineOrder>
auto
RecursiveBSplineInterpolationWeightFunction<TCoordRep, VSpaceDimension, VSplineOrder>::EvaluateDerivative(
  const ContinuousIndexType & cindex,
  const IndexType &           startIndex) const -> WeightsType
{
  WeightsType derivativeWeights;

  for (unsigned int i = 0; i < SpaceDimension; ++i)
  {
    double x = cindex[i] - static_cast<double>(startIndex[i]);
    DerivativeKernelType::FastEvaluate(x, &derivativeWeights[i * this->m_SupportSize[i]]);
  }

  return derivativeWeights;

} // end EvaluateDerivative()

/**
 * ********************* EvaluateSecondOrderDerivative ****************************
 */

template <typename TCoordRep, unsigned int VSpaceDimension, unsigned int VSplineOrder>
auto
RecursiveBSplineInterpolationWeightFunction<TCoordRep, VSpaceDimension, VSplineOrder>::EvaluateSecondOrderDerivative(
  const ContinuousIndexType & cindex,
  const IndexType &           startIndex) const -> WeightsType
{
  WeightsType hessianWeights;

  for (unsigned int i = 0; i < SpaceDimension; ++i)
  {
    double x = cindex[i] - static_cast<double>(startIndex[i]);
    SecondOrderDerivativeKernelType::FastEvaluate(x, &hessianWeights[i * this->m_SupportSize[i]]);
  }

  return hessianWeights;
} // end EvaluateSecondOrderDerivative()

} // end namespace itk

#endif
<commit_msg>STYLE: Simplify `RecursiveBSplineInterpolationWeightFunction::Evaluate`<commit_after>/*=========================================================================
 *
 *  Copyright UMC Utrecht and contributors
 *
 *  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.txt
 *
 *  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.
 *
 *=========================================================================*/
#ifndef itkRecursiveBSplineInterpolationWeightFunction_hxx
#define itkRecursiveBSplineInterpolationWeightFunction_hxx

#include "itkRecursiveBSplineInterpolationWeightFunction.h"

#include "itkImage.h"
#include "itkMatrix.h"
#include "itkMath.h"
#include "itkImageRegionConstIteratorWithIndex.h"

namespace itk
{

/**
 * ********************* Constructor ****************************
 */

template <typename TCoordRep, unsigned int VSpaceDimension, unsigned int VSplineOrder>
RecursiveBSplineInterpolationWeightFunction<TCoordRep, VSpaceDimension, VSplineOrder>::
  RecursiveBSplineInterpolationWeightFunction()
{
  // Initialize support region is a hypercube of length SplineOrder + 1
  this->m_SupportSize.Fill(SplineOrder + 1);

  this->m_NumberOfWeights = 1;
  for (unsigned int i = 0; i < SpaceDimension; ++i)
  {
    this->m_NumberOfWeights *= this->m_SupportSize[i];
  }

} // end Constructor

/**
 * ********************* PrintSelf ****************************
 */

template <typename TCoordRep, unsigned int VSpaceDimension, unsigned int VSplineOrder>
void
RecursiveBSplineInterpolationWeightFunction<TCoordRep, VSpaceDimension, VSplineOrder>::PrintSelf(std::ostream & os,
                                                                                Indent indent) const
{
  Superclass::PrintSelf(os, indent);

  os << indent << "NumberOfWeights: " << m_NumberOfWeights << std::endl;
  os << indent << "SupportSize: " << m_SupportSize << std::endl;
} // end PrintSelf()

/**
 * ********************* Evaluate ****************************
 */

template <typename TCoordRep, unsigned int VSpaceDimension, unsigned int VSplineOrder>
auto
RecursiveBSplineInterpolationWeightFunction<TCoordRep, VSpaceDimension, VSplineOrder>::Evaluate(
  const ContinuousIndexType & index) const -> WeightsType
{
  IndexType startIndex;
  return this->Evaluate(index, startIndex);
} // end Evaluate()

/**
 * ********************* Evaluate ****************************
 */

template <typename TCoordRep, unsigned int VSpaceDimension, unsigned int VSplineOrder>
auto
RecursiveBSplineInterpolationWeightFunction<TCoordRep, VSpaceDimension, VSplineOrder>::Evaluate(
  const ContinuousIndexType & cindex,
  IndexType &                 startIndex) const -> WeightsType
{
  WeightsType weights;

  typename WeightsType::ValueType * weightsPtr = &weights[0];
  for (unsigned int i = 0; i < SpaceDimension; ++i)
  {
    startIndex[i] = Math::Floor<IndexValueType>(cindex[i] + 0.5 - SplineOrder / 2.0);
    double x = cindex[i] - static_cast<double>(startIndex[i]);
    KernelType::FastEvaluate(x, weightsPtr);
    weightsPtr += SplineOrder + 1;
  }

  return weights;

} // end Evaluate()

template <typename TCoordRep, unsigned int VSpaceDimension, unsigned int VSplineOrder>
void
RecursiveBSplineInterpolationWeightFunction<TCoordRep, VSpaceDimension, VSplineOrder>::Evaluate(
  const ContinuousIndexType & cindex,
  WeightsType &               weights,
  IndexType &                 startIndex) const
{
  weights = this->Evaluate(cindex, startIndex);

} // end Evaluate()

/**
 * ********************* EvaluateDerivative ****************************
 */

template <typename TCoordRep, unsigned int VSpaceDimension, unsigned int VSplineOrder>
auto
RecursiveBSplineInterpolationWeightFunction<TCoordRep, VSpaceDimension, VSplineOrder>::EvaluateDerivative(
  const ContinuousIndexType & cindex,
  const IndexType &           startIndex) const -> WeightsType
{
  WeightsType derivativeWeights;

  for (unsigned int i = 0; i < SpaceDimension; ++i)
  {
    double x = cindex[i] - static_cast<double>(startIndex[i]);
    DerivativeKernelType::FastEvaluate(x, &derivativeWeights[i * this->m_SupportSize[i]]);
  }

  return derivativeWeights;

} // end EvaluateDerivative()

/**
 * ********************* EvaluateSecondOrderDerivative ****************************
 */

template <typename TCoordRep, unsigned int VSpaceDimension, unsigned int VSplineOrder>
auto
RecursiveBSplineInterpolationWeightFunction<TCoordRep, VSpaceDimension, VSplineOrder>::EvaluateSecondOrderDerivative(
  const ContinuousIndexType & cindex,
  const IndexType &           startIndex) const -> WeightsType
{
  WeightsType hessianWeights;

  for (unsigned int i = 0; i < SpaceDimension; ++i)
  {
    double x = cindex[i] - static_cast<double>(startIndex[i]);
    SecondOrderDerivativeKernelType::FastEvaluate(x, &hessianWeights[i * this->m_SupportSize[i]]);
  }

  return hessianWeights;
} // end EvaluateSecondOrderDerivative()

} // end namespace itk

#endif
<|endoftext|>