for (size_t iIter = 0; iIter < theXcbImage->width * theXcbImage->height; iIter++) {
            lData[iIter] |= 0xff000000;
        }

/* This file is part of Spectacle, the KDE screenshot utility

 */

#include "PlatformXcb.h"

#include <xcb/xcb_cursor.h>
#include <xcb/xcb_util.h>
#include <xcb/xfixes.h>

#include <X11/Xatom.h>
#include <X11/Xdefs.h>

#include <QAbstractNativeEventFilter>
#include <QApplication>
#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QDBusInterface>
#include <QGraphicsDropShadowEffect>
#include <QGraphicsPixmapItem>
#include <QGraphicsScene>
#include <QPainter>
#include <QScreen>
#include <QSet>
#include <QStack>
#include <QTimer>
#include <QX11Info>
#include <QtMath>

#include <KWindowInfo>
#include <KWindowSystem>

#include <memory>

/* -- XCB Image Smart Pointer ------------------------------------------------------------------ */

struct XcbImagePtrDeleter {
    void operator()(xcb_image_t *theXcbImage) const
    {
        if (theXcbImage) {
            xcb_image_destroy(theXcbImage);
        }
    }
};
using XcbImagePtr = std::unique_ptr<xcb_image_t, XcbImagePtrDeleter>;

struct CFreeDeleter {
    void operator()(void *ptr) const
    {
        free(ptr);
    }
};
template<typename Reply>
using XcbReplyPtr = std::unique_ptr<Reply, CFreeDeleter>;

/* -- On Click Native Event Filter ------------------------------------------------------------- */

class PlatformXcb::OnClickEventFilter : public QAbstractNativeEventFilter
{
public:
    explicit OnClickEventFilter(PlatformXcb *thePlatformPtr)
        : mPlatformPtr(thePlatformPtr)
    {
    }

    void setCaptureOptions(Platform::GrabMode theGrabMode, bool theIncludePointer, bool theIncludeDecorations)
    {
        mGrabMode = theGrabMode;
        mIncludePointer = theIncludePointer;
        mIncludeDecorations = theIncludeDecorations;
    }

    bool nativeEventFilter(const QByteArray &theEventType, void *theMessage, long * /* theResult */) override
    {
        if (theEventType == "xcb_generic_event_t") {
            auto lFirstEvent = static_cast<xcb_generic_event_t *>(theMessage);

            switch (lFirstEvent->response_type & ~0x80) {
            case XCB_BUTTON_RELEASE: {
                // uninstall the eventfilter and release the mouse
                qApp->removeNativeEventFilter(this);
                xcb_ungrab_pointer(QX11Info::connection(), XCB_TIME_CURRENT_TIME);

                // decide whether to grab or abort. regrab the mouse on mouse-wheel events
                {
                    auto lSecondEvent = static_cast<xcb_button_release_event_t *>(theMessage);
                    if (lSecondEvent->detail == 1) {
                        QTimer::singleShot(0, [this]() {
                            mPlatformPtr->doGrabNow(mGrabMode, mIncludePointer, mIncludeDecorations);
                        });
                    } else if (lSecondEvent->detail < 4) {
                        Q_EMIT mPlatformPtr->newScreenshotFailed();
                    } else {
                        QTimer::singleShot(0, [this]() {
                            mPlatformPtr->doGrabOnClick(mGrabMode, mIncludePointer, mIncludeDecorations);
                        });
                    }
                }
                return true;
            }
            default:
                return false;
            }
        }
        return false;
    }

private:
    PlatformXcb *mPlatformPtr;
    Platform::GrabMode mGrabMode{GrabMode::AllScreens};
    bool mIncludePointer{true};
    bool mIncludeDecorations{true};
};

/* -- General Plumbing ------------------------------------------------------------------------- */

PlatformXcb::PlatformXcb(QObject *theParent)
    : Platform(theParent)
    , mNativeEventFilter(new OnClickEventFilter(this))
{
}

PlatformXcb::~PlatformXcb()
{
    delete mNativeEventFilter;
}

QString PlatformXcb::platformName() const
{
    return QStringLiteral("Xcb");
}

Platform::GrabModes PlatformXcb::supportedGrabModes() const
{
    Platform::GrabModes lSupportedModes(
        {GrabMode::AllScreens, GrabMode::ActiveWindow, GrabMode::WindowUnderCursor, GrabMode::TransientWithParent, GrabMode::PerScreenImageNative});
    if (QApplication::screens().count() > 1) {
        lSupportedModes |= Platform::GrabMode::CurrentScreen;
    }
    return lSupportedModes;
}

Platform::ShutterModes PlatformXcb::supportedShutterModes() const
{
    return {ShutterMode::Immediate | ShutterMode::OnClick};
}

void PlatformXcb::doGrab(ShutterMode theShutterMode, GrabMode theGrabMode, bool theIncludePointer, bool theIncludeDecorations)
{
    switch (theShutterMode) {
    case ShutterMode::Immediate: {
        doGrabNow(theGrabMode, theIncludePointer, theIncludeDecorations);
        return;
    }
    case ShutterMode::OnClick: {
        doGrabOnClick(theGrabMode, theIncludePointer, theIncludeDecorations);
        return;
    }
    }
}

/* -- Platform Utilities ----------------------------------------------------------------------- */

void PlatformXcb::updateWindowTitle(xcb_window_t theWindow)
{
    auto lTitle = KWindowSystem::readNameProperty(theWindow, XA_WM_NAME);
    Q_EMIT windowTitleChanged(lTitle);
}

bool PlatformXcb::isKWinAvailable()
{
    if (QDBusConnection::sessionBus().interface()->isServiceRegistered(QStringLiteral("org.kde.KWin"))) {
        QDBusInterface lIface(QStringLiteral("org.kde.KWin"), QStringLiteral("/Effects"), QStringLiteral("org.kde.kwin.Effects"));
        QDBusReply<bool> lReply = lIface.call(QStringLiteral("isEffectLoaded"), QStringLiteral("screenshot"));
        return lReply.value();
    }
    return false;
}

/* -- XCB Utilities ---------------------------------------------------------------------------- */

QPoint PlatformXcb::getCursorPosition()
{
    // QCursor::pos() is not used because it requires additional calculations.
    // Its value is the offset to the origin of the current screen is in
    // device-independent pixels while the origin itself uses native pixels.

    auto lXcbConn = QX11Info::connection();
    auto lPointerCookie = xcb_query_pointer_unchecked(lXcbConn, QX11Info::appRootWindow());
    XcbReplyPtr<xcb_query_pointer_reply_t> lPointerReply(xcb_query_pointer_reply(lXcbConn, lPointerCookie, nullptr));

    return QPoint(lPointerReply->root_x, lPointerReply->root_y);
}

QRect PlatformXcb::getDrawableGeometry(xcb_drawable_t theDrawable)
{
    auto lXcbConn = QX11Info::connection();
    auto lGeoCookie = xcb_get_geometry_unchecked(lXcbConn, theDrawable);
    XcbReplyPtr<xcb_get_geometry_reply_t> lGeoReply(xcb_get_geometry_reply(lXcbConn, lGeoCookie, nullptr));
    if (!lGeoReply) {
        return QRect();
    }
    return QRect(lGeoReply->x, lGeoReply->y, lGeoReply->width, lGeoReply->height);
}

xcb_window_t PlatformXcb::getWindowUnderCursor()
{
    auto lXcbConn = QX11Info::connection();
    auto lAppWin = QX11Info::appRootWindow();

    const QByteArray lAtomName("WM_STATE");
    auto lAtomCookie = xcb_intern_atom_unchecked(lXcbConn, 0, lAtomName.length(), lAtomName.constData());
    auto lPointerCookie = xcb_query_pointer_unchecked(lXcbConn, lAppWin);
    XcbReplyPtr<xcb_intern_atom_reply_t> lAtomReply(xcb_intern_atom_reply(lXcbConn, lAtomCookie, nullptr));
    XcbReplyPtr<xcb_query_pointer_reply_t> lPointerReply(xcb_query_pointer_reply(lXcbConn, lPointerCookie, nullptr));

    if (lAtomReply->atom == XCB_ATOM_NONE) {
        return QX11Info::appRootWindow();
    }

    // now start testing
    QStack<xcb_window_t> lWindowStack;
    lWindowStack.push(lPointerReply->child);

    while (!lWindowStack.isEmpty()) {
        lAppWin = lWindowStack.pop();

        // next, check if our window has the WM_STATE property set on
        // the window. if yes, return the window - we have found it
        auto lPropCookie = xcb_get_property_unchecked(lXcbConn, 0, lAppWin, lAtomReply->atom, XCB_ATOM_ANY, 0, 0);
        XcbReplyPtr<xcb_get_property_reply_t> lPropReply(xcb_get_property_reply(lXcbConn, lPropCookie, nullptr));

        if (lPropReply->type != XCB_ATOM_NONE) {
            return lAppWin;
        }

        // if we're here, this means the window is not the real window
        // we should start looking at its children
        auto lTreeCookie = xcb_query_tree_unchecked(lXcbConn, lAppWin);
        XcbReplyPtr<xcb_query_tree_reply_t> lTreeReply(xcb_query_tree_reply(lXcbConn, lTreeCookie, nullptr));
        auto lWindowChildren = xcb_query_tree_children(lTreeReply.get());
        auto lWindowChildrenLength = xcb_query_tree_children_length(lTreeReply.get());

        for (int iIdx = lWindowChildrenLength - 1; iIdx >= 0; iIdx--) {
            lWindowStack.push(lWindowChildren[iIdx]);
        }
    }

    // return the window. it has geometry information for a crop
    return lPointerReply->child;
}

xcb_window_t PlatformXcb::getTransientWindowParent(xcb_window_t theChildWindow, QRect &theWindowRectOut, bool theIncludeDecorations)
{
    NET::Properties lNetProp = theIncludeDecorations ? NET::WMFrameExtents : NET::WMGeometry;
    KWindowInfo lWindowInfo(theChildWindow, lNetProp, NET::WM2TransientFor);

    // add the current window to the image
    if (theIncludeDecorations) {
        theWindowRectOut = lWindowInfo.frameGeometry();
    } else {
        theWindowRectOut = lWindowInfo.geometry();
    }
    return lWindowInfo.transientFor();
}

/* -- Image Processing Utilities --------------------------------------------------------------- */

QPixmap PlatformXcb::convertFromNative(xcb_image_t *theXcbImage)
{
    auto lImageFormat = QImage::Format_Invalid;
    switch (theXcbImage->depth) {
    case 1:
        lImageFormat = QImage::Format_MonoLSB;
        break;
    case 16:
        lImageFormat = QImage::Format_RGB16;
        break;
    case 24:
        lImageFormat = QImage::Format_RGB32;
        break;
    case 30:
        lImageFormat = QImage::Format_RGB30;
        break;
    case 32:
        lImageFormat = QImage::Format_ARGB32_Premultiplied;
        break;
    default:
        return QPixmap(); // we don't know
    }

    // the RGB32 format requires data format 0xffRRGGBB, ensure that this fourth byte really is 0xff
    if (lImageFormat == QImage::Format_RGB32) {
        auto lData = reinterpret_cast<quint32 *>(theXcbImage->data);

    }

    QImage lImage(theXcbImage->data, theXcbImage->width, theXcbImage->height, lImageFormat);
    if (lImage.isNull()) {
        return QPixmap();
    }

    // work around an abort in QImage::color
    if (lImage.format() == QImage::Format_MonoLSB) {
        lImage.setColorCount(2);
        lImage.setColor(0, QColor(Qt::white).rgb());
        lImage.setColor(1, QColor(Qt::black).rgb());
    }

    // the image is ready. Since the backing data from xcbImage could be freed
    // before the QPixmap goes away, a deep copy is necessary.
    return QPixmap::fromImage(lImage).copy();
}

QPixmap PlatformXcb::blendCursorImage(QPixmap &thePixmap, const QRect theRect)
{
    // If the cursor position lies outside the area, do not bother drawing a cursor.

    auto lCursorPos = getCursorPosition();
    if (!theRect.contains(lCursorPos)) {
        return thePixmap;
    }

    // now we can get the image and start processing
    auto lXcbConn = QX11Info::connection();

    auto lCursorCookie = xcb_xfixes_get_cursor_image_unchecked(lXcbConn);
    XcbReplyPtr<xcb_xfixes_get_cursor_image_reply_t> lCursorReply(xcb_xfixes_get_cursor_image_reply(lXcbConn, lCursorCookie, nullptr));
    if (!lCursorReply) {
        return thePixmap;
    }

    // get the image and process it into a qimage
    auto lPixelData = xcb_xfixes_get_cursor_image_cursor_image(lCursorReply.get());
    if (!lPixelData) {
        return thePixmap;
    }
    QImage lCursorImage(reinterpret_cast<quint8 *>(lPixelData), lCursorReply->width, lCursorReply->height, QImage::Format_ARGB32_Premultiplied);

    // a small fix for the cursor position for fancier cursors
    lCursorPos -= QPoint(lCursorReply->xhot, lCursorReply->yhot);

    // now we translate the cursor point to our screen rectangle and do the painting
    lCursorPos -= QPoint(theRect.x(), theRect.y());
    QPainter lPainter(&thePixmap);
    lPainter.drawImage(lCursorPos, lCursorImage);
    return thePixmap;
}

QPixmap PlatformXcb::postProcessPixmap(QPixmap &thePixmap, QRect theRect, bool theBlendPointer)
{
    if (!(theBlendPointer)) {
        // note: this may be the null pixmap if an error occurred.
        return thePixmap;
    }
    return blendCursorImage(thePixmap, theRect);
}

/* -- Capture Helpers -------------------------------------------------------------------------- */

QPixmap PlatformXcb::getPixmapFromDrawable(xcb_drawable_t theXcbDrawable, const QRect &theRect)
{
    auto lXcbConn = QX11Info::connection();

    // proceed to get an image based on the geometry (in device pixels)
    XcbImagePtr lXcbImage(xcb_image_get(lXcbConn, theXcbDrawable, theRect.x(), theRect.y(), theRect.width(), theRect.height(), ~0, XCB_IMAGE_FORMAT_Z_PIXMAP));

    // too bad, the capture failed.
    if (!lXcbImage) {
        return QPixmap();
    }

    // now process the image
    auto lPixmap = convertFromNative(lXcbImage.get());
    return lPixmap;
}

QPixmap PlatformXcb::getToplevelPixmap(QRect theRect, bool theBlendPointer)
{
    auto lRootWindow = QX11Info::appRootWindow();

    // treat a null rect as an alias for capturing fullscreen
    if (!theRect.isValid()) {
        theRect = getDrawableGeometry(lRootWindow);
    } else {
        QRegion lScreenRegion;
        const auto lScreens = QGuiApplication::screens();
        for (auto lScreen : lScreens) {
            auto lScreenRect = lScreen->geometry();

            // Do not use setSize() here, because QSize::operator*=()
            // performs qRound() which can result in xcb_image_get() failing
            const auto lPixelRatio = lScreen->devicePixelRatio();
            lScreenRect.setHeight(qFloor(lScreenRect.height() * lPixelRatio));
            lScreenRect.setWidth(qFloor(lScreenRect.width() * lPixelRatio));

            lScreenRegion += lScreenRect;
        }
        theRect = (lScreenRegion & theRect).boundingRect();
    }

    auto lPixmap = getPixmapFromDrawable(lRootWindow, theRect);
    return postProcessPixmap(lPixmap, theRect, theBlendPointer);
}

QPixmap PlatformXcb::getWindowPixmap(xcb_window_t theWindow, bool theBlendPointer)
{
    auto lXcbConn = QX11Info::connection();

    // first get geometry information for our window
    auto lGeoCookie = xcb_get_geometry_unchecked(lXcbConn, theWindow);
    XcbReplyPtr<xcb_get_geometry_reply_t> lGeoReply(xcb_get_geometry_reply(lXcbConn, lGeoCookie, nullptr));
    QRect lWindowRect(lGeoReply->x, lGeoReply->y, lGeoReply->width, lGeoReply->height);

    // then proceed to get an image
    auto lPixmap = getPixmapFromDrawable(theWindow, lWindowRect);

    // translate window coordinates to global ones.
    auto lRootGeoCookie = xcb_get_geometry_unchecked(lXcbConn, lGeoReply->root);
    XcbReplyPtr<xcb_get_geometry_reply_t> lRootGeoReply(xcb_get_geometry_reply(lXcbConn, lRootGeoCookie, nullptr));
    auto lTranslateCookie = xcb_translate_coordinates_unchecked(lXcbConn, theWindow, lGeoReply->root, lRootGeoReply->x, lRootGeoReply->y);
    XcbReplyPtr<xcb_translate_coordinates_reply_t> lTranslateReply(xcb_translate_coordinates_reply(lXcbConn, lTranslateCookie, nullptr));

    // adjust local to global coordinates.
    lWindowRect.moveRight(lWindowRect.x() + lTranslateReply->dst_x);
    lWindowRect.moveTop(lWindowRect.y() + lTranslateReply->dst_y);

    // if the window capture failed, try to obtain one from the full screen.
    if (lPixmap.isNull()) {
        return getToplevelPixmap(lWindowRect, theBlendPointer);
    }
    return postProcessPixmap(lPixmap, lWindowRect, theBlendPointer);
}

void PlatformXcb::handleKWinScreenshotReply(quint64 theDrawable)
{
    QDBusConnection::sessionBus().disconnect(QStringLiteral("org.kde.KWin"),
                                             QStringLiteral("/Screenshot"),
                                             QStringLiteral("org.kde.kwin.Screenshot"),
                                             QStringLiteral("screenshotCreated"),
                                             this,
                                             SLOT(handleKWinScreenshotReply(quint64)));

    // obtain width and height and grab an image (x and y are always zero for pixmaps)
    auto lDrawable = static_cast<xcb_drawable_t>(theDrawable);
    auto lRect = getDrawableGeometry(lDrawable);
    auto lPixmap = getPixmapFromDrawable(lDrawable, lRect);

    if (!lPixmap.isNull()) {
        Q_EMIT newScreenshotTaken(lPixmap);
        return;
    }
    Q_EMIT newScreenshotFailed();
}

/* -- Grabber Methods -------------------------------------------------------------------------- */

void PlatformXcb::grabAllScreens(bool theIncludePointer)
{
    auto lPixmap = getToplevelPixmap(QRect(), theIncludePointer);
    Q_EMIT newScreenshotTaken(lPixmap);
}

void PlatformXcb::grabCurrentScreen(bool theIncludePointer)
{
    auto lCursorPosition = QCursor::pos();
    const auto lScreens = QGuiApplication::screens();
    for (auto lScreen : lScreens) {
        auto lScreenRect = lScreen->geometry();
        if (!lScreenRect.contains(lCursorPosition)) {
            continue;
        }

        // the screen origin is in native pixels, but the size is device-dependent.
        // convert these also to native pixels.
        QRect lNativeScreenRect(lScreenRect.topLeft(), lScreenRect.size() * lScreen->devicePixelRatio());
        auto lPixmap = getToplevelPixmap(lNativeScreenRect, theIncludePointer);
        Q_EMIT newScreenshotTaken(lPixmap);
        return;
    }

    // no screen found with our cursor, fallback to capturing all screens
    grabAllScreens(theIncludePointer);
}

void PlatformXcb::grabApplicationWindow(xcb_window_t theWindow, bool theIncludePointer, bool theIncludeDecorations)
{
    // if the user doesn't want decorations captured, we're in luck. This is
    // the easiest bit

    auto lPixmap = getWindowPixmap(theWindow, theIncludePointer);
    if (!theIncludeDecorations || theWindow == QX11Info::appRootWindow()) {
        Q_EMIT newScreenshotTaken(lPixmap);
        return;
    }

    // if the user wants the window decorations, things get a little tricky.
    // we can't simply get a handle to the window manager frame window and
    // just grab it, because some compositing window managers (yes, kwin
    // included) do not render the window onto the frame but keep it in a
    // separate opengl buffer, so grabbing this window is going to simply
    // give us a transparent image with the frame and titlebar.

    // all is not lost. what we need to do is grab the image of the entire
    // desktop, find the geometry of the window including its frame, and
    // crop the root image accordingly.

    KWindowInfo lWindowInfo(theWindow, NET::WMFrameExtents);
    if (lWindowInfo.valid()) {
        auto lFrameGeom = lWindowInfo.frameGeometry();
        lPixmap = getToplevelPixmap(lFrameGeom, theIncludePointer);
    }

    // fallback is window without the frame
    Q_EMIT newScreenshotTaken(lPixmap);
}

void PlatformXcb::grabActiveWindow(bool theIncludePointer, bool theIncludeDecorations)
{
    auto lActiveWindow = KWindowSystem::activeWindow();
    updateWindowTitle(lActiveWindow);

    // if KWin is available, use the KWin DBus interfaces
    if (theIncludeDecorations && isKWinAvailable()) {
        auto lBus = QDBusConnection::sessionBus();
        lBus.connect(QStringLiteral("org.kde.KWin"),
                     QStringLiteral("/Screenshot"),
                     QStringLiteral("org.kde.kwin.Screenshot"),
                     QStringLiteral("screenshotCreated"),
                     this,
                     SLOT(handleKWinScreenshotReply(quint64)));
        QDBusInterface lIface(QStringLiteral("org.kde.KWin"), QStringLiteral("/Screenshot"), QStringLiteral("org.kde.kwin.Screenshot"));

        int lOpMask = 1;
        if (theIncludePointer) {
            lOpMask |= 1 << 1;
        }
        lIface.call(QStringLiteral("screenshotForWindow"), static_cast<quint64>(lActiveWindow), lOpMask);

        return;
    }

    // otherwise, use the native functionality
    grabApplicationWindow(lActiveWindow, theIncludePointer, theIncludeDecorations);
}

void PlatformXcb::grabWindowUnderCursor(bool theIncludePointer, bool theIncludeDecorations)
{
    auto lWindow = getWindowUnderCursor();
    updateWindowTitle(lWindow);

    // if KWin is available, use the KWin DBus interfaces
    if (theIncludeDecorations && isKWinAvailable()) {
        auto lBus = QDBusConnection::sessionBus();
        lBus.connect(QStringLiteral("org.kde.KWin"),
                     QStringLiteral("/Screenshot"),
                     QStringLiteral("org.kde.kwin.Screenshot"),
                     QStringLiteral("screenshotCreated"),
                     this,
                     SLOT(handleKWinScreenshotReply(quint64)));
        QDBusInterface lInterface(QStringLiteral("org.kde.KWin"), QStringLiteral("/Screenshot"), QStringLiteral("org.kde.kwin.Screenshot"));

        int lOpMask = 1;
        if (theIncludePointer) {
            lOpMask |= 1 << 1;
        }
        lInterface.call(QStringLiteral("screenshotWindowUnderCursor"), lOpMask);

        return;
    }

    // otherwise, use the native functionality
    grabApplicationWindow(lWindow, theIncludePointer, theIncludeDecorations);
}

void PlatformXcb::grabTransientWithParent(bool theIncludePointer, bool theIncludeDecorations)
{
    auto lWindow = getWindowUnderCursor();
    updateWindowTitle(lWindow);

    // grab the image early
    auto lPixmap = getToplevelPixmap(QRect(), false);

    // now that we know we have a transient window, let's
    // find other possible transient windows and the app window itself.
    QRegion lClipRegion;
    QSet<xcb_window_t> lTransientWindows;
    auto lParentWindow = lWindow;
    const QRect lDesktopRect(0, 0, 1, 1);
    do {
        // find parent window and add the window to the visible region
        auto lWinId = lParentWindow;
        QRect lWinRect;
        lParentWindow = getTransientWindowParent(lWinId, lWinRect, theIncludeDecorations);
        lTransientWindows << lWinId;

        // Don't include the 1x1 pixel sized desktop window in the top left corner that is present
        // if the window is a QDialog without a parent.
        if (lWinRect != lDesktopRect) {
            lClipRegion += lWinRect;
        }

        // Continue walking only if this is a transient window (having a parent)
    } while (lParentWindow != XCB_WINDOW_NONE && !lTransientWindows.contains(lParentWindow));

    // All parents are known now, find other transient children.
    // Assume that the lowest window is behind everything else, then if a new
    // transient window is discovered, its children can then also be found.
    auto lWinList = KWindowSystem::stackingOrder();
    for (auto lWinId : lWinList) {
        QRect lWinRect;
        auto lParentWindow = getTransientWindowParent(lWinId, lWinRect, theIncludeDecorations);

        // if the parent should be displayed, then show the child too
        if (lTransientWindows.contains(lParentWindow)) {
            if (!lTransientWindows.contains(lWinId)) {
                lTransientWindows << lWinId;
                lClipRegion += lWinRect;
            }
        }
    }

    // we can probably go ahead and generate the image now
    QImage lImage(lPixmap.size(), QImage::Format_ARGB32);
    lImage.fill(Qt::transparent);

    QPainter lPainter(&lImage);
    lPainter.setClipRegion(lClipRegion);
    lPainter.drawPixmap(0, 0, lPixmap);
    lPainter.end();
    lPixmap = QPixmap::fromImage(lImage).copy(lClipRegion.boundingRect());

    // why stop here, when we can render a 20px drop shadow all around it
    auto lShadowEffect = new QGraphicsDropShadowEffect;
    lShadowEffect->setOffset(0);
    lShadowEffect->setBlurRadius(20);

    auto lPixmapItem = new QGraphicsPixmapItem;
    lPixmapItem->setPixmap(lPixmap);
    lPixmapItem->setGraphicsEffect(lShadowEffect);

    QImage lShadowImage(lPixmap.size() + QSize(40, 40), QImage::Format_ARGB32);
    lShadowImage.fill(Qt::transparent);
    QPainter lShadowPainter(&lShadowImage);

    QGraphicsScene lGraphicsScene;
    lGraphicsScene.addItem(lPixmapItem);
    lGraphicsScene.render(&lShadowPainter, QRectF(), QRectF(-20, -20, lPixmap.width() + 40, lPixmap.height() + 40));
    lShadowPainter.end();

    // we can finish up now
    lPixmap = QPixmap::fromImage(lShadowImage);
    if (theIncludePointer) {
        auto lTopLeft = lClipRegion.boundingRect().topLeft() - QPoint(20, 20);
        lPixmap = blendCursorImage(lPixmap, QRect(lTopLeft, QSize(lPixmap.width(), lPixmap.height())));
    }
    Q_EMIT newScreenshotTaken(lPixmap);
}

void PlatformXcb::doGrabNow(GrabMode theGrabMode, bool theIncludePointer, bool theIncludeDecorations)
{
    switch (theGrabMode) {
    case GrabMode::AllScreens:
    case GrabMode::AllScreensScaled:
        grabAllScreens(theIncludePointer);
        break;
    case GrabMode::PerScreenImageNative: {
        auto lPixmap = getToplevelPixmap(QRect(), theIncludePointer);
        // break thePixmap into list of images
        const auto screens = QGuiApplication::screens();
        QVector<QImage> images;
        for (const auto screen : screens) {
            QRect geom = screen->geometry();
            geom.setSize(screen->size() * screen->devicePixelRatio());
            images << lPixmap.copy(geom).toImage();
        }
        Q_EMIT newScreensScreenshotTaken(images);
        break;
    }
    case GrabMode::CurrentScreen:
        grabCurrentScreen(theIncludePointer);
        break;
    case GrabMode::ActiveWindow:
        grabActiveWindow(theIncludePointer, theIncludeDecorations);
        break;
    case GrabMode::WindowUnderCursor:
        grabWindowUnderCursor(theIncludePointer, theIncludeDecorations);
        break;
    case GrabMode::TransientWithParent:
        grabTransientWithParent(theIncludePointer, theIncludeDecorations);
        break;
    case GrabMode::InvalidChoice:
        Q_EMIT newScreenshotFailed();
    }
}

void PlatformXcb::doGrabOnClick(GrabMode theGrabMode, bool theIncludePointer, bool theIncludeDecorations)
{
    // get the cursor image
    xcb_cursor_t lXcbCursor = XCB_CURSOR_NONE;
    xcb_cursor_context_t *lXcbCursorCtx = nullptr;
    xcb_screen_t *lXcbAppScreen = xcb_aux_get_screen(QX11Info::connection(), QX11Info::appScreen());

    if (xcb_cursor_context_new(QX11Info::connection(), lXcbAppScreen, &lXcbCursorCtx) >= 0) {
        QVector<QByteArray> lCursorNames = {QByteArrayLiteral("cross"),
                                            QByteArrayLiteral("crosshair"),
                                            QByteArrayLiteral("diamond-cross"),
                                            QByteArrayLiteral("cross-reverse")};

        for (const auto &lCursorName : lCursorNames) {
            xcb_cursor_t lCursor = xcb_cursor_load_cursor(lXcbCursorCtx, lCursorName.constData());
            if (lCursor != XCB_CURSOR_NONE) {
                lXcbCursor = lCursor;
                break;
            }
        }
    }

    // grab the cursor
    xcb_grab_pointer_cookie_t grabPointerCookie = xcb_grab_pointer_unchecked(QX11Info::connection(), // xcb connection
                                                                             0, // deliver events to owner? nope
                                                                             QX11Info::appRootWindow(), // window to grab pointer for (root)
                                                                             XCB_EVENT_MASK_BUTTON_RELEASE, // which events do I want
                                                                             XCB_GRAB_MODE_SYNC, // pointer grab mode
                                                                             XCB_GRAB_MODE_ASYNC, // keyboard grab mode (why is this even here)
                                                                             XCB_NONE, // confine pointer to which window (none)
                                                                             lXcbCursor, // cursor to change to for the duration of grab
                                                                             XCB_TIME_CURRENT_TIME // do this right now
    );
    XcbReplyPtr<xcb_grab_pointer_reply_t> lGrabPointerReply(xcb_grab_pointer_reply(QX11Info::connection(), grabPointerCookie, nullptr));

    // if the grab failed, take the screenshot right away
    if (lGrabPointerReply->status != XCB_GRAB_STATUS_SUCCESS) {
        doGrabNow(theGrabMode, theIncludePointer, theIncludeDecorations);
        return;
    }

    // fix things if our pointer grab causes a lockup and install our event filter
    mNativeEventFilter->setCaptureOptions(theGrabMode, theIncludePointer, theIncludeDecorations);
    xcb_allow_events(QX11Info::connection(), XCB_ALLOW_SYNC_POINTER, XCB_TIME_CURRENT_TIME);
    qApp->installNativeEventFilter(mNativeEventFilter);

    // done. clean stuff up
    xcb_cursor_context_free(lXcbCursorCtx);
    xcb_free_cursor(QX11Info::connection(), lXcbCursor);
}


/*
 * NumericIntegratorTests.cpp
 *
 *  Created on: Oct 7, 2012
 *      Author: hannes
 */

#include "gtest/gtest.h"
#include "boost/typeof/typeof.hpp"
#include "bsplines/NumericIntegrator.hpp"
#include <sm/assert_macros.hpp>
#include <cmath>

using namespace numeric_integrator;

const double bounds[] = {-10, -2, -0.5, 0, 0.5, 2, 10};
const int numberOfBounds = sizeof(bounds) / sizeof(double);

double fabs(Eigen::Vector3d a){
	return a.norm();
}

template <typename TValue>
struct ZeroGetter{
	static TValue getZero(){
		return static_cast<TValue>(0);
	}
};

template <>
struct ZeroGetter<Eigen::Vector3d>{
	inline static Eigen::Vector3d getZero(){
		return Eigen::Vector3d::Zero();
	}
};

template <typename TValue, typename TAlgorithm, int INumberOfPoints, typename TFunctor>

{
	for(int i = 0; i < numberOfBounds; i ++){
		for(int j = 0; j < numberOfBounds; j ++){
			double lBound = bounds[i], uBound = bounds[j];
			TValue val = integrateFunctor<TAlgorithm>(lBound, uBound, f, INumberOfPoints, ZeroGetter<TValue>::getZero());
			TValue analyticalVal = f.calcIntegral(lBound, uBound);
			SM_ASSERT_NEAR(std::runtime_error, val, analyticalVal, fmax(fabs(analyticalVal) * 1e-3, 1e-6), f.getName());
		}
	}
}

template <typename TFunctor>
void checkIntegral(TFunctor & f){
	checkIntegral<typename TFunctor::ValueT, algorithms::TrapezoidalRule, 200>(f);
	checkIntegral<typename TFunctor::ValueT, algorithms::SimpsonRule, 50>(f);
}

namespace test_functions {
	struct XSquared {
		typedef double ValueT;
		inline double operator () (double x) const {
			return x * x;
		}

		inline double calcIntegral(double a, double b){
			return (b * b * b - a * a * a) / 3.;
		}
		inline const char * getName() { return "XSquared"; }
	} xSquared;

	struct XCubix{
		typedef double ValueT;
		inline double operator () (double x) const {
			return x * x * x;
		}

		inline double calcIntegral(double a, double b){
			return (b * b * b * b - a * a * a * a) / 4.;
		}
		inline const char * getName() { return "XCubix"; }
	} xCubic;

	struct SinX{
		typedef double ValueT;
		inline double operator () (double x)const {
			return sin(x);
		}

		inline double calcIntegral(double a, double b){
			return cos(a) - cos(b);
		}
		inline const char * getName() { return "Sin"; }
	} sinX;

	struct ExpX{
		typedef double ValueT;
		inline double operator () (double x) const {
			return exp(x);
		}

		inline double calcIntegral(double a, double b){
			return exp(b) - exp(a);
		}
		inline const char * getName() { return "Exp"; }
	} expX;

	struct SinhX{
		typedef double ValueT;
		inline double operator () (double x) const {
			return sinh(x);
		}
		inline double calcIntegral(double a, double b){
			return cosh(b) - cosh(a);
		}
		inline const char * getName() { return "Sinh"; }
	} sinhX;

	struct XSquaredInR3{
		typedef Eigen::Vector3d ValueT;
		inline ValueT operator () (double x) const {
			double v = x * x;
			return ValueT(v, 2 * v, 3 * v);
		}

		inline ValueT calcIntegral(double a, double b){
			double I = (b * b * b - a * a * a) / 3.;
			return ValueT(I, 2 * I, 3 * I);
		}
		inline const char * getName() { return "XSquaredInR3"; }
	} xSquaredInR3;
}

using namespace test_functions;

TEST(NumericIntegratorTestSuite, compareWithAnalyticalIntegration)
{
	checkIntegral(xSquared);
	checkIntegral(xCubic);
	checkIntegral(sinX);
	checkIntegral(expX);
	checkIntegral(sinhX);
}

TEST(NumericIntegratorTestSuite, eigenVectorValueIntegration)
{
	checkIntegral(xSquaredInR3);
}

TEST(NumericIntegratorTestSuite, testFunctionInterface)
{
	struct Integrand {
		typedef double ValueT;
		inline static ValueT integrand(const double & x){
			return x * x;
		}
	};

	integrateFunction(0., 1., Integrand::integrand, 100, 0.);
}


/*
 * NumericIntegratorTests.cpp
 *
 *  Created on: Oct 7, 2012
 *      Author: hannes
 */

#include "gtest/gtest.h"
#include "boost/typeof/typeof.hpp"
#include "bsplines/NumericIntegrator.hpp"
#include <sm/assert_macros.hpp>
#include <cmath>

using namespace numeric_integrator;

const double bounds[] = {-10, -2, -0.5, 0, 0.5, 2, 10};
const int numberOfBounds = sizeof(bounds) / sizeof(double);

double fabs(Eigen::Vector3d a){
	return a.norm();
}

template <typename TValue>
struct ZeroGetter{
	static TValue getZero(){
		return static_cast<TValue>(0);
	}
};

template <>
struct ZeroGetter<Eigen::Vector3d>{
	inline static Eigen::Vector3d getZero(){
		return Eigen::Vector3d::Zero();
	}
};

template <typename TValue, typename TAlgorithm, int INumberOfPoints, typename TFunctor>
void checkIntegral(TFunctor & f){
	for(int i = 0; i < numberOfBounds; i ++){
		for(int j = 0; j < numberOfBounds; j ++){
			double lBound = bounds[i], uBound = bounds[j];
			TValue val = integrateFunctor<TAlgorithm>(lBound, uBound, f, INumberOfPoints, ZeroGetter<TValue>::getZero());
			TValue analyticalVal = f.calcIntegral(lBound, uBound);
			SM_ASSERT_NEAR(std::runtime_error, val, analyticalVal, fmax(fabs(analyticalVal) * 1e-3, 1e-6), f.getName());
		}
	}
}

template <typename TFunctor>
void checkIntegral(TFunctor & f){
	checkIntegral<typename TFunctor::ValueT, algorithms::TrapezoidalRule, 200>(f);
	checkIntegral<typename TFunctor::ValueT, algorithms::SimpsonRule, 50>(f);
}

namespace test_functions {
	struct XSquared {
		typedef double ValueT;
		inline double operator () (double x) const {
			return x * x;
		}

		inline double calcIntegral(double a, double b){
			return (b * b * b - a * a * a) / 3.;
		}
		inline const char * getName() { return "XSquared"; }
	} xSquared;

	struct XCubix{
		typedef double ValueT;
		inline double operator () (double x) const {
			return x * x * x;
		}

		inline double calcIntegral(double a, double b){
			return (b * b * b * b - a * a * a * a) / 4.;
		}
		inline const char * getName() { return "XCubix"; }
	} xCubic;

	struct SinX{
		typedef double ValueT;
		inline double operator () (double x)const {
			return sin(x);
		}

		inline double calcIntegral(double a, double b){
			return cos(a) - cos(b);
		}
		inline const char * getName()

	} sinX;

	struct ExpX{
		typedef double ValueT;
		inline double operator () (double x) const {
			return exp(x);
		}

		inline double calcIntegral(double a, double b){
			return exp(b) - exp(a);
		}
		inline const char * getName() { return "Exp"; }
	} expX;

	struct SinhX{
		typedef double ValueT;
		inline double operator () (double x) const {
			return sinh(x);
		}
		inline double calcIntegral(double a, double b){
			return cosh(b) - cosh(a);
		}
		inline const char * getName() { return "Sinh"; }
	} sinhX;

	struct XSquaredInR3{
		typedef Eigen::Vector3d ValueT;
		inline ValueT operator () (double x) const {
			double v = x * x;
			return ValueT(v, 2 * v, 3 * v);
		}

		inline ValueT calcIntegral(double a, double b){
			double I = (b * b * b - a * a * a) / 3.;
			return ValueT(I, 2 * I, 3 * I);
		}
		inline const char * getName() { return "XSquaredInR3"; }
	} xSquaredInR3;
}

using namespace test_functions;

TEST(NumericIntegratorTestSuite, compareWithAnalyticalIntegration)
{
	checkIntegral(xSquared);
	checkIntegral(xCubic);
	checkIntegral(sinX);
	checkIntegral(expX);
	checkIntegral(sinhX);
}

TEST(NumericIntegratorTestSuite, eigenVectorValueIntegration)
{
	checkIntegral(xSquaredInR3);
}

TEST(NumericIntegratorTestSuite, testFunctionInterface)
{
	struct Integrand {
		typedef double ValueT;
		inline static ValueT integrand(const double & x){
			return x * x;
		}
	};

	integrateFunction(0., 1., Integrand::integrand, 100, 0.);
}


{
	checkIntegral(xSquared);
	checkIntegral(xCubic);

/*
 * NumericIntegratorTests.cpp
 *
 *  Created on: Oct 7, 2012
 *      Author: hannes
 */

#include "gtest/gtest.h"
#include "boost/typeof/typeof.hpp"
#include "bsplines/NumericIntegrator.hpp"
#include <sm/assert_macros.hpp>
#include <cmath>

using namespace numeric_integrator;

const double bounds[] = {-10, -2, -0.5, 0, 0.5, 2, 10};
const int numberOfBounds = sizeof(bounds) / sizeof(double);

double fabs(Eigen::Vector3d a){
	return a.norm();
}

template <typename TValue>
struct ZeroGetter{
	static TValue getZero(){
		return static_cast<TValue>(0);
	}
};

template <>
struct ZeroGetter<Eigen::Vector3d>{
	inline static Eigen::Vector3d getZero(){
		return Eigen::Vector3d::Zero();
	}
};

template <typename TValue, typename TAlgorithm, int INumberOfPoints, typename TFunctor>
void checkIntegral(TFunctor & f){
	for(int i = 0; i < numberOfBounds; i ++){
		for(int j = 0; j < numberOfBounds; j ++){
			double lBound = bounds[i], uBound = bounds[j];
			TValue val = integrateFunctor<TAlgorithm>(lBound, uBound, f, INumberOfPoints, ZeroGetter<TValue>::getZero());
			TValue analyticalVal = f.calcIntegral(lBound, uBound);
			SM_ASSERT_NEAR(std::runtime_error, val, analyticalVal, fmax(fabs(analyticalVal) * 1e-3, 1e-6), f.getName());
		}
	}
}

template <typename TFunctor>
void checkIntegral(TFunctor & f){
	checkIntegral<typename TFunctor::ValueT, algorithms::TrapezoidalRule, 200>(f);
	checkIntegral<typename TFunctor::ValueT, algorithms::SimpsonRule, 50>(f);
}

namespace test_functions {
	struct XSquared {
		typedef double ValueT;
		inline double operator () (double x) const {
			return x * x;
		}

		inline double calcIntegral(double a, double b){
			return (b * b * b - a * a * a) / 3.;
		}
		inline const char * getName() { return "XSquared"; }
	} xSquared;

	struct XCubix{
		typedef double ValueT;
		inline double operator () (double x) const {
			return x * x * x;
		}

		inline double calcIntegral(double a, double b){
			return (b * b * b * b - a * a * a * a) / 4.;
		}
		inline const char * getName() { return "XCubix"; }
	} xCubic;

	struct SinX{
		typedef double ValueT;
		inline double operator () (double x)const {
			return sin(x);
		}

		inline double calcIntegral(double a, double b){
			return cos(a) - cos(b);
		}
		inline const char * getName() { return "Sin"; }
	} sinX;

	struct ExpX{
		typedef double ValueT;
		inline double operator () (double x) const {
			return exp(x);
		}

		inline double calcIntegral(double a, double b){
			return exp(b) - exp(a);
		}
		inline const char * getName() { return "Exp"; }
	} expX;

	struct SinhX{
		typedef double ValueT;
		inline double operator () (double x) const {
			return sinh(x);
		}
		inline double calcIntegral(double a, double b){
			return cosh(b) - cosh(a);
		}
		inline const char * getName() { return "Sinh"; }
	} sinhX;

	struct XSquaredInR3{
		typedef Eigen::Vector3d ValueT;
		inline ValueT operator () (double x) const {
			double v = x * x;
			return ValueT(v, 2 * v, 3 * v);
		}

		inline ValueT calcIntegral(double a, double b){
			double I = (b * b * b - a * a * a) / 3.;
			return ValueT(I, 2 * I, 3 * I);
		}
		inline const char * getName() { return "XSquaredInR3"; }
	} xSquaredInR3;
}

using namespace test_functions;

TEST(NumericIntegratorTestSuite, compareWithAnalyticalIntegration)

	checkIntegral(sinX);
	checkIntegral(expX);
	checkIntegral(sinhX);
}

TEST(NumericIntegratorTestSuite, eigenVectorValueIntegration)
{
	checkIntegral(xSquaredInR3);
}

TEST(NumericIntegratorTestSuite, testFunctionInterface)
{
	struct Integrand {
		typedef double ValueT;
		inline static ValueT integrand(const double & x){
			return x * x;
		}
	};

	integrateFunction(0., 1., Integrand::integrand, 100, 0.);
}


/*
 * NumericIntegratorTests.cpp
 *
 *  Created on: Oct 7, 2012
 *      Author: hannes
 */

#include "gtest/gtest.h"
#include "boost/typeof/typeof.hpp"
#include "bsplines/NumericIntegrator.hpp"
#include <sm/assert_macros.hpp>
#include <cmath>

using namespace numeric_integrator;

const double bounds[] = {-10, -2, -0.5, 0, 0.5, 2, 10};
const int numberOfBounds = sizeof(bounds) / sizeof(double);

double fabs(Eigen::Vector3d a){
	return a.norm();
}

template <typename TValue>
struct ZeroGetter{
	static TValue getZero(){
		return static_cast<TValue>(0);
	}
};

template <>
struct ZeroGetter<Eigen::Vector3d>{
	inline static Eigen::Vector3d getZero(){
		return Eigen::Vector3d::Zero();
	}
};

template <typename TValue, typename TAlgorithm, int INumberOfPoints, typename TFunctor>
void checkIntegral(TFunctor & f){
	for(int i = 0; i < numberOfBounds; i ++){
		for(int j = 0; j < numberOfBounds; j ++){
			double lBound = bounds[i], uBound = bounds[j];
			TValue val = integrateFunctor<TAlgorithm>(lBound, uBound, f, INumberOfPoints, ZeroGetter<TValue>::getZero());
			TValue analyticalVal = f.calcIntegral(lBound, uBound);
			SM_ASSERT_NEAR(std::runtime_error, val, analyticalVal, fmax(fabs(analyticalVal) * 1e-3, 1e-6), f.getName());
		}
	}
}

template <typename TFunctor>
void checkIntegral(TFunctor & f){
	checkIntegral<typename TFunctor::ValueT, algorithms::TrapezoidalRule, 200>(f);
	checkIntegral<typename TFunctor::ValueT, algorithms::SimpsonRule, 50>(f);
}

namespace test_functions {
	struct XSquared {
		typedef double ValueT;
		inline double operator () (double x) const {
			return x * x;
		}

		inline double calcIntegral(double a, double b){
			return (b * b * b - a * a * a) / 3.;
		}
		inline const char * getName() { return "XSquared"; }
	} xSquared;

	struct XCubix{
		typedef double ValueT;
		inline double operator () (double x) const {
			return x * x * x;
		}

		inline double calcIntegral(double a, double b){
			return (b * b * b * b - a * a * a * a) / 4.;
		}
		inline const char * getName() { return "XCubix"; }
	} xCubic;

	struct SinX{
		typedef double ValueT;
		inline double operator () (double x)const {
			return sin(x);
		}

		inline double calcIntegral(double a, double b){
			return cos(a) - cos(b);
		}
		inline const char * getName() { return "Sin"; }
	} sinX;

	struct ExpX{
		typedef double ValueT;
		inline double operator () (double x) const {
			return exp(x);
		}

		inline double calcIntegral(double a, double b){
			return exp(b) - exp(a);
		}
		inline const char * getName() { return "Exp"; }
	} expX;

	struct SinhX{
		typedef double ValueT;
		inline double operator () (double x) const {
			return sinh(x);
		}
		inline double calcIntegral(double a, double b){
			return cosh(b) - cosh(a);
		}
		inline const char * getName() { return "Sinh"; }
	} sinhX;

	struct XSquaredInR3{
		typedef Eigen::Vector3d ValueT;
		inline ValueT operator () (double x) const {
			double v = x * x;
			return ValueT(v, 2 * v, 3 * v);
		}

		inline ValueT calcIntegral(double a, double b){
			double I = (b * b * b - a * a * a) / 3.;
			return ValueT(I, 2 * I, 3 * I);
		}
		inline const char * getName() { return "XSquaredInR3"; }
	} xSquaredInR3;
}

using namespace test_functions;

TEST(NumericIntegratorTestSuite, compareWithAnalyticalIntegration)
{
	checkIntegral(xSquared);
	checkIntegral(xCubic);

	checkIntegral(sinhX);
}

TEST(NumericIntegratorTestSuite, eigenVectorValueIntegration)
{
	checkIntegral(xSquaredInR3);
}

TEST(NumericIntegratorTestSuite, testFunctionInterface)
{
	struct Integrand {
		typedef double ValueT;
		inline static ValueT integrand(const double & x){
			return x * x;
		}
	};

	integrateFunction(0., 1., Integrand::integrand, 100, 0.);
}


/*
 * NumericIntegratorTests.cpp
 *
 *  Created on: Oct 7, 2012
 *      Author: hannes
 */

#include "gtest/gtest.h"
#include "boost/typeof/typeof.hpp"
#include "bsplines/NumericIntegrator.hpp"
#include <sm/assert_macros.hpp>
#include <cmath>

using namespace numeric_integrator;

const double bounds[] = {-10, -2, -0.5, 0, 0.5, 2, 10};
const int numberOfBounds = sizeof(bounds) / sizeof(double);

double fabs(Eigen::Vector3d a){
	return a.norm();
}

template <typename TValue>
struct ZeroGetter{
	static TValue getZero(){
		return static_cast<TValue>(0);
	}
};

template <>
struct ZeroGetter<Eigen::Vector3d>{
	inline static Eigen::Vector3d getZero(){
		return Eigen::Vector3d::Zero();
	}
};

template <typename TValue, typename TAlgorithm, int INumberOfPoints, typename TFunctor>
void checkIntegral(TFunctor & f){
	for(int i = 0; i < numberOfBounds; i ++){
		for(int j = 0; j < numberOfBounds; j ++){
			double lBound = bounds[i], uBound = bounds[j];
			TValue val = integrateFunctor<TAlgorithm>(lBound, uBound, f, INumberOfPoints, ZeroGetter<TValue>::getZero());
			TValue analyticalVal = f.calcIntegral(lBound, uBound);
			SM_ASSERT_NEAR(std::runtime_error, val, analyticalVal, fmax(fabs(analyticalVal) * 1e-3, 1e-6), f.getName());
		}
	}
}

template <typename TFunctor>
void checkIntegral(TFunctor & f){
	checkIntegral<typename TFunctor::ValueT, algorithms::TrapezoidalRule, 200>(f);
	checkIntegral<typename TFunctor::ValueT, algorithms::SimpsonRule, 50>(f);
}

namespace test_functions {
	struct XSquared {
		typedef double ValueT;
		inline double operator () (double x) const {
			return x * x;
		}

		inline double calcIntegral(double a, double b){
			return (b * b * b - a * a * a) / 3.;
		}
		inline const char * getName() { return "XSquared"; }
	} xSquared;

	struct XCubix{
		typedef double ValueT;
		inline double operator () (double x) const {
			return x * x * x;
		}

		inline double calcIntegral(double a, double b){
			return (b * b * b * b - a * a * a * a) / 4.;
		}
		inline const char * getName() { return "XCubix"; }
	} xCubic;

	struct SinX{
		typedef double ValueT;
		inline double operator () (double x)const {
			return sin(x);
		}

		inline double calcIntegral(double a, double b){
			return cos(a) - cos(b);
		}
		inline const char * getName() { return "Sin"; }
	} sinX;

	struct ExpX{
		typedef double ValueT;
		inline double operator () (double x) const {
			return exp(x);
		}

		inline double calcIntegral(double a, double b){
			return exp(b) - exp(a);
		}
		inline const char * getName() { return "Exp"; }
	} expX;

	struct SinhX{
		typedef double ValueT;
		inline double operator () (double x) const {
			return sinh(x);
		}
		inline double calcIntegral(double a, double b){
			return cosh(b) - cosh(a);
		}
		inline const char * getName() { return "Sinh"; }
	} sinhX;

	struct XSquaredInR3{
		typedef Eigen::Vector3d ValueT;
		inline ValueT operator () (double x) const {
			double v = x * x;
			return ValueT(v, 2 * v, 3 * v);
		}

		inline ValueT calcIntegral(double a, double b){
			double I = (b * b * b - a * a * a) / 3.;
			return ValueT(I, 2 * I, 3 * I);
		}
		inline const char * getName() { return "XSquaredInR3"; }
	} xSquaredInR3;
}

using namespace test_functions;

TEST(NumericIntegratorTestSuite, compareWithAnalyticalIntegration)
{
	checkIntegral(xSquared);
	checkIntegral(xCubic);
	checkIntegral(sinX);
	checkIntegral(expX);

TEST(NumericIntegratorTestSuite, eigenVectorValueIntegration)
{
	checkIntegral(xSquaredInR3);
}

TEST(NumericIntegratorTestSuite, testFunctionInterface)
{
	struct Integrand {
		typedef double ValueT;
		inline static ValueT integrand(const double & x){
			return x * x;
		}
	};

	integrateFunction(0., 1., Integrand::integrand, 100, 0.);
}


/*
 * NumericIntegratorTests.cpp
 *
 *  Created on: Oct 7, 2012
 *      Author: hannes
 */

#include "gtest/gtest.h"
#include "boost/typeof/typeof.hpp"
#include "bsplines/NumericIntegrator.hpp"
#include <sm/assert_macros.hpp>
#include <cmath>

using namespace numeric_integrator;

const double bounds[] = {-10, -2, -0.5, 0, 0.5, 2, 10};
const int numberOfBounds = sizeof(bounds) / sizeof(double);

double fabs(Eigen::Vector3d a){
	return a.norm();
}

template <typename TValue>
struct ZeroGetter{
	static TValue getZero(){
		return static_cast<TValue>(0);
	}
};

template <>
struct ZeroGetter<Eigen::Vector3d>{
	inline static Eigen::Vector3d getZero(){
		return Eigen::Vector3d::Zero();
	}
};

template <typename TValue, typename TAlgorithm, int INumberOfPoints, typename TFunctor>
void checkIntegral(TFunctor & f){
	for(int i = 0; i < numberOfBounds; i ++){
		for(int j = 0; j < numberOfBounds; j ++){
			double lBound = bounds[i], uBound = bounds[j];
			TValue val = integrateFunctor<TAlgorithm>(lBound, uBound, f, INumberOfPoints, ZeroGetter<TValue>::getZero());
			TValue analyticalVal = f.calcIntegral(lBound, uBound);
			SM_ASSERT_NEAR(std::runtime_error, val, analyticalVal, fmax(fabs(analyticalVal) * 1e-3, 1e-6), f.getName());
		}
	}
}

template <typename TFunctor>
void checkIntegral(TFunctor & f){
	checkIntegral<typename TFunctor::ValueT, algorithms::TrapezoidalRule, 200>(f);
	checkIntegral<typename TFunctor::ValueT, algorithms::SimpsonRule, 50>(f);
}

namespace test_functions {
	struct XSquared {
		typedef double ValueT;
		inline double operator () (double x) const {
			return x * x;
		}

		inline double calcIntegral(double a, double b){
			return (b * b * b - a * a * a) / 3.;
		}
		inline const char * getName() { return "XSquared"; }
	} xSquared;

	struct XCubix{
		typedef double ValueT;
		inline double operator () (double x) const {
			return

		}

		inline double calcIntegral(double a, double b){
			return (b * b * b * b - a * a * a * a) / 4.;
		}
		inline const char * getName() { return "XCubix"; }
	} xCubic;

	struct SinX{
		typedef double ValueT;
		inline double operator () (double x)const {
			return sin(x);
		}

		inline double calcIntegral(double a, double b){
			return cos(a) - cos(b);
		}
		inline const char * getName() { return "Sin"; }
	} sinX;

	struct ExpX{
		typedef double ValueT;
		inline double operator () (double x) const {
			return exp(x);
		}

		inline double calcIntegral(double a, double b){
			return exp(b) - exp(a);
		}
		inline const char * getName() { return "Exp"; }
	} expX;

	struct SinhX{
		typedef double ValueT;
		inline double operator () (double x) const {
			return sinh(x);
		}
		inline double calcIntegral(double a, double b){
			return cosh(b) - cosh(a);
		}
		inline const char * getName() { return "Sinh"; }
	} sinhX;

	struct XSquaredInR3{
		typedef Eigen::Vector3d ValueT;
		inline ValueT operator () (double x) const {
			double v = x * x;
			return ValueT(v, 2 * v, 3 * v);
		}

		inline ValueT calcIntegral(double a, double b){
			double I = (b * b * b - a * a * a) / 3.;
			return ValueT(I, 2 * I, 3 * I);
		}
		inline const char * getName() { return "XSquaredInR3"; }
	} xSquaredInR3;
}

using namespace test_functions;

TEST(NumericIntegratorTestSuite, compareWithAnalyticalIntegration)
{
	checkIntegral(xSquared);
	checkIntegral(xCubic);
	checkIntegral(sinX);
	checkIntegral(expX);
	checkIntegral(sinhX);
}

TEST(NumericIntegratorTestSuite, eigenVectorValueIntegration)
{
	checkIntegral(xSquaredInR3);
}

TEST(NumericIntegratorTestSuite, testFunctionInterface)
{
	struct Integrand {
		typedef double ValueT;
		inline static ValueT integrand(const double & x){
			return x * x;
		}
	};

	integrateFunction(0., 1., Integrand::integrand, 100, 0.);
}


for(int i = 0; i < numberOfBounds; i ++){
		for(int j = 0; j < numberOfBounds; j ++){
			double lBound = bounds[i], uBound = bounds[j];
			TValue val = integrateFunctor<TAlgorithm>(lBound, uBound, f, INumberOfPoints, ZeroGetter<TValue>::getZero());
			TValue analyticalVal = f.calcIntegral(lBound, uBound);
			SM_ASSERT_NEAR(std::runtime_error, val, analyticalVal, fmax(fabs(analyticalVal) * 1e-3, 1e-6), f.getName());
		}
	}

/*
 * NumericIntegratorTests.cpp
 *
 *  Created on: Oct 7, 2012
 *      Author: hannes
 */

#include "gtest/gtest.h"
#include "boost/typeof/typeof.hpp"
#include "bsplines/NumericIntegrator.hpp"
#include <sm/assert_macros.hpp>
#include <cmath>

using namespace numeric_integrator;

const double bounds[] = {-10, -2, -0.5, 0, 0.5, 2, 10};
const int numberOfBounds = sizeof(bounds) / sizeof(double);

double fabs(Eigen::Vector3d a){
	return a.norm();
}

template <typename TValue>
struct ZeroGetter{
	static TValue getZero(){
		return static_cast<TValue>(0);
	}
};

template <>
struct ZeroGetter<Eigen::Vector3d>{
	inline static Eigen::Vector3d getZero(){
		return Eigen::Vector3d::Zero();
	}
};

template <typename TValue, typename TAlgorithm, int INumberOfPoints, typename TFunctor>
void checkIntegral(TFunctor & f){

}

template <typename TFunctor>
void checkIntegral(TFunctor & f){
	checkIntegral<typename TFunctor::ValueT, algorithms::TrapezoidalRule, 200>(f);
	checkIntegral<typename TFunctor::ValueT, algorithms::SimpsonRule, 50>(f);
}

namespace test_functions {
	struct XSquared {
		typedef double ValueT;
		inline double operator () (double x) const {
			return x * x;
		}

		inline double calcIntegral(double a, double b){
			return (b * b * b - a * a * a) / 3.;
		}
		inline const char * getName() { return "XSquared"; }
	} xSquared;

	struct XCubix{
		typedef double ValueT;
		inline double operator () (double x) const {
			return x * x * x;
		}

		inline double calcIntegral(double a, double b){
			return (b * b * b * b - a * a * a * a) / 4.;
		}
		inline const char * getName() { return "XCubix"; }
	} xCubic;

	struct SinX{
		typedef double ValueT;
		inline double operator () (double x)const {
			return sin(x);
		}

		inline double calcIntegral(double a, double b){
			return cos(a) - cos(b);
		}
		inline const char * getName() { return "Sin"; }
	} sinX;

	struct ExpX{
		typedef double ValueT;
		inline double operator () (double x) const {
			return exp(x);
		}

		inline double calcIntegral(double a, double b){
			return exp(b) - exp(a);
		}
		inline const char * getName() { return "Exp"; }
	} expX;

	struct SinhX{
		typedef double ValueT;
		inline double operator () (double x) const {
			return sinh(x);
		}
		inline double calcIntegral(double a, double b){
			return cosh(b) - cosh(a);
		}
		inline const char * getName() { return "Sinh"; }
	} sinhX;

	struct XSquaredInR3{
		typedef Eigen::Vector3d ValueT;
		inline ValueT operator () (double x) const {
			double v = x * x;
			return ValueT(v, 2 * v, 3 * v);
		}

		inline ValueT calcIntegral(double a, double b){
			double I = (b * b * b - a * a * a) / 3.;
			return ValueT(I, 2 * I, 3 * I);
		}
		inline const char * getName() { return "XSquaredInR3"; }
	} xSquaredInR3;
}

using namespace test_functions;

TEST(NumericIntegratorTestSuite, compareWithAnalyticalIntegration)
{
	checkIntegral(xSquared);
	checkIntegral(xCubic);
	checkIntegral(sinX);
	checkIntegral(expX);
	checkIntegral(sinhX);
}

TEST(NumericIntegratorTestSuite, eigenVectorValueIntegration)
{
	checkIntegral(xSquaredInR3);
}

TEST(NumericIntegratorTestSuite, testFunctionInterface)
{
	struct Integrand {
		typedef double ValueT;
		inline static ValueT integrand(const double & x){
			return x * x;
		}
	};

	integrateFunction(0., 1., Integrand::integrand, 100, 0.);
}


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

#include "canvasitemparts.h"
#include "cells.h"
#include "component.h"
#include "icndocument.h"
#include "inputflownode.h"
#include "itemdocumentdata.h"
#include "junctionflownode.h"
#include "junctionnode.h"
#include "outputflownode.h"
#include "pinnode.h"

#include <QBitArray>
#include <QPainter>

#include <cmath>
#include <cstdlib>

#include <ktechlab_debug.h>

CNItem::CNItem(ICNDocument *icnDocument, bool newItem, const QString &id)
    : Item(icnDocument, newItem, id)
    , CIWidgetMgr(icnDocument ? icnDocument->canvas() : nullptr, this)
    , p_icnDocument(icnDocument)
    , b_pointsAdded(false)
{
    qCDebug(KTL_LOG) << " this=" << this;

    setZ(ICNDocument::Z::Item);
    setSelected(false);

    m_brushCol = QColor(0xf7, 0xf7, 0xff);
    m_selectedCol = QColor(101, 134, 192);

    setBrush(m_brushCol);
    setPen(QPen(Qt::black));
}

CNItem::~CNItem()
{
    const TextMap::iterator textMapEnd = m_textMap.end();
    for (TextMap::iterator it = m_textMap.begin(); it != textMapEnd; ++it) {
        if (it.value())
            it.value()->setCanvas(nullptr);

        delete (Text *)it.value();
    }
    m_textMap.clear();

    updateConnectorPoints(false);
}

bool CNItem::preResize(QRect sizeRect)
{
    if ((std::abs(sizeRect.width()) < minimumSize().width()) || (std::abs(sizeRect.height()) < minimumSize().height()))
        return false;

    updateConnectorPoints(false);
    return true;
}

void CNItem::postResize()
{
    updateAttachedPositioning();
}

void CNItem::setVisible(bool yes)
{
    if (b_deleted) {
        Item::setVisible(false);
        return;
    }

    Item::setVisible(yes);

    const TextMap::iterator textMapEnd = m_textMap.end();
    for (TextMap::iterator it = m_textMap.begin(); it != textMapEnd; ++it) {
        it.value()->setVisible(yes);
    }

    const NodeInfoMap::iterator nodeMapEnd = m_nodeMap.end();
    for (NodeInfoMap::iterator it = m_nodeMap.begin(); it != nodeMapEnd; ++it) {
        it.value().node->setVisible(yes);
    }

    CNItem::setDrawWidgets(yes);

    if (!yes)
        updateConnectorPoints(false);
}

void CNItem::reparented(Item *oldParent, Item *newParent)
{
    Item::reparented(oldParent, newParent);
    updateNodeLevels();
}

void CNItem::updateNodeLevels()
{
    int l = level();

    // Tell our nodes about our level
    const NodeInfoMap::iterator nodeMapEnd = m_nodeMap.end();
    for (NodeInfoMap::iterator it = m_nodeMap.begin(); it != nodeMapEnd; ++it) {
        it.value().node->setLevel(l);
    }

    const ItemList::iterator end = m_children.end();
    for (ItemList::iterator it = m_children.begin(); it != end; ++it) {
        if (CNItem *cnItem = dynamic_cast<CNItem *>((Item *)*it))
            cnItem->updateNodeLevels();
    }
}

ConnectorList CNItem::connectorList()
{
    ConnectorList list;

    const NodeInfoMap::iterator nodeMapEnd = m_nodeMap.end();
    for (NodeInfoMap::iterator it = m_nodeMap.begin(); it != nodeMapEnd; ++it) {
        Node *node = p_icnDocument->nodeWithID(it.value().id);
        if (node) {
            ConnectorList nodeList = node->getAllConnectors();
            ConnectorList::iterator end = nodeList.end();
            for (ConnectorList::iterator it = nodeList.begin(); it != end; ++it) {
                if (*it && !list.contains(*it)) {
                    list.append(*it);
                }
            }
        }
    }

    return list;
}

void CNItem::removeItem()
{
    if (b_deleted)
        return;

    const TextMap::iterator textMapEnd = m_textMap.end();
    for (TextMap::iterator it = m_textMap.begin(); it != textMapEnd; ++it)
        it.value()->setCanvas(nullptr);

    Item::removeItem();
    updateConnectorPoints(false);
}

void CNItem::restoreFromItemData(const ItemData &itemData)
{
    Item::restoreFromItemData(itemData);

    updateConnectorPoints(false);

    {
        const BoolMap::const_iterator end = itemData.buttonMap.end();
        for (BoolMap::const_iterator it = itemData.buttonMap.begin(); it != end; ++it) {
            Button *b = button(it.key());
            if (b)
                b->setState(it.value());
        }
    }
    {
        const IntMap::const_iterator end = itemData.sliderMap.end();
        for (IntMap::const_iterator it = itemData.sliderMap.begin(); it != end; ++it) {
            Slider *s = slider(it.key());
            if (s)
                s->setValue(it.value());
        }
    }
}

ItemData CNItem::itemData() const
{
    ItemData itemData = Item::itemData();

    const WidgetMap::const_iterator end = m_widgetMap.end();
    for (WidgetMap::const_iterator it = m_widgetMap.begin(); it != end; ++it) {
        if (Slider *slider = dynamic_cast<Slider *>(*it))
            itemData.sliderMap[slider->id()] = slider->value();

        else if (Button *button = dynamic_cast<Button *>(*it))
            itemData.buttonMap[button->id()] = button->state();
    }

    return itemData;
}

Node *CNItem::createNode(double _x, double _y, int orientation, const QString &name, uint type)
{
    orientation %= 360;
    if (orientation < 0)
        orientation += 360;

    Node *node = nullptr;

    // TODO get rid of this switch statement...
    switch (type) {
    case Node::ec_pin:
        node = new PinNode(p_icnDocument, orientation, QPoint(0, 0));
        break;
    case Node::ec_junction:
        node = new JunctionNode(p_icnDocument, orientation, QPoint(0, 0));
        break;
    case Node::fp_junction:
        node = new JunctionFlowNode(p_icnDocument, orientation, QPoint(0, 0));
        break;
    case Node::fp_in:
        node = new InputFlowNode(p_icnDocument, orientation, QPoint(0, 0));
        break;
    case Node::fp_out:
        node = new OutputFlowNode(p_icnDocument, orientation, QPoint(0, 0));
        break;
    }

    node->setLevel(level());

    node->setParentItem(this);
    node->setChildId(name);

    NodeInfo info;
    info.id = node->id();
    info.node = node;
    info.x = _x;
    info.y = _y;
    info.orientation = orientation;

    m_nodeMap[name] = info;

    updateAttachedPositioning();

    return node;
}

bool CNItem::removeNode(const QString &name)
{
    NodeInfoMap::iterator it = m_nodeMap.find(name);
    if (it == m_nodeMap.end()) {
        return false;
    }
    it.value().node->removeNode();
    p_icnDocument->flushDeleteList();
    m_nodeMap.erase(it);
    return true;
}

Node *CNItem::getClosestNode(const QPoint &pos)
{
    // Work through the nodes, finding the one closest to the (x, y) position
    Node *shortestNode = nullptr;
    double shortestDistance = 1e10; // Nice large distance :-)

    const NodeInfoMap::iterator end = m_nodeMap.end();
    for (NodeInfoMap::iterator it = m_nodeMap.begin(); it != end; ++it) {
        Node *node = p_icnDocument->nodeWithID(it.value().id);
        if (node) {
            // Calculate the distance
            // Yeah, it's actually the distance squared; but it's all relative, so doesn't matter
            double distance = std::pow(node->x() - pos.x(), 2) + std::pow(node->y() - pos.y(), 2);

            if (distance < shortestDistance) {
                shortestDistance = distance;
                shortestNode = node;
            }
        }
    }

    return shortestNode;
}

{
    if (b_deleted)
        return;

}

void CNItem::updateZ(int baseZ)
{
    Item::updateZ(baseZ);

    double _z = z();

    const NodeInfoMap::iterator nodeMapEnd = m_nodeMap.end();
    for (NodeInfoMap::iterator it = m_nodeMap.begin(); it != nodeMapEnd; ++it)
        it.value().node->setZ(_z + 0.5);

    const WidgetMap::iterator widgetMapEnd = m_widgetMap.end();
    for (WidgetMap::iterator it = m_widgetMap.begin(); it != widgetMapEnd; ++it)
        it.value()->setZ(_z + 0.5);

    const TextMap::iterator textMapEnd = m_textMap.end();
    for (TextMap::iterator it = m_textMap.begin(); it != textMapEnd; ++it)
        it.value()->setZ(_z + 0.5);
}

void CNItem::moveBy(double dx, double dy)
{
    if (dx == 0 && dy == 0)
        return;
    updateConnectorPoints(false);
    Item::moveBy(dx, dy);

    setWidgetsPos(QPoint(int(x()), int(y())));
}

bool CNItem::mousePressEvent(const EventInfo &info)
{
    bool accepted = Item::mousePressEvent(info);
    if (!accepted)
        accepted = CIWidgetMgr::mousePressEvent(info);
    if (accepted)
        setChanged();
    return accepted;
}

bool CNItem::mouseReleaseEvent(const EventInfo &info)
{
    bool accepted = Item::mouseReleaseEvent(info);
    if (!accepted)
        accepted = CIWidgetMgr::mouseReleaseEvent(info);
    if (accepted)
        setChanged();
    return accepted;
}

bool CNItem::mouseDoubleClickEvent(const EventInfo &info)
{
    bool accepted = Item::mouseDoubleClickEvent(info);
    if (!accepted)
        accepted = CIWidgetMgr::mouseDoubleClickEvent(info);
    if (accepted)
        setChanged();
    return accepted;
}

bool CNItem::mouseMoveEvent(const EventInfo &info)
{
    bool accepted = Item::mouseMoveEvent(info);
    if (!accepted)
        accepted = CIWidgetMgr::mouseMoveEvent(info);
    if (accepted)
        setChanged();
    return accepted;
}

bool CNItem::wheelEvent(const EventInfo &info)
{
    bool accepted = Item::wheelEvent(info);
    if (!accepted)
        accepted = CIWidgetMgr::wheelEvent(info);
    if (accepted)
        setChanged();
    return accepted;
}

void CNItem::enterEvent(QEvent *)
{
    Item::enterEvent(nullptr);
    CIWidgetMgr::enterEvent(nullptr);
    setChanged();
}

void CNItem::leaveEvent(QEvent *)
{
    Item::leaveEvent(nullptr);
    CIWidgetMgr::leaveEvent(nullptr);
    setChanged();
}

void CNItem::drawShape(QPainter &p)
{
    if (!isVisible())
        return;

    if (isSelected())
        p.setPen(m_selectedCol);

    p.drawPolygon(areaPoints());
    p.drawPolyline(areaPoints());
}

void CNItem::initPainter(QPainter &p)
{
    if (isSelected())
        p.setPen(m_selectedCol);
}

void CNItem::updateConnectorPoints(bool add)
{
    if (b_deleted || !isVisible())
        add = false;

    if (b_pointsAdded == add)
        return;

    b_pointsAdded = add;

    Cells *cells = p_icnDocument->cells();
    if (!cells)
        return;

    // Get translation matrix
    QTransform m;
    if (Component *c = dynamic_cast<Component *>(this))
        m = c->transMatrix(c->angleDegrees(), c->flipped(), int(x()), int(y()), false);

    // Convention used here: _UM = unmapped by both matrix and cell reference, _M = mapped

    const QPoint start_UM = QPoint(int(x() + offsetX()) - 8, int(y() + offsetY()) - 8);
    const QPoint end_UM = start_UM + QPoint(width() + 2 * 8, height() + 2 * 8);

    const QPoint start_M = roundDown(m.map(start_UM), 8);
    const QPoint end_M = roundDown(m.map(end_UM), 8);

    int sx_M = start_M.x();
    int ex_M = end_M.x();

    int sy_M = start_M.y();
    int ey_M = end_M.y();

    // Normalise start and end points
    if (sx_M > ex_M) {
        const int temp = sx_M;
        sx_M = ex_M;
        ex_M = temp;
    }
    if (sy_M > ey_M) {
        const int temp = sy_M;
        sy_M = ey_M;
        ey_M = temp;
    }

    ex_M++;
    ey_M++;

    const int mult = add ? 1 : -1;

    for (int x = sx_M; x < ex_M; x++) {
        for (int y = sy_M; y < ey_M; y++) {
            if (cells->haveCell(x, y)) {
                if (x != sx_M && y != sy_M && x != (ex_M - 1) && y != (ey_M - 1)) {
                    cells->cell(x, y).CIpenalty += mult * ICNDocument::hs_item;
                } else {
                    cells->cell(x, y).CIpenalty += mult * ICNDocument::hs_connector * 5;
                }
            }
        }
    }

#if 0
	// And subtract the positions of the node on the border
	NodeInfoMap::iterator end = m_nodeMap.end();
	for ( NodeInfoMap::iterator it = m_nodeMap.begin(); it != end; ++it )
	{
		const int x = (int)((it->second.node->x()-4)/cellSize);
		const int y = (int)((it->second.node->y()-4)/cellSize);
		if ( p_icnDocument->isValidCellReference(x,y) ) {
			(*cells)[x][y].CIpenalty -= mult*ICNDocument::hs_connector*5;
		}
	}
#endif

    const TextMap::iterator textMapEnd = m_textMap.end();
    for (TextMap::iterator it = m_textMap.begin(); it != textMapEnd; ++it) {
        it.value()->updateConnectorPoints(add);
    }
    const WidgetMap::iterator widgetMapEnd = m_widgetMap.end();
    for (WidgetMap::iterator it = m_widgetMap.begin(); it != widgetMapEnd; ++it) {
        it.value()->updateConnectorPoints(add);
    }
}

Text *CNItem::addDisplayText(const QString &id, const QRect &pos, const QString &display, bool internal, int flags)
{
    Text *text = nullptr;
    TextMap::iterator it = m_textMap.find(id);
    if (it != m_textMap.end()) {
        // 		qCWarning(KTL_LOG) << "CNItem::addDisplayText: removing old text";
        delete it.value();
        m_textMap.erase(it);
    }

    text = new Text("", this, pos, canvas(), flags);
    text->setZ(z() + (internal ? 0.1 : -0.1));

    m_textMap[id] = text;

    // Calculate the correct size
    setDisplayText(id, display);
    text->show();
    return text;
}

void CNItem::setDisplayText(const QString &id, const QString &display)
{
    TextMap::iterator it = m_textMap.find(id);
    if (it == m_textMap.end()) {
        qCCritical(KTL_LOG) << "CNItem::setDisplayText: Could not find text with id \"" << id << "\"";
        return;
    }
    it.value()->setText(display);
    updateAttachedPositioning();
}

void CNItem::removeDisplayText(const QString &id)
{
    TextMap::iterator it = m_textMap.find(id);
    if (it == m_textMap.end()) {
        // 		qCCritical(KTL_LOG) << "CNItem::removeDisplayText: Could not find text with id \""<<id<<"\"";
        return;
    }
    it.value()->updateConnectorPoints(false);
    delete it.value();
    m_textMap.erase(it);
}

QString CNItem::nodeId(const QString &internalNodeId)
{
    NodeInfoMap::iterator it = m_nodeMap.find(internalNodeId);
    if (it == m_nodeMap.end())
        return "";
    else
        return it.value().id;
}

Node *CNItem::childNode(const QString &childId)
{
    return p_icnDocument->nodeWithID(nodeId(childId));
}

NodeInfo::NodeInfo()
{
    node = nullptr;
    x = 0.;
    y = 0.;
    orientation = 0;
}


{
    Item::reparented(oldParent, newParent);
    updateNodeLevels();
}

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

#include "canvasitemparts.h"
#include "cells.h"
#include "component.h"
#include "icndocument.h"
#include "inputflownode.h"
#include "itemdocumentdata.h"
#include "junctionflownode.h"
#include "junctionnode.h"
#include "outputflownode.h"
#include "pinnode.h"

#include <QBitArray>
#include <QPainter>

#include <cmath>
#include <cstdlib>

#include <ktechlab_debug.h>

CNItem::CNItem(ICNDocument *icnDocument, bool newItem, const QString &id)
    : Item(icnDocument, newItem, id)
    , CIWidgetMgr(icnDocument ? icnDocument->canvas() : nullptr, this)
    , p_icnDocument(icnDocument)
    , b_pointsAdded(false)
{
    qCDebug(KTL_LOG) << " this=" << this;

    setZ(ICNDocument::Z::Item);
    setSelected(false);

    m_brushCol = QColor(0xf7, 0xf7, 0xff);
    m_selectedCol = QColor(101, 134, 192);

    setBrush(m_brushCol);
    setPen(QPen(Qt::black));
}

CNItem::~CNItem()
{
    const TextMap::iterator textMapEnd = m_textMap.end();
    for (TextMap::iterator it = m_textMap.begin(); it != textMapEnd; ++it) {
        if (it.value())
            it.value()->setCanvas(nullptr);

        delete (Text *)it.value();
    }
    m_textMap.clear();

    updateConnectorPoints(false);
}

bool CNItem::preResize(QRect sizeRect)
{
    if ((std::abs(sizeRect.width()) < minimumSize().width()) || (std::abs(sizeRect.height()) < minimumSize().height()))
        return false;

    updateConnectorPoints(false);
    return true;
}

void CNItem::postResize()
{
    updateAttachedPositioning();
}

void CNItem::setVisible(bool yes)
{
    if (b_deleted) {
        Item::setVisible(false);
        return;
    }

    Item::setVisible(yes);

    const TextMap::iterator textMapEnd = m_textMap.end();
    for (TextMap::iterator it = m_textMap.begin(); it != textMapEnd; ++it) {
        it.value()->setVisible(yes);
    }

    const NodeInfoMap::iterator nodeMapEnd = m_nodeMap.end();
    for (NodeInfoMap::iterator it = m_nodeMap.begin(); it != nodeMapEnd; ++it) {
        it.value().node->setVisible(yes);
    }

    CNItem::setDrawWidgets(yes);

    if (!yes)
        updateConnectorPoints(false);
}

void CNItem::reparented(Item *oldParent, Item *newParent)

void CNItem::updateNodeLevels()
{
    int l = level();

    // Tell our nodes about our level
    const NodeInfoMap::iterator nodeMapEnd = m_nodeMap.end();
    for (NodeInfoMap::iterator it = m_nodeMap.begin(); it != nodeMapEnd; ++it) {
        it.value().node->setLevel(l);
    }

    const ItemList::iterator end = m_children.end();
    for (ItemList::iterator it = m_children.begin(); it != end; ++it) {
        if (CNItem *cnItem = dynamic_cast<CNItem *>((Item *)*it))
            cnItem->updateNodeLevels();
    }
}

ConnectorList CNItem::connectorList()
{
    ConnectorList list;

    const NodeInfoMap::iterator nodeMapEnd = m_nodeMap.end();
    for (NodeInfoMap::iterator it = m_nodeMap.begin(); it != nodeMapEnd; ++it) {
        Node *node = p_icnDocument->nodeWithID(it.value().id);
        if (node) {
            ConnectorList nodeList = node->getAllConnectors();
            ConnectorList::iterator end = nodeList.end();
            for (ConnectorList::iterator it = nodeList.begin(); it != end; ++it) {
                if (*it && !list.contains(*it)) {
                    list.append(*it);
                }
            }
        }
    }

    return list;
}

void CNItem::removeItem()
{
    if (b_deleted)
        return;

    const TextMap::iterator textMapEnd = m_textMap.end();
    for (TextMap::iterator it = m_textMap.begin(); it != textMapEnd; ++it)
        it.value()->setCanvas(nullptr);

    Item::removeItem();
    updateConnectorPoints(false);
}

void CNItem::restoreFromItemData(const ItemData &itemData)
{
    Item::restoreFromItemData(itemData);

    updateConnectorPoints(false);

    {
        const BoolMap::const_iterator end = itemData.buttonMap.end();
        for (BoolMap::const_iterator it = itemData.buttonMap.begin(); it != end; ++it) {
            Button *b = button(it.key());
            if (b)
                b->setState(it.value());
        }
    }
    {
        const IntMap::const_iterator end = itemData.sliderMap.end();
        for (IntMap::const_iterator it = itemData.sliderMap.begin(); it != end; ++it) {
            Slider *s = slider(it.key());
            if (s)
                s->setValue(it.value());
        }
    }
}

ItemData CNItem::itemData() const
{
    ItemData itemData = Item::itemData();

    const WidgetMap::const_iterator end = m_widgetMap.end();
    for (WidgetMap::const_iterator it = m_widgetMap.begin(); it != end; ++it) {
        if (Slider *slider = dynamic_cast<Slider *>(*it))
            itemData.sliderMap[slider->id()] = slider->value();

        else if (Button *button = dynamic_cast<Button *>(*it))
            itemData.buttonMap[button->id()] = button->state();
    }

    return itemData;
}

Node *CNItem::createNode(double _x, double _y, int orientation, const QString &name, uint type)
{
    orientation %= 360;
    if (orientation < 0)
        orientation += 360;

    Node *node = nullptr;

    // TODO get rid of this switch statement...
    switch (type) {
    case Node::ec_pin:
        node = new PinNode(p_icnDocument, orientation, QPoint(0, 0));
        break;
    case Node::ec_junction:
        node = new JunctionNode(p_icnDocument, orientation, QPoint(0, 0));
        break;
    case Node::fp_junction:
        node = new JunctionFlowNode(p_icnDocument, orientation, QPoint(0, 0));
        break;
    case Node::fp_in:
        node = new InputFlowNode(p_icnDocument, orientation, QPoint(0, 0));
        break;
    case Node::fp_out:
        node = new OutputFlowNode(p_icnDocument, orientation, QPoint(0, 0));
        break;
    }

    node->setLevel(level());

    node->setParentItem(this);
    node->setChildId(name);

    NodeInfo info;
    info.id = node->id();
    info.node = node;
    info.x = _x;
    info.y = _y;
    info.orientation = orientation;

    m_nodeMap[name] = info;

    updateAttachedPositioning();

    return node;
}

bool CNItem::removeNode(const QString &name)
{
    NodeInfoMap::iterator it = m_nodeMap.find(name);
    if (it == m_nodeMap.end()) {
        return false;
    }
    it.value().node->removeNode();
    p_icnDocument->flushDeleteList();
    m_nodeMap.erase(it);
    return true;
}

Node *CNItem::getClosestNode(const QPoint &pos)
{
    // Work through the nodes, finding the one closest to the (x, y) position
    Node *shortestNode = nullptr;
    double shortestDistance = 1e10; // Nice large distance :-)

    const NodeInfoMap::iterator end = m_nodeMap.end();
    for (NodeInfoMap::iterator it = m_nodeMap.begin(); it != end; ++it) {
        Node *node = p_icnDocument->nodeWithID(it.value().id);
        if (node) {
            // Calculate the distance
            // Yeah, it's actually the distance squared; but it's all relative, so doesn't matter
            double distance = std::pow(node->x() - pos.x(), 2) + std::pow(node->y() - pos.y(), 2);

            if (distance < shortestDistance) {
                shortestDistance = distance;
                shortestNode = node;
            }
        }
    }

    return shortestNode;
}

void CNItem::updateAttachedPositioning()
{
    if (b_deleted)
        return;

}

void CNItem::updateZ(int baseZ)
{
    Item::updateZ(baseZ);

    double _z = z();

    const NodeInfoMap::iterator nodeMapEnd = m_nodeMap.end();
    for (NodeInfoMap::iterator it = m_nodeMap.begin(); it != nodeMapEnd; ++it)
        it.value().node->setZ(_z + 0.5);

    const WidgetMap::iterator widgetMapEnd = m_widgetMap.end();
    for (WidgetMap::iterator it = m_widgetMap.begin(); it != widgetMapEnd; ++it)
        it.value()->setZ(_z + 0.5);

    const TextMap::iterator textMapEnd = m_textMap.end();
    for (TextMap::iterator it = m_textMap.begin(); it != textMapEnd; ++it)
        it.value()->setZ(_z + 0.5);
}

void CNItem::moveBy(double dx, double dy)
{
    if (dx == 0 && dy == 0)
        return;
    updateConnectorPoints(false);
    Item::moveBy(dx, dy);

    setWidgetsPos(QPoint(int(x()), int(y())));
}

bool CNItem::mousePressEvent(const EventInfo &info)
{
    bool accepted = Item::mousePressEvent(info);
    if (!accepted)
        accepted = CIWidgetMgr::mousePressEvent(info);
    if (accepted)
        setChanged();
    return accepted;
}

bool CNItem::mouseReleaseEvent(const EventInfo &info)
{
    bool accepted = Item::mouseReleaseEvent(info);
    if (!accepted)
        accepted = CIWidgetMgr::mouseReleaseEvent(info);
    if (accepted)
        setChanged();
    return accepted;
}

bool CNItem::mouseDoubleClickEvent(const EventInfo &info)
{
    bool accepted = Item::mouseDoubleClickEvent(info);
    if (!accepted)
        accepted = CIWidgetMgr::mouseDoubleClickEvent(info);
    if (accepted)
        setChanged();
    return accepted;
}

bool CNItem::mouseMoveEvent(const EventInfo &info)
{
    bool accepted = Item::mouseMoveEvent(info);
    if (!accepted)
        accepted = CIWidgetMgr::mouseMoveEvent(info);
    if (accepted)
        setChanged();
    return accepted;
}

bool CNItem::wheelEvent(const EventInfo &info)
{
    bool accepted = Item::wheelEvent(info);
    if (!accepted)
        accepted = CIWidgetMgr::wheelEvent(info);
    if (accepted)
        setChanged();
    return accepted;
}

void CNItem::enterEvent(QEvent *)
{
    Item::enterEvent(nullptr);
    CIWidgetMgr::enterEvent(nullptr);
    setChanged();
}

void CNItem::leaveEvent(QEvent *)
{
    Item::leaveEvent(nullptr);
    CIWidgetMgr::leaveEvent(nullptr);
    setChanged();
}

void CNItem::drawShape(QPainter &p)
{
    if (!isVisible())
        return;

    if (isSelected())
        p.setPen(m_selectedCol);

    p.drawPolygon(areaPoints());
    p.drawPolyline(areaPoints());
}

void CNItem::initPainter(QPainter &p)
{
    if (isSelected())
        p.setPen(m_selectedCol);
}

void CNItem::updateConnectorPoints(bool add)
{
    if (b_deleted || !isVisible())
        add = false;

    if (b_pointsAdded == add)
        return;

    b_pointsAdded = add;

    Cells *cells = p_icnDocument->cells();
    if (!cells)
        return;

    // Get translation matrix
    QTransform m;
    if (Component *c = dynamic_cast<Component *>(this))
        m = c->transMatrix(c->angleDegrees(), c->flipped(), int(x()), int(y()), false);

    // Convention used here: _UM = unmapped by both matrix and cell reference, _M = mapped

    const QPoint start_UM = QPoint(int(x() + offsetX()) - 8, int(y() + offsetY()) - 8);
    const QPoint end_UM = start_UM + QPoint(width() + 2 * 8, height() + 2 * 8);

    const QPoint start_M = roundDown(m.map(start_UM), 8);
    const QPoint end_M = roundDown(m.map(end_UM), 8);

    int sx_M = start_M.x();
    int ex_M = end_M.x();

    int sy_M = start_M.y();
    int ey_M = end_M.y();

    // Normalise start and end points
    if (sx_M > ex_M) {
        const int temp = sx_M;
        sx_M = ex_M;
        ex_M = temp;
    }
    if (sy_M > ey_M) {
        const int temp = sy_M;
        sy_M = ey_M;
        ey_M = temp;
    }

    ex_M++;
    ey_M++;

    const int mult = add ? 1 : -1;

    for (int x = sx_M; x < ex_M; x++) {
        for (int y = sy_M; y < ey_M; y++) {
            if (cells->haveCell(x, y)) {
                if (x != sx_M && y != sy_M && x != (ex_M - 1) && y != (ey_M - 1)) {
                    cells->cell(x, y).CIpenalty += mult * ICNDocument::hs_item;
                } else {
                    cells->cell(x, y).CIpenalty += mult * ICNDocument::hs_connector * 5;
                }
            }
        }
    }

#if 0
	// And subtract the positions of the node on the border
	NodeInfoMap::iterator end = m_nodeMap.end();
	for ( NodeInfoMap::iterator it = m_nodeMap.begin(); it != end; ++it )
	{
		const int x = (int)((it->second.node->x()-4)/cellSize);
		const int y = (int)((it->second.node->y()-4)/cellSize);
		if ( p_icnDocument->isValidCellReference(x,y) ) {
			(*cells)[x][y].CIpenalty -= mult*ICNDocument::hs_connector*5;
		}
	}
#endif

    const TextMap::iterator textMapEnd = m_textMap.end();
    for (TextMap::iterator it = m_textMap.begin(); it != textMapEnd; ++it) {
        it.value()->updateConnectorPoints(add);
    }
    const WidgetMap::iterator widgetMapEnd = m_widgetMap.end();
    for (WidgetMap::iterator it = m_widgetMap.begin(); it != widgetMapEnd; ++it) {
        it.value()->updateConnectorPoints(add);
    }
}

Text *CNItem::addDisplayText(const QString &id, const QRect &pos, const QString &display, bool internal, int flags)
{
    Text *text = nullptr;
    TextMap::iterator it = m_textMap.find(id);
    if (it != m_textMap.end()) {
        // 		qCWarning(KTL_LOG) << "CNItem::addDisplayText: removing old text";
        delete it.value();
        m_textMap.erase(it);
    }

    text = new Text("", this, pos, canvas(), flags);
    text->setZ(z() + (internal ? 0.1 : -0.1));

    m_textMap[id] = text;

    // Calculate the correct size
    setDisplayText(id, display);
    text->show();
    return text;
}

void CNItem::setDisplayText(const QString &id, const QString &display)
{
    TextMap::iterator it = m_textMap.find(id);
    if (it == m_textMap.end()) {
        qCCritical(KTL_LOG) << "CNItem::setDisplayText: Could not find text with id \"" << id << "\"";
        return;
    }
    it.value()->setText(display);
    updateAttachedPositioning();
}

void CNItem::removeDisplayText(const QString &id)
{
    TextMap::iterator it = m_textMap.find(id);
    if (it == m_textMap.end()) {
        // 		qCCritical(KTL_LOG) << "CNItem::removeDisplayText: Could not find text with id \""<<id<<"\"";
        return;
    }
    it.value()->updateConnectorPoints(false);
    delete it.value();
    m_textMap.erase(it);
}

QString CNItem::nodeId(const QString &internalNodeId)
{
    NodeInfoMap::iterator it = m_nodeMap.find(internalNodeId);
    if (it == m_nodeMap.end())
        return "";
    else
        return it.value().id;
}

Node *CNItem::childNode(const QString &childId)
{
    return p_icnDocument->nodeWithID(nodeId(childId));
}

NodeInfo::NodeInfo()
{
    node = nullptr;
    x = 0.;
    y = 0.;
    orientation = 0;
}


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

#include "canvasitemparts.h"
#include "cells.h"
#include "component.h"
#include "icndocument.h"
#include "inputflownode.h"
#include "itemdocumentdata.h"
#include "junctionflownode.h"
#include "junctionnode.h"
#include "outputflownode.h"
#include "pinnode.h"

#include <QBitArray>
#include <QPainter>

#include <cmath>
#include <cstdlib>

#include <ktechlab_debug.h>

CNItem::CNItem(ICNDocument *icnDocument, bool newItem, const QString &id)
    : Item(icnDocument, newItem, id)
    , CIWidgetMgr(icnDocument ? icnDocument->canvas() : nullptr, this)
    , p_icnDocument(icnDocument)
    , b_pointsAdded(false)
{
    qCDebug(KTL_LOG) << " this=" << this;

    setZ(ICNDocument::Z::Item);
    setSelected(false);

    m_brushCol = QColor(0xf7, 0xf7, 0xff);
    m_selectedCol = QColor(101, 134, 192);

    setBrush(m_brushCol);
    setPen(QPen(Qt::black));
}

CNItem::~CNItem()
{
    const TextMap::iterator textMapEnd = m_textMap.end();
    for (TextMap::iterator it = m_textMap.begin(); it != textMapEnd; ++it) {
        if (it.value())
            it.value()->setCanvas(nullptr);

        delete (Text *)it.value();
    }
    m_textMap.clear();

    updateConnectorPoints(false);
}

bool CNItem::preResize(QRect sizeRect)
{
    if ((std::abs(sizeRect.width()) < minimumSize().width()) || (std::abs(sizeRect.height()) < minimumSize().height()))
        return false;

    updateConnectorPoints(false);
    return true;
}

void CNItem::postResize()
{
    updateAttachedPositioning();
}

void CNItem::setVisible(bool yes)
{
    if (b_deleted) {
        Item::setVisible(false);
        return;
    }

    Item::setVisible(yes);

    const TextMap::iterator textMapEnd = m_textMap.end();
    for (TextMap::iterator it = m_textMap.begin(); it != textMapEnd; ++it) {
        it.value()->setVisible(yes);
    }

    const NodeInfoMap::iterator nodeMapEnd = m_nodeMap.end();
    for (NodeInfoMap::iterator it = m_nodeMap.begin(); it != nodeMapEnd; ++it) {
        it.value().node->setVisible(yes);
    }

    CNItem::setDrawWidgets(yes);

    if (!yes)
        updateConnectorPoints(false);
}

void CNItem::reparented(Item *oldParent, Item *newParent)
{
    Item::reparented(oldParent, newParent);
    updateNodeLevels();
}

void CNItem::updateNodeLevels()
{
    int l = level();

    // Tell our nodes about our level
    const NodeInfoMap::iterator nodeMapEnd = m_nodeMap.end();
    for (NodeInfoMap::iterator it = m_nodeMap.begin(); it != nodeMapEnd; ++it) {
        it.value().node->setLevel(l);
    }

    const ItemList::iterator end = m_children.end();
    for (ItemList::iterator it = m_children.begin(); it != end; ++it) {
        if (CNItem *cnItem = dynamic_cast<CNItem *>((Item *)*it))
            cnItem->updateNodeLevels();
    }
}

ConnectorList CNItem::connectorList()

    const NodeInfoMap::iterator nodeMapEnd = m_nodeMap.end();
    for (NodeInfoMap::iterator it = m_nodeMap.begin(); it != nodeMapEnd; ++it) {
        Node *node = p_icnDocument->nodeWithID(it.value().id);
        if (node) {
            ConnectorList nodeList = node->getAllConnectors();
            ConnectorList::iterator end = nodeList.end();
            for (ConnectorList::iterator it = nodeList.begin(); it != end; ++it) {
                if (*it && !list.contains(*it)) {
                    list.append(*it);
                }
            }
        }
    }

    return list;
}

void CNItem::removeItem()
{
    if (b_deleted)
        return;

    const TextMap::iterator textMapEnd = m_textMap.end();
    for (TextMap::iterator it = m_textMap.begin(); it != textMapEnd; ++it)
        it.value()->setCanvas(nullptr);

    Item::removeItem();
    updateConnectorPoints(false);
}

void CNItem::restoreFromItemData(const ItemData &itemData)
{
    Item::restoreFromItemData(itemData);

    updateConnectorPoints(false);

    {
        const BoolMap::const_iterator end = itemData.buttonMap.end();
        for (BoolMap::const_iterator it = itemData.buttonMap.begin(); it != end; ++it) {
            Button *b = button(it.key());
            if (b)
                b->setState(it.value());
        }
    }
    {
        const IntMap::const_iterator end = itemData.sliderMap.end();
        for (IntMap::const_iterator it = itemData.sliderMap.begin(); it != end; ++it) {
            Slider *s = slider(it.key());
            if (s)
                s->setValue(it.value());
        }
    }
}

ItemData CNItem::itemData() const
{
    ItemData itemData = Item::itemData();

    const WidgetMap::const_iterator end = m_widgetMap.end();
    for (WidgetMap::const_iterator it = m_widgetMap.begin(); it != end; ++it) {
        if (Slider *slider = dynamic_cast<Slider *>(*it))
            itemData.sliderMap[slider->id()] = slider->value();

        else if (Button *button = dynamic_cast<Button *>(*it))
            itemData.buttonMap[button->id()] = button->state();
    }

    return itemData;
}

Node *CNItem::createNode(double _x, double _y, int orientation, const QString &name, uint type)
{
    orientation %= 360;
    if (orientation < 0)
        orientation += 360;

    Node *node = nullptr;

    // TODO get rid of this switch statement...
    switch (type) {
    case Node::ec_pin:
        node = new PinNode(p_icnDocument, orientation, QPoint(0, 0));
        break;
    case Node::ec_junction:
        node = new JunctionNode(p_icnDocument, orientation, QPoint(0, 0));
        break;
    case Node::fp_junction:
        node = new JunctionFlowNode(p_icnDocument, orientation, QPoint(0, 0));
        break;
    case Node::fp_in:
        node = new InputFlowNode(p_icnDocument, orientation, QPoint(0, 0));
        break;
    case Node::fp_out:
        node = new OutputFlowNode(p_icnDocument, orientation, QPoint(0, 0));
        break;
    }

    node->setLevel(level());

    node->setParentItem(this);
    node->setChildId(name);

    NodeInfo info;
    info.id = node->id();
    info.node = node;
    info.x = _x;
    info.y = _y;
    info.orientation = orientation;

    m_nodeMap[name] = info;

    updateAttachedPositioning();

    return node;
}

bool CNItem::removeNode(const QString &name)
{
    NodeInfoMap::iterator it = m_nodeMap.find(name);
    if (it == m_nodeMap.end()) {
        return false;
    }
    it.value().node->removeNode();
    p_icnDocument->flushDeleteList();
    m_nodeMap.erase(it);
    return true;
}

Node *CNItem::getClosestNode(const QPoint &pos)
{
    // Work through the nodes, finding the one closest to the (x, y) position
    Node *shortestNode = nullptr;
    double shortestDistance = 1e10; // Nice large distance :-)

    const NodeInfoMap::iterator end = m_nodeMap.end();
    for (NodeInfoMap::iterator it = m_nodeMap.begin(); it != end; ++it) {
        Node *node = p_icnDocument->nodeWithID(it.value().id);
        if (node) {
            // Calculate the distance
            // Yeah, it's actually the distance squared; but it's all relative, so doesn't matter
            double distance = std::pow(node->x() - pos.x(), 2) + std::pow(node->y() - pos.y(), 2);

            if (distance < shortestDistance) {
                shortestDistance = distance;
                shortestNode = node;
            }
        }
    }

    return shortestNode;
}

void CNItem::updateAttachedPositioning()
{
    if (b_deleted)
        return;

}

void CNItem::updateZ(int baseZ)
{
    Item::updateZ(baseZ);

    double _z = z();

    const NodeInfoMap::iterator nodeMapEnd = m_nodeMap.end();
    for (NodeInfoMap::iterator it = m_nodeMap.begin(); it != nodeMapEnd; ++it)
        it.value().node->setZ(_z + 0.5);

    const WidgetMap::iterator widgetMapEnd = m_widgetMap.end();
    for (WidgetMap::iterator it = m_widgetMap.begin(); it != widgetMapEnd; ++it)
        it.value()->setZ(_z + 0.5);

    const TextMap::iterator textMapEnd = m_textMap.end();
    for (TextMap::iterator it = m_textMap.begin(); it != textMapEnd; ++it)
        it.value()->setZ(_z + 0.5);
}

void CNItem::moveBy(double dx, double dy)
{
    if (dx == 0 && dy == 0)
        return;
    updateConnectorPoints(false);
    Item::moveBy(dx, dy);

    setWidgetsPos(QPoint(int(x()), int(y())));
}

bool CNItem::mousePressEvent(const EventInfo &info)
{
    bool accepted = Item::mousePressEvent(info);
    if (!accepted)
        accepted = CIWidgetMgr::mousePressEvent(info);
    if (accepted)
        setChanged();
    return accepted;
}

bool CNItem::mouseReleaseEvent(const EventInfo &info)
{
    bool accepted = Item::mouseReleaseEvent(info);
    if (!accepted)
        accepted = CIWidgetMgr::mouseReleaseEvent(info);
    if (accepted)
        setChanged();
    return accepted;
}

bool CNItem::mouseDoubleClickEvent(const EventInfo &info)
{
    bool accepted = Item::mouseDoubleClickEvent(info);
    if (!accepted)
        accepted = CIWidgetMgr::mouseDoubleClickEvent(info);
    if (accepted)
        setChanged();
    return accepted;
}

bool CNItem::mouseMoveEvent(const EventInfo &info)
{
    bool accepted = Item::mouseMoveEvent(info);
    if (!accepted)
        accepted = CIWidgetMgr::mouseMoveEvent(info);
    if (accepted)
        setChanged();
    return accepted;
}

bool CNItem::wheelEvent(const EventInfo &info)
{
    bool accepted = Item::wheelEvent(info);
    if (!accepted)
        accepted = CIWidgetMgr::wheelEvent(info);
    if (accepted)
        setChanged();
    return accepted;
}

void CNItem::enterEvent(QEvent *)
{
    Item::enterEvent(nullptr);
    CIWidgetMgr::enterEvent(nullptr);
    setChanged();
}

void CNItem::leaveEvent(QEvent *)
{
    Item::leaveEvent(nullptr);
    CIWidgetMgr::leaveEvent(nullptr);
    setChanged();
}

void CNItem::drawShape(QPainter &p)
{
    if (!isVisible())
        return;

    if (isSelected())
        p.setPen(m_selectedCol);

    p.drawPolygon(areaPoints());
    p.drawPolyline(areaPoints());
}

void CNItem::initPainter(QPainter &p)
{
    if (isSelected())
        p.setPen(m_selectedCol);
}

void CNItem::updateConnectorPoints(bool add)
{
    if (b_deleted || !isVisible())
        add = false;

    if (b_pointsAdded == add)
        return;

    b_pointsAdded = add;

    Cells *cells = p_icnDocument->cells();
    if (!cells)
        return;

    // Get translation matrix
    QTransform m;
    if (Component *c = dynamic_cast<Component *>(this))
        m = c->transMatrix(c->angleDegrees(), c->flipped(), int(x()), int(y()), false);

    // Convention used here: _UM = unmapped by both matrix and cell reference, _M = mapped

    const QPoint start_UM = QPoint(int(x() + offsetX()) - 8, int(y() + offsetY()) - 8);
    const QPoint end_UM = start_UM + QPoint(width() + 2 * 8, height() + 2 * 8);

    const QPoint start_M = roundDown(m.map(start_UM), 8);
    const QPoint end_M = roundDown(m.map(end_UM), 8);

    int sx_M = start_M.x();
    int ex_M = end_M.x();

    int sy_M = start_M.y();
    int ey_M = end_M.y();

    // Normalise start and end points
    if (sx_M > ex_M) {
        const int temp = sx_M;
        sx_M = ex_M;
        ex_M = temp;
    }
    if (sy_M > ey_M) {
        const int temp = sy_M;
        sy_M = ey_M;
        ey_M = temp;
    }

    ex_M++;
    ey_M++;

    const int mult = add ? 1 : -1;

    for (int x = sx_M; x < ex_M; x++) {
        for (int y = sy_M; y < ey_M; y++) {
            if (cells->haveCell(x, y)) {
                if (x != sx_M && y != sy_M && x != (ex_M - 1) && y != (ey_M - 1)) {
                    cells->cell(x, y).CIpenalty += mult * ICNDocument::hs_item;
                } else {
                    cells->cell(x, y).CIpenalty += mult * ICNDocument::hs_connector * 5;
                }
            }
        }
    }

#if 0
	// And subtract the positions of the node on the border
	NodeInfoMap::iterator end = m_nodeMap.end();
	for ( NodeInfoMap::iterator it = m_nodeMap.begin(); it != end; ++it )
	{
		const int x = (int)((it->second.node->x()-4)/cellSize);
		const int y = (int)((it->second.node->y()-4)/cellSize);
		if ( p_icnDocument->isValidCellReference(x,y) ) {
			(*cells)[x][y].CIpenalty -= mult*ICNDocument::hs_connector*5;
		}
	}
#endif

    const TextMap::iterator textMapEnd = m_textMap.end();
    for (TextMap::iterator it = m_textMap.begin(); it != textMapEnd; ++it) {
        it.value()->updateConnectorPoints(add);
    }
    const WidgetMap::iterator widgetMapEnd = m_widgetMap.end();
    for (WidgetMap::iterator it = m_widgetMap.begin(); it != widgetMapEnd; ++it) {
        it.value()->updateConnectorPoints(add);
    }
}

Text *CNItem::addDisplayText(const QString &id, const QRect &pos, const QString &display, bool internal, int flags)
{
    Text *text = nullptr;
    TextMap::iterator it = m_textMap.find(id);
    if (it != m_textMap.end()) {
        // 		qCWarning(KTL_LOG) << "CNItem::addDisplayText: removing old text";
        delete it.value();
        m_textMap.erase(it);
    }

    text = new Text("", this, pos, canvas(), flags);
    text->setZ(z() + (internal ? 0.1 : -0.1));

    m_textMap[id] = text;

    // Calculate the correct size
    setDisplayText(id, display);
    text->show();
    return text;
}

void CNItem::setDisplayText(const QString &id, const QString &display)
{
    TextMap::iterator it = m_textMap.find(id);
    if (it == m_textMap.end()) {
        qCCritical(KTL_LOG) << "CNItem::setDisplayText: Could not find text with id \"" << id << "\"";
        return;
    }
    it.value()->setText(display);
    updateAttachedPositioning();
}

void CNItem::removeDisplayText(const QString &id)
{
    TextMap::iterator it = m_textMap.find(id);
    if (it == m_textMap.end()) {
        // 		qCCritical(KTL_LOG) << "CNItem::removeDisplayText: Could not find text with id \""<<id<<"\"";
        return;
    }
    it.value()->updateConnectorPoints(false);
    delete it.value();
    m_textMap.erase(it);
}

QString CNItem::nodeId(const QString &internalNodeId)
{
    NodeInfoMap::iterator it = m_nodeMap.find(internalNodeId);
    if (it == m_nodeMap.end())
        return "";
    else
        return it.value().id;
}

Node *CNItem::childNode(const QString &childId)
{
    return p_icnDocument->nodeWithID(nodeId(childId));
}

NodeInfo::NodeInfo()
{
    node = nullptr;
    x = 0.;
    y = 0.;
    orientation = 0;
}