<commit_before>/****************************************************************************
**
** This file is part of QtCompositor**
**
** Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
**
** Contact:  Nokia Corporation qt-info@nokia.com
**
** You may use this file under the terms of the BSD license as follows:
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**
** Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
**
** Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
**
** Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the
** names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
****************************************************************************/

#include "wlsurface.h"

#include "waylandsurface.h"

#include "wlcompositor.h"
#include "wlshmbuffer.h"

#include <QtCore/QDebug>

#include <wayland-server.h>

#ifdef Q_OS_LINUX
#include <linux/input.h>
#endif

#ifdef QT_COMPOSITOR_WAYLAND_GL
#include "hardware_integration/graphicshardwareintegration.h"
#include <QtGui/QPlatformOpenGLContext>
#endif

#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
#include "waylandwindowmanagerintegration.h"
#endif

namespace Wayland {

class SurfacePrivate
{
public:
    SurfacePrivate(struct wl_client *client, Compositor *compositor)
        : client(client)
        , compositor(compositor)
        , textureCreatedForBuffer(false)
        , directRenderBuffer(0)
        , processId(0)
        , previousBuffer(0)
        , surfaceBuffer(0)
        , surfaceType(WaylandSurface::Invalid)

    {
#ifdef QT_COMPOSITOR_WAYLAND_GL
        texture_id = 0;
#endif
    }

    WaylandSurface::Type type() const {
        if (surfaceType == WaylandSurface::Invalid) {
            SurfacePrivate *that = const_cast<SurfacePrivate *>(this);
            if (qtSurface->handle() == compositor->directRenderSurface()) {
                that->surfaceType = WaylandSurface::Direct;
            } else if (surfaceBuffer && wl_buffer_is_shm(surfaceBuffer)) {
                that->surfaceType = WaylandSurface::Shm;
            } else if (surfaceBuffer){
                that->surfaceType = WaylandSurface::Texture;
            }
        }
        return surfaceType;
    }

    void attach(struct wl_buffer *buffer) {
        bool emitMap = !surfaceBuffer;
        if (surfaceBuffer && ! textureCreatedForBuffer) {
            qWarning() << "### WaylandSurface::attach() releasing undisplayed buffer ###";
             wl_client_post_event(client,&surfaceBuffer->resource.object,WL_BUFFER_RELEASE);
        }
        surfaceBuffer = buffer;
        surfaceType = WaylandSurface::Invalid;
        textureCreatedForBuffer = false;
        if (emitMap) {
            qtSurface->mapped(QSize(surfaceBuffer->width,surfaceBuffer->height));
        }
    }

    inline struct wl_buffer *buffer() const { return surfaceBuffer; }

    struct wl_client *client;
    Compositor *compositor;
    WaylandSurface *qtSurface;

#ifdef QT_COMPOSITOR_WAYLAND_GL
    GLuint texture_id;
#endif
    bool textureCreatedForBuffer;
    struct wl_buffer *directRenderBuffer;
    qint64 processId;
    QByteArray authenticationToken;
    QVariantMap windowProperties;

    QPoint lastMousePos;

    struct wl_buffer *previousBuffer;
private:
    struct wl_buffer *surfaceBuffer;
    WaylandSurface::Type surfaceType;
};

void surface_destroy(struct wl_client *client, struct wl_surface *surface)
{
    wl_resource_destroy(&surface->resource, client, Compositor::currentTimeMsecs());
}

void surface_attach(struct wl_client *client, struct wl_surface *surface,
                    struct wl_buffer *buffer, int x, int y)
{
    Q_UNUSED(client);
    Q_UNUSED(x);
    Q_UNUSED(y);

    wayland_cast<Surface *>(surface)->attach(buffer);
}

void surface_damage(struct wl_client *client, struct wl_surface *surface,
                    int32_t x, int32_t y, int32_t width, int32_t height)
{
    Q_UNUSED(client);
    wayland_cast<Surface *>(surface)->damage(QRect(x, y, width, height));
}

Surface::Surface(struct wl_client *client, Compositor *compositor)
    : d_ptr(new SurfacePrivate(client,compositor))
{
    base()->client = client;
    d_ptr->qtSurface = new WaylandSurface(this);

}

Surface::~Surface()
{
    Q_D(Surface);
    d->compositor->surfaceDestroyed(this);
#ifdef QT_COMPOSITOR_WAYLAND_GL
    if (d->compositor->graphicsHWIntegration())
        glDeleteTextures(1,&d->texture_id);
#endif
    delete d->qtSurface;
}

WaylandSurface::Type Surface::type() const
{
    Q_D(const Surface);
    return d->type();
}

bool Surface::isYInverted() const
{
#ifdef QT_COMPOSITOR_WAYLAND_GL
    Q_D(const Surface);

    if (d->compositor->graphicsHWIntegration()) {
        if (d->type() == WaylandSurface::Texture) {
            if (textureId()) {
                return d->compositor->graphicsHWIntegration()->isYInverted(d->buffer());
            }
        } else if (d->type() == WaylandSurface::Direct) {
            return d->compositor->graphicsHWIntegration()->isYInverted(d->buffer());
        }
    }
#endif
    //shm surfaces are not flipped (in our "world")
    return false;
}

void Surface::damage(const QRect &rect)
{
    Q_D(Surface);

#ifdef QT_COMPOSITOR_WAYLAND_GL
    if (d->compositor->graphicsHWIntegration() && d->type() == WaylandSurface::Direct) {
        //should the texture be deleted here, or should we explicitly delete it
        //when going into direct mode...
        if (d->textureCreatedForBuffer) {
            glDeleteTextures(1,&d->texture_id);
            d->textureCreatedForBuffer = false;
        }
        if (d->compositor->graphicsHWIntegration()->postBuffer(d->buffer())) {
            if (d->previousBuffer) {
                wl_client_post_event(d->client,&d->previousBuffer->resource.object,WL_BUFFER_RELEASE);
            }
            d->previousBuffer = d->buffer();
            return;
        }
    }
#endif

    d->compositor->markSurfaceAsDirty(this);

    emit d->qtSurface->damaged(rect);
}

QImage Surface::image() const
{
    Q_D(const Surface);
    if (d->type() == WaylandSurface::Shm) {
        ShmBuffer *shmBuffer = static_cast<ShmBuffer *>(d->buffer()->user_data);
        return shmBuffer->image();
    }
    return QImage();
}

#ifdef QT_COMPOSITOR_WAYLAND_GL
GLuint Surface::textureId() const
{
    Q_D(const Surface);
    if (d->compositor->graphicsHWIntegration() && d->type() == WaylandSurface::Texture
         && !d->textureCreatedForBuffer) {
        glDeleteTextures(1,&d->texture_id);
        if (d->previousBuffer) {
            wl_client_post_event(d->client,&d->previousBuffer->resource.object,WL_BUFFER_RELEASE);
        }
        Surface *that = const_cast<Surface *>(this);
        GraphicsHardwareIntegration *hwIntegration = d->compositor->graphicsHWIntegration();
        that->d_func()->previousBuffer = d->buffer();
        that->d_func()->texture_id = hwIntegration->createTextureFromBuffer(d->buffer());
        that->d_func()->textureCreatedForBuffer = true;
    }
    return d->texture_id;
}
#endif // QT_COMPOSITOR_WAYLAND_GL

void Surface::attach(struct wl_buffer *buffer)
{
    Q_D(Surface);
    d->attach(buffer);
}

WaylandSurface * Surface::handle() const
{
    Q_D(const Surface);
    return d->qtSurface;
}

wl_client *Surface::clientHandle() const
{
    Q_D(const Surface);
    return d->client;
}

qint64 Surface::processId() const
{
    Q_D(const Surface);
    return d->processId;
}

void Surface::setProcessId(qint64 processId)
{
    Q_D(Surface);
    d->processId = processId;
}

QByteArray Surface::authenticationToken() const
{
    Q_D(const Surface);
    return WindowManagerServerIntegration::instance()->managedClient(d->client)->authenticationToken();
}

QVariantMap Surface::windowProperties() const
{
    Q_D(const Surface);
    return d->windowProperties;
}

QVariant Surface::windowProperty(const QString &propertyName) const
{
    Q_D(const Surface);
    QVariantMap props = d->windowProperties;
    return props.value(propertyName);
}

void Surface::setWindowProperty(const QString &name, const QVariant &value, bool writeUpdateToClient)
{
    Q_D(Surface);
    d->windowProperties.insert(name, value);
    if (writeUpdateToClient)
        WindowManagerServerIntegration::instance()->setWindowProperty(d->client, base(), name, value);
}

uint32_t toWaylandButton(Qt::MouseButton button)
{
#ifndef BTN_LEFT
uint32_t BTN_LEFT = 0x110;
uint32_t BTN_RIGHT = 0x111;
uint32_t BTN_MIDDLE = 0x112;
#endif
    switch (button) {
    case Qt::LeftButton:
        return BTN_LEFT;
    case Qt::RightButton:
        return BTN_RIGHT;
    default:
        return BTN_MIDDLE;
    }

}

QPoint Surface::lastMousePos() const
{
    Q_D(const Surface);
    return d->lastMousePos;
}

void Surface::sendMousePressEvent(int x, int y, Qt::MouseButton button)
{
    Q_D(Surface);
    sendMouseMoveEvent(x, y);
    if (d->client) {
        uint32_t time = d->compositor->currentTimeMsecs();
        wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object,
                             WL_INPUT_DEVICE_BUTTON, time, toWaylandButton(button), 1);
    }
}

void Surface::sendMouseReleaseEvent(int x, int y, Qt::MouseButton button)
{
    Q_D(Surface);
    sendMouseMoveEvent(x, y);
    if (d->client) {
        uint32_t time = d->compositor->currentTimeMsecs();
        wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object,
                             WL_INPUT_DEVICE_BUTTON, time, toWaylandButton(button), 0);
    }
}

void Surface::sendMouseMoveEvent(int x, int y)
{
    Q_D(Surface);
    if (d->client) {
        d->lastMousePos = QPoint(x, y);
        uint32_t time = d->compositor->currentTimeMsecs();
        d->compositor->setPointerFocus(this, QPoint(x, y));
        wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object,
             WL_INPUT_DEVICE_MOTION, time, x, y, x, y);
    }
}

void Surface::sendKeyPressEvent(uint code)
{
    Q_D(Surface);
    if (d->compositor->defaultInputDevice()->keyboard_focus != NULL) {
        uint32_t time = d->compositor->currentTimeMsecs();
        wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object,
                             WL_INPUT_DEVICE_KEY, time, code - 8, 1);
    }

}

void Surface::sendKeyReleaseEvent(uint code)
{
    Q_D(Surface);
    if (d->compositor->defaultInputDevice()->keyboard_focus != NULL) {
        uint32_t time = d->compositor->currentTimeMsecs();
        wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object,
                             WL_INPUT_DEVICE_KEY, time, code - 8, 0);
    }
}

void Surface::sendTouchPointEvent(int id, int x, int y, Qt::TouchPointState state)
{
    Q_D(Surface);
    uint32_t time = d->compositor->currentTimeMsecs();
    struct wl_client *client = d->client;
    struct wl_object *dev = &d->compositor->defaultInputDevice()->object;
    switch (state) {
    case Qt::TouchPointPressed:
        wl_client_post_event(client, dev, WL_INPUT_DEVICE_TOUCH_DOWN, time, id, x, y);
        break;
    case Qt::TouchPointMoved:
        wl_client_post_event(client, dev, WL_INPUT_DEVICE_TOUCH_MOTION, time, id, x, y);
        break;
    case Qt::TouchPointReleased:
        wl_client_post_event(client, dev, WL_INPUT_DEVICE_TOUCH_UP, time, id);
        break;
    case Qt::TouchPointStationary:
        // stationary points are not sent through wayland, the client must cache them
        break;
    default:
        break;
    }
}

void Surface::sendTouchFrameEvent()
{
    Q_D(Surface);
    wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object,
                         WL_INPUT_DEVICE_TOUCH_FRAME);
}

void Surface::sendTouchCancelEvent()
{
    Q_D(Surface);
    wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object,
                         WL_INPUT_DEVICE_TOUCH_CANCEL);
}

void Surface::frameFinished()
{
    Q_D(Surface);
    d->compositor->frameFinished(this);
}

void Surface::setInputFocus()
{
    Q_D(Surface);
    d->compositor->setInputFocus(this);
}

void Surface::sendOnScreenVisibilityChange(bool visible)
{
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
    Q_D(Surface);
    WindowManagerServerIntegration::instance()->setVisibilityOnScreen(d->client, visible);
#endif
}

} // namespace Wayland

<commit_msg>Don't call glDeleteTextures() when texture_id is 0.<commit_after>/****************************************************************************
**
** This file is part of QtCompositor**
**
** Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
**
** Contact:  Nokia Corporation qt-info@nokia.com
**
** You may use this file under the terms of the BSD license as follows:
**
** Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**
** Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
**
** Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in the
** documentation and/or other materials provided with the distribution.
**
** Neither the name of Nokia Corporation and its Subsidiary(-ies) nor the
** names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
****************************************************************************/

#include "wlsurface.h"

#include "waylandsurface.h"

#include "wlcompositor.h"
#include "wlshmbuffer.h"

#include <QtCore/QDebug>

#include <wayland-server.h>

#ifdef Q_OS_LINUX
#include <linux/input.h>
#endif

#ifdef QT_COMPOSITOR_WAYLAND_GL
#include "hardware_integration/graphicshardwareintegration.h"
#include <QtGui/QPlatformOpenGLContext>
#endif

#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
#include "waylandwindowmanagerintegration.h"
#endif

namespace Wayland {

class SurfacePrivate
{
public:
    SurfacePrivate(struct wl_client *client, Compositor *compositor)
        : client(client)
        , compositor(compositor)
        , textureCreatedForBuffer(false)
        , directRenderBuffer(0)
        , processId(0)
        , previousBuffer(0)
        , surfaceBuffer(0)
        , surfaceType(WaylandSurface::Invalid)

    {
#ifdef QT_COMPOSITOR_WAYLAND_GL
        texture_id = 0;
#endif
    }

    WaylandSurface::Type type() const {
        if (surfaceType == WaylandSurface::Invalid) {
            SurfacePrivate *that = const_cast<SurfacePrivate *>(this);
            if (qtSurface->handle() == compositor->directRenderSurface()) {
                that->surfaceType = WaylandSurface::Direct;
            } else if (surfaceBuffer && wl_buffer_is_shm(surfaceBuffer)) {
                that->surfaceType = WaylandSurface::Shm;
            } else if (surfaceBuffer){
                that->surfaceType = WaylandSurface::Texture;
            }
        }
        return surfaceType;
    }

    void attach(struct wl_buffer *buffer) {
        bool emitMap = !surfaceBuffer;
        if (surfaceBuffer && ! textureCreatedForBuffer) {
            qWarning() << "### WaylandSurface::attach() releasing undisplayed buffer ###";
             wl_client_post_event(client,&surfaceBuffer->resource.object,WL_BUFFER_RELEASE);
        }
        surfaceBuffer = buffer;
        surfaceType = WaylandSurface::Invalid;
        textureCreatedForBuffer = false;
        if (emitMap) {
            qtSurface->mapped(QSize(surfaceBuffer->width,surfaceBuffer->height));
        }
    }

    inline struct wl_buffer *buffer() const { return surfaceBuffer; }

    struct wl_client *client;
    Compositor *compositor;
    WaylandSurface *qtSurface;

#ifdef QT_COMPOSITOR_WAYLAND_GL
    GLuint texture_id;
#endif
    bool textureCreatedForBuffer;
    struct wl_buffer *directRenderBuffer;
    qint64 processId;
    QByteArray authenticationToken;
    QVariantMap windowProperties;

    QPoint lastMousePos;

    struct wl_buffer *previousBuffer;
private:
    struct wl_buffer *surfaceBuffer;
    WaylandSurface::Type surfaceType;
};

void surface_destroy(struct wl_client *client, struct wl_surface *surface)
{
    wl_resource_destroy(&surface->resource, client, Compositor::currentTimeMsecs());
}

void surface_attach(struct wl_client *client, struct wl_surface *surface,
                    struct wl_buffer *buffer, int x, int y)
{
    Q_UNUSED(client);
    Q_UNUSED(x);
    Q_UNUSED(y);

    wayland_cast<Surface *>(surface)->attach(buffer);
}

void surface_damage(struct wl_client *client, struct wl_surface *surface,
                    int32_t x, int32_t y, int32_t width, int32_t height)
{
    Q_UNUSED(client);
    wayland_cast<Surface *>(surface)->damage(QRect(x, y, width, height));
}

Surface::Surface(struct wl_client *client, Compositor *compositor)
    : d_ptr(new SurfacePrivate(client,compositor))
{
    base()->client = client;
    d_ptr->qtSurface = new WaylandSurface(this);

}

Surface::~Surface()
{
    Q_D(Surface);
    d->compositor->surfaceDestroyed(this);
#ifdef QT_COMPOSITOR_WAYLAND_GL
    if (d->compositor->graphicsHWIntegration())
        glDeleteTextures(1,&d->texture_id);
#endif
    delete d->qtSurface;
}

WaylandSurface::Type Surface::type() const
{
    Q_D(const Surface);
    return d->type();
}

bool Surface::isYInverted() const
{
#ifdef QT_COMPOSITOR_WAYLAND_GL
    Q_D(const Surface);

    if (d->compositor->graphicsHWIntegration()) {
        if (d->type() == WaylandSurface::Texture) {
            if (textureId()) {
                return d->compositor->graphicsHWIntegration()->isYInverted(d->buffer());
            }
        } else if (d->type() == WaylandSurface::Direct) {
            return d->compositor->graphicsHWIntegration()->isYInverted(d->buffer());
        }
    }
#endif
    //shm surfaces are not flipped (in our "world")
    return false;
}

void Surface::damage(const QRect &rect)
{
    Q_D(Surface);

#ifdef QT_COMPOSITOR_WAYLAND_GL
    if (d->compositor->graphicsHWIntegration() && d->type() == WaylandSurface::Direct) {
        //should the texture be deleted here, or should we explicitly delete it
        //when going into direct mode...
        if (d->textureCreatedForBuffer) {
            glDeleteTextures(1,&d->texture_id);
            d->textureCreatedForBuffer = false;
        }
        if (d->compositor->graphicsHWIntegration()->postBuffer(d->buffer())) {
            if (d->previousBuffer) {
                wl_client_post_event(d->client,&d->previousBuffer->resource.object,WL_BUFFER_RELEASE);
            }
            d->previousBuffer = d->buffer();
            return;
        }
    }
#endif

    d->compositor->markSurfaceAsDirty(this);

    emit d->qtSurface->damaged(rect);
}

QImage Surface::image() const
{
    Q_D(const Surface);
    if (d->type() == WaylandSurface::Shm) {
        ShmBuffer *shmBuffer = static_cast<ShmBuffer *>(d->buffer()->user_data);
        return shmBuffer->image();
    }
    return QImage();
}

#ifdef QT_COMPOSITOR_WAYLAND_GL
GLuint Surface::textureId() const
{
    Q_D(const Surface);
    if (d->compositor->graphicsHWIntegration() && d->type() == WaylandSurface::Texture
         && !d->textureCreatedForBuffer) {
        if (d->texture_id)
            glDeleteTextures(1,&d->texture_id);
        if (d->previousBuffer) {
            wl_client_post_event(d->client,&d->previousBuffer->resource.object,WL_BUFFER_RELEASE);
        }
        Surface *that = const_cast<Surface *>(this);
        GraphicsHardwareIntegration *hwIntegration = d->compositor->graphicsHWIntegration();
        that->d_func()->previousBuffer = d->buffer();
        that->d_func()->texture_id = hwIntegration->createTextureFromBuffer(d->buffer());
        that->d_func()->textureCreatedForBuffer = true;
    }
    return d->texture_id;
}
#endif // QT_COMPOSITOR_WAYLAND_GL

void Surface::attach(struct wl_buffer *buffer)
{
    Q_D(Surface);
    d->attach(buffer);
}

WaylandSurface * Surface::handle() const
{
    Q_D(const Surface);
    return d->qtSurface;
}

wl_client *Surface::clientHandle() const
{
    Q_D(const Surface);
    return d->client;
}

qint64 Surface::processId() const
{
    Q_D(const Surface);
    return d->processId;
}

void Surface::setProcessId(qint64 processId)
{
    Q_D(Surface);
    d->processId = processId;
}

QByteArray Surface::authenticationToken() const
{
    Q_D(const Surface);
    return WindowManagerServerIntegration::instance()->managedClient(d->client)->authenticationToken();
}

QVariantMap Surface::windowProperties() const
{
    Q_D(const Surface);
    return d->windowProperties;
}

QVariant Surface::windowProperty(const QString &propertyName) const
{
    Q_D(const Surface);
    QVariantMap props = d->windowProperties;
    return props.value(propertyName);
}

void Surface::setWindowProperty(const QString &name, const QVariant &value, bool writeUpdateToClient)
{
    Q_D(Surface);
    d->windowProperties.insert(name, value);
    if (writeUpdateToClient)
        WindowManagerServerIntegration::instance()->setWindowProperty(d->client, base(), name, value);
}

uint32_t toWaylandButton(Qt::MouseButton button)
{
#ifndef BTN_LEFT
uint32_t BTN_LEFT = 0x110;
uint32_t BTN_RIGHT = 0x111;
uint32_t BTN_MIDDLE = 0x112;
#endif
    switch (button) {
    case Qt::LeftButton:
        return BTN_LEFT;
    case Qt::RightButton:
        return BTN_RIGHT;
    default:
        return BTN_MIDDLE;
    }

}

QPoint Surface::lastMousePos() const
{
    Q_D(const Surface);
    return d->lastMousePos;
}

void Surface::sendMousePressEvent(int x, int y, Qt::MouseButton button)
{
    Q_D(Surface);
    sendMouseMoveEvent(x, y);
    if (d->client) {
        uint32_t time = d->compositor->currentTimeMsecs();
        wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object,
                             WL_INPUT_DEVICE_BUTTON, time, toWaylandButton(button), 1);
    }
}

void Surface::sendMouseReleaseEvent(int x, int y, Qt::MouseButton button)
{
    Q_D(Surface);
    sendMouseMoveEvent(x, y);
    if (d->client) {
        uint32_t time = d->compositor->currentTimeMsecs();
        wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object,
                             WL_INPUT_DEVICE_BUTTON, time, toWaylandButton(button), 0);
    }
}

void Surface::sendMouseMoveEvent(int x, int y)
{
    Q_D(Surface);
    if (d->client) {
        d->lastMousePos = QPoint(x, y);
        uint32_t time = d->compositor->currentTimeMsecs();
        d->compositor->setPointerFocus(this, QPoint(x, y));
        wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object,
             WL_INPUT_DEVICE_MOTION, time, x, y, x, y);
    }
}

void Surface::sendKeyPressEvent(uint code)
{
    Q_D(Surface);
    if (d->compositor->defaultInputDevice()->keyboard_focus != NULL) {
        uint32_t time = d->compositor->currentTimeMsecs();
        wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object,
                             WL_INPUT_DEVICE_KEY, time, code - 8, 1);
    }

}

void Surface::sendKeyReleaseEvent(uint code)
{
    Q_D(Surface);
    if (d->compositor->defaultInputDevice()->keyboard_focus != NULL) {
        uint32_t time = d->compositor->currentTimeMsecs();
        wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object,
                             WL_INPUT_DEVICE_KEY, time, code - 8, 0);
    }
}

void Surface::sendTouchPointEvent(int id, int x, int y, Qt::TouchPointState state)
{
    Q_D(Surface);
    uint32_t time = d->compositor->currentTimeMsecs();
    struct wl_client *client = d->client;
    struct wl_object *dev = &d->compositor->defaultInputDevice()->object;
    switch (state) {
    case Qt::TouchPointPressed:
        wl_client_post_event(client, dev, WL_INPUT_DEVICE_TOUCH_DOWN, time, id, x, y);
        break;
    case Qt::TouchPointMoved:
        wl_client_post_event(client, dev, WL_INPUT_DEVICE_TOUCH_MOTION, time, id, x, y);
        break;
    case Qt::TouchPointReleased:
        wl_client_post_event(client, dev, WL_INPUT_DEVICE_TOUCH_UP, time, id);
        break;
    case Qt::TouchPointStationary:
        // stationary points are not sent through wayland, the client must cache them
        break;
    default:
        break;
    }
}

void Surface::sendTouchFrameEvent()
{
    Q_D(Surface);
    wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object,
                         WL_INPUT_DEVICE_TOUCH_FRAME);
}

void Surface::sendTouchCancelEvent()
{
    Q_D(Surface);
    wl_client_post_event(d->client, &d->compositor->defaultInputDevice()->object,
                         WL_INPUT_DEVICE_TOUCH_CANCEL);
}

void Surface::frameFinished()
{
    Q_D(Surface);
    d->compositor->frameFinished(this);
}

void Surface::setInputFocus()
{
    Q_D(Surface);
    d->compositor->setInputFocus(this);
}

void Surface::sendOnScreenVisibilityChange(bool visible)
{
#ifdef QT_WAYLAND_WINDOWMANAGER_SUPPORT
    Q_D(Surface);
    WindowManagerServerIntegration::instance()->setVisibilityOnScreen(d->client, visible);
#endif
}

} // namespace Wayland

<|endoftext|>


<commit_before>// Copyright (c) 2017 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: http://opensource.org/licenses/AFL-3.0
// http://vittorioromeo.info | vittorio.romeo@outlook.com

#include "./example_utils.hpp"
#include <fstream>
#include <iostream>
#include <memory>
#include <string>
#include <tuple>

// clang-format off
using num = int;
struct o_add { };
struct o_sub { };
struct o_mul { };
struct o_div { };
// clang-format on

using op = example::variant<o_add, o_sub, o_mul, o_div>;

namespace impl
{
    namespace sr = scelta::recursive;
    using _ = sr::placeholder;

    template <typename T>
    using recr_expr = std::tuple<num, op, std::unique_ptr<_>>;

    using builder = sr::builder<example::variant<num, recr_expr<_>>>;

    using type = sr::type<builder>;
    using resolved_recr_expr = sr::resolve<builder, recr_expr<_>>;
}

using base_expr = impl::type;
using recr_expr = impl::resolved_recr_expr;

template <typename Op, typename Rest>
auto recr(num x, Op op, Rest&& rest)
{
    return std::make_unique<recr_expr>(x, op, FWD(rest));
}

int main()
{
}<commit_msg>Added expression evaluation example<commit_after>// Copyright (c) 2017 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: http://opensource.org/licenses/AFL-3.0
// http://vittorioromeo.info | vittorio.romeo@outlook.com

#include "./example_utils.hpp"
#include <fstream>
#include <iostream>
#include <memory>
#include <string>
#include <tuple>

// clang-format off
using num = int;
struct o_add { };
struct o_sub { };
struct o_mul { };
struct o_div { };
// clang-format on

using op = example::variant<o_add, o_sub, o_mul, o_div>;

namespace impl
{
    namespace sr = scelta::recursive;
    using _ = sr::placeholder;

    template <typename T>
    using recr_expr = std::tuple<num, op, _>;

    using builder =
        sr::builder<example::variant<num, std::unique_ptr<recr_expr<_>>>>;

    using type = sr::type<builder>;
    using resolved_recr_expr = sr::resolve<builder, recr_expr<_>>;
}

using expr = impl::type;
using recr_expr = impl::resolved_recr_expr;

template <typename Op, typename Rest>
auto recr(num x, Op o, Rest&& rest)
{
    return std::make_unique<recr_expr>(x, op{o}, FWD(rest));
}

int main()
{
    expr e = recr(2, o_mul{}, recr(5, o_add{}, recr(15, o_div{}, 3)));

    // clang-format off
    std::cout << scelta::recursive::match<num>(
        [](auto, const num& x)
        {
            return x;
        },
        [](auto recurse, const std::unique_ptr<recr_expr>& x)
        {
            const auto& lhs = std::get<0>(*x);
            const auto& op  = std::get<1>(*x);
            const auto& rhs = recurse(std::get<2>(*x));

            return scelta::match([&](o_add){ return lhs + rhs; },
                                 [&](o_sub){ return lhs - rhs; },
                                 [&](o_mul){ return lhs * rhs; },
                                 [&](o_div){ return lhs / rhs; })(op);
        })
        (e);
    // clang-format on
}<|endoftext|>


<commit_before>#include <Arduino.h>
#include "ArduinoClass.h"
#include <stdlib.h>

const char* nanpy::ArduinoClass::get_firmware_id()
{
    return "A";
}

void nanpy::ArduinoClass::elaborate( nanpy::MethodDescriptor* m ) {
        if (strcmp(m->getName(), "dw") == 0) { // digitalWrite
            digitalWrite(m->getInt(0), m->getInt(1));
            m->returns(0);
        }

        if (strcmp(m->getName(), "r") == 0) {  // digitalRead
            m->returns(digitalRead(m->getInt(0)));
        }

        if (strcmp(m->getName(), "aw") == 0) { // analogWrite
            analogWrite(m->getInt(0), m->getInt(1));
            m->returns(0);
        }

        if (strcmp(m->getName(), "a") == 0) {  // analogRead
            m->returns(analogRead(m->getInt(0)));
        }

        if (strcmp(m->getName(), "pm") == 0) {  // pinMode
            pinMode(m->getInt(0), m->getInt(1));
            m->returns(0);
        }

        if (strcmp(m->getName(), "delay") == 0) {
            m->returns(0);
        }

        if (strcmp(m->getName(), "m") == 0) {  // millis
            m->returns(millis());
        }

        if (strcmp(m->getName(), "s") == 0) {  // shiftOut
            // shiftOut(dataPin, clockPin, bitOrder, value)
            shiftOut(m->getInt(0), m->getInt(1), m->getInt(2), m->getInt(3));
            m->returns(0);
        }
};
<commit_msg>Experimental PulseIn<commit_after>#include <Arduino.h>
#include "ArduinoClass.h"
#include <stdlib.h>

const char* nanpy::ArduinoClass::get_firmware_id()
{
    return "A";
}

void nanpy::ArduinoClass::elaborate( nanpy::MethodDescriptor* m ) {
        if (strcmp(m->getName(), "dw") == 0) { // digitalWrite
            digitalWrite(m->getInt(0), m->getInt(1));
            m->returns(0);
        }

        if (strcmp(m->getName(), "r") == 0) {  // digitalRead
            m->returns(digitalRead(m->getInt(0)));
        }

        if (strcmp(m->getName(), "aw") == 0) { // analogWrite
            analogWrite(m->getInt(0), m->getInt(1));
            m->returns(0);
        }

        if (strcmp(m->getName(), "a") == 0) {  // analogRead
            m->returns(analogRead(m->getInt(0)));
        }

        if (strcmp(m->getName(), "pm") == 0) {  // pinMode
            pinMode(m->getInt(0), m->getInt(1));
            m->returns(0);
        }

        if (strcmp(m->getName(), "delay") == 0) {
            m->returns(0);
        }

        if (strcmp(m->getName(), "m") == 0) {  // millis
            m->returns(millis());
        }

	if (strcmp(m->getName(), "pi") == 0) {  // pulseIn
	  pulseIn(m->getInt(0), m->getInt(1));
	  m->returns(0);
	}

        if (strcmp(m->getName(), "s") == 0) {  // shiftOut
            // shiftOut(dataPin, clockPin, bitOrder, value)
            shiftOut(m->getInt(0), m->getInt(1), m->getInt(2), m->getInt(3));
            m->returns(0);
        }
};
<|endoftext|>


<commit_before>/*=========================================================================

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbPerBandVectorImageFilter.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkShrinkImageFilter.h"
#include "otbImageFileReader.h"
#include "otbObjectList.h"
#include "otbStreamingImageFileWriter.h"
#include "otbCommandLineArgumentParser.h"
#include "otbStandardWriterWatcher.h"

#include "otbWrapperParameter.h"
#include "otbWrapperOutputImageParameter.h"

namespace otb
{
namespace Wrapper
{

class MultiResolutionPyramid : public Application
{

public:
  /** Standard class typedefs. */
  typedef MultiResolutionPyramid        Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(MultiResolutionPyramid, otb::Application);

  /** Image and filters typedef */
  typedef otb::Image<float>                                         SingleImageType;
  typedef itk::DiscreteGaussianImageFilter<SingleImageType,
                                           SingleImageType>         SmoothingImageFilterType;

  typedef otb::PerBandVectorImageFilter<FloatVectorImageType,
                                        FloatVectorImageType,
                                        SmoothingImageFilterType>   SmoothingVectorImageFilterType;

  typedef itk::ShrinkImageFilter<FloatVectorImageType,
                                 FloatVectorImageType>              ShrinkFilterType;

private:
  MultiResolutionPyramid()
  {
    SetName("MultiResolutionPyramid");
    SetDescription("Build a multi-resolution pyramid of the image.");
  }

  void DoCreateParameters()
  {
    AddParameter(ParameterType_InputImage, "in", "Input Image");

    AddParameter(ParameterType_OutputImage, "out", "Output Image");
    SetParameterDescription("out","will be used to get the prefix and the extension of the images to write");

    AddParameter(ParameterType_Int, "level", "Number Of Levels");
    SetParameterInt("level", 1);
    SetParameterDescription( "level", "Number of levels in the pyramid (default is 1)");

    AddParameter(ParameterType_Int, "sfactor", "Subsampling factor");
    SetParameterInt("sfactor", 2);

    AddParameter(ParameterType_Float,  "vfactor", "Subsampling factor");
    SetParameterFloat("vfactor", 0.6);

    // Boolean Fast scheme
    //     AddParameter(ParameterType_Empty, "fast", "Use Fast Scheme");
    //     std::ostringstream desc;
    //     desc<<"If used, this option allows to speed-up computation by iteratively"
    //        <<" subsampling previous level of pyramid instead of processing the full input";
    //     SetParameterDescription("fast", desc.str());
    //     MandatoryOff("fast");
  }

  void DoUpdateParameters()
  {
    // Nothing to do here for the parameters : all are independent

    // Reinitialize the internal process used
  }

  void DoExecute()
  {
    // Initializing the process
    m_SmoothingFilter =  SmoothingVectorImageFilterType::New();
    m_ShrinkFilter    = ShrinkFilterType::New();

    // Extract Parameters
    unsigned int nbLevels     = GetParameterInt("level");
    unsigned int shrinkFactor = GetParameterInt("sfactor");
    double varianceFactor     = GetParameterFloat("vfactor");

    //bool fastScheme = parseResult->IsOptionPresent("FastScheme");
    bool fastScheme = false;

    // Get the input image
    FloatVectorImageType::Pointer inImage = GetParameterImage("in");

    // Get the Initial Output Image FileName
    Parameter* param = GetParameterByKey("out");
    std::string path, fname, ext;
    if (dynamic_cast<OutputImageParameter*>(param))
      {
      OutputImageParameter* paramDown = dynamic_cast<OutputImageParameter*>(param);
      std::string ofname = paramDown->GetFileName();

      // Get the extension and the prefix of the filename
      path  = itksys::SystemTools::GetFilenamePath(ofname);
      fname = itksys::SystemTools::GetFilenameWithoutExtension(ofname);
      ext   = itksys::SystemTools::GetFilenameExtension(ofname);
      }

    unsigned int currentLevel = 1;
    unsigned int currentFactor = shrinkFactor;

    while(currentLevel <= nbLevels)
      {
      otbAppLogDEBUG( << "Processing level " << currentLevel << " with shrink factor "<<currentFactor);

      m_SmoothingFilter->SetInput(inImage);

      // According to
      // http://www.ipol.im/pub/algo/gjmr_line_segment_detector/
      // This is a good balance between blur and aliasing
      double variance = varianceFactor * static_cast<double>(currentFactor);
      m_SmoothingFilter->GetFilter()->SetVariance(variance);

      m_ShrinkFilter->SetInput(m_SmoothingFilter->GetOutput());
      m_ShrinkFilter->SetShrinkFactors(currentFactor);

      if(!fastScheme)
        {
        currentFactor*=shrinkFactor;
        }

      // Get the Output Parameter to change the current image filename
      Parameter* param = GetParameterByKey("out");
      if (dynamic_cast<OutputImageParameter*>(param))
        {
        OutputImageParameter* paramDown = dynamic_cast<OutputImageParameter*>(param);

        // build the current image filename
        std::ostringstream oss;
        oss <<path<<"/"<<fname<<"_"<<currentLevel<<ext;

        // writer label
        std::ostringstream osswriter;
        osswriter<< "writer (level "<< currentLevel<<")";

        // Set the filename of the current output image
        paramDown->SetFileName(oss.str());

        // Add the current level to be written
        SetParameterOutputImage("out", m_ShrinkFilter->GetOutput());
        paramDown->InitializeWriters();
        AddProcess(paramDown->GetWriter(),osswriter.str());
        paramDown->Write();
        }
      ++currentLevel;
      }

    // Disable the output Image parameter to avoid writing
    // the last image (Application::ExecuteAndWriteOutput method)
    GetParameterByKey("out")->SetActive(false);
  }

  SmoothingVectorImageFilterType::Pointer   m_SmoothingFilter;
  ShrinkFilterType::Pointer                 m_ShrinkFilter;
};
}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::MultiResolutionPyramid)

<commit_msg>STYLE<commit_after>/*=========================================================================

 Program:   ORFEO Toolbox
 Language:  C++
 Date:      $Date$
 Version:   $Revision$

 Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
 See OTBCopyright.txt for details.

 This software is distributed WITHOUT ANY WARRANTY; without even
 the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 PURPOSE.  See the above copyright notices for more information.

 =========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbPerBandVectorImageFilter.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkShrinkImageFilter.h"
#include "otbImageFileReader.h"
#include "otbObjectList.h"
#include "otbStreamingImageFileWriter.h"
#include "otbCommandLineArgumentParser.h"
#include "otbStandardWriterWatcher.h"

#include "otbWrapperParameter.h"
#include "otbWrapperOutputImageParameter.h"

namespace otb
{
namespace Wrapper
{

class MultiResolutionPyramid : public Application
{

public:
  /** Standard class typedefs. */
  typedef MultiResolutionPyramid        Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(MultiResolutionPyramid, otb::Application);

  /** Image and filters typedef */
  typedef otb::Image<float>                                         SingleImageType;
  typedef itk::DiscreteGaussianImageFilter<SingleImageType,
                                           SingleImageType>         SmoothingImageFilterType;

  typedef otb::PerBandVectorImageFilter<FloatVectorImageType,
                                        FloatVectorImageType,
                                        SmoothingImageFilterType>   SmoothingVectorImageFilterType;

  typedef itk::ShrinkImageFilter<FloatVectorImageType,
                                 FloatVectorImageType>              ShrinkFilterType;

private:
  MultiResolutionPyramid()
  {
    SetName("MultiResolutionPyramid");
    SetDescription("Build a multi-resolution pyramid of the image.");
  }

  void DoCreateParameters()
  {
    AddParameter(ParameterType_InputImage, "in", "Input Image");

    AddParameter(ParameterType_OutputImage, "out", "Output Image");
    SetParameterDescription("out","will be used to get the prefix and the extension of the images to write");

    AddParameter(ParameterType_Int, "level", "Number Of Levels");
    SetParameterInt("level", 1);
    SetParameterDescription( "level", "Number of levels in the pyramid (default is 1)");

    AddParameter(ParameterType_Int, "sfactor", "Subsampling factor");
    SetParameterInt("sfactor", 2);

    AddParameter(ParameterType_Float,  "vfactor", "Subsampling factor");
    SetParameterFloat("vfactor", 0.6);

    // Boolean Fast scheme
    //     AddParameter(ParameterType_Empty, "fast", "Use Fast Scheme");
    //     std::ostringstream desc;
    //     desc<<"If used, this option allows to speed-up computation by iteratively"
    //        <<" subsampling previous level of pyramid instead of processing the full input";
    //     SetParameterDescription("fast", desc.str());
    //     MandatoryOff("fast");
  }

  void DoUpdateParameters()
  {
    // Nothing to do here for the parameters : all are independent

    // Reinitialize the internal process used
  }

  void DoExecute()
  {
    // Initializing the process
    m_SmoothingFilter =  SmoothingVectorImageFilterType::New();
    m_ShrinkFilter    = ShrinkFilterType::New();

    // Extract Parameters
    unsigned int nbLevels     = GetParameterInt("level");
    unsigned int shrinkFactor = GetParameterInt("sfactor");
    double varianceFactor     = GetParameterFloat("vfactor");

    //bool fastScheme = parseResult->IsOptionPresent("FastScheme");
    bool fastScheme = false;

    // Get the input image
    FloatVectorImageType::Pointer inImage = GetParameterImage("in");

    // Get the Initial Output Image FileName
    Parameter* param = GetParameterByKey("out");
    std::string path, fname, ext;
    if (dynamic_cast<OutputImageParameter*>(param))
      {
      OutputImageParameter* paramDown =
        dynamic_cast<OutputImageParameter*>(param);
      std::string ofname = paramDown->GetFileName();

      // Get the extension and the prefix of the filename
      path  = itksys::SystemTools::GetFilenamePath(ofname);
      fname = itksys::SystemTools::GetFilenameWithoutExtension(ofname);
      ext   = itksys::SystemTools::GetFilenameExtension(ofname);
      }

    unsigned int currentLevel = 1;
    unsigned int currentFactor = shrinkFactor;

    while(currentLevel <= nbLevels)
      {
      otbAppLogDEBUG( << "Processing level " << currentLevel
                      << " with shrink factor "<<currentFactor);

      m_SmoothingFilter->SetInput(inImage);

      // According to
      // http://www.ipol.im/pub/algo/gjmr_line_segment_detector/
      // This is a good balance between blur and aliasing
      double variance = varianceFactor * static_cast<double>(currentFactor);
      m_SmoothingFilter->GetFilter()->SetVariance(variance);

      m_ShrinkFilter->SetInput(m_SmoothingFilter->GetOutput());
      m_ShrinkFilter->SetShrinkFactors(currentFactor);

      if(!fastScheme)
        {
        currentFactor *= shrinkFactor;
        }

      // Get the Output Parameter to change the current image filename
      Parameter* param = GetParameterByKey("out");
      if (dynamic_cast<OutputImageParameter*>(param))
        {
        OutputImageParameter* paramDown = dynamic_cast<OutputImageParameter*>(param);

        // build the current image filename
        std::ostringstream oss;
        oss <<path<<"/"<<fname<<"_"<<currentLevel<<ext;

        // writer label
        std::ostringstream osswriter;
        osswriter<< "writer (level "<< currentLevel<<")";

        // Set the filename of the current output image
        paramDown->SetFileName(oss.str());

        // Add the current level to be written
        SetParameterOutputImage("out", m_ShrinkFilter->GetOutput());
        paramDown->InitializeWriters();
        AddProcess(paramDown->GetWriter(),osswriter.str());
        paramDown->Write();
        }
      ++currentLevel;
      }

    // Disable the output Image parameter to avoid writing
    // the last image (Application::ExecuteAndWriteOutput method)
    GetParameterByKey("out")->SetActive(false);
  }

  SmoothingVectorImageFilterType::Pointer   m_SmoothingFilter;
  ShrinkFilterType::Pointer                 m_ShrinkFilter;
};
}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::MultiResolutionPyramid)
<|endoftext|>


<commit_before>#include "metadata_editor.h"
#include "halley/tools/project/project.h"
#include "halley/ui/ui_factory.h"
#include "halley/ui/ui_validator.h"
#include "halley/ui/widgets/ui_checkbox.h"
#include "halley/ui/widgets/ui_label.h"
#include "halley/ui/widgets/ui_textinput.h"
#include "src/ui/select_asset_widget.h"
using namespace Halley;

MetadataEditor::MetadataEditor(UIFactory& factory)
	: UIWidget("metadataEditor", {}, UISizer(UISizerType::Grid, 1, 2))
	, factory(factory)
{
}

void MetadataEditor::setResource(Project& p, AssetType type, const Path& path, Metadata effectiveMeta)
{
	assetType = type;
	filePath = path;
	project = &p;
	metadata = project->readMetadataFromDisk(filePath);
	effectiveMetadata = std::move(effectiveMeta);

	makeUI();
}

void MetadataEditor::onMetadataChanged()
{
	changed = true;
	getWidget("applyChanges")->setEnabled(true);
}

void MetadataEditor::saveMetadata()
{
	if (changed) {
		project->writeMetadataToDisk(filePath, metadata);
		changed = false;
		getWidget("applyChanges")->setEnabled(false);
	}
}

void MetadataEditor::makeUI()
{
	clear();
	add(factory.makeUI("ui/halley/metadata_editor"));
	fields = getWidget("fields");
	getWidget("applyChanges")->setEnabled(false);

	setHandle(UIEventType::ButtonClicked, "applyChanges", [=](const UIEvent& event)
	{
		saveMetadata();
	});

	switch (assetType) {
	case AssetType::Sprite:
	case AssetType::Animation:
		addInt2Field("Pivot", "pivotX", "pivotY", Vector2i());
		addInt4Field("Slices", "slice_left", "slice_right", "slice_bottom", "slice_top", Vector4i());
		addBoolField("By Group", "group_separated", false);
		addAssetTypeField("Material", "material", AssetType::MaterialDefinition, "Halley/Sprite");
		addStringField("Atlas", "atlas", "");
		addStringField("Palette", "palette", "");
		addBoolField("Filtering", "filtering", false);
		addBoolField("Minimap", "minimap", false);
		addEnumField<TextureFormat>("Format", "format", "rgba");
		addEnumField<TextureAddressMode>("Address", "addressMode", "clamp");
		addInt2Field("Tile Split", "tileWidth", "tileHeight", Vector2i());
		addBoolField("Trim", "trim", true);
		addIntField("Padding", "padding", 0);
		break;

	case AssetType::AudioClip:
		addBoolField("Streaming", "streaming", false);
		addIntField("Loop Point", "loopPoint", 0);
		break;

	case AssetType::Font:
		addFloatField("Font Size", "fontSize", 0);
		addStringField("Font Name", "fontName", "");
		addInt2Field("Image Size", "width", "height", Vector2i(512, 512));
		addIntField("Supersample", "supersample", 4);
		addInt2Field("Range", "rangeStart", "rangeEnd", Vector2i(0, 255));
		addIntField("Ascender Adj.", "ascenderAdjustment", 0);
		addIntField("Line Spacing", "lineSpacing", 0);
		addFloatField("Radius", "radius", 8.0f);
		addStringField("Fallback", "fallback", "");
		addFloatField("Fallback Scale", "replacementScale", 1.0f);
		addStringField("Extra characters", "extraCharacters", "");
		break;
	}
}

void MetadataEditor::addIntField(const String& name, const String& key, int defaultValue)
{
	makeLabel(name);
	makeIntField(fields->getSizer(), key, defaultValue);
}

void MetadataEditor::addInt2Field(const String& name, const String& x, const String& y, Vector2i defaultValue)
{
	makeLabel(name);
	auto sizer = std::make_shared<UISizer>();
	fields->add(sizer, 1);
	makeIntField(*sizer, x, defaultValue.x);
	makeIntField(*sizer, y, defaultValue.y);
}

void MetadataEditor::addInt4Field(const String& name, const String& x, const String& y, const String& z, const String& w, Vector4i defaultValue)
{
	makeLabel(name);
	auto sizer = std::make_shared<UISizer>();
	fields->add(sizer, 1);
	makeIntField(*sizer, x, defaultValue.x);
	makeIntField(*sizer, y, defaultValue.y);
	makeIntField(*sizer, z, defaultValue.z);
	makeIntField(*sizer, w, defaultValue.w);
}

void MetadataEditor::addFloatField(const String& name, const String& key, float defaultValue)
{
	makeLabel(name);
	makeFloatField(fields->getSizer(), key, defaultValue);
}

void MetadataEditor::addBoolField(const String& name, const String& key, bool defaultValue)
{
	makeLabel(name);
	makeBoolField(fields->getSizer(), key, defaultValue);
}

void MetadataEditor::addStringField(const String& name, const String& key, const String& defaultValue)
{
	makeLabel(name);
	makeStringField(fields->getSizer(), key, defaultValue);
}

void MetadataEditor::addAssetTypeField(const String& name, const String& key, AssetType type, const String& defaultValue)
{
	makeLabel(name);
	makeAssetTypeField(fields->getSizer(), key, type, defaultValue);
}

void MetadataEditor::addDropdownField(const String& name, const String& key, std::vector<String> values, const String& defaultValue)
{
	makeLabel(name);
	makeDropdownField(fields->getSizer(), key, std::move(values), defaultValue);
}

void MetadataEditor::makeLabel(const String& name)
{
	fields->add(std::make_shared<UILabel>("", factory.getStyle("label").getTextRenderer("label"), LocalisedString::fromUserString(name)), 0, Vector4f(0, 0, 10, 0), UISizerAlignFlags::CentreVertical);
}

template <typename T>
void updateMetadata(Metadata& metadata, const String& key, MetadataEditor& editor, const T& value, const T& defaultValue)
{
	if (value == defaultValue) {
		if (metadata.erase(key)) {
			editor.onMetadataChanged();
		}
	} else {
		if (metadata.set(key, value)) {
			editor.onMetadataChanged();
		}
	}
}

void MetadataEditor::makeIntField(UISizer& sizer, const String& key, int defaultValue)
{
	const auto result = std::make_shared<UITextInput>(key, factory.getStyle("inputThin"));
	result->setMinSize(Vector2f(40, 22));
	result->setValidator(std::make_shared<UINumericValidator>(true, false));
	sizer.add(result, 1);

	const auto effectiveDefault = effectiveMetadata.getInt(":" + key, defaultValue);

	bindData(key, metadata.getInt(key, effectiveDefault), [=] (int value)
	{
		updateMetadata(metadata, key, *this, value, effectiveDefault);
	});
}

void MetadataEditor::makeFloatField(UISizer& sizer, const String& key, float defaultValue)
{
	const auto result = std::make_shared<UITextInput>(key, factory.getStyle("inputThin"));
	result->setMinSize(Vector2f(40, 22));
	result->setValidator(std::make_shared<UINumericValidator>(true, true));
	sizer.add(result, 1);
	bindData(key, metadata.getFloat(key, defaultValue), [=] (float value)
	{
		updateMetadata(metadata, key, *this, value, defaultValue);
	});
}

void MetadataEditor::makeBoolField(UISizer& sizer, const String& key, bool defaultValue)
{
	const auto result = std::make_shared<UICheckbox>(key, factory.getStyle("checkbox"));
	result->setMinSize(Vector2f(22, 22));
	sizer.add(result, 1, {}, UISizerAlignFlags::Left | UISizerAlignFlags::CentreVertical);
	bindData(key, metadata.getBool(key, defaultValue), [=] (bool value)
	{
		updateMetadata(metadata, key, *this, value, defaultValue);
	});
}

void MetadataEditor::makeStringField(UISizer& sizer, const String& key, const String& defaultValue)
{
	const auto result = std::make_shared<UITextInput>(key, factory.getStyle("inputThin"));
	result->setMinSize(Vector2f(40, 22));
	sizer.add(result, 1);

	const auto effectiveDefault = effectiveMetadata.getString(":" + key, defaultValue);
	const auto value = metadata.getString(key, "");
	result->setGhostText(LocalisedString::fromUserString(effectiveDefault));

	bindData(key, value, [=] (const String& value)
	{
		updateMetadata(metadata, key, *this, value, defaultValue);
	});
}

void MetadataEditor::makeDropdownField(UISizer& sizer, const String& key, std::vector<String> values, const String& defaultValue)
{
	const auto result = std::make_shared<UIDropdown>(key, factory.getStyle("dropdown"), factory.getStyle("scrollbar"), factory.getStyle("list"));
	result->setOptions(std::move(values));
	sizer.add(result, 1);

	const auto effectiveDefault = effectiveMetadata.getString(":" + key, defaultValue);
	const auto value = metadata.getString(key, effectiveDefault);

	bindData(key, value, [=] (const String& value)
	{
		updateMetadata(metadata, key, *this, value, defaultValue);
	});
}

void MetadataEditor::makeAssetTypeField(UISizer& sizer, const String& key, AssetType type, const String& defaultValue)
{
	const auto result = std::make_shared<SelectAssetWidget>(key, factory, type);
	result->setGameResources(project->getGameResources());
	result->setMinSize(Vector2f(40, 22));
	sizer.add(result, 1);

	const auto effectiveDefault = effectiveMetadata.getString(":" + key, defaultValue);
	const auto value = metadata.getString(key, effectiveDefault);

	bindData(key, value, [=] (const String& value)
	{
		updateMetadata(metadata, key, *this, value, defaultValue);
	});
}
<commit_msg>Further improvements to metadata editor<commit_after>#include "metadata_editor.h"
#include "halley/tools/project/project.h"
#include "halley/ui/ui_factory.h"
#include "halley/ui/ui_validator.h"
#include "halley/ui/widgets/ui_checkbox.h"
#include "halley/ui/widgets/ui_label.h"
#include "halley/ui/widgets/ui_textinput.h"
#include "src/ui/select_asset_widget.h"
using namespace Halley;

MetadataEditor::MetadataEditor(UIFactory& factory)
	: UIWidget("metadataEditor", {}, UISizer(UISizerType::Grid, 1, 2))
	, factory(factory)
{
}

void MetadataEditor::setResource(Project& p, AssetType type, const Path& path, Metadata effectiveMeta)
{
	assetType = type;
	filePath = path;
	project = &p;
	metadata = project->readMetadataFromDisk(filePath);
	effectiveMetadata = std::move(effectiveMeta);

	makeUI();
}

void MetadataEditor::onMetadataChanged()
{
	changed = true;
	getWidget("applyChanges")->setEnabled(true);
}

void MetadataEditor::saveMetadata()
{
	if (changed) {
		project->writeMetadataToDisk(filePath, metadata);
		changed = false;
		getWidget("applyChanges")->setEnabled(false);
	}
}

void MetadataEditor::makeUI()
{
	clear();
	add(factory.makeUI("ui/halley/metadata_editor"));
	fields = getWidget("fields");
	getWidget("applyChanges")->setEnabled(false);

	setHandle(UIEventType::ButtonClicked, "applyChanges", [=](const UIEvent& event)
	{
		saveMetadata();
	});

	const bool isAseprite = filePath.getExtension() == ".ase" || filePath.getExtension() == ".aseprite";

	switch (assetType) {
	case AssetType::Sprite:
	case AssetType::Animation:
		addInt2Field("Pivot", "pivotX", "pivotY", Vector2i());
		addInt4Field("Slices", "slice_left", "slice_right", "slice_bottom", "slice_top", Vector4i());
		if (isAseprite) {
			addBoolField("By Group", "group_separated", false);
		}
		addAssetTypeField("Material", "material", AssetType::MaterialDefinition, "Halley/Sprite");
		addStringField("Atlas", "atlas", "");
		addAssetTypeField("Palette", "palette", AssetType::Texture, "");
		addBoolField("Filtering", "filtering", false);
		addBoolField("Minimap", "minimap", false);
		addEnumField<TextureFormat>("Format", "format", "rgba");
		addEnumField<TextureAddressMode>("Address", "addressMode", "clamp");
		addInt2Field("Tile Split", "tileWidth", "tileHeight", Vector2i());
		addBoolField("Trim", "trim", true);
		addIntField("Padding", "padding", 0);
		break;

	case AssetType::AudioClip:
		addBoolField("Streaming", "streaming", false);
		addIntField("Loop Point", "loopPoint", 0);
		break;

	case AssetType::Font:
		addFloatField("Font Size", "fontSize", 0);
		addStringField("Font Name", "fontName", "");
		addInt2Field("Image Size", "width", "height", Vector2i(512, 512));
		addIntField("Supersample", "supersample", 4);
		addInt2Field("Range", "rangeStart", "rangeEnd", Vector2i(0, 255));
		addIntField("Ascender Adj.", "ascenderAdjustment", 0);
		addIntField("Line Spacing", "lineSpacing", 0);
		addFloatField("Radius", "radius", 8.0f);
		addStringField("Fallback", "fallback", "");
		addFloatField("Fallback Scale", "replacementScale", 1.0f);
		addStringField("Extra characters", "extraCharacters", "");
		break;
	}
}

void MetadataEditor::addIntField(const String& name, const String& key, int defaultValue)
{
	makeLabel(name);
	makeIntField(fields->getSizer(), key, defaultValue);
}

void MetadataEditor::addInt2Field(const String& name, const String& x, const String& y, Vector2i defaultValue)
{
	makeLabel(name);
	auto sizer = std::make_shared<UISizer>();
	fields->add(sizer, 1);
	makeIntField(*sizer, x, defaultValue.x);
	makeIntField(*sizer, y, defaultValue.y);
}

void MetadataEditor::addInt4Field(const String& name, const String& x, const String& y, const String& z, const String& w, Vector4i defaultValue)
{
	makeLabel(name);
	auto sizer = std::make_shared<UISizer>();
	fields->add(sizer, 1);
	makeIntField(*sizer, x, defaultValue.x);
	makeIntField(*sizer, y, defaultValue.y);
	makeIntField(*sizer, z, defaultValue.z);
	makeIntField(*sizer, w, defaultValue.w);
}

void MetadataEditor::addFloatField(const String& name, const String& key, float defaultValue)
{
	makeLabel(name);
	makeFloatField(fields->getSizer(), key, defaultValue);
}

void MetadataEditor::addBoolField(const String& name, const String& key, bool defaultValue)
{
	makeLabel(name);
	makeBoolField(fields->getSizer(), key, defaultValue);
}

void MetadataEditor::addStringField(const String& name, const String& key, const String& defaultValue)
{
	makeLabel(name);
	makeStringField(fields->getSizer(), key, defaultValue);
}

void MetadataEditor::addAssetTypeField(const String& name, const String& key, AssetType type, const String& defaultValue)
{
	makeLabel(name);
	makeAssetTypeField(fields->getSizer(), key, type, defaultValue);
}

void MetadataEditor::addDropdownField(const String& name, const String& key, std::vector<String> values, const String& defaultValue)
{
	makeLabel(name);
	makeDropdownField(fields->getSizer(), key, std::move(values), defaultValue);
}

void MetadataEditor::makeLabel(const String& name)
{
	fields->add(std::make_shared<UILabel>("", factory.getStyle("label").getTextRenderer("label"), LocalisedString::fromUserString(name)), 0, Vector4f(0, 0, 10, 0), UISizerAlignFlags::CentreVertical);
}

template <typename T>
void updateMetadata(Metadata& metadata, const String& key, MetadataEditor& editor, const T& value, const T& defaultValue)
{
	if (value == defaultValue) {
		if (metadata.erase(key)) {
			editor.onMetadataChanged();
		}
	} else {
		if (metadata.set(key, value)) {
			editor.onMetadataChanged();
		}
	}
}

void MetadataEditor::makeIntField(UISizer& sizer, const String& key, int defaultValue)
{
	const auto result = std::make_shared<UITextInput>(key, factory.getStyle("inputThin"));
	result->setMinSize(Vector2f(40, 22));
	result->setValidator(std::make_shared<UINumericValidator>(true, false));
	sizer.add(result, 1);

	const auto effectiveDefault = effectiveMetadata.getString(":" + key, toString(defaultValue));
	const auto value = metadata.getString(key, "");
	result->setGhostText(LocalisedString::fromUserString(effectiveDefault));

	bindData(key, value, [=] (const String& value)
	{
		updateMetadata(metadata, key, *this, value, toString(defaultValue));
	});
}

void MetadataEditor::makeFloatField(UISizer& sizer, const String& key, float defaultValue)
{
	const auto result = std::make_shared<UITextInput>(key, factory.getStyle("inputThin"));
	result->setMinSize(Vector2f(40, 22));
	result->setValidator(std::make_shared<UINumericValidator>(true, true));
	sizer.add(result, 1);

	const auto effectiveDefault = effectiveMetadata.getString(":" + key, toString(defaultValue));
	const auto value = metadata.getString(key, "");
	result->setGhostText(LocalisedString::fromUserString(effectiveDefault));

	bindData(key, value, [=] (const String& value)
	{
		updateMetadata(metadata, key, *this, value, toString(defaultValue));
	});
}

void MetadataEditor::makeBoolField(UISizer& sizer, const String& key, bool defaultValue)
{
	const auto result = std::make_shared<UICheckbox>(key, factory.getStyle("checkbox"));
	result->setMinSize(Vector2f(22, 22));
	sizer.add(result, 1, {}, UISizerAlignFlags::Left | UISizerAlignFlags::CentreVertical);

	const auto effectiveDefault = effectiveMetadata.getBool(":" + key, defaultValue);

	bindData(key, metadata.getBool(key, effectiveDefault), [=] (bool value)
	{
		updateMetadata(metadata, key, *this, value, defaultValue);
	});
}

void MetadataEditor::makeStringField(UISizer& sizer, const String& key, const String& defaultValue)
{
	const auto result = std::make_shared<UITextInput>(key, factory.getStyle("inputThin"));
	result->setMinSize(Vector2f(40, 22));
	sizer.add(result, 1);

	const auto effectiveDefault = effectiveMetadata.getString(":" + key, defaultValue);
	const auto value = metadata.getString(key, "");
	result->setGhostText(LocalisedString::fromUserString(effectiveDefault));

	bindData(key, value, [=] (const String& value)
	{
		updateMetadata(metadata, key, *this, value, defaultValue);
	});
}

void MetadataEditor::makeDropdownField(UISizer& sizer, const String& key, std::vector<String> values, const String& defaultValue)
{
	const auto result = std::make_shared<UIDropdown>(key, factory.getStyle("dropdown"), factory.getStyle("scrollbar"), factory.getStyle("list"));
	result->setOptions(std::move(values));
	sizer.add(result, 1);

	const auto effectiveDefault = effectiveMetadata.getString(":" + key, defaultValue);
	const auto value = metadata.getString(key, effectiveDefault);

	bindData(key, value, [=] (const String& value)
	{
		updateMetadata(metadata, key, *this, value, defaultValue);
	});
}

void MetadataEditor::makeAssetTypeField(UISizer& sizer, const String& key, AssetType type, const String& defaultValue)
{
	const auto result = std::make_shared<SelectAssetWidget>(key, factory, type);
	result->setGameResources(project->getGameResources());
	result->setMinSize(Vector2f(40, 22));
	sizer.add(result, 1);

	const auto effectiveDefault = effectiveMetadata.getString(":" + key, defaultValue);
	const auto value = metadata.getString(key, effectiveDefault);

	bindData(key, value, [=] (const String& value)
	{
		updateMetadata(metadata, key, *this, value, defaultValue);
	});
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ImageControl.hxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-10 16:01:22 $
 *
 *  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 _FRM_IMAGE_CONTROL_HXX_
#define _FRM_IMAGE_CONTROL_HXX_

#include "FormComponent.hxx"

#ifndef _PRODUCE_HXX //autogen
#include <svtools/imgprod.hxx>
#endif

#ifndef _COM_SUN_STAR_FORM_XIMAGEPRODUCERSUPPLIER_HPP_
#include <com/sun/star/form/XImageProducerSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XMOUSELISTENER_HPP_
#include <com/sun/star/awt/XMouseListener.hpp>
#endif

#ifndef _COMPHELPER_PROPERTY_MULTIPLEX_HXX_
#include <comphelper/propmultiplex.hxx>
#endif
#ifndef _COMPHELPER_IMPLEMENTATIONREFERENCE_HXX
#include <comphelper/implementationreference.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

using namespace comphelper;

//.........................................................................
namespace frm
{
//.........................................................................

//==================================================================
// OImageControlModel
//==================================================================
typedef ::cppu::ImplHelper2 <   ::com::sun::star::form::XImageProducerSupplier
                            ,   ::com::sun::star::awt::XImageProducer
                            >   OImageControlModel_Base;

class OImageControlModel
                :public OImageControlModel_Base
                ,public ::comphelper::OAggregationArrayUsageHelper<OImageControlModel>
                ,public OBoundControlModel
{
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XImageProducer>    m_xImageProducer;
    ImageProducer*                                  m_pImageProducer;
    sal_Bool                                        m_bReadOnly;

protected:
    // UNO Anbindung
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();

    inline ImageProducer* GetImageProducer() { return m_pImageProducer; }

public:
    DECLARE_DEFAULT_LEAF_XTOR( OImageControlModel );

    virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const;
    virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue) throw ( ::com::sun::star::uno::Exception);

    virtual sal_Bool SAL_CALL convertFastPropertyValue(::com::sun::star::uno::Any& rConvertedValue, ::com::sun::star::uno::Any& rOldValue, sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue )
        throw(::com::sun::star::lang::IllegalArgumentException);

    // UNO Anbindung
    DECLARE_UNO3_AGG_DEFAULTS(OImageControlModel, OBoundControlModel);
    virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException);

// ::com::sun::star::lang::XServiceInfo
    IMPLEMENTATION_NAME(OImageControlModel);
    virtual StringSequence SAL_CALL getSupportedServiceNames() throw();

// OComponentHelper
    virtual void SAL_CALL disposing();

// OPropertyChangeListener
    virtual void _propertyChanged( const ::com::sun::star::beans::PropertyChangeEvent& ) throw(::com::sun::star::uno::RuntimeException);

// ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
    virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();

// ::com::sun::star::io::XPersistObject
    virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);

// ::com::sun::star::form::XImageProducerSupplier
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XImageProducer> SAL_CALL getImageProducer() throw ( ::com::sun::star::uno::RuntimeException);

// XImageProducer
    virtual void SAL_CALL addConsumer( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XImageConsumer >& xConsumer ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeConsumer( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XImageConsumer >& xConsumer ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL startProduction(  ) throw (::com::sun::star::uno::RuntimeException);

// ::comphelper::OAggregationArrayUsageHelper
    virtual void fillProperties(
        ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps,
        ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps
        ) const;
    IMPLEMENT_INFO_SERVICE()

protected:
    // OBoundControlModel overridables
    virtual ::com::sun::star::uno::Any
                            translateDbColumnToControlValue( );
    virtual sal_Bool        commitControlValueToDbColumn( bool _bPostReset );

    virtual void            doSetControlValue( const ::com::sun::star::uno::Any& _rValue );

    virtual sal_Bool        approveDbColumnType(sal_Int32 _nColumnType);

    virtual void            resetNoBroadcast();

protected:
    DECLARE_XCLONEABLE();

    void implConstruct();

    /** updates the database column we're bound to with the given stream

If the stream is <NULL/>, then XColumnUpdate::updateNull will be called for the
        column.

        @precond
            m_xColumnUpdate is not <NULL/>
    */
    void        updateColumnWithStream( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& _rxStream );

    /** displays the image described by the given URL
        @precond
            our own mutex is locked
    */
    sal_Bool    handleNewImageURL( const ::rtl::OUString& _rURL, ValueChangeInstigator _eInstigator );
};

//==================================================================
//= OImageIndicator (helper class for OImageControlControl)
//==================================================================
typedef ::cppu::WeakImplHelper1 <   ::com::sun::star::awt::XImageConsumer
                                >   OImageIndicator_Base;

class OImageIndicator : public OImageIndicator_Base
{
private:
    sal_Bool    m_bIsProducing  : 1;
    sal_Bool    m_bIsEmptyImage : 1;

public:
    OImageIndicator( );

            void        reset();
    inline  sal_Bool    isEmptyImage() const { return m_bIsEmptyImage; }

protected:
    ~OImageIndicator( );
    // XImageProducer
    virtual void SAL_CALL init( sal_Int32 Width, sal_Int32 Height ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setColorModel( sal_Int16 BitCount, const ::com::sun::star::uno::Sequence< sal_Int32 >& RGBAPal, sal_Int32 RedMask, sal_Int32 GreenMask, sal_Int32 BlueMask, sal_Int32 AlphaMask ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPixelsByBytes( sal_Int32 nX, sal_Int32 nY, sal_Int32 nWidth, sal_Int32 nHeight, const ::com::sun::star::uno::Sequence< sal_Int8 >& aProducerData, sal_Int32 nOffset, sal_Int32 nScanSize ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPixelsByLongs( sal_Int32 nX, sal_Int32 nY, sal_Int32 nWidth, sal_Int32 nHeight, const ::com::sun::star::uno::Sequence< sal_Int32 >& aProducerData, sal_Int32 nOffset, sal_Int32 nScanSize ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL complete( sal_Int32 Status, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XImageProducer >& xProducer ) throw (::com::sun::star::uno::RuntimeException);

private:
    OImageIndicator( const OImageIndicator& );              // never implemented
    OImageIndicator& operator=( const OImageIndicator& );   // never implemented
};

//==================================================================
//= OImageControlControl
//==================================================================
class OImageControlControl  :public ::com::sun::star::awt::XMouseListener
                            ,public OBoundControl
{
private:
    typedef ::comphelper::ImplementationReference< OImageIndicator, ::com::sun::star::awt::XImageConsumer >
                                ImageIndicatorReference;
    ImageIndicatorReference     m_pImageIndicator;

protected:
    // XTypeProvider
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();

public:
    OImageControlControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);

    // UNO
    DECLARE_UNO3_AGG_DEFAULTS(OImageControlControl, OBoundControl);
    virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException);

    // XEventListener
    virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException)
        { OBoundControl::disposing(_rSource); }

    // XServiceInfo
    IMPLEMENTATION_NAME(OImageControlControl);
    virtual StringSequence SAL_CALL getSupportedServiceNames() throw();

    // XMouseListener
    virtual void SAL_CALL mousePressed(const ::com::sun::star::awt::MouseEvent& e) throw ( ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL mouseReleased(const ::com::sun::star::awt::MouseEvent& e) throw ( ::com::sun::star::uno::RuntimeException) { }
    virtual void SAL_CALL mouseEntered(const ::com::sun::star::awt::MouseEvent& e) throw ( ::com::sun::star::uno::RuntimeException) { }
    virtual void SAL_CALL mouseExited(const ::com::sun::star::awt::MouseEvent& e) throw ( ::com::sun::star::uno::RuntimeException) { }

    // XControl
    virtual sal_Bool SAL_CALL setModel(const ::com::sun::star::uno::Reference<starawt::XControlModel>& _rxModel ) throw (::com::sun::star::uno::RuntimeException);

private:
    void    implClearGraphics( sal_Bool _bForce );
    void    implInsertGraphics();
};

//.........................................................................
}   // namespace frm
//.........................................................................

#endif // _FRM_IMAGE_CONTROL_HXX_

<commit_msg>INTEGRATION: CWS visibility03 (1.10.44); FILE MERGED 2005/03/24 23:39:07 mhu 1.10.44.2: RESYNC: (1.10-1.11); FILE MERGED 2005/03/24 14:31:58 mhu 1.10.44.1: #i45006# Adapted imgprod.hxx include.<commit_after>/*************************************************************************
 *
 *  $RCSfile: ImageControl.hxx,v $
 *
 *  $Revision: 1.12 $
 *
 *  last change: $Author: obo $ $Date: 2005-04-13 09:46:12 $
 *
 *  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 _FRM_IMAGE_CONTROL_HXX_
#define _FRM_IMAGE_CONTROL_HXX_

#include "FormComponent.hxx"

#ifndef _PRODUCE_HXX
#include "imgprod.hxx"
#endif

#ifndef _COM_SUN_STAR_FORM_XIMAGEPRODUCERSUPPLIER_HPP_
#include <com/sun/star/form/XImageProducerSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XMOUSELISTENER_HPP_
#include <com/sun/star/awt/XMouseListener.hpp>
#endif

#ifndef _COMPHELPER_PROPERTY_MULTIPLEX_HXX_
#include <comphelper/propmultiplex.hxx>
#endif
#ifndef _COMPHELPER_IMPLEMENTATIONREFERENCE_HXX
#include <comphelper/implementationreference.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

using namespace comphelper;

//.........................................................................
namespace frm
{
//.........................................................................

//==================================================================
// OImageControlModel
//==================================================================
typedef ::cppu::ImplHelper2 <   ::com::sun::star::form::XImageProducerSupplier
                            ,   ::com::sun::star::awt::XImageProducer
                            >   OImageControlModel_Base;

class OImageControlModel
                :public OImageControlModel_Base
                ,public ::comphelper::OAggregationArrayUsageHelper<OImageControlModel>
                ,public OBoundControlModel
{
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XImageProducer>    m_xImageProducer;
    ImageProducer*                                  m_pImageProducer;
    sal_Bool                                        m_bReadOnly;

protected:
    // UNO Anbindung
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();

    inline ImageProducer* GetImageProducer() { return m_pImageProducer; }

public:
    DECLARE_DEFAULT_LEAF_XTOR( OImageControlModel );

    virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const;
    virtual void SAL_CALL setFastPropertyValue_NoBroadcast(sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue) throw ( ::com::sun::star::uno::Exception);

    virtual sal_Bool SAL_CALL convertFastPropertyValue(::com::sun::star::uno::Any& rConvertedValue, ::com::sun::star::uno::Any& rOldValue, sal_Int32 nHandle, const ::com::sun::star::uno::Any& rValue )
        throw(::com::sun::star::lang::IllegalArgumentException);

    // UNO Anbindung
    DECLARE_UNO3_AGG_DEFAULTS(OImageControlModel, OBoundControlModel);
    virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException);

// ::com::sun::star::lang::XServiceInfo
    IMPLEMENTATION_NAME(OImageControlModel);
    virtual StringSequence SAL_CALL getSupportedServiceNames() throw();

// OComponentHelper
    virtual void SAL_CALL disposing();

// OPropertyChangeListener
    virtual void _propertyChanged( const ::com::sun::star::beans::PropertyChangeEvent& ) throw(::com::sun::star::uno::RuntimeException);

// ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet>
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);
    virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();

// ::com::sun::star::io::XPersistObject
    virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);

// ::com::sun::star::form::XImageProducerSupplier
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::awt::XImageProducer> SAL_CALL getImageProducer() throw ( ::com::sun::star::uno::RuntimeException);

// XImageProducer
    virtual void SAL_CALL addConsumer( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XImageConsumer >& xConsumer ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeConsumer( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XImageConsumer >& xConsumer ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL startProduction(  ) throw (::com::sun::star::uno::RuntimeException);

// ::comphelper::OAggregationArrayUsageHelper
    virtual void fillProperties(
        ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rProps,
        ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& /* [out] */ _rAggregateProps
        ) const;
    IMPLEMENT_INFO_SERVICE()

protected:
    // OBoundControlModel overridables
    virtual ::com::sun::star::uno::Any
                            translateDbColumnToControlValue( );
    virtual sal_Bool        commitControlValueToDbColumn( bool _bPostReset );

    virtual void            doSetControlValue( const ::com::sun::star::uno::Any& _rValue );

    virtual sal_Bool        approveDbColumnType(sal_Int32 _nColumnType);

    virtual void            resetNoBroadcast();

protected:
    DECLARE_XCLONEABLE();

    void implConstruct();

    /** updates the database column we're bound to with the given stream

If the stream is <NULL/>, then XColumnUpdate::updateNull will be called for the
        column.

        @precond
            m_xColumnUpdate is not <NULL/>
    */
    void        updateColumnWithStream( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& _rxStream );

    /** displays the image described by the given URL
        @precond
            our own mutex is locked
    */
    sal_Bool    handleNewImageURL( const ::rtl::OUString& _rURL, ValueChangeInstigator _eInstigator );
};

//==================================================================
//= OImageIndicator (helper class for OImageControlControl)
//==================================================================
typedef ::cppu::WeakImplHelper1 <   ::com::sun::star::awt::XImageConsumer
                                >   OImageIndicator_Base;

class OImageIndicator : public OImageIndicator_Base
{
private:
    sal_Bool    m_bIsProducing  : 1;
    sal_Bool    m_bIsEmptyImage : 1;

public:
    OImageIndicator( );

            void        reset();
    inline  sal_Bool    isEmptyImage() const { return m_bIsEmptyImage; }

protected:
    ~OImageIndicator( );
    // XImageProducer
    virtual void SAL_CALL init( sal_Int32 Width, sal_Int32 Height ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setColorModel( sal_Int16 BitCount, const ::com::sun::star::uno::Sequence< sal_Int32 >& RGBAPal, sal_Int32 RedMask, sal_Int32 GreenMask, sal_Int32 BlueMask, sal_Int32 AlphaMask ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPixelsByBytes( sal_Int32 nX, sal_Int32 nY, sal_Int32 nWidth, sal_Int32 nHeight, const ::com::sun::star::uno::Sequence< sal_Int8 >& aProducerData, sal_Int32 nOffset, sal_Int32 nScanSize ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL setPixelsByLongs( sal_Int32 nX, sal_Int32 nY, sal_Int32 nWidth, sal_Int32 nHeight, const ::com::sun::star::uno::Sequence< sal_Int32 >& aProducerData, sal_Int32 nOffset, sal_Int32 nScanSize ) throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL complete( sal_Int32 Status, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XImageProducer >& xProducer ) throw (::com::sun::star::uno::RuntimeException);

private:
    OImageIndicator( const OImageIndicator& );              // never implemented
    OImageIndicator& operator=( const OImageIndicator& );   // never implemented
};

//==================================================================
//= OImageControlControl
//==================================================================
class OImageControlControl  :public ::com::sun::star::awt::XMouseListener
                            ,public OBoundControl
{
private:
    typedef ::comphelper::ImplementationReference< OImageIndicator, ::com::sun::star::awt::XImageConsumer >
                                ImageIndicatorReference;
    ImageIndicatorReference     m_pImageIndicator;

protected:
    // XTypeProvider
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();

public:
    OImageControlControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);

    // UNO
    DECLARE_UNO3_AGG_DEFAULTS(OImageControlControl, OBoundControl);
    virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException);

    // XEventListener
    virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException)
        { OBoundControl::disposing(_rSource); }

    // XServiceInfo
    IMPLEMENTATION_NAME(OImageControlControl);
    virtual StringSequence SAL_CALL getSupportedServiceNames() throw();

    // XMouseListener
    virtual void SAL_CALL mousePressed(const ::com::sun::star::awt::MouseEvent& e) throw ( ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL mouseReleased(const ::com::sun::star::awt::MouseEvent& e) throw ( ::com::sun::star::uno::RuntimeException) { }
    virtual void SAL_CALL mouseEntered(const ::com::sun::star::awt::MouseEvent& e) throw ( ::com::sun::star::uno::RuntimeException) { }
    virtual void SAL_CALL mouseExited(const ::com::sun::star::awt::MouseEvent& e) throw ( ::com::sun::star::uno::RuntimeException) { }

    // XControl
    virtual sal_Bool SAL_CALL setModel(const ::com::sun::star::uno::Reference<starawt::XControlModel>& _rxModel ) throw (::com::sun::star::uno::RuntimeException);

private:
    void    implClearGraphics( sal_Bool _bForce );
    void    implInsertGraphics();
};

//.........................................................................
}   // namespace frm
//.........................................................................

#endif // _FRM_IMAGE_CONTROL_HXX_

<|endoftext|>


<commit_before>

#include "tiio_jpg.h"
#include "tiio_bmp.h"
#include "tiio_std.h"
#include "tfiletype.h"
#include "tflash.h"

using namespace Tiio;
using namespace TFileType;

void Tiio::defineStd() {
  defineReaderMaker("jpg", Tiio::makeJpgReader);
  defineWriterMaker("jpg", Tiio::makeJpgWriter, true);
  declare("jpg", TFileType::RASTER_IMAGE);
  defineWriterProperties("jpg", new JpgWriterProperties());

  defineReaderMaker("bmp", Tiio::makeBmpReader);
  defineWriterMaker("bmp", Tiio::makeBmpWriter, true);
  declare("bmp", TFileType::RASTER_IMAGE);
  defineWriterProperties("bmp", new BmpWriterProperties());
}
<commit_msg>support for jpeg import (#656)<commit_after>

#include "tiio_jpg.h"
#include "tiio_bmp.h"
#include "tiio_std.h"
#include "tfiletype.h"
#include "tflash.h"

using namespace Tiio;
using namespace TFileType;

void Tiio::defineStd() {
  defineReaderMaker("jpg", Tiio::makeJpgReader);
  defineWriterMaker("jpg", Tiio::makeJpgWriter, true);
  declare("jpg", TFileType::RASTER_IMAGE);
  defineWriterProperties("jpg", new JpgWriterProperties());

  defineReaderMaker("jpeg", Tiio::makeJpgReader);
  declare("jpeg", TFileType::RASTER_IMAGE);

  defineReaderMaker("bmp", Tiio::makeBmpReader);
  defineWriterMaker("bmp", Tiio::makeBmpWriter, true);
  declare("bmp", TFileType::RASTER_IMAGE);
  defineWriterProperties("bmp", new BmpWriterProperties());
}
<|endoftext|>