<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Quick Controls module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qtmenu_p.h"
#include "qdebug.h"
#include "qtaction_p.h"
#include "qtmenupopupwindow_p.h"
#include <qabstractitemmodel.h>

#include <QtGui/QCursor>
#include "private/qguiapplication_p.h"
#include <QtGui/qpa/qplatformtheme.h>
#include <QtGui/qpa/qplatformmenu.h>

QT_BEGIN_NAMESPACE

/*!
  \class QtMenu
  \internal
 */

/*!
  \qmltype MenuPrivate
  \instantiates QtMenu
  \internal
  \inqmlmodule QtQuick.Controls 1.0
 */

/*!
    \qmlproperty readonly list Menu::items
    \default

    The list of items in the menu.

    \sa MenuItem, MenuSeparator
*/

/*!
    \qmlproperty bool Menu::visible

    Whether the menu should be visible. This is only enabled when the menu is used as
    a submenu.
*/

/*!
    \qmlproperty string Menu::text

    Text for the menu as a submenu or in a menubar.

    Mnemonics are supported by prefixing the shortcut letter with \&.
    For instance, \c "\&File" will bind the \c Alt-F shortcut to the
    \c "File" menu. Note that not all platforms support mnemonics.
*/

/*!
    \qmlproperty bool Menu::enabled

    Whether the menu is enabled, and responsive to user interaction as a submenu.
*/

/*!
    \qmlproperty url Menu::iconSource

    Sets the icon file or resource url for the menu icon as a submenu.

    \sa iconName
*/

/*!
    \qmlproperty string Menu::iconName

    Sets the icon name for the menu icon. This will pick the icon
    with the given name from the current theme. Only works as a submenu.

    \sa iconSource
*/

/*!
    \qmlproperty int Menu::selectedIndex

    The index of the last selected item in the menu.
*/

/*!
    \qmlmethod void Menu::popup()

    Opens this menu under the mouse cursor.
    It can block on some platforms, so test it accordingly.
*/

/*!
    \qmlproperty var Menu::model
*/

QtMenu::QtMenu(QObject *parent)
    : QtMenuText(parent),
      m_selectedIndex(-1),
      m_highlightedIndex(0),
      m_hasNativeModel(false),
      m_minimumWidth(0),
      m_popupWindow(0),
      m_menuContentItem(0),
      m_popupVisible(false),
      m_parentWindow(0)
{
    m_platformMenu = QGuiApplicationPrivate::platformTheme()->createPlatformMenu();
    if (m_platformMenu) {
        connect(m_platformMenu, SIGNAL(aboutToHide()), this, SLOT(__closeMenu()));
        if (platformItem())
            platformItem()->setMenu(m_platformMenu);
    }
}

QtMenu::~QtMenu()
{
    delete m_platformMenu;
}

void QtMenu::setText(const QString &text)
{
    QtMenuText::setText(text);
    if (m_platformMenu)
        m_platformMenu->setText(this->text());
}

void QtMenu::setMinimumWidth(int w)
{
    if (w == m_minimumWidth)
        return;

    m_minimumWidth = w;
    if (m_platformMenu)
        m_platformMenu->setMinimumWidth(w);
}

void QtMenu::setFont(const QFont &arg)
{
    if (m_platformMenu)
        m_platformMenu->setFont(arg);
}

void QtMenu::setSelectedIndex(int index)
{
    if (m_selectedIndex == index)
        return;

    m_selectedIndex = index;
    emit selectedIndexChanged();
}

void QtMenu::updateSelectedIndex()
{
    if (QtMenuBase *menuItem = qobject_cast<QtMenuItem*>(sender())) {
        int index = m_menuItems.indexOf(menuItem);
        setSelectedIndex(index);
    }
}

QQmlListProperty<QtMenuBase> QtMenu::menuItems()
{
    return QQmlListProperty<QtMenuBase>(this, 0, &QtMenu::append_menuItems, &QtMenu::count_menuItems, &QtMenu::at_menuItems, 0);
}

QQuickWindow *QtMenu::findParentWindow()
{
    if (!m_parentWindow) {
        QQuickItem *parentAsItem = qobject_cast<QQuickItem *>(parent());
        m_parentWindow = visualItem() ? visualItem()->window() :    // Menu as menu item case
                         parentAsItem ? parentAsItem->window() : 0; //Menu as context menu/popup case
    }
    return m_parentWindow;
}

void QtMenu::popup()
{
    QPoint mousePos = QCursor::pos();
    if (QQuickWindow *parentWindow = findParentWindow())
        mousePos = parentWindow->mapFromGlobal(mousePos);

    __popup(mousePos.x(), mousePos.y());
}

void QtMenu::__popup(qreal x, qreal y, int atItemIndex)
{
    if (popupVisible())
        __closeMenu();

    setPopupVisible(true);

    // If atItemIndex is valid, x and y is specified from the
    // the position of the corresponding QtMenuItem:
    QtMenuItem *atItem = 0;
    if (atItemIndex >= 0)
        while (!atItem && atItemIndex < m_menuItems.size())
            atItem = qobject_cast<QtMenuItem *>(m_menuItems[atItemIndex++]);

    QQuickWindow *parentWindow = findParentWindow();

    if (m_platformMenu) {
        QPointF screenPosition(x, y);
        if (visualItem())
            screenPosition = visualItem()->mapToScene(screenPosition);
        m_platformMenu->showPopup(parentWindow, screenPosition.toPoint(), atItem ? atItem->platformItem() : 0);
    } else {
        m_popupWindow = new QtMenuPopupWindow();
        m_popupWindow->setParentWindow(parentWindow);
        m_popupWindow->setMenuContentItem(m_menuContentItem);
        connect(m_popupWindow, SIGNAL(visibleChanged(bool)), this, SLOT(windowVisibleChanged(bool)));

        if (parentWindow) {
            if (visualItem()) {
                QPointF pos = visualItem()->mapToItem(parentWindow->contentItem(), QPointF(x, y));
                x = pos.x();
                y = pos.y();
            }

            x += parentWindow->geometry().left();
            y += parentWindow->geometry().top();
        }

        QQuickItem *visualItem = atItem ? atItem->visualItem() : 0;
        if (visualItem) {
            QPointF pos = visualItem->position();
            x -= pos.x();
            y -= pos.y();
            m_popupWindow->setItemAt(visualItem);
        }

        m_popupWindow->setGeometry(x, y, m_menuContentItem->width(), m_menuContentItem->height());
        m_popupWindow->show();
        m_popupWindow->setMouseGrabEnabled(true); // Needs to be done after calling show()
        m_popupWindow->setKeyboardGrabEnabled(true);
    }
}

void QtMenu::setMenuContentItem(QQuickItem *item)
{
    if (m_menuContentItem != item)
        m_menuContentItem = item;
}

void QtMenu::setPopupVisible(bool v)
{
    if (m_popupVisible != v) {
        m_popupVisible = v;
        emit popupVisibleChanged();
    }
}

void QtMenu::__closeMenu()
{
    setPopupVisible(false);
    if (m_popupWindow)
        m_popupWindow->setVisible(false);
    m_parentWindow = 0;
    emit __menuClosed();
}

void QtMenu::__dismissMenu()
{
    if (m_popupWindow)
        m_popupWindow->dismissMenu();
}

void QtMenu::windowVisibleChanged(bool v)
{
    if (!v) {
        if (qobject_cast<QtMenuPopupWindow *>(m_popupWindow->transientParent())) {
            m_popupWindow->transientParent()->setMouseGrabEnabled(true);
            m_popupWindow->transientParent()->setKeyboardGrabEnabled(true);
        }
        m_popupWindow->deleteLater();
        m_popupWindow = 0;
        __closeMenu();
    }
}

void QtMenu::clear()
{
    foreach (QtMenuBase *item, m_menuItems) {
        if (m_platformMenu)
            m_platformMenu->removeMenuItem(item->platformItem());
        delete item;
    }
    m_menuItems.clear();
}

void QtMenu::addMenuItem(QtMenuBase *menuItem)
{
    menuItem->setParentMenu(this);
    m_menuItems.append(menuItem);
    if (QPlatformMenuItem *platformItem = menuItem->platformItem()) {
        if (m_platformMenu)
            m_platformMenu->insertMenuItem(platformItem, 0 /* append */);
    }
}

QtMenuItem *QtMenu::addItem(const QString &text)
{
    QtMenuItem *menuItem = new QtMenuItem(this);
    menuItem->setText(text);
    addMenuItem(menuItem);

    emit itemsChanged();
    return menuItem;
}

QString QtMenu::__modelTextAt(int index) const
{
    if (QAbstractItemModel *model = qobject_cast<QAbstractItemModel*>(m_model.value<QObject*>())) {
        return model->data(model->index(index, 0)).toString();
    } else if (m_model.canConvert(QVariant::StringList)) {
        return m_model.toStringList().at(index);
    }
    return "";
}

int QtMenu::__modelCount() const
{
    if (QAbstractItemModel *model = qobject_cast<QAbstractItemModel*>(m_model.value<QObject*>())) {
        return model->rowCount();
    } else if (m_model.canConvert(QVariant::StringList)) {
        return m_model.toStringList().count();
    }
    return -1;
}

void QtMenu::append_menuItems(QQmlListProperty<QtMenuBase> *list, QtMenuBase *menuItem)
{
    if (QtMenu *menu = qobject_cast<QtMenu *>(list->object))
        menu->addMenuItem(menuItem);
}

int QtMenu::count_menuItems(QQmlListProperty<QtMenuBase> *list)
{
    QtMenu *menu = qobject_cast<QtMenu *>(list->object);
    if (menu)
        return menu->m_menuItems.size();
    return 0;
}

QtMenuBase *QtMenu::at_menuItems(QQmlListProperty<QtMenuBase> *list, int index)
{
    QtMenu *menu = qobject_cast<QtMenu *>(list->object);
    if (menu && 0 <= index && index < menu->m_menuItems.size())
        return menu->m_menuItems[index];
    return 0;
}

void QtMenu::setModel(const QVariant &newModel) {
    if (m_model != newModel) {
        m_hasNativeModel = false;
        m_model = newModel;

        if (qobject_cast<QAbstractItemModel*>(newModel.value<QObject*>()))
            m_hasNativeModel = true;
        else if (newModel.canConvert(QVariant::StringList))
            m_hasNativeModel = true;

        emit modelChanged(m_model);
    }
}

QT_END_NAMESPACE
<commit_msg>QtMenu: fix member variable initialization order<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Quick Controls module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qtmenu_p.h"
#include "qdebug.h"
#include "qtaction_p.h"
#include "qtmenupopupwindow_p.h"
#include <qabstractitemmodel.h>

#include <QtGui/QCursor>
#include "private/qguiapplication_p.h"
#include <QtGui/qpa/qplatformtheme.h>
#include <QtGui/qpa/qplatformmenu.h>

QT_BEGIN_NAMESPACE

/*!
  \class QtMenu
  \internal
 */

/*!
  \qmltype MenuPrivate
  \instantiates QtMenu
  \internal
  \inqmlmodule QtQuick.Controls 1.0
 */

/*!
    \qmlproperty readonly list Menu::items
    \default

    The list of items in the menu.

    \sa MenuItem, MenuSeparator
*/

/*!
    \qmlproperty bool Menu::visible

    Whether the menu should be visible. This is only enabled when the menu is used as
    a submenu.
*/

/*!
    \qmlproperty string Menu::text

    Text for the menu as a submenu or in a menubar.

    Mnemonics are supported by prefixing the shortcut letter with \&.
    For instance, \c "\&File" will bind the \c Alt-F shortcut to the
    \c "File" menu. Note that not all platforms support mnemonics.
*/

/*!
    \qmlproperty bool Menu::enabled

    Whether the menu is enabled, and responsive to user interaction as a submenu.
*/

/*!
    \qmlproperty url Menu::iconSource

    Sets the icon file or resource url for the menu icon as a submenu.

    \sa iconName
*/

/*!
    \qmlproperty string Menu::iconName

    Sets the icon name for the menu icon. This will pick the icon
    with the given name from the current theme. Only works as a submenu.

    \sa iconSource
*/

/*!
    \qmlproperty int Menu::selectedIndex

    The index of the last selected item in the menu.
*/

/*!
    \qmlmethod void Menu::popup()

    Opens this menu under the mouse cursor.
    It can block on some platforms, so test it accordingly.
*/

/*!
    \qmlproperty var Menu::model
*/

QtMenu::QtMenu(QObject *parent)
    : QtMenuText(parent),
      m_selectedIndex(-1),
      m_highlightedIndex(0),
      m_parentWindow(0),
      m_hasNativeModel(false),
      m_minimumWidth(0),
      m_popupWindow(0),
      m_menuContentItem(0),
      m_popupVisible(false)
{
    m_platformMenu = QGuiApplicationPrivate::platformTheme()->createPlatformMenu();
    if (m_platformMenu) {
        connect(m_platformMenu, SIGNAL(aboutToHide()), this, SLOT(__closeMenu()));
        if (platformItem())
            platformItem()->setMenu(m_platformMenu);
    }
}

QtMenu::~QtMenu()
{
    delete m_platformMenu;
}

void QtMenu::setText(const QString &text)
{
    QtMenuText::setText(text);
    if (m_platformMenu)
        m_platformMenu->setText(this->text());
}

void QtMenu::setMinimumWidth(int w)
{
    if (w == m_minimumWidth)
        return;

    m_minimumWidth = w;
    if (m_platformMenu)
        m_platformMenu->setMinimumWidth(w);
}

void QtMenu::setFont(const QFont &arg)
{
    if (m_platformMenu)
        m_platformMenu->setFont(arg);
}

void QtMenu::setSelectedIndex(int index)
{
    if (m_selectedIndex == index)
        return;

    m_selectedIndex = index;
    emit selectedIndexChanged();
}

void QtMenu::updateSelectedIndex()
{
    if (QtMenuBase *menuItem = qobject_cast<QtMenuItem*>(sender())) {
        int index = m_menuItems.indexOf(menuItem);
        setSelectedIndex(index);
    }
}

QQmlListProperty<QtMenuBase> QtMenu::menuItems()
{
    return QQmlListProperty<QtMenuBase>(this, 0, &QtMenu::append_menuItems, &QtMenu::count_menuItems, &QtMenu::at_menuItems, 0);
}

QQuickWindow *QtMenu::findParentWindow()
{
    if (!m_parentWindow) {
        QQuickItem *parentAsItem = qobject_cast<QQuickItem *>(parent());
        m_parentWindow = visualItem() ? visualItem()->window() :    // Menu as menu item case
                         parentAsItem ? parentAsItem->window() : 0; //Menu as context menu/popup case
    }
    return m_parentWindow;
}

void QtMenu::popup()
{
    QPoint mousePos = QCursor::pos();
    if (QQuickWindow *parentWindow = findParentWindow())
        mousePos = parentWindow->mapFromGlobal(mousePos);

    __popup(mousePos.x(), mousePos.y());
}

void QtMenu::__popup(qreal x, qreal y, int atItemIndex)
{
    if (popupVisible())
        __closeMenu();

    setPopupVisible(true);

    // If atItemIndex is valid, x and y is specified from the
    // the position of the corresponding QtMenuItem:
    QtMenuItem *atItem = 0;
    if (atItemIndex >= 0)
        while (!atItem && atItemIndex < m_menuItems.size())
            atItem = qobject_cast<QtMenuItem *>(m_menuItems[atItemIndex++]);

    QQuickWindow *parentWindow = findParentWindow();

    if (m_platformMenu) {
        QPointF screenPosition(x, y);
        if (visualItem())
            screenPosition = visualItem()->mapToScene(screenPosition);
        m_platformMenu->showPopup(parentWindow, screenPosition.toPoint(), atItem ? atItem->platformItem() : 0);
    } else {
        m_popupWindow = new QtMenuPopupWindow();
        m_popupWindow->setParentWindow(parentWindow);
        m_popupWindow->setMenuContentItem(m_menuContentItem);
        connect(m_popupWindow, SIGNAL(visibleChanged(bool)), this, SLOT(windowVisibleChanged(bool)));

        if (parentWindow) {
            if (visualItem()) {
                QPointF pos = visualItem()->mapToItem(parentWindow->contentItem(), QPointF(x, y));
                x = pos.x();
                y = pos.y();
            }

            x += parentWindow->geometry().left();
            y += parentWindow->geometry().top();
        }

        QQuickItem *visualItem = atItem ? atItem->visualItem() : 0;
        if (visualItem) {
            QPointF pos = visualItem->position();
            x -= pos.x();
            y -= pos.y();
            m_popupWindow->setItemAt(visualItem);
        }

        m_popupWindow->setGeometry(x, y, m_menuContentItem->width(), m_menuContentItem->height());
        m_popupWindow->show();
        m_popupWindow->setMouseGrabEnabled(true); // Needs to be done after calling show()
        m_popupWindow->setKeyboardGrabEnabled(true);
    }
}

void QtMenu::setMenuContentItem(QQuickItem *item)
{
    if (m_menuContentItem != item)
        m_menuContentItem = item;
}

void QtMenu::setPopupVisible(bool v)
{
    if (m_popupVisible != v) {
        m_popupVisible = v;
        emit popupVisibleChanged();
    }
}

void QtMenu::__closeMenu()
{
    setPopupVisible(false);
    if (m_popupWindow)
        m_popupWindow->setVisible(false);
    m_parentWindow = 0;
    emit __menuClosed();
}

void QtMenu::__dismissMenu()
{
    if (m_popupWindow)
        m_popupWindow->dismissMenu();
}

void QtMenu::windowVisibleChanged(bool v)
{
    if (!v) {
        if (qobject_cast<QtMenuPopupWindow *>(m_popupWindow->transientParent())) {
            m_popupWindow->transientParent()->setMouseGrabEnabled(true);
            m_popupWindow->transientParent()->setKeyboardGrabEnabled(true);
        }
        m_popupWindow->deleteLater();
        m_popupWindow = 0;
        __closeMenu();
    }
}

void QtMenu::clear()
{
    foreach (QtMenuBase *item, m_menuItems) {
        if (m_platformMenu)
            m_platformMenu->removeMenuItem(item->platformItem());
        delete item;
    }
    m_menuItems.clear();
}

void QtMenu::addMenuItem(QtMenuBase *menuItem)
{
    menuItem->setParentMenu(this);
    m_menuItems.append(menuItem);
    if (QPlatformMenuItem *platformItem = menuItem->platformItem()) {
        if (m_platformMenu)
            m_platformMenu->insertMenuItem(platformItem, 0 /* append */);
    }
}

QtMenuItem *QtMenu::addItem(const QString &text)
{
    QtMenuItem *menuItem = new QtMenuItem(this);
    menuItem->setText(text);
    addMenuItem(menuItem);

    emit itemsChanged();
    return menuItem;
}

QString QtMenu::__modelTextAt(int index) const
{
    if (QAbstractItemModel *model = qobject_cast<QAbstractItemModel*>(m_model.value<QObject*>())) {
        return model->data(model->index(index, 0)).toString();
    } else if (m_model.canConvert(QVariant::StringList)) {
        return m_model.toStringList().at(index);
    }
    return "";
}

int QtMenu::__modelCount() const
{
    if (QAbstractItemModel *model = qobject_cast<QAbstractItemModel*>(m_model.value<QObject*>())) {
        return model->rowCount();
    } else if (m_model.canConvert(QVariant::StringList)) {
        return m_model.toStringList().count();
    }
    return -1;
}

void QtMenu::append_menuItems(QQmlListProperty<QtMenuBase> *list, QtMenuBase *menuItem)
{
    if (QtMenu *menu = qobject_cast<QtMenu *>(list->object))
        menu->addMenuItem(menuItem);
}

int QtMenu::count_menuItems(QQmlListProperty<QtMenuBase> *list)
{
    QtMenu *menu = qobject_cast<QtMenu *>(list->object);
    if (menu)
        return menu->m_menuItems.size();
    return 0;
}

QtMenuBase *QtMenu::at_menuItems(QQmlListProperty<QtMenuBase> *list, int index)
{
    QtMenu *menu = qobject_cast<QtMenu *>(list->object);
    if (menu && 0 <= index && index < menu->m_menuItems.size())
        return menu->m_menuItems[index];
    return 0;
}

void QtMenu::setModel(const QVariant &newModel) {
    if (m_model != newModel) {
        m_hasNativeModel = false;
        m_model = newModel;

        if (qobject_cast<QAbstractItemModel*>(newModel.value<QObject*>()))
            m_hasNativeModel = true;
        else if (newModel.canConvert(QVariant::StringList))
            m_hasNativeModel = true;

        emit modelChanged(m_model);
    }
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>#include <mlopen/convolution.hpp>
#include <mlopen/convolution_fft.hpp>
#include <mlopen/errors.hpp>

namespace mlopen {

	size_t ConvolutionDescriptor::ForwardGetWorkSpaceSizeFFT(
		const TensorDescriptor& wDesc,
		const TensorDescriptor& xDesc,
		const TensorDescriptor& yDesc) const
{

	int in_n, in_c, in_h, in_w;
	std::tie(in_n, in_c, in_h, in_w) = mlopen::tie4(xDesc.GetLengths());

	int out_n, out_c, out_h, out_w;
	std::tie(out_n, out_c, out_h, out_w) = mlopen::tie4(yDesc.GetLengths());

	int wei_k, wei_c, wei_h, wei_w;
	std::tie(wei_k, wei_c, wei_h, wei_w) = mlopen::tie4(wDesc.GetLengths());

	bool supported = true;

	// FFT convolutions only works for specific config(s)
	// coverage to expand gradually

	supported = ((in_n < 1) || (in_n > 512)) ? false : supported;
	supported = ((wei_k < 1) && (wei_k > 512)) ? false : supported;
	supported = (std::tie(in_c, in_h, in_w) != std::make_tuple(64, 27, 27)) ? false : supported;
	supported = (std::tie(wei_c, wei_h, wei_w) != std::make_tuple(64, 5, 5)) ? false : supported;
	supported = (std::tie(out_h, out_w) != std::make_tuple(27, 27)) ? false : supported;
	supported = (std::tie(pad_h, pad_w, u, v) != std::make_tuple(2, 2, 1, 1)) ? false : supported;
	supported = (yDesc.GetType() != mlopenFloat) ? false : supported;

	const int N = FFTConvParams::N;
	const int Padding = FFTConvParams::TransposePadding;

	if(supported)
	{
		int temp_size1 = (in_c*in_n + Padding) + (wei_k*wei_c + Padding);
		int temp_size2 = (out_n*out_c + Padding);
		int temp_size = temp_size1 > temp_size2 ? temp_size1 : temp_size2;

		return 2*2*N*temp_size*sizeof(float);
	}
	else
		return 0;
}

} // namespace mlopen
<commit_msg>fixing a bug in K comparison<commit_after>#include <mlopen/convolution.hpp>
#include <mlopen/convolution_fft.hpp>
#include <mlopen/errors.hpp>

namespace mlopen {

	size_t ConvolutionDescriptor::ForwardGetWorkSpaceSizeFFT(
		const TensorDescriptor& wDesc,
		const TensorDescriptor& xDesc,
		const TensorDescriptor& yDesc) const
{

	int in_n, in_c, in_h, in_w;
	std::tie(in_n, in_c, in_h, in_w) = mlopen::tie4(xDesc.GetLengths());

	int out_n, out_c, out_h, out_w;
	std::tie(out_n, out_c, out_h, out_w) = mlopen::tie4(yDesc.GetLengths());

	int wei_k, wei_c, wei_h, wei_w;
	std::tie(wei_k, wei_c, wei_h, wei_w) = mlopen::tie4(wDesc.GetLengths());

	bool supported = true;

	// FFT convolutions only works for specific config(s)
	// coverage to expand gradually

	supported = ((in_n < 1) || (in_n > 512)) ? false : supported;
	supported = ((wei_k < 1) || (wei_k > 512)) ? false : supported;
	supported = (std::tie(in_c, in_h, in_w) != std::make_tuple(64, 27, 27)) ? false : supported;
	supported = (std::tie(wei_c, wei_h, wei_w) != std::make_tuple(64, 5, 5)) ? false : supported;
	supported = (std::tie(out_h, out_w) != std::make_tuple(27, 27)) ? false : supported;
	supported = (std::tie(pad_h, pad_w, u, v) != std::make_tuple(2, 2, 1, 1)) ? false : supported;
	supported = (yDesc.GetType() != mlopenFloat) ? false : supported;

	const int N = FFTConvParams::N;
	const int Padding = FFTConvParams::TransposePadding;

	if(supported)
	{
		int temp_size1 = (in_c*in_n + Padding) + (wei_k*wei_c + Padding);
		int temp_size2 = (out_n*out_c + Padding);
		int temp_size = temp_size1 > temp_size2 ? temp_size1 : temp_size2;

		return 2*2*N*temp_size*sizeof(float);
	}
	else
		return 0;
}

} // namespace mlopen
<|endoftext|>


<commit_before>
/*
 * Copyright 2006 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkGraphics.h"

#include "Sk64.h"
#include "SkBlitter.h"
#include "SkCanvas.h"
#include "SkFloat.h"
#include "SkGeometry.h"
#include "SkGlobals.h"
#include "SkMath.h"
#include "SkMatrix.h"
#include "SkPath.h"
#include "SkPathEffect.h"
#include "SkRandom.h"
#include "SkRefCnt.h"
#include "SkScalerContext.h"
#include "SkShader.h"
#include "SkStream.h"
#include "SkTSearch.h"
#include "SkTime.h"
#include "SkUtils.h"
#include "SkXfermode.h"

void SkGraphics::GetVersion(int32_t* major, int32_t* minor, int32_t* patch) {
    if (major) {
        *major = SKIA_VERSION_MAJOR;
    }
    if (minor) {
        *minor = SKIA_VERSION_MINOR;
    }
    if (patch) {
        *patch = SKIA_VERSION_PATCH;
    }
}

#define typesizeline(type)  { #type , sizeof(type) }

#ifdef BUILD_EMBOSS_TABLE
    extern void SkEmbossMask_BuildTable();
#endif

#ifdef BUILD_RADIALGRADIENT_TABLE
    extern void SkRadialGradient_BuildTable();
#endif

void SkGraphics::Init() {
    SkGlobals::Init();

#ifdef BUILD_EMBOSS_TABLE
    SkEmbossMask_BuildTable();
#endif
#ifdef BUILD_RADIALGRADIENT_TABLE
    SkRadialGradient_BuildTable();
#endif

#ifdef SK_DEBUGx
    int i;

    static const struct {
        const char* fTypeName;
        size_t      fSizeOf;
    } gTypeSize[] = {
        typesizeline(char),
        typesizeline(short),
        typesizeline(int),
        typesizeline(long),
        typesizeline(size_t),
        typesizeline(void*),

        typesizeline(S8CPU),
        typesizeline(U8CPU),
        typesizeline(S16CPU),
        typesizeline(U16CPU),

        typesizeline(SkPoint),
        typesizeline(SkRect),
        typesizeline(SkMatrix),
        typesizeline(SkPath),
        typesizeline(SkGlyph),
        typesizeline(SkRefCnt),

        typesizeline(SkPaint),
        typesizeline(SkCanvas),
        typesizeline(SkBlitter),
        typesizeline(SkShader),
        typesizeline(SkXfermode),
        typesizeline(SkPathEffect)
    };

#ifdef SK_CPU_BENDIAN
    SkDebugf("SkGraphics: big-endian\n");
#else
    SkDebugf("SkGraphics: little-endian\n");
#endif

    {
        char    test = 0xFF;
        int     itest = test;   // promote to int, see if it sign-extended
        if (itest < 0)
            SkDebugf("SkGraphics: char is signed\n");
        else
            SkDebugf("SkGraphics: char is unsigned\n");
    }
    for (i = 0; i < (int)SK_ARRAY_COUNT(gTypeSize); i++) {
        SkDebugf("SkGraphics: sizeof(%s) = %d\n",
                 gTypeSize[i].fTypeName, gTypeSize[i].fSizeOf);
    }

#endif
}

///////////////////////////////////////////////////////////////////////////////

#include "SkGlyphCache.h"
#include "SkTypefaceCache.h"

void SkGraphics::Term() {
    SkGraphics::SetFontCacheUsed(0);
    SkTypefaceCache::PurgeAll();
    SkGlobals::Term();
}

size_t SkGraphics::GetFontCacheUsed() {
    return SkGlyphCache::GetCacheUsed();
}

bool SkGraphics::SetFontCacheUsed(size_t usageInBytes) {
    return SkGlyphCache::SetCacheUsed(usageInBytes);
}

#ifndef SK_DEFAULT_FONT_CACHE_LIMIT
    #define SK_DEFAULT_FONT_CACHE_LIMIT (1024 * 1024)
#endif

#define SK_MIN_FONT_CACHE_LIMIT    (256 * 1024)

static size_t gFontCacheLimit = SK_DEFAULT_FONT_CACHE_LIMIT;

size_t SkGraphics::GetFontCacheLimit() {
    return gFontCacheLimit;
}

size_t SkGraphics::SetFontCacheLimit(size_t bytes) {
    size_t prev = gFontCacheLimit;

    if (bytes < SK_MIN_FONT_CACHE_LIMIT) {
        bytes = SK_MIN_FONT_CACHE_LIMIT;
    }
    gFontCacheLimit = bytes;

    // trigger a purge if the new size is smaller that our currently used amount
    if (bytes < GetFontCacheUsed()) {
        SetFontCacheUsed(bytes);
    }
    return prev;
}

<commit_msg>up default limit to 2Mg<commit_after>
/*
 * Copyright 2006 The Android Open Source Project
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkGraphics.h"

#include "Sk64.h"
#include "SkBlitter.h"
#include "SkCanvas.h"
#include "SkFloat.h"
#include "SkGeometry.h"
#include "SkGlobals.h"
#include "SkMath.h"
#include "SkMatrix.h"
#include "SkPath.h"
#include "SkPathEffect.h"
#include "SkRandom.h"
#include "SkRefCnt.h"
#include "SkScalerContext.h"
#include "SkShader.h"
#include "SkStream.h"
#include "SkTSearch.h"
#include "SkTime.h"
#include "SkUtils.h"
#include "SkXfermode.h"

void SkGraphics::GetVersion(int32_t* major, int32_t* minor, int32_t* patch) {
    if (major) {
        *major = SKIA_VERSION_MAJOR;
    }
    if (minor) {
        *minor = SKIA_VERSION_MINOR;
    }
    if (patch) {
        *patch = SKIA_VERSION_PATCH;
    }
}

#define typesizeline(type)  { #type , sizeof(type) }

#ifdef BUILD_EMBOSS_TABLE
    extern void SkEmbossMask_BuildTable();
#endif

#ifdef BUILD_RADIALGRADIENT_TABLE
    extern void SkRadialGradient_BuildTable();
#endif

void SkGraphics::Init() {
    SkGlobals::Init();

#ifdef BUILD_EMBOSS_TABLE
    SkEmbossMask_BuildTable();
#endif
#ifdef BUILD_RADIALGRADIENT_TABLE
    SkRadialGradient_BuildTable();
#endif

#ifdef SK_DEBUGx
    int i;

    static const struct {
        const char* fTypeName;
        size_t      fSizeOf;
    } gTypeSize[] = {
        typesizeline(char),
        typesizeline(short),
        typesizeline(int),
        typesizeline(long),
        typesizeline(size_t),
        typesizeline(void*),

        typesizeline(S8CPU),
        typesizeline(U8CPU),
        typesizeline(S16CPU),
        typesizeline(U16CPU),

        typesizeline(SkPoint),
        typesizeline(SkRect),
        typesizeline(SkMatrix),
        typesizeline(SkPath),
        typesizeline(SkGlyph),
        typesizeline(SkRefCnt),

        typesizeline(SkPaint),
        typesizeline(SkCanvas),
        typesizeline(SkBlitter),
        typesizeline(SkShader),
        typesizeline(SkXfermode),
        typesizeline(SkPathEffect)
    };

#ifdef SK_CPU_BENDIAN
    SkDebugf("SkGraphics: big-endian\n");
#else
    SkDebugf("SkGraphics: little-endian\n");
#endif

    {
        char    test = 0xFF;
        int     itest = test;   // promote to int, see if it sign-extended
        if (itest < 0)
            SkDebugf("SkGraphics: char is signed\n");
        else
            SkDebugf("SkGraphics: char is unsigned\n");
    }
    for (i = 0; i < (int)SK_ARRAY_COUNT(gTypeSize); i++) {
        SkDebugf("SkGraphics: sizeof(%s) = %d\n",
                 gTypeSize[i].fTypeName, gTypeSize[i].fSizeOf);
    }

#endif
}

///////////////////////////////////////////////////////////////////////////////

#include "SkGlyphCache.h"
#include "SkTypefaceCache.h"

void SkGraphics::Term() {
    SkGraphics::SetFontCacheUsed(0);
    SkTypefaceCache::PurgeAll();
    SkGlobals::Term();
}

size_t SkGraphics::GetFontCacheUsed() {
    return SkGlyphCache::GetCacheUsed();
}

bool SkGraphics::SetFontCacheUsed(size_t usageInBytes) {
    return SkGlyphCache::SetCacheUsed(usageInBytes);
}

#ifndef SK_DEFAULT_FONT_CACHE_LIMIT
    #define SK_DEFAULT_FONT_CACHE_LIMIT (2 * 1024 * 1024)
#endif

#define SK_MIN_FONT_CACHE_LIMIT    (256 * 1024)

static size_t gFontCacheLimit = SK_DEFAULT_FONT_CACHE_LIMIT;

size_t SkGraphics::GetFontCacheLimit() {
    return gFontCacheLimit;
}

size_t SkGraphics::SetFontCacheLimit(size_t bytes) {
    size_t prev = gFontCacheLimit;

    if (bytes < SK_MIN_FONT_CACHE_LIMIT) {
        bytes = SK_MIN_FONT_CACHE_LIMIT;
    }
    gFontCacheLimit = bytes;

    // trigger a purge if the new size is smaller that our currently used amount
    if (bytes < GetFontCacheUsed()) {
        SetFontCacheUsed(bytes);
    }
    return prev;
}

<|endoftext|>


<commit_before>#include "include/calculator.h"
#include <assert.h>

#define GET_POINT(n, on_y_axis) ((on_y_axis) ? get_point(n) : get_point(0, n))

Calculator::Calculator(MoveListener *lis) : Constructor(lis) {}

Calculator::~Calculator() {}

const Point *Calculator::get_point(constr_num x, constr_num y)
{
    Point *p = new Point(x, y);

    if (add_point(p)) // doesn't add to cli
        return p;
    delete p;
    return nullptr;
}

const Point *Calculator::get_add(constr_num a, constr_num b, bool on_y_axis)
{
    const Point *pa = GET_POINT(a, on_y_axis),
                *pb = GET_POINT(b, on_y_axis),
                *p  = GET_POINT(a + b, on_y_axis);

    if (pa == nullptr || pb == nullptr)
        return nullptr;
    if (p != nullptr)
        return p;

    auto *l = join_segment(*origin, *pb);
    if (l == nullptr) // b = 0
        return pa;

    l = translate(*l, *pa);
    assert(l != nullptr); // translate only returns null for arguments not contained

    return &l->end;
}

const Point *Calculator::get_sub(constr_num a, constr_num b, bool on_y_axis)
{
    const Point *pa = GET_POINT(a, on_y_axis),
                *pb = GET_POINT(b, on_y_axis),
                *p  = GET_POINT(a - b, on_y_axis);

    if (pa == nullptr || pb == nullptr)
        return nullptr;
    if (p != nullptr)
        return p;

    auto *l = join_segment(*pb, *origin);
    if (l == nullptr) // b = 0
        return pa;

    l = translate(*l, *pa);
    assert(l != nullptr); // translate only returns null for arguments not contained

    return &l->end;
}

const Point *Calculator::get_mul(constr_num a, constr_num b, bool on_y_axis)
{
    const Point *pa = GET_POINT(a, on_y_axis),
                *pb = GET_POINT(b, !on_y_axis),
                *p  = GET_POINT(a * b, on_y_axis);

    if (pa == nullptr || pb == nullptr)
        return nullptr;
    if (p != nullptr)
        return p;

    auto *l = join_line(*pa, on_y_axis ? *unit_x : *unit_y);
    assert(l != nullptr);

    return meet(*parallel(*l, *pb), on_y_axis ? *y_axis : *x_axis); // both l and pb are contained
}

const Point *Calculator::get_div(constr_num a, constr_num b, bool on_y_axis)
{
    if (b == 0)
        return nullptr;

    const Point *pa = GET_POINT(a, on_y_axis),
                *pb = GET_POINT(b, !on_y_axis),
                *p  = GET_POINT(a / b, on_y_axis);

    if (pa == nullptr || pb == nullptr)
        return nullptr;
    if (p != nullptr)
        return p;

    auto *l = join_line(*pa, *pb);
    assert(l != nullptr); // true only if a = b = 0

    return meet(*parallel(*l, on_y_axis ? *unit_x : *unit_y), on_y_axis ? *y_axis : *x_axis); // both l and unit_y are contained
}

const Point *Calculator::get_sqrt(constr_num a, bool on_y_axis)
{
    const Point *pa =  GET_POINT(a, on_y_axis),
                *neg = GET_POINT(-1, on_y_axis),
                *p   = GET_POINT(sqrt(a), on_y_axis);

    if (pa == nullptr || a < 0)
        return nullptr;
    if (a == 0)
        return origin;
    if (p != nullptr)
        return p;

    auto *center = midpoint(*neg, *pa);
    assert(center != nullptr); // both neg and pa are contained

    auto meets = meet(on_y_axis ? *x_axis : *y_axis, *join_circle(*center, *pa)); // circle will always exist, as center != pa

    return (on_y_axis ? meets.first->x : meets.first->y) < 0 ? meets.second : meets.first; // (0, √a)
}

// TODO check for subtraction and division for binary operations
const Point *Calculator::construct_number(constr_num n, bool on_y_axis)
{
    switch (n.expr->type) {
    case 0:
        return GET_POINT(n, on_y_axis);
    case 1:
        construct_number(n.expr->expr_union.unary.arg);
        switch (n.expr->expr_union.unary.op) {
        case 1:
            return get_sub(0, n.expr->expr_union.unary.arg, on_y_axis);
        case 2:
            return get_div(1, n.expr->expr_union.unary.arg, on_y_axis);
        default:
            return get_sqrt(n.expr->expr_union.unary.arg, on_y_axis);
        }
    default:
        construct_number(n.expr->expr_union.binary.arg1);
        construct_number(n.expr->expr_union.binary.arg2);
        switch (n.expr->expr_union.binary.op) {
        case 1:
            return get_add(n.expr->expr_union.binary.arg1,
                           n.expr->expr_union.binary.arg2, on_y_axis);
        default:
            return get_mul(n.expr->expr_union.binary.arg1,
                           n.expr->expr_union.binary.arg2, on_y_axis);
        }
    }
}

const Point *Calculator::construct_point(const Point &p)
{
    const Point *px = construct_number(p.x),
                *py = construct_number(p.y, true);

    if (px == nullptr || py == nullptr)
        return nullptr;

    return meet(*parallel(*x_axis, *py),
                *parallel(*y_axis, *px));
}
<commit_msg>Fixed construction of square roots<commit_after>#include "include/calculator.h"
#include <assert.h>

#define GET_POINT(n, on_y_axis) ((on_y_axis) ? get_point(n) : get_point(0, n))

Calculator::Calculator(MoveListener *lis) : Constructor(lis) {}

Calculator::~Calculator() {}

const Point *Calculator::get_point(constr_num x, constr_num y)
{
    Point *p = new Point(x, y);

    if (add_point(p)) // doesn't add to cli
        return p;
    delete p;
    return nullptr;
}

const Point *Calculator::get_add(constr_num a, constr_num b, bool on_y_axis)
{
    const Point *pa = GET_POINT(a, on_y_axis),
                *pb = GET_POINT(b, on_y_axis),
                *p  = GET_POINT(a + b, on_y_axis);

    if (pa == nullptr || pb == nullptr)
        return nullptr;
    if (p != nullptr)
        return p;

    auto *l = join_segment(*origin, *pb);
    if (l == nullptr) // b = 0
        return pa;

    l = translate(*l, *pa);
    assert(l != nullptr); // translate only returns null for arguments not contained

    return &l->end;
}

const Point *Calculator::get_sub(constr_num a, constr_num b, bool on_y_axis)
{
    const Point *pa = GET_POINT(a, on_y_axis),
                *pb = GET_POINT(b, on_y_axis),
                *p  = GET_POINT(a - b, on_y_axis);

    if (pa == nullptr || pb == nullptr)
        return nullptr;
    if (p != nullptr)
        return p;

    auto *l = join_segment(*pb, *origin);
    if (l == nullptr) // b = 0
        return pa;

    l = translate(*l, *pa);
    assert(l != nullptr); // translate only returns null for arguments not contained

    return &l->end;
}

const Point *Calculator::get_mul(constr_num a, constr_num b, bool on_y_axis)
{
    const Point *pa = GET_POINT(a, on_y_axis),
                *pb = GET_POINT(b, !on_y_axis),
                *p  = GET_POINT(a * b, on_y_axis);

    if (pa == nullptr || pb == nullptr)
        return nullptr;
    if (p != nullptr)
        return p;

    auto *l = join_line(*pa, on_y_axis ? *unit_x : *unit_y);
    assert(l != nullptr);

    return meet(*parallel(*l, *pb), on_y_axis ? *y_axis : *x_axis); // both l and pb are contained
}

const Point *Calculator::get_div(constr_num a, constr_num b, bool on_y_axis)
{
    if (b == 0)
        return nullptr;

    const Point *pa = GET_POINT(a, on_y_axis),
                *pb = GET_POINT(b, !on_y_axis),
                *p  = GET_POINT(a / b, on_y_axis);

    if (pa == nullptr || pb == nullptr)
        return nullptr;
    if (p != nullptr)
        return p;

    auto *l = join_line(*pa, *pb);
    assert(l != nullptr); // true only if a = b = 0

    return meet(*parallel(*l, on_y_axis ? *unit_x : *unit_y), on_y_axis ? *y_axis : *x_axis); // both l and unit_y are contained
}

const Point *Calculator::get_sqrt(constr_num a, bool on_y_axis)
{
    const Point *pa =  GET_POINT(a, on_y_axis),
                *neg = GET_POINT(-1, on_y_axis),
                *p   = GET_POINT(sqrt(a), on_y_axis);

    if (pa == nullptr || a < 0)
        return nullptr;
    if (a == 0)
        return origin;
    if (p != nullptr)
        return p;

    auto *center = midpoint(*neg, *pa);
    assert(center != nullptr); // both neg and pa are contained

    auto meets = meet(on_y_axis ? *y_axis : *x_axis, *join_circle(*center, *pa)); // circle will always exist, as center != pa

    return (on_y_axis ? meets.first->x : meets.first->y) < 0 ? meets.second : meets.first; // (0, √a)
}

// TODO check for subtraction and division for binary operations
const Point *Calculator::construct_number(constr_num n, bool on_y_axis)
{
    switch (n.expr->type) {
    case 0:
        return GET_POINT(n, on_y_axis);
    case 1:
        construct_number(n.expr->expr_union.unary.arg);
        switch (n.expr->expr_union.unary.op) {
        case 1:
            return get_sub(0, n.expr->expr_union.unary.arg, on_y_axis);
        case 2:
            return get_div(1, n.expr->expr_union.unary.arg, on_y_axis);
        default:
            return get_sqrt(n.expr->expr_union.unary.arg, on_y_axis);
        }
    default:
        construct_number(n.expr->expr_union.binary.arg1);
        construct_number(n.expr->expr_union.binary.arg2);
        switch (n.expr->expr_union.binary.op) {
        case 1:
            return get_add(n.expr->expr_union.binary.arg1,
                           n.expr->expr_union.binary.arg2, on_y_axis);
        default:
            return get_mul(n.expr->expr_union.binary.arg1,
                           n.expr->expr_union.binary.arg2, on_y_axis);
        }
    }
}

const Point *Calculator::construct_point(const Point &p)
{
    const Point *px = construct_number(p.x),
                *py = construct_number(p.y, true);

    if (px == nullptr || py == nullptr)
        return nullptr;

    return meet(*parallel(*x_axis, *py),
                *parallel(*y_axis, *px));
}
<|endoftext|>


<commit_before>/*
 * This file is part of `et engine`
 * Copyright 2009-2013 by Sergey Reznik
 * Please, do not modify content without approval.
 *
 */

#include <et/core/et.h>
#include <et/core/dictionary.h>

using namespace et;

void printDictionary(Dictionary dict, const std::string& tabs);
void printArray(ArrayValue arr, const std::string& tabs);

void Dictionary::printContent() const
{
	log::info("<");
	printDictionary(*this, "\t");
	log::info(">");
}

void ArrayValue::printContent() const
{
	log::info("{");
	printArray(*this, "\t");
	log::info("}");
}

ValueBase::Pointer Dictionary::baseValueForKeyPathInHolder(const std::vector<std::string>& path,
	ValueBase::Pointer holder) const
{
	if (holder->valueClass() == ValueClass_Dictionary)
	{
		Dictionary dictionary(holder);
		auto value = dictionary->content.find(path.front());

		if (value == dictionary->content.end())
			return ValueBase::Pointer();

		return (path.size() == 1) ? value->second : baseValueForKeyPathInHolder(
			std::vector<std::string>(path.begin() + 1, path.end()), value->second);
	}
	else if (holder->valueClass() == ValueClass_Array)
	{
		size_t index = strToInt(path.front());
		ArrayValue array(holder);

		if (index >= array->content.size())
			return ValueBase::Pointer();

		ValueBase::Pointer value = array->content.at(index);

		return (path.size() == 1) ? value : baseValueForKeyPathInHolder(
			std::vector<std::string>(path.begin() + 1, path.end()), value);
	}
	else if (holder->valueClass() == ValueClass_String)
	{
		StringValue string(holder);
		log::warning("Trying to extract subvalue `%s` from string `%s`", path.front().c_str(),
			string->content.c_str());
	}
	else if (holder->valueClass() == ValueClass_Integer)
	{
		IntegerValue number(holder);
		log::warning("Trying to extract subvalue `%s` from number %d.", path.front().c_str(),
			number->content);
	}
	else
	{
		assert(false);
	}

	return ValueBase::Pointer();
}

ValueBase::Pointer Dictionary::baseValueForKeyPath(const std::vector<std::string>& path) const
{
	assert(path.size() > 0);
	return baseValueForKeyPathInHolder(path, *this);
}

bool Dictionary::valueForKeyPathIsClassOf(const std::vector<std::string>& key, ValueClass c) const
{
	auto v = baseValueForKeyPath(key);
	return v.valid() && (v->valueClass() == c);
}

bool Dictionary::hasKey(const std::string& key) const
{
	return reference().content.count(key) > 0;
}

ValueClass Dictionary::valueClassForKey(const std::string& key) const
{
	return hasKey(key) ? baseValueForKeyPath(StringList(1, key))->valueClass() : ValueClass_Invalid;
}

StringList Dictionary::allKeyPaths()
{
	StringList result;
	addKeyPathsFromHolder(*this, std::string(), result);
	return result;
}

void Dictionary::addKeyPathsFromHolder(ValueBase::Pointer holder, const std::string& baseKeyPath, StringList& keyPaths) const
{
	std::string nextKeyPath = baseKeyPath.empty() ? std::string() : (baseKeyPath + "/");
	if (holder->valueClass() == ValueClass_Dictionary)
	{
		Dictionary d(holder);
		for (auto& v : d->content)
		{
			std::string keyPath = nextKeyPath + v.first;
			keyPaths.push_back(keyPath);
			addKeyPathsFromHolder(v.second, keyPath, keyPaths);
		}
	}
	else if (holder->valueClass() == ValueClass_Array)
	{
		size_t index = 0;
		ArrayValue a(holder);
		for (auto& v : a->content)
		{
			std::string keyPath = nextKeyPath + intToStr(index++);
			keyPaths.push_back(keyPath);
			addKeyPathsFromHolder(v, keyPath, keyPaths);
		}
	}
}

/*
 * Service functions
 */
void printArray(ArrayValue arr, const std::string& tabs)
{
	for (auto i : arr->content)
	{
		if (i->valueClass() == ValueClass_Integer)
		{
			IntegerValue val = i;
			log::info("%s%d", tabs.c_str(), val->content);
		}
		if (i->valueClass() == ValueClass_Float)
		{
			FloatValue val = i;
			log::info("%s%f", tabs.c_str(), val->content);
		}
		else if (i->valueClass() == ValueClass_String)
		{
			StringValue val = i;
			log::info("%s%s", tabs.c_str(), val->content.c_str());
		}
		else if (i->valueClass() == ValueClass_Array)
		{
			log::info("%s{", tabs.c_str());
			printArray(i, tabs + "\t");
			log::info("%s}", tabs.c_str());
		}
		else if (i->valueClass() == ValueClass_Dictionary)
		{
			Dictionary val = i;
			log::info("%s<", tabs.c_str());
			printDictionary(val, tabs + "\t");
			log::info("%s>", tabs.c_str());
		}
	}
}

void printDictionary(Dictionary dict, const std::string& tabs)
{
	for (auto i : dict->content)
	{
		if (i.second->valueClass() == ValueClass_Integer)
		{
			IntegerValue val = i.second;
			log::info("%s%s = %d", tabs.c_str(), i.first.c_str(), val->content);
		}
		else if (i.second->valueClass() == ValueClass_Float)
		{
			FloatValue val = i.second;
			log::info("%s%s = %f", tabs.c_str(), i.first.c_str(), val->content);
		}
		else if (i.second->valueClass() == ValueClass_String)
		{
			StringValue val = i.second;
			log::info("%s%s = %s", tabs.c_str(), i.first.c_str(), val->content.c_str());
		}
		else if (i.second->valueClass() == ValueClass_Array)
		{
			ArrayValue val = i.second;
			log::info("%s%s =\n%s{", tabs.c_str(), i.first.c_str(), tabs.c_str());
			printArray(val, tabs + "\t");
			log::info("%s}", tabs.c_str());
		}
		else if (i.second->valueClass() == ValueClass_Dictionary)
		{
			Dictionary val = i.second;
			log::info("%s%s =\n%s<", tabs.c_str(), i.first.c_str(), tabs.c_str());
			printDictionary(val, tabs + "\t");
			log::info("%s>", tabs.c_str());
		}
	}
}
<commit_msg>dictionary printContent method now outputs strings in quotes<commit_after>/*
 * This file is part of `et engine`
 * Copyright 2009-2013 by Sergey Reznik
 * Please, do not modify content without approval.
 *
 */

#include <et/core/et.h>
#include <et/core/dictionary.h>

using namespace et;

void printDictionary(Dictionary dict, const std::string& tabs);
void printArray(ArrayValue arr, const std::string& tabs);

void Dictionary::printContent() const
{
	log::info("<");
	printDictionary(*this, "\t");
	log::info(">");
}

void ArrayValue::printContent() const
{
	log::info("{");
	printArray(*this, "\t");
	log::info("}");
}

ValueBase::Pointer Dictionary::baseValueForKeyPathInHolder(const std::vector<std::string>& path,
	ValueBase::Pointer holder) const
{
	if (holder->valueClass() == ValueClass_Dictionary)
	{
		Dictionary dictionary(holder);
		auto value = dictionary->content.find(path.front());

		if (value == dictionary->content.end())
			return ValueBase::Pointer();

		return (path.size() == 1) ? value->second : baseValueForKeyPathInHolder(
			std::vector<std::string>(path.begin() + 1, path.end()), value->second);
	}
	else if (holder->valueClass() == ValueClass_Array)
	{
		size_t index = strToInt(path.front());
		ArrayValue array(holder);

		if (index >= array->content.size())
			return ValueBase::Pointer();

		ValueBase::Pointer value = array->content.at(index);

		return (path.size() == 1) ? value : baseValueForKeyPathInHolder(
			std::vector<std::string>(path.begin() + 1, path.end()), value);
	}
	else if (holder->valueClass() == ValueClass_String)
	{
		StringValue string(holder);
		log::warning("Trying to extract subvalue `%s` from string `%s`", path.front().c_str(),
			string->content.c_str());
	}
	else if (holder->valueClass() == ValueClass_Integer)
	{
		IntegerValue number(holder);
		log::warning("Trying to extract subvalue `%s` from number %d.", path.front().c_str(),
			number->content);
	}
	else
	{
		assert(false);
	}

	return ValueBase::Pointer();
}

ValueBase::Pointer Dictionary::baseValueForKeyPath(const std::vector<std::string>& path) const
{
	assert(path.size() > 0);
	return baseValueForKeyPathInHolder(path, *this);
}

bool Dictionary::valueForKeyPathIsClassOf(const std::vector<std::string>& key, ValueClass c) const
{
	auto v = baseValueForKeyPath(key);
	return v.valid() && (v->valueClass() == c);
}

bool Dictionary::hasKey(const std::string& key) const
{
	return reference().content.count(key) > 0;
}

ValueClass Dictionary::valueClassForKey(const std::string& key) const
{
	return hasKey(key) ? baseValueForKeyPath(StringList(1, key))->valueClass() : ValueClass_Invalid;
}

StringList Dictionary::allKeyPaths()
{
	StringList result;
	addKeyPathsFromHolder(*this, std::string(), result);
	return result;
}

void Dictionary::addKeyPathsFromHolder(ValueBase::Pointer holder, const std::string& baseKeyPath, StringList& keyPaths) const
{
	std::string nextKeyPath = baseKeyPath.empty() ? std::string() : (baseKeyPath + "/");
	if (holder->valueClass() == ValueClass_Dictionary)
	{
		Dictionary d(holder);
		for (auto& v : d->content)
		{
			std::string keyPath = nextKeyPath + v.first;
			keyPaths.push_back(keyPath);
			addKeyPathsFromHolder(v.second, keyPath, keyPaths);
		}
	}
	else if (holder->valueClass() == ValueClass_Array)
	{
		size_t index = 0;
		ArrayValue a(holder);
		for (auto& v : a->content)
		{
			std::string keyPath = nextKeyPath + intToStr(index++);
			keyPaths.push_back(keyPath);
			addKeyPathsFromHolder(v, keyPath, keyPaths);
		}
	}
}

/*
 * Service functions
 */
void printArray(ArrayValue arr, const std::string& tabs)
{
	for (auto i : arr->content)
	{
		if (i->valueClass() == ValueClass_Integer)
		{
			IntegerValue val = i;
			log::info("%s%d", tabs.c_str(), val->content);
		}
		if (i->valueClass() == ValueClass_Float)
		{
			FloatValue val = i;
			log::info("%s%f", tabs.c_str(), val->content);
		}
		else if (i->valueClass() == ValueClass_String)
		{
			StringValue val = i;
			log::info("%s\"%s\"", tabs.c_str(), val->content.c_str());
		}
		else if (i->valueClass() == ValueClass_Array)
		{
			log::info("%s{", tabs.c_str());
			printArray(i, tabs + "\t");
			log::info("%s}", tabs.c_str());
		}
		else if (i->valueClass() == ValueClass_Dictionary)
		{
			Dictionary val = i;
			log::info("%s<", tabs.c_str());
			printDictionary(val, tabs + "\t");
			log::info("%s>", tabs.c_str());
		}
	}
}

void printDictionary(Dictionary dict, const std::string& tabs)
{
	for (auto i : dict->content)
	{
		if (i.second->valueClass() == ValueClass_Integer)
		{
			IntegerValue val = i.second;
			log::info("%s%s = %d", tabs.c_str(), i.first.c_str(), val->content);
		}
		else if (i.second->valueClass() == ValueClass_Float)
		{
			FloatValue val = i.second;
			log::info("%s%s = %f", tabs.c_str(), i.first.c_str(), val->content);
		}
		else if (i.second->valueClass() == ValueClass_String)
		{
			StringValue val = i.second;
			log::info("%s%s = \"%s\"", tabs.c_str(), i.first.c_str(), val->content.c_str());
		}
		else if (i.second->valueClass() == ValueClass_Array)
		{
			ArrayValue val = i.second;
			log::info("%s%s =\n%s{", tabs.c_str(), i.first.c_str(), tabs.c_str());
			printArray(val, tabs + "\t");
			log::info("%s}", tabs.c_str());
		}
		else if (i.second->valueClass() == ValueClass_Dictionary)
		{
			Dictionary val = i.second;
			log::info("%s%s =\n%s<", tabs.c_str(), i.first.c_str(), tabs.c_str());
			printDictionary(val, tabs + "\t");
			log::info("%s>", tabs.c_str());
		}
	}
}
<|endoftext|>


<commit_before>#include <sys/systm.h>

#include "remap.hpp"
#include "RemapUtil.hpp"
#include "Config.hpp"
#include "keycode.hpp"
#include "util/PointingButtonStatus.hpp"

namespace org_pqrs_KeyRemap4MacBook {
  namespace GeneratedCode {
#include "config/output/include.remapcode_func.cpp"
  }

  // ----------------------------------------
  static bool
  remap_enter2commandL_enter2controlL_vm(const RemapParams &remapParams)
  {
    if (! config.remap_enter2commandL_enter2controlL_vm) return false;

    if (remapParams.workspacedata.type == KeyRemap4MacBook_bridge::GetWorkspaceData::VIRTUALMACHINE) {
      static RemapUtil::KeyToKey keytokey;
      return keytokey.remap(remapParams, KeyCode::ENTER, KeyCode::CONTROL_L);
    } else {
      static RemapUtil::KeyToKey keytokey;
      return keytokey.remap(remapParams, KeyCode::ENTER, KeyCode::COMMAND_L);
    }
  }

  // ----------------------------------------
  static bool
  remap_f6_to_numlock(const RemapParams &remapParams)
  {
    if (! config.remap_f6_to_numlock) return false;

    if (! RemapUtil::isKey(remapParams, KeyCode::F6)) return false;

    if (RemapUtil::isKeyDown(remapParams, KeyCode::F6)) {
      static bool flag = true;
      if (flag) {
        FlagStatus::lock_increase(ModifierFlag::FN);
      } else {
        FlagStatus::lock_decrease(ModifierFlag::FN);
      }
      flag = ! flag;
    }

    RemapUtil::drop(remapParams);
    return true;
  }

  // ----------------------------------------
  static bool
  remap_tab2option_withControlL(const RemapParams &remapParams)
  {
    if (! config.remap_tab2option_withControlL) return false;

    if (! FlagStatus::isHeldDown(ModifierFlag::CONTROL_L)) return false;

    static KeyOverlaidModifier kom;
    return kom.remap(remapParams, KeyCode::TAB, KeyCode::OPTION_L, KeyCode::TAB);
  }

  // ----------------------------------------
  static bool
  remap_keypadnumlock_togglekey_clear(const RemapParams &remapParams)
  {
    if (! config.option_keypadnumlock_togglekey_clear) return false;

    if (! RemapUtil::isKey(remapParams, KeyCode::KEYPAD_CLEAR)) return false;

    if (RemapUtil::isKeyDown(remapParams, KeyCode::KEYPAD_CLEAR)) {
      config.remap_keypadnumlock = ! config.remap_keypadnumlock;
    }
    RemapUtil::drop(remapParams);
    return true;
  }

  // ----------------------------------------
  static bool
  remap_jis_eisuu2commandL_eisuu_eisuu2optionL_term(const RemapParams &remapParams)
  {
    if (! config.remap_jis_eisuu2commandL_eisuu_eisuu2optionL_term) return false;

    if (remapParams.workspacedata.type == KeyRemap4MacBook_bridge::GetWorkspaceData::TERMINAL) {
      static KeyOverlaidModifier kom;
      return kom.remap(remapParams, KeyCode::JIS_EISUU, KeyCode::OPTION_L, KeyCode::JIS_EISUU);
    } else {
      static KeyOverlaidModifier kom;
      return kom.remap(remapParams, KeyCode::JIS_EISUU, KeyCode::COMMAND_L, KeyCode::JIS_EISUU);
    }
  }

  // ----------------------------------------
  static bool
  remap_jis_underscore2backslash(const RemapParams &remapParams)
  {
    if (! config.remap_jis_underscore2backslash) return false;

    static RemapUtil::KeyToKey keytokey;
    if (! keytokey.remap(remapParams, KeyCode::JIS_UNDERSCORE, ModifierFlag::NONE, KeyCode::BACKSLASH)) {
      return false;
    }
    remapParams.params.keyboardType = KeyboardType::MACBOOK;
    return true;
  }

  // ----------------------------------------
  static bool
  remap_jis_yen2backslash(const RemapParams &remapParams)
  {
    if (! config.remap_jis_yen2backslash) return false;

    static RemapUtil::KeyToKey keytokey;
    if (! keytokey.remap(remapParams, KeyCode::JIS_YEN, KeyCode::BACKSLASH)) {
      return false;
    }
    remapParams.params.keyboardType = KeyboardType::MACBOOK;
    return true;
  }

  // ----------------------------------------
  static bool
  remap_jis_app_vi_eisuu2eisuu_escape(const RemapParams &remapParams)
  {
    if (! config.remap_jis_app_vi_eisuu2eisuu_escape) return false;

    if (remapParams.workspacedata.type != KeyRemap4MacBook_bridge::GetWorkspaceData::VI) return false;

    if (! RemapUtil::isKeyDown(remapParams, KeyCode::JIS_EISUU)) return false;

    RemapUtil::fireKey(remapParams.params, remapParams.workspacedata);
    RemapUtil::fireKey_downup(remapParams.params.flags, KeyCode::ESCAPE, remapParams.params, remapParams.workspacedata);
    remapParams.isremapped = true;
    return true;
  }

  static bool
  remap_jis_jansi(const RemapParams &remapParams)
  {
    if (! config.remap_jis_jansi) return false;

    remapParams.params.keyboardType = KeyboardType::MACBOOK;

    {
      static RemapUtil::KeyToKey keytokey;
      if (keytokey.remap(remapParams, KeyCode::JIS_YEN, KeyCode::BACKQUOTE)) return true;
    }
    {
      static RemapUtil::KeyToKey keytokey;
      if (keytokey.remap(remapParams, KeyCode::JIS_UNDERSCORE, KeyCode::BACKQUOTE)) return true;
    }

    // Note: remap_jis_jansi return false if changed keyboardType only.
    return false;
  }

  static bool
  remap_pointing_relative_to_scroll(const RemapPointingParams_relative &remapParams)
  {
    if (! config.remap_pointing_relative_to_scroll) return false;

    RemapUtil::pointingRelativeToScroll(remapParams);
    return true;
  }
}

// ----------------------------------------------------------------------
void
org_pqrs_KeyRemap4MacBook::remap_core(const RemapParams &remapParams)
{
  FlagStatus::set(remapParams);

  // ======================================================================
  // normal remapping
#include "config/output/include.remapcode_call.cpp"

  remap_enter2commandL_enter2controlL_vm(remapParams);

  remap_f6_to_numlock(remapParams);

  remap_tab2option_withControlL(remapParams);

  // ----------------------------------------
  remap_keypadnumlock_togglekey_clear(remapParams);

  // ------------------------------------------------------------
  // jis
  remap_jis_underscore2backslash(remapParams);
  remap_jis_yen2backslash(remapParams);

  remap_jis_app_vi_eisuu2eisuu_escape(remapParams);

  remap_jis_jansi(remapParams);

  // ------------------------------------------------------------
  // *** Note: we need to call remap_space2shift, remap_enter2optionL_commandSpace (has SandS like behavior) as possible late. ***
  // *** If any key2modifier or modifier2key remappings are enabled, miss-cancelling are occured. ***
#include "config/output/include.remapcode_call_kom.cpp"
  remap_jis_eisuu2commandL_eisuu_eisuu2optionL_term(remapParams);

  // ------------------------------------------------------------
#include "config/output/include.remapcode_call_mhkk.cpp"

  // ------------------------------------------------------------
  remapParams.params.flags = FlagStatus::makeFlags(remapParams);
}

void
org_pqrs_KeyRemap4MacBook::remap_consumer(const RemapConsumerParams &remapParams)
{
  FlagStatus::set();

#include "config/output/include.remapcode_call_consumer.cpp"

  remapParams.params.flags = FlagStatus::makeFlags(KeyCode::VK_NONE);
}

void
org_pqrs_KeyRemap4MacBook::remap_pointing_relative_core(const RemapPointingParams_relative &remapParams)
{
  FlagStatus::set();

  remapParams.params.buttons |= PointingButtonStatus::get();

#include "config/output/include.remapcode_call_pointing_relative.cpp"
  remap_pointing_relative_to_scroll(remapParams);
}
<commit_msg>update remap.cpp @ kext<commit_after>#include <sys/systm.h>

#include "remap.hpp"
#include "RemapUtil.hpp"
#include "Config.hpp"
#include "keycode.hpp"

namespace org_pqrs_KeyRemap4MacBook {
  namespace GeneratedCode {
#include "config/output/include.remapcode_func.cpp"
  }

  // ----------------------------------------
  static bool
  remap_enter2commandL_enter2controlL_vm(const RemapParams &remapParams)
  {
    if (! config.remap_enter2commandL_enter2controlL_vm) return false;

    if (remapParams.workspacedata.type == KeyRemap4MacBook_bridge::GetWorkspaceData::VIRTUALMACHINE) {
      static RemapUtil::KeyToKey keytokey;
      return keytokey.remap(remapParams, KeyCode::ENTER, KeyCode::CONTROL_L);
    } else {
      static RemapUtil::KeyToKey keytokey;
      return keytokey.remap(remapParams, KeyCode::ENTER, KeyCode::COMMAND_L);
    }
  }

  // ----------------------------------------
  static bool
  remap_f6_to_numlock(const RemapParams &remapParams)
  {
    if (! config.remap_f6_to_numlock) return false;

    if (! RemapUtil::isKey(remapParams, KeyCode::F6)) return false;

    if (RemapUtil::isKeyDown(remapParams, KeyCode::F6)) {
      static bool flag = true;
      if (flag) {
        FlagStatus::lock_increase(ModifierFlag::FN);
      } else {
        FlagStatus::lock_decrease(ModifierFlag::FN);
      }
      flag = ! flag;
    }

    RemapUtil::drop(remapParams);
    return true;
  }

  // ----------------------------------------
  static bool
  remap_tab2option_withControlL(const RemapParams &remapParams)
  {
    if (! config.remap_tab2option_withControlL) return false;

    if (! FlagStatus::isHeldDown(ModifierFlag::CONTROL_L)) return false;

    static KeyOverlaidModifier kom;
    return kom.remap(remapParams, KeyCode::TAB, KeyCode::OPTION_L, KeyCode::TAB);
  }

  // ----------------------------------------
  static bool
  remap_keypadnumlock_togglekey_clear(const RemapParams &remapParams)
  {
    if (! config.option_keypadnumlock_togglekey_clear) return false;

    if (! RemapUtil::isKey(remapParams, KeyCode::KEYPAD_CLEAR)) return false;

    if (RemapUtil::isKeyDown(remapParams, KeyCode::KEYPAD_CLEAR)) {
      config.remap_keypadnumlock = ! config.remap_keypadnumlock;
    }
    RemapUtil::drop(remapParams);
    return true;
  }

  // ----------------------------------------
  static bool
  remap_jis_eisuu2commandL_eisuu_eisuu2optionL_term(const RemapParams &remapParams)
  {
    if (! config.remap_jis_eisuu2commandL_eisuu_eisuu2optionL_term) return false;

    if (remapParams.workspacedata.type == KeyRemap4MacBook_bridge::GetWorkspaceData::TERMINAL) {
      static KeyOverlaidModifier kom;
      return kom.remap(remapParams, KeyCode::JIS_EISUU, KeyCode::OPTION_L, KeyCode::JIS_EISUU);
    } else {
      static KeyOverlaidModifier kom;
      return kom.remap(remapParams, KeyCode::JIS_EISUU, KeyCode::COMMAND_L, KeyCode::JIS_EISUU);
    }
  }

  // ----------------------------------------
  static bool
  remap_jis_underscore2backslash(const RemapParams &remapParams)
  {
    if (! config.remap_jis_underscore2backslash) return false;

    static RemapUtil::KeyToKey keytokey;
    if (! keytokey.remap(remapParams, KeyCode::JIS_UNDERSCORE, ModifierFlag::NONE, KeyCode::BACKSLASH)) {
      return false;
    }
    remapParams.params.keyboardType = KeyboardType::MACBOOK;
    return true;
  }

  // ----------------------------------------
  static bool
  remap_jis_yen2backslash(const RemapParams &remapParams)
  {
    if (! config.remap_jis_yen2backslash) return false;

    static RemapUtil::KeyToKey keytokey;
    if (! keytokey.remap(remapParams, KeyCode::JIS_YEN, KeyCode::BACKSLASH)) {
      return false;
    }
    remapParams.params.keyboardType = KeyboardType::MACBOOK;
    return true;
  }

  // ----------------------------------------
  static bool
  remap_jis_app_vi_eisuu2eisuu_escape(const RemapParams &remapParams)
  {
    if (! config.remap_jis_app_vi_eisuu2eisuu_escape) return false;

    if (remapParams.workspacedata.type != KeyRemap4MacBook_bridge::GetWorkspaceData::VI) return false;

    if (! RemapUtil::isKeyDown(remapParams, KeyCode::JIS_EISUU)) return false;

    RemapUtil::fireKey(remapParams.params, remapParams.workspacedata);
    RemapUtil::fireKey_downup(remapParams.params.flags, KeyCode::ESCAPE, remapParams.params, remapParams.workspacedata);
    remapParams.isremapped = true;
    return true;
  }

  static bool
  remap_jis_jansi(const RemapParams &remapParams)
  {
    if (! config.remap_jis_jansi) return false;

    remapParams.params.keyboardType = KeyboardType::MACBOOK;

    {
      static RemapUtil::KeyToKey keytokey;
      if (keytokey.remap(remapParams, KeyCode::JIS_YEN, KeyCode::BACKQUOTE)) return true;
    }
    {
      static RemapUtil::KeyToKey keytokey;
      if (keytokey.remap(remapParams, KeyCode::JIS_UNDERSCORE, KeyCode::BACKQUOTE)) return true;
    }

    // Note: remap_jis_jansi return false if changed keyboardType only.
    return false;
  }

  static bool
  remap_pointing_relative_to_scroll(const RemapPointingParams_relative &remapParams)
  {
    if (! config.remap_pointing_relative_to_scroll) return false;

    RemapUtil::pointingRelativeToScroll(remapParams);
    return true;
  }
}

// ----------------------------------------------------------------------
void
org_pqrs_KeyRemap4MacBook::remap_core(const RemapParams &remapParams)
{
  FlagStatus::set(remapParams);

  // ======================================================================
  // normal remapping
#include "config/output/include.remapcode_call.cpp"

  remap_enter2commandL_enter2controlL_vm(remapParams);

  remap_f6_to_numlock(remapParams);

  remap_tab2option_withControlL(remapParams);

  // ----------------------------------------
  remap_keypadnumlock_togglekey_clear(remapParams);

  // ------------------------------------------------------------
  // jis
  remap_jis_underscore2backslash(remapParams);
  remap_jis_yen2backslash(remapParams);

  remap_jis_app_vi_eisuu2eisuu_escape(remapParams);

  remap_jis_jansi(remapParams);

  // ------------------------------------------------------------
  // *** Note: we need to call remap_space2shift, remap_enter2optionL_commandSpace (has SandS like behavior) as possible late. ***
  // *** If any key2modifier or modifier2key remappings are enabled, miss-cancelling are occured. ***
#include "config/output/include.remapcode_call_kom.cpp"
  remap_jis_eisuu2commandL_eisuu_eisuu2optionL_term(remapParams);

  // ------------------------------------------------------------
#include "config/output/include.remapcode_call_mhkk.cpp"

  // ------------------------------------------------------------
  remapParams.params.flags = FlagStatus::makeFlags();
}

void
org_pqrs_KeyRemap4MacBook::remap_consumer(const RemapConsumerParams &remapParams)
{
  FlagStatus::set();

#include "config/output/include.remapcode_call_consumer.cpp"

  remapParams.params.flags = FlagStatus::makeFlags();
}

void
org_pqrs_KeyRemap4MacBook::remap_pointing_relative_core(const RemapPointingParams_relative &remapParams)
{
  FlagStatus::set();

  remapParams.params.buttons.add(RemapUtil::getRemappedButtons());

#include "config/output/include.remapcode_call_pointing_relative.cpp"
  remap_pointing_relative_to_scroll(remapParams);
}
<|endoftext|>


<commit_before>#include "text-buffer.h"
#include "text-slice.h"

using std::move;

TextBuffer::TextBuffer(Text &&text) :
  base_text {std::move(text)},
  extent_ {base_text.extent()} {}

TextBuffer::TextBuffer(std::u16string text) : TextBuffer {Text {text}} {}

TextBuffer TextBuffer::build(std::istream &stream, size_t input_size, const char *encoding_name,
                             size_t cchange_size, std::function<void(size_t)> progress_callback) {
  return TextBuffer {Text::build(stream, input_size, encoding_name, cchange_size, progress_callback)};
}

Point TextBuffer::extent() const {
  return extent_;
}

uint32_t TextBuffer::line_length_for_row(uint32_t row) {
  return begin().traverse(Point {row, UINT32_MAX}) - begin().traverse(Point {row, 0});
}

Point TextBuffer::clip_position(Point position) {
  if (position > extent()) {
    return extent();
  } else {
    uint32_t max_column = line_length_for_row(position.row);
    if (position.column > max_column) {
      return Point {position.row, max_column};
    } else {
      return position;
    }
  }
}

Range TextBuffer::clip_range(Range range) {
  return Range {clip_position(range.start), clip_position(range.end)};
}

Text TextBuffer::text() {
  return Text {begin(), end()};
}

Text TextBuffer::text_in_range(Range range) {
  return Text {
    begin().traverse(range.start),
    begin().traverse(range.end)
  };
}

void TextBuffer::set_text_in_range(Range old_range, Text &&new_text) {
  old_range = clip_range(old_range);
  Point new_range_end = old_range.start.traverse(new_text.extent());
  uint32_t deleted_text_size = begin().traverse(old_range.end) - begin().traverse(old_range.start);
  patch.splice(old_range.start, old_range.extent(), new_text.extent(), optional<Text> {}, move(new_text), deleted_text_size);
  extent_ = new_range_end.traverse(extent_.traversal(old_range.end));
}

TextBuffer::Iterator TextBuffer::begin() {
  return Iterator {*this};
}

TextBuffer::Iterator TextBuffer::end() {
  return Iterator {*this}.traverse(extent());
}

TextBuffer::Iterator::Iterator(TextBuffer &buffer) :
  buffer {buffer},
  next_change {optional<Patch::Change> {}},
  offset_from_next_change_start {0},
  next_change_base_offset {0},
  current_offset {0} {
  fetch_next_change();
}

uint16_t TextBuffer::Iterator::operator*() const {
  if (next_change && offset_from_next_change_start >= 0) {
    return next_change->new_text->at(offset_from_next_change_start);
  } else {
    return buffer.base_text.at(next_change_base_offset + offset_from_next_change_start);
  }
}

TextBuffer::Iterator &TextBuffer::Iterator::operator++() {
  current_offset++;
  offset_from_next_change_start++;
  if (next_change && offset_from_next_change_start == next_change->new_text->size()) {
    fetch_next_change();
  }
  return *this;
}

bool TextBuffer::Iterator::operator!=(const Iterator &other) const {
  return &buffer != &other.buffer || current_offset != other.current_offset;
}

TextBuffer::Iterator::difference_type TextBuffer::Iterator::operator-(const Iterator &other) const {
  return current_offset - other.current_offset;
}

void TextBuffer::Iterator::fetch_next_change() {
  int64_t preceding_text_delta;
  if (next_change) {
    preceding_text_delta =
      static_cast<int64_t>(next_change->preceding_new_text_size) + next_change->new_text->size() -
      next_change->preceding_old_text_size - next_change->old_text_size;
    next_change = buffer.patch.change_ending_after_new_position(next_change->new_end, true);
  } else {
    preceding_text_delta = 0;
    next_change = buffer.patch.change_ending_after_new_position(Point {0, 0});
  }

  if (next_change) {
    next_change_base_offset = buffer.base_text.offset_for_position(next_change->old_start);
  } else {
    next_change_base_offset = buffer.base_text.size();
  }

  uint32_t next_change_current_offset = next_change_base_offset + preceding_text_delta;
  offset_from_next_change_start = static_cast<int64_t>(current_offset) - next_change_current_offset;
}

TextBuffer::Iterator TextBuffer::Iterator::traverse(Point position) const {
  auto result = buffer.begin();

  auto preceding_change = buffer.patch.change_for_new_position(position);
  if (preceding_change) {
    uint32_t preceding_change_base_offset =
      buffer.base_text.offset_for_position(preceding_change->old_start);
    int32_t preceding_text_delta =
      preceding_change->preceding_new_text_size -
      preceding_change->preceding_old_text_size;
    uint32_t preceding_change_current_offset =
      preceding_change_base_offset + preceding_text_delta;

    uint32_t offset_from_preceding_change_start;
    if (position <= preceding_change->new_end) {
      offset_from_preceding_change_start =
        preceding_change->new_text->offset_for_position(
          position.traversal(preceding_change->new_start)
        );
    } else {
      Point base_text_position =
        preceding_change->old_end.traverse(
          position.traversal(preceding_change->new_end)
        );
      offset_from_preceding_change_start =
        preceding_change->new_text->size() +
        (
          buffer.base_text.offset_for_position(base_text_position) -
          buffer.base_text.offset_for_position(preceding_change->old_end)
        );
    }

    result.next_change = preceding_change;
    result.next_change_base_offset = preceding_change_base_offset;
    result.offset_from_next_change_start = offset_from_preceding_change_start;
    result.current_offset = preceding_change_current_offset + offset_from_preceding_change_start;
    result.fetch_next_change();
  } else {
    result.current_offset = buffer.base_text.offset_for_position(position);
    result.offset_from_next_change_start = static_cast<int64_t>(result.current_offset) - result.next_change_base_offset;
  }

  return result;
}
<commit_msg>Handle deletions at the beginning of the buffer in fetch_next_change<commit_after>#include "text-buffer.h"
#include "text-slice.h"

using std::move;

TextBuffer::TextBuffer(Text &&text) :
  base_text {std::move(text)},
  extent_ {base_text.extent()} {}

TextBuffer::TextBuffer(std::u16string text) : TextBuffer {Text {text}} {}

TextBuffer TextBuffer::build(std::istream &stream, size_t input_size, const char *encoding_name,
                             size_t cchange_size, std::function<void(size_t)> progress_callback) {
  return TextBuffer {Text::build(stream, input_size, encoding_name, cchange_size, progress_callback)};
}

Point TextBuffer::extent() const {
  return extent_;
}

uint32_t TextBuffer::line_length_for_row(uint32_t row) {
  return begin().traverse(Point {row, UINT32_MAX}) - begin().traverse(Point {row, 0});
}

Point TextBuffer::clip_position(Point position) {
  if (position > extent()) {
    return extent();
  } else {
    uint32_t max_column = line_length_for_row(position.row);
    if (position.column > max_column) {
      return Point {position.row, max_column};
    } else {
      return position;
    }
  }
}

Range TextBuffer::clip_range(Range range) {
  return Range {clip_position(range.start), clip_position(range.end)};
}

Text TextBuffer::text() {
  return Text {begin(), end()};
}

Text TextBuffer::text_in_range(Range range) {
  return Text {
    begin().traverse(range.start),
    begin().traverse(range.end)
  };
}

void TextBuffer::set_text_in_range(Range old_range, Text &&new_text) {
  old_range = clip_range(old_range);
  Point new_range_end = old_range.start.traverse(new_text.extent());
  uint32_t deleted_text_size = begin().traverse(old_range.end) - begin().traverse(old_range.start);
  patch.splice(old_range.start, old_range.extent(), new_text.extent(), optional<Text> {}, move(new_text), deleted_text_size);
  extent_ = new_range_end.traverse(extent_.traversal(old_range.end));
}

TextBuffer::Iterator TextBuffer::begin() {
  return Iterator {*this};
}

TextBuffer::Iterator TextBuffer::end() {
  return Iterator {*this}.traverse(extent());
}

TextBuffer::Iterator::Iterator(TextBuffer &buffer) :
  buffer {buffer},
  next_change {optional<Patch::Change> {}},
  offset_from_next_change_start {0},
  next_change_base_offset {0},
  current_offset {0} {
  fetch_next_change();
}

uint16_t TextBuffer::Iterator::operator*() const {
  if (next_change && offset_from_next_change_start >= 0) {
    return next_change->new_text->at(offset_from_next_change_start);
  } else {
    return buffer.base_text.at(next_change_base_offset + offset_from_next_change_start);
  }
}

TextBuffer::Iterator &TextBuffer::Iterator::operator++() {
  current_offset++;
  offset_from_next_change_start++;
  if (next_change && offset_from_next_change_start == next_change->new_text->size()) {
    fetch_next_change();
  }
  return *this;
}

bool TextBuffer::Iterator::operator!=(const Iterator &other) const {
  return &buffer != &other.buffer || current_offset != other.current_offset;
}

TextBuffer::Iterator::difference_type TextBuffer::Iterator::operator-(const Iterator &other) const {
  return current_offset - other.current_offset;
}

void TextBuffer::Iterator::fetch_next_change() {
  do {
    int64_t preceding_text_delta;
    if (next_change) {
      preceding_text_delta =
        static_cast<int64_t>(next_change->preceding_new_text_size) + next_change->new_text->size() -
        next_change->preceding_old_text_size - next_change->old_text_size;
      next_change = buffer.patch.change_ending_after_new_position(next_change->new_end, true);
    } else {
      preceding_text_delta = 0;
      next_change = buffer.patch.change_ending_after_new_position(Point {0, 0});
    }

    if (next_change) {
      next_change_base_offset = buffer.base_text.offset_for_position(next_change->old_start);
    } else {
      next_change_base_offset = buffer.base_text.size();
    }

    uint32_t next_change_current_offset = next_change_base_offset + preceding_text_delta;
    offset_from_next_change_start = static_cast<int64_t>(current_offset) - next_change_current_offset;
  } while (next_change && next_change->new_end.is_zero());
}

TextBuffer::Iterator TextBuffer::Iterator::traverse(Point position) const {
  auto result = buffer.begin();

  auto preceding_change = buffer.patch.change_for_new_position(position);
  if (preceding_change) {
    uint32_t preceding_change_base_offset =
      buffer.base_text.offset_for_position(preceding_change->old_start);
    int32_t preceding_text_delta =
      preceding_change->preceding_new_text_size -
      preceding_change->preceding_old_text_size;
    uint32_t preceding_change_current_offset =
      preceding_change_base_offset + preceding_text_delta;

    uint32_t offset_from_preceding_change_start;
    if (position <= preceding_change->new_end) {
      offset_from_preceding_change_start =
        preceding_change->new_text->offset_for_position(
          position.traversal(preceding_change->new_start)
        );
    } else {
      Point base_text_position =
        preceding_change->old_end.traverse(
          position.traversal(preceding_change->new_end)
        );
      offset_from_preceding_change_start =
        preceding_change->new_text->size() +
        (
          buffer.base_text.offset_for_position(base_text_position) -
          buffer.base_text.offset_for_position(preceding_change->old_end)
        );
    }

    result.next_change = preceding_change;
    result.next_change_base_offset = preceding_change_base_offset;
    result.offset_from_next_change_start = offset_from_preceding_change_start;
    result.current_offset = preceding_change_current_offset + offset_from_preceding_change_start;
    result.fetch_next_change();
  } else {
    result.current_offset = buffer.base_text.offset_for_position(position);
    result.offset_from_next_change_start = static_cast<int64_t>(result.current_offset) - result.next_change_base_offset;
  }

  return result;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cstring>
#include "socket.h"

int main(int argc, char** argv) {
    using namespace std;

    if (argc == 2 && !strcmp(argv[1], "s")) {
        socket_t sockfd = udp_socket();

        UdpSocketAddr addr("192.168.1.100", 10000);

        if (udp_bind(sockfd, addr) == -1) {
            std::cout << "Bind error!" << std::endl;
            return 1;
        }

        string message = "hello";

        addr.setPort(8888);

        udp_send(sockfd, message, addr);

        memset(&addr, 0x00, sizeof(addr));

        udp_recv(sockfd, message, addr);
        std::cout << message << std::endl;

    } else {
        std::cout << "Unknown arguments." << std::endl;
    }
}
<commit_msg>slight improve<commit_after>#include <iostream>
#include <cstring>
#include "socket.h"

int main(int argc, char** argv) {
    using namespace std;

    if (argc == 2 && !strcmp(argv[1], "s")) {
        socket_t sockfd = udp_socket();

        UdpSocketAddr addr("192.168.1.100", 10000);

        if (udp_bind(sockfd, addr) == -1) {
            std::cout << "Bind error!" << std::endl;
            return 1;
        }

        string message = "hello";
        addr.setAddr("192.168.1.101");

        addr.setPort(8888);

        udp_send(sockfd, message, addr);

        memset(&addr, 0x00, sizeof(addr));

        udp_recv(sockfd, message, addr);
        std::cout << message << std::endl;

    } else {
        std::cout << "Unknown arguments." << std::endl;
    }
}
<|endoftext|>