<commit_before>#include "widgets/helper/NotebookTab.hpp"

#include "Application.hpp"
#include "common/Common.hpp"
#include "debug/Log.hpp"
#include "singletons/Fonts.hpp"
#include "singletons/Settings.hpp"
#include "singletons/Theme.hpp"
#include "singletons/WindowManager.hpp"
#include "util/Clamp.hpp"
#include "util/Helpers.hpp"
#include "widgets/Notebook.hpp"
#include "widgets/dialogs/SettingsDialog.hpp"
#include "widgets/dialogs/TextInputDialog.hpp"
#include "widgets/splits/SplitContainer.hpp"

#include <QApplication>
#include <QDebug>
#include <QLinearGradient>
#include <QMimeData>
#include <QPainter>
#include <boost/bind.hpp>

namespace chatterino {

NotebookTab::NotebookTab(Notebook *notebook)
    : Button(notebook)
    , positionChangedAnimation_(this, "pos")
    , notebook_(notebook)
    , menu_(this)
{
    auto app = getApp();

    this->setAcceptDrops(true);

    this->positionChangedAnimation_.setEasingCurve(
        QEasingCurve(QEasingCurve::InCubic));

    getSettings()->showTabCloseButton.connect(
        boost::bind(&NotebookTab::hideTabXChanged, this, _1),
        this->managedConnections_);

    this->setMouseTracking(true);

    this->menu_.addAction("Rename", [this]() {
        TextInputDialog d(this);

        d.setWindowTitle(
            "Change tab title (Leave empty for default behaviour)");
        d.setText(this->getCustomTitle());
        d.highlightText();

        if (d.exec() == QDialog::Accepted) {
            QString newTitle = d.getText();
            this->setCustomTitle(newTitle);
        }
    });

    this->menu_.addAction("Close",
                          [=]() { this->notebook_->removePage(this->page); });

    highlightNewMessagesAction_ =
        new QAction("Enable highlights on new messages", &this->menu_);
    highlightNewMessagesAction_->setCheckable(true);
    highlightNewMessagesAction_->setChecked(highlightEnabled_);
    QObject::connect(
        highlightNewMessagesAction_, &QAction::triggered,
        [this](bool checked) { this->highlightEnabled_ = checked; });
    this->menu_.addAction(highlightNewMessagesAction_);
}

void NotebookTab::themeChangedEvent()
{
    this->update();

    //    this->setMouseEffectColor(QColor("#999"));
    this->setMouseEffectColor(this->theme->tabs.regular.text);
}

void NotebookTab::updateSize()
{
    float scale = getScale();

    int width;
    QFontMetrics metrics = getApp()->fonts->getFontMetrics(
        FontStyle::UiTabs,
        float(qreal(this->getScale()) * this->devicePixelRatioF()));

    if (this->hasXButton()) {
        width = (metrics.width(this->getTitle()) + int(32 * scale));
    } else {
        width = (metrics.width(this->getTitle()) + int(16 * scale));
    }

    width = clamp(width, this->height(), int(150 * scale));

    if (this->width() != width) {
        this->resize(width, int(NOTEBOOK_TAB_HEIGHT * scale));
        this->notebook_->performLayout();
    }
}

const QString &NotebookTab::getCustomTitle() const
{
    return this->customTitle_;
}

void NotebookTab::setCustomTitle(const QString &newTitle)
{
    if (this->customTitle_ != newTitle) {
        this->customTitle_ = newTitle;
        this->titleUpdated();
    }
}

void NotebookTab::resetCustomTitle()
{
    this->setCustomTitle(QString());
}

bool NotebookTab::hasCustomTitle() const
{
    return !this->customTitle_.isEmpty();
}

void NotebookTab::setDefaultTitle(const QString &title)
{
    if (this->defaultTitle_ != title) {
        this->defaultTitle_ = title;

        if (this->customTitle_.isEmpty()) {
            this->titleUpdated();
        }
    }
}

const QString &NotebookTab::getDefaultTitle() const
{
    return this->defaultTitle_;
}

const QString &NotebookTab::getTitle() const
{
    return this->customTitle_.isEmpty() ? this->defaultTitle_
                                        : this->customTitle_;
}

void NotebookTab::titleUpdated()
{
    // Queue up save because: Tab title changed
    getApp()->windows->queueSave();

    this->updateSize();
    this->update();
}

bool NotebookTab::isSelected() const
{
    return this->selected_;
}

void NotebookTab::setSelected(bool value)
{
    this->selected_ = value;

    this->highlightState_ = HighlightState::None;

    this->update();
}

void NotebookTab::setLive(bool isLive)
{
    if (this->isLive_ != isLive) {
        this->isLive_ = isLive;
        this->update();
    }
}

void NotebookTab::setHighlightState(HighlightState newHighlightStyle)
{
    if (this->isSelected() || !this->highlightEnabled_) {
        return;
    }
    if (this->highlightState_ != HighlightState::Highlighted) {
        this->highlightState_ = newHighlightStyle;

        this->update();
    }
}

void NotebookTab::setHighlightsEnabled(const bool &newVal)
{
    this->highlightNewMessagesAction_->setChecked(newVal);
    this->highlightEnabled_ = newVal;
}

bool NotebookTab::hasHighlightsEnabled() const
{
    return this->highlightEnabled_;
}

QRect NotebookTab::getDesiredRect() const
{
    return QRect(this->positionAnimationDesiredPoint_, size());
}

void NotebookTab::hideTabXChanged(bool)
{
    this->updateSize();
    this->update();
}

void NotebookTab::moveAnimated(QPoint pos, bool animated)
{
    this->positionAnimationDesiredPoint_ = pos;

    QWidget *w = this->window();

    if ((w != nullptr && !w->isVisible()) || !animated ||
        !this->positionChangedAnimationRunning_) {
        this->move(pos);

        this->positionChangedAnimationRunning_ = true;
        return;
    }

    if (this->positionChangedAnimation_.endValue() == pos) {
        return;
    }

    this->positionChangedAnimation_.stop();
    this->positionChangedAnimation_.setDuration(75);
    this->positionChangedAnimation_.setStartValue(this->pos());
    this->positionChangedAnimation_.setEndValue(pos);
    this->positionChangedAnimation_.start();
}

void NotebookTab::paintEvent(QPaintEvent *)
{
    auto app = getApp();
    QPainter painter(this);
    float scale = this->getScale();

    painter.setFont(getApp()->fonts->getFont(
        FontStyle::UiTabs,
        scale * 96.f / this->logicalDpiX() * this->devicePixelRatioF()));
    QFontMetrics metrics = app->fonts->getFontMetrics(
        FontStyle::UiTabs,
        scale * 96.f / this->logicalDpiX() * this->devicePixelRatioF());

    int height = int(scale * NOTEBOOK_TAB_HEIGHT);
    //    int fullHeight = (int)(scale * 48);

    // select the right tab colors
    Theme::TabColors colors;
    Theme::TabColors regular = this->theme->tabs.regular;

    if (this->selected_) {
        colors = this->theme->tabs.selected;
    } else if (this->highlightState_ == HighlightState::Highlighted) {
        colors = this->theme->tabs.highlighted;
    } else if (this->highlightState_ == HighlightState::NewMessage) {
        colors = this->theme->tabs.newMessage;
    } else {
        colors = this->theme->tabs.regular;
    }

    bool windowFocused = this->window() == QApplication::activeWindow();
    // || SettingsDialog::getHandle() == QApplication::activeWindow();

    QBrush tabBackground = /*this->mouseOver_ ? colors.backgrounds.hover
                                            :*/
        (windowFocused ? colors.backgrounds.regular
                       : colors.backgrounds.unfocused);

    //    painter.fillRect(rect(), this->mouseOver_ ? regular.backgrounds.hover
    //                                              : (windowFocused ?
    //                                              regular.backgrounds.regular
    //                                                               :
    //                                                               regular.backgrounds.unfocused));

    // fill the tab background
    auto bgRect = rect();
    bgRect.setTop(bgRect.top() + 2);

    painter.fillRect(bgRect, tabBackground);

    // draw border
    //    painter.setPen(QPen("#fff"));
    //    QPainterPath path(QPointF(0, height));
    //    path.lineTo(0, 0);
    //    path.lineTo(this->width() - 1, 0);
    //    path.lineTo(this->width() - 1, this->height() - 1);
    //    path.lineTo(0, this->height() - 1);
    //    painter.drawPath(path);

    // top line
    painter.fillRect(
        QRectF(0, (this->selected_ ? 0.f : 1.f) * scale, this->width(),
               (this->selected_ ? 2.f : 1.f) * scale),
        this->mouseOver_
            ? colors.line.hover
            : (windowFocused ? colors.line.regular : colors.line.unfocused));

    // draw live indicator
    if (this->isLive_) {
        painter.setPen(QColor(Qt::GlobalColor::red));
        QBrush b;
        b.setColor(QColor(Qt::GlobalColor::red));
        b.setStyle(Qt::SolidPattern);
        painter.setBrush(b);

        auto x = this->width() - (6.f * scale);
        auto y = 4.f * scale;
        auto diameter = 4.f * scale;
        painter.drawEllipse(QRectF(x, y, diameter, diameter));
    }

    // set the pen color
    painter.setPen(colors.text);

    // set area for text
    int rectW = (!getSettings()->showTabCloseButton ? 0 : int(16 * scale));
    QRect rect(0, 0, this->width() - rectW, height);

    // draw text
    int offset = int(scale * 8);
    QRect textRect(offset, this->selected_ ? 1 : 2,
                   this->width() - offset - offset, height);

    if (this->shouldDrawXButton()) {
        textRect.setRight(textRect.right() - this->height() / 2);
    }

    int width = metrics.width(this->getTitle());
    Qt::Alignment alignment = width > textRect.width()
                                  ? Qt::AlignLeft | Qt::AlignVCenter
                                  : Qt::AlignHCenter | Qt::AlignVCenter;

    QTextOption option(alignment);
    option.setWrapMode(QTextOption::NoWrap);
    painter.drawText(textRect, this->getTitle(), option);

    // draw close x
    if (this->shouldDrawXButton()) {
        QRect xRect = this->getXRect();
        if (!xRect.isNull()) {
            if (this->selected_) xRect.moveTop(xRect.top() - 1);

            painter.setBrush(QColor("#fff"));

            if (this->mouseOverX_) {
                painter.fillRect(xRect, QColor(0, 0, 0, 64));

                if (this->mouseDownX_) {
                    painter.fillRect(xRect, QColor(0, 0, 0, 64));
                }
            }

            int a = static_cast<int>(scale * 4);

            painter.drawLine(xRect.topLeft() + QPoint(a, a),
                             xRect.bottomRight() + QPoint(-a, -a));
            painter.drawLine(xRect.topRight() + QPoint(-a, a),
                             xRect.bottomLeft() + QPoint(a, -a));
        }
    }

    // draw line at bottom
    if (!this->selected_) {
        painter.fillRect(0, this->height() - 1, this->width(), 1,
                         app->themes->window.background);

        this->fancyPaint(painter);
    }
}

bool NotebookTab::hasXButton()
{
    return getSettings()->showTabCloseButton &&
           this->notebook_->getAllowUserTabManagement();
}

bool NotebookTab::shouldDrawXButton()
{
    return this->hasXButton() && (this->mouseOver_ || this->selected_);
}

void NotebookTab::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        this->mouseDown_ = true;
        this->mouseDownX_ = this->getXRect().contains(event->pos());

        this->notebook_->select(page);
    }

    this->update();

    if (this->notebook_->getAllowUserTabManagement()) {
        switch (event->button()) {
            case Qt::RightButton: {
                this->menu_.popup(event->globalPos());
            } break;
            default:;
        }
    }
}

void NotebookTab::mouseReleaseEvent(QMouseEvent *event)
{
    this->mouseDown_ = false;

    auto removeThisPage = [this] {
        auto reply = QMessageBox::question(
            this, "Remove this tab",
            "Are you sure that you want to remove this tab?",
            QMessageBox::Yes | QMessageBox::Cancel);

        if (reply == QMessageBox::Yes) {
            this->notebook_->removePage(this->page);
        }
    };

    if (event->button() == Qt::MiddleButton) {
        if (this->rect().contains(event->pos())) {
            removeThisPage();
        }
    } else {
        if (this->hasXButton() && this->mouseDownX_ &&
            this->getXRect().contains(event->pos())) {
            this->mouseDownX_ = false;

            removeThisPage();
        } else {
            this->update();
        }
    }
}

void NotebookTab::enterEvent(QEvent *event)
{
    this->mouseOver_ = true;

    this->update();

    Button::enterEvent(event);
}

void NotebookTab::leaveEvent(QEvent *event)
{
    this->mouseOverX_ = false;
    this->mouseOver_ = false;

    this->update();

    Button::leaveEvent(event);
}

void NotebookTab::dragEnterEvent(QDragEnterEvent *event)
{
    if (!event->mimeData()->hasFormat("chatterino/split")) return;

    if (!SplitContainer::isDraggingSplit) return;

    if (this->notebook_->getAllowUserTabManagement()) {
        this->notebook_->select(this->page);
    }
}

void NotebookTab::mouseMoveEvent(QMouseEvent *event)
{
    auto app = getApp();

    if (getSettings()->showTabCloseButton &&
        this->notebook_->getAllowUserTabManagement())  //
    {
        bool overX = this->getXRect().contains(event->pos());

        if (overX != this->mouseOverX_) {
            // Over X state has been changed (we either left or entered it;
            this->mouseOverX_ = overX;

            this->update();
        }
    }

    QPoint relPoint = this->mapToParent(event->pos());

    if (this->mouseDown_ && !this->getDesiredRect().contains(relPoint) &&
        this->notebook_->getAllowUserTabManagement())  //
    {
        int index;
        QWidget *clickedPage =
            this->notebook_->tabAt(relPoint, index, this->width());

        if (clickedPage != nullptr && clickedPage != this->page) {
            this->notebook_->rearrangePage(this->page, index);
        }
    }

    Button::mouseMoveEvent(event);
}

void NotebookTab::wheelEvent(QWheelEvent *event)
{
    if (event->delta() > 0) {
        this->notebook_->selectPreviousTab();
    } else {
        this->notebook_->selectNextTab();
    }
}

QRect NotebookTab::getXRect()
{
    //    if (!this->notebook->getAllowUserTabManagement()) {
    //        return QRect();
    //    }

    float s = this->getScale();
    return QRect(this->width() - static_cast<int>(20 * s),
                 static_cast<int>(9 * s), static_cast<int>(16 * s),
                 static_cast<int>(16 * s));
}

}  // namespace chatterino
<commit_msg>got triggered by pixels<commit_after>#include "widgets/helper/NotebookTab.hpp"

#include "Application.hpp"
#include "common/Common.hpp"
#include "debug/Log.hpp"
#include "singletons/Fonts.hpp"
#include "singletons/Settings.hpp"
#include "singletons/Theme.hpp"
#include "singletons/WindowManager.hpp"
#include "util/Clamp.hpp"
#include "util/Helpers.hpp"
#include "widgets/Notebook.hpp"
#include "widgets/dialogs/SettingsDialog.hpp"
#include "widgets/dialogs/TextInputDialog.hpp"
#include "widgets/splits/SplitContainer.hpp"

#include <QApplication>
#include <QDebug>
#include <QLinearGradient>
#include <QMimeData>
#include <QPainter>
#include <boost/bind.hpp>

namespace chatterino {

NotebookTab::NotebookTab(Notebook *notebook)
    : Button(notebook)
    , positionChangedAnimation_(this, "pos")
    , notebook_(notebook)
    , menu_(this)
{
    auto app = getApp();

    this->setAcceptDrops(true);

    this->positionChangedAnimation_.setEasingCurve(
        QEasingCurve(QEasingCurve::InCubic));

    getSettings()->showTabCloseButton.connect(
        boost::bind(&NotebookTab::hideTabXChanged, this, _1),
        this->managedConnections_);

    this->setMouseTracking(true);

    this->menu_.addAction("Rename", [this]() {
        TextInputDialog d(this);

        d.setWindowTitle(
            "Change tab title (Leave empty for default behaviour)");
        d.setText(this->getCustomTitle());
        d.highlightText();

        if (d.exec() == QDialog::Accepted) {
            QString newTitle = d.getText();
            this->setCustomTitle(newTitle);
        }
    });

    this->menu_.addAction("Close",
                          [=]() { this->notebook_->removePage(this->page); });

    highlightNewMessagesAction_ =
        new QAction("Enable highlights on new messages", &this->menu_);
    highlightNewMessagesAction_->setCheckable(true);
    highlightNewMessagesAction_->setChecked(highlightEnabled_);
    QObject::connect(
        highlightNewMessagesAction_, &QAction::triggered,
        [this](bool checked) { this->highlightEnabled_ = checked; });
    this->menu_.addAction(highlightNewMessagesAction_);
}

void NotebookTab::themeChangedEvent()
{
    this->update();

    //    this->setMouseEffectColor(QColor("#999"));
    this->setMouseEffectColor(this->theme->tabs.regular.text);
}

void NotebookTab::updateSize()
{
    float scale = getScale();

    int width;
    QFontMetrics metrics = getApp()->fonts->getFontMetrics(
        FontStyle::UiTabs,
        float(qreal(this->getScale()) * this->devicePixelRatioF()));

    if (this->hasXButton()) {
        width = (metrics.width(this->getTitle()) + int(32 * scale));
    } else {
        width = (metrics.width(this->getTitle()) + int(16 * scale));
    }

    width = clamp(width, this->height(), int(150 * scale));

    if (this->width() != width) {
        this->resize(width, int(NOTEBOOK_TAB_HEIGHT * scale));
        this->notebook_->performLayout();
    }
}

const QString &NotebookTab::getCustomTitle() const
{
    return this->customTitle_;
}

void NotebookTab::setCustomTitle(const QString &newTitle)
{
    if (this->customTitle_ != newTitle) {
        this->customTitle_ = newTitle;
        this->titleUpdated();
    }
}

void NotebookTab::resetCustomTitle()
{
    this->setCustomTitle(QString());
}

bool NotebookTab::hasCustomTitle() const
{
    return !this->customTitle_.isEmpty();
}

void NotebookTab::setDefaultTitle(const QString &title)
{
    if (this->defaultTitle_ != title) {
        this->defaultTitle_ = title;

        if (this->customTitle_.isEmpty()) {
            this->titleUpdated();
        }
    }
}

const QString &NotebookTab::getDefaultTitle() const
{
    return this->defaultTitle_;
}

const QString &NotebookTab::getTitle() const
{
    return this->customTitle_.isEmpty() ? this->defaultTitle_
                                        : this->customTitle_;
}

void NotebookTab::titleUpdated()
{
    // Queue up save because: Tab title changed
    getApp()->windows->queueSave();

    this->updateSize();
    this->update();
}

bool NotebookTab::isSelected() const
{
    return this->selected_;
}

void NotebookTab::setSelected(bool value)
{
    this->selected_ = value;

    this->highlightState_ = HighlightState::None;

    this->update();
}

void NotebookTab::setLive(bool isLive)
{
    if (this->isLive_ != isLive) {
        this->isLive_ = isLive;
        this->update();
    }
}

void NotebookTab::setHighlightState(HighlightState newHighlightStyle)
{
    if (this->isSelected() || !this->highlightEnabled_) {
        return;
    }
    if (this->highlightState_ != HighlightState::Highlighted) {
        this->highlightState_ = newHighlightStyle;

        this->update();
    }
}

void NotebookTab::setHighlightsEnabled(const bool &newVal)
{
    this->highlightNewMessagesAction_->setChecked(newVal);
    this->highlightEnabled_ = newVal;
}

bool NotebookTab::hasHighlightsEnabled() const
{
    return this->highlightEnabled_;
}

QRect NotebookTab::getDesiredRect() const
{
    return QRect(this->positionAnimationDesiredPoint_, size());
}

void NotebookTab::hideTabXChanged(bool)
{
    this->updateSize();
    this->update();
}

void NotebookTab::moveAnimated(QPoint pos, bool animated)
{
    this->positionAnimationDesiredPoint_ = pos;

    QWidget *w = this->window();

    if ((w != nullptr && !w->isVisible()) || !animated ||
        !this->positionChangedAnimationRunning_) {
        this->move(pos);

        this->positionChangedAnimationRunning_ = true;
        return;
    }

    if (this->positionChangedAnimation_.endValue() == pos) {
        return;
    }

    this->positionChangedAnimation_.stop();
    this->positionChangedAnimation_.setDuration(75);
    this->positionChangedAnimation_.setStartValue(this->pos());
    this->positionChangedAnimation_.setEndValue(pos);
    this->positionChangedAnimation_.start();
}

void NotebookTab::paintEvent(QPaintEvent *)
{
    auto app = getApp();
    QPainter painter(this);
    float scale = this->getScale();

    painter.setFont(getApp()->fonts->getFont(
        FontStyle::UiTabs,
        scale * 96.f / this->logicalDpiX() * this->devicePixelRatioF()));
    QFontMetrics metrics = app->fonts->getFontMetrics(
        FontStyle::UiTabs,
        scale * 96.f / this->logicalDpiX() * this->devicePixelRatioF());

    int height = int(scale * NOTEBOOK_TAB_HEIGHT);
    //    int fullHeight = (int)(scale * 48);

    // select the right tab colors
    Theme::TabColors colors;
    Theme::TabColors regular = this->theme->tabs.regular;

    if (this->selected_) {
        colors = this->theme->tabs.selected;
    } else if (this->highlightState_ == HighlightState::Highlighted) {
        colors = this->theme->tabs.highlighted;
    } else if (this->highlightState_ == HighlightState::NewMessage) {
        colors = this->theme->tabs.newMessage;
    } else {
        colors = this->theme->tabs.regular;
    }

    bool windowFocused = this->window() == QApplication::activeWindow();
    // || SettingsDialog::getHandle() == QApplication::activeWindow();

    QBrush tabBackground = /*this->mouseOver_ ? colors.backgrounds.hover
                                            :*/
        (windowFocused ? colors.backgrounds.regular
                       : colors.backgrounds.unfocused);

    //    painter.fillRect(rect(), this->mouseOver_ ? regular.backgrounds.hover
    //                                              : (windowFocused ?
    //                                              regular.backgrounds.regular
    //                                                               :
    //                                                               regular.backgrounds.unfocused));

    // fill the tab background
    auto bgRect = rect();
    bgRect.setTop(bgRect.top() + 2);

    painter.fillRect(bgRect, tabBackground);

    // draw border
    //    painter.setPen(QPen("#fff"));
    //    QPainterPath path(QPointF(0, height));
    //    path.lineTo(0, 0);
    //    path.lineTo(this->width() - 1, 0);
    //    path.lineTo(this->width() - 1, this->height() - 1);
    //    path.lineTo(0, this->height() - 1);
    //    painter.drawPath(path);

    // top line
    painter.fillRect(
        QRectF(0, (this->selected_ ? 0.f : 1.f) * scale, this->width(),
               (this->selected_ ? 2.f : 1.f) * scale),
        this->mouseOver_
            ? colors.line.hover
            : (windowFocused ? colors.line.regular : colors.line.unfocused));

    // draw live indicator
    if (this->isLive_) {
        painter.setPen(QColor(Qt::GlobalColor::red));
        QBrush b;
        b.setColor(QColor(Qt::GlobalColor::red));
        b.setStyle(Qt::SolidPattern);
        painter.setBrush(b);

        auto x = this->width() - (7.f * scale);
        auto y = 4.f * scale;
        auto diameter = 4.f * scale;
        painter.drawEllipse(QRectF(x, y, diameter, diameter));
    }

    // set the pen color
    painter.setPen(colors.text);

    // set area for text
    int rectW = (!getSettings()->showTabCloseButton ? 0 : int(16 * scale));
    QRect rect(0, 0, this->width() - rectW, height);

    // draw text
    int offset = int(scale * 8);
    QRect textRect(offset, this->selected_ ? 1 : 2,
                   this->width() - offset - offset, height);

    if (this->shouldDrawXButton()) {
        textRect.setRight(textRect.right() - this->height() / 2);
    }

    int width = metrics.width(this->getTitle());
    Qt::Alignment alignment = width > textRect.width()
                                  ? Qt::AlignLeft | Qt::AlignVCenter
                                  : Qt::AlignHCenter | Qt::AlignVCenter;

    QTextOption option(alignment);
    option.setWrapMode(QTextOption::NoWrap);
    painter.drawText(textRect, this->getTitle(), option);

    // draw close x
    if (this->shouldDrawXButton()) {
        QRect xRect = this->getXRect();
        if (!xRect.isNull()) {
            if (this->selected_) xRect.moveTop(xRect.top() - 1);

            painter.setBrush(QColor("#fff"));

            if (this->mouseOverX_) {
                painter.fillRect(xRect, QColor(0, 0, 0, 64));

                if (this->mouseDownX_) {
                    painter.fillRect(xRect, QColor(0, 0, 0, 64));
                }
            }

            int a = static_cast<int>(scale * 4);

            painter.drawLine(xRect.topLeft() + QPoint(a, a),
                             xRect.bottomRight() + QPoint(-a, -a));
            painter.drawLine(xRect.topRight() + QPoint(-a, a),
                             xRect.bottomLeft() + QPoint(a, -a));
        }
    }

    // draw line at bottom
    if (!this->selected_) {
        painter.fillRect(0, this->height() - 1, this->width(), 1,
                         app->themes->window.background);

        this->fancyPaint(painter);
    }
}

bool NotebookTab::hasXButton()
{
    return getSettings()->showTabCloseButton &&
           this->notebook_->getAllowUserTabManagement();
}

bool NotebookTab::shouldDrawXButton()
{
    return this->hasXButton() && (this->mouseOver_ || this->selected_);
}

void NotebookTab::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        this->mouseDown_ = true;
        this->mouseDownX_ = this->getXRect().contains(event->pos());

        this->notebook_->select(page);
    }

    this->update();

    if (this->notebook_->getAllowUserTabManagement()) {
        switch (event->button()) {
            case Qt::RightButton: {
                this->menu_.popup(event->globalPos());
            } break;
            default:;
        }
    }
}

void NotebookTab::mouseReleaseEvent(QMouseEvent *event)
{
    this->mouseDown_ = false;

    auto removeThisPage = [this] {
        auto reply = QMessageBox::question(
            this, "Remove this tab",
            "Are you sure that you want to remove this tab?",
            QMessageBox::Yes | QMessageBox::Cancel);

        if (reply == QMessageBox::Yes) {
            this->notebook_->removePage(this->page);
        }
    };

    if (event->button() == Qt::MiddleButton) {
        if (this->rect().contains(event->pos())) {
            removeThisPage();
        }
    } else {
        if (this->hasXButton() && this->mouseDownX_ &&
            this->getXRect().contains(event->pos())) {
            this->mouseDownX_ = false;

            removeThisPage();
        } else {
            this->update();
        }
    }
}

void NotebookTab::enterEvent(QEvent *event)
{
    this->mouseOver_ = true;

    this->update();

    Button::enterEvent(event);
}

void NotebookTab::leaveEvent(QEvent *event)
{
    this->mouseOverX_ = false;
    this->mouseOver_ = false;

    this->update();

    Button::leaveEvent(event);
}

void NotebookTab::dragEnterEvent(QDragEnterEvent *event)
{
    if (!event->mimeData()->hasFormat("chatterino/split")) return;

    if (!SplitContainer::isDraggingSplit) return;

    if (this->notebook_->getAllowUserTabManagement()) {
        this->notebook_->select(this->page);
    }
}

void NotebookTab::mouseMoveEvent(QMouseEvent *event)
{
    auto app = getApp();

    if (getSettings()->showTabCloseButton &&
        this->notebook_->getAllowUserTabManagement())  //
    {
        bool overX = this->getXRect().contains(event->pos());

        if (overX != this->mouseOverX_) {
            // Over X state has been changed (we either left or entered it;
            this->mouseOverX_ = overX;

            this->update();
        }
    }

    QPoint relPoint = this->mapToParent(event->pos());

    if (this->mouseDown_ && !this->getDesiredRect().contains(relPoint) &&
        this->notebook_->getAllowUserTabManagement())  //
    {
        int index;
        QWidget *clickedPage =
            this->notebook_->tabAt(relPoint, index, this->width());

        if (clickedPage != nullptr && clickedPage != this->page) {
            this->notebook_->rearrangePage(this->page, index);
        }
    }

    Button::mouseMoveEvent(event);
}

void NotebookTab::wheelEvent(QWheelEvent *event)
{
    if (event->delta() > 0) {
        this->notebook_->selectPreviousTab();
    } else {
        this->notebook_->selectNextTab();
    }
}

QRect NotebookTab::getXRect()
{
    //    if (!this->notebook->getAllowUserTabManagement()) {
    //        return QRect();
    //    }

    float s = this->getScale();
    return QRect(this->width() - static_cast<int>(20 * s),
                 static_cast<int>(9 * s), static_cast<int>(16 * s),
                 static_cast<int>(16 * s));
}

}  // namespace chatterino
<|endoftext|>


<commit_before>#ifndef STAN_MATH_REV_FUNCTOR_GRADIENT_HPP
#define STAN_MATH_REV_FUNCTOR_GRADIENT_HPP

#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stdexcept>
#include <vector>

namespace stan {
namespace math {

/**
 * Calculate the value and the gradient of the specified function
 * at the specified argument.
 *
 *
The functor must implement
 *
 *
 * var
 * operator()(const
 * Eigen::Matrix<var, Eigen::Dynamic, 1>&)
 *
 *
 * using only operations that are defined for
 * var.  This latter constraint usually
 * requires the functions to be defined in terms of the libraries
 * defined in Stan or in terms of functions with appropriately
 * general namespace imports that eventually depend on functions
 * defined in Stan.
 *
 * The evaluated gradient is stored into a
 * Eigen::VectorXd named grad_fx.
 *
 *
Time and memory usage is on the order of the size of the
 * fully unfolded expression for the function applied to the
 * argument, independently of dimension.
 *
 * @tparam F Type of function
 * @param[in] f Function
 * @param[in] x Argument to function
 * @param[out] fx Function applied to argument
 * @param[out] grad_fx Gradient of function at argument
 */
template <typename F>
void gradient(const F& f, const Eigen::Matrix<double, Eigen::Dynamic, 1>& x,
              double& fx, Eigen::Matrix<double, Eigen::Dynamic, 1>& grad_fx) {
  nested_rev_autodiff nested;

  Eigen::Matrix<var, Eigen::Dynamic, 1> x_var(x);
  var fx_var = f(x_var);
  fx = fx_var.val();
  grad_fx.resize(x.size());
  grad(fx_var.vi_);
  grad_fx = x_var.adj();
}

/**
 * Calculate the value and the gradient of the specified function
 * at the specified argument.
 *
 *
The functor must implement
 *
 *
 * var
 * operator()(const
 * Eigen::Matrix<var, Eigen::Dynamic, 1>&)
 *
 *
 * using only operations that are defined for
 * var.  This latter constraint usually
 * requires the functions to be defined in terms of the libraries
 * defined in Stan or in terms of functions with appropriately
 * general namespace imports that eventually depend on functions
 * defined in Stan.
 *
 * The evaluated gradient is stored into the object whose data
 * begins at *first_grad_fx and ends at
 * *last_grad_fx.  The caller is responsible for
 * ensuring the size of the object pointed to by
 * first_grad_fx matches the size of the argument
 * x.
 *
 *
Time and memory usage is on the order of the size of the
 * fully unfolded expression for the function applied to the
 * argument, independently of dimension.
 *
 * @tparam F Type of function
 * @tparam EigVec Type of Eigen vector
 * @tparam InputIt must meet the requirements of [LegacyInputIterator](https://en.cppreference.com/w/cpp/named_req/InputIterator).
 * @param[in] f Function
 * @param[in] x Argument to function
 * @param[out] fx Function applied to argument
 * @param[out] first_grad_fx First element of gradient of function at argument
 * @param[out] last_grad_fx Last element of gradient of function at argument
 * @throw std::invalid_argument if the iterator isn't the right size
 * to hold the gradients
 */
template <typename F, typename EigVec, typename InputIt,
          require_eigen_vector_vt<std::is_arithmetic, EigVec>* = nullptr>
void gradient(const F& f, const EigVec& x, double& fx, InputIt first_grad_fx,
              InputIt last_grad_fx) {
  nested_rev_autodiff nested;

  if (last_grad_fx - first_grad_fx != x.size()) {
    std::stringstream s;
    s << "gradient(): iterator and gradient different sizes; iterator size = "
      << last_grad_fx - first_grad_fx << "; grad size = " << x.size()
      << std::endl;
    throw std::invalid_argument(s.str());
  }

  Eigen::Matrix<var, Eigen::Dynamic, 1> x_var(x);
  var fx_var = f(x_var);
  fx = fx_var.val();
  grad(fx_var.vi_);
  for (Eigen::VectorXd::Index i = 0; i < x_var.size(); ++i) {
    *first_grad_fx++ = x_var.coeff(i).adj();
  }
}

}  // namespace math
}  // namespace stan
#endif
<commit_msg>[Jenkins] auto-formatting by clang-format version 10.0.0-4ubuntu1<commit_after>#ifndef STAN_MATH_REV_FUNCTOR_GRADIENT_HPP
#define STAN_MATH_REV_FUNCTOR_GRADIENT_HPP

#include <stan/math/rev/meta.hpp>
#include <stan/math/rev/core.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <stdexcept>
#include <vector>

namespace stan {
namespace math {

/**
 * Calculate the value and the gradient of the specified function
 * at the specified argument.
 *
 *
The functor must implement
 *
 *
 * var
 * operator()(const
 * Eigen::Matrix<var, Eigen::Dynamic, 1>&)
 *
 *
 * using only operations that are defined for
 * var.  This latter constraint usually
 * requires the functions to be defined in terms of the libraries
 * defined in Stan or in terms of functions with appropriately
 * general namespace imports that eventually depend on functions
 * defined in Stan.
 *
 * The evaluated gradient is stored into a
 * Eigen::VectorXd named grad_fx.
 *
 *
Time and memory usage is on the order of the size of the
 * fully unfolded expression for the function applied to the
 * argument, independently of dimension.
 *
 * @tparam F Type of function
 * @param[in] f Function
 * @param[in] x Argument to function
 * @param[out] fx Function applied to argument
 * @param[out] grad_fx Gradient of function at argument
 */
template <typename F>
void gradient(const F& f, const Eigen::Matrix<double, Eigen::Dynamic, 1>& x,
              double& fx, Eigen::Matrix<double, Eigen::Dynamic, 1>& grad_fx) {
  nested_rev_autodiff nested;

  Eigen::Matrix<var, Eigen::Dynamic, 1> x_var(x);
  var fx_var = f(x_var);
  fx = fx_var.val();
  grad_fx.resize(x.size());
  grad(fx_var.vi_);
  grad_fx = x_var.adj();
}

/**
 * Calculate the value and the gradient of the specified function
 * at the specified argument.
 *
 *
The functor must implement
 *
 *
 * var
 * operator()(const
 * Eigen::Matrix<var, Eigen::Dynamic, 1>&)
 *
 *
 * using only operations that are defined for
 * var.  This latter constraint usually
 * requires the functions to be defined in terms of the libraries
 * defined in Stan or in terms of functions with appropriately
 * general namespace imports that eventually depend on functions
 * defined in Stan.
 *
 * The evaluated gradient is stored into the object whose data
 * begins at *first_grad_fx and ends at
 * *last_grad_fx.  The caller is responsible for
 * ensuring the size of the object pointed to by
 * first_grad_fx matches the size of the argument
 * x.
 *
 *
Time and memory usage is on the order of the size of the
 * fully unfolded expression for the function applied to the
 * argument, independently of dimension.
 *
 * @tparam F Type of function
 * @tparam EigVec Type of Eigen vector
 * @tparam InputIt must meet the requirements of
 * [LegacyInputIterator](https://en.cppreference.com/w/cpp/named_req/InputIterator).
 * @param[in] f Function
 * @param[in] x Argument to function
 * @param[out] fx Function applied to argument
 * @param[out] first_grad_fx First element of gradient of function at argument
 * @param[out] last_grad_fx Last element of gradient of function at argument
 * @throw std::invalid_argument if the iterator isn't the right size
 * to hold the gradients
 */
template <typename F, typename EigVec, typename InputIt,
          require_eigen_vector_vt<std::is_arithmetic, EigVec>* = nullptr>
void gradient(const F& f, const EigVec& x, double& fx, InputIt first_grad_fx,
              InputIt last_grad_fx) {
  nested_rev_autodiff nested;

  if (last_grad_fx - first_grad_fx != x.size()) {
    std::stringstream s;
    s << "gradient(): iterator and gradient different sizes; iterator size = "
      << last_grad_fx - first_grad_fx << "; grad size = " << x.size()
      << std::endl;
    throw std::invalid_argument(s.str());
  }

  Eigen::Matrix<var, Eigen::Dynamic, 1> x_var(x);
  var fx_var = f(x_var);
  fx = fx_var.val();
  grad(fx_var.vi_);
  for (Eigen::VectorXd::Index i = 0; i < x_var.size(); ++i) {
    *first_grad_fx++ = x_var.coeff(i).adj();
  }
}

}  // namespace math
}  // namespace stan
#endif
<|endoftext|>


<commit_before>//-------------------------------------------------------------------------
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Andrew Duncan
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-------------------------------------------------------------------------

#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif

#include <cmath>
#include <cstdint>
#include <regex>
#include <stdexcept>
#include <string>

#include <unistd.h>

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#include <bcm_host.h>
#pragma GCC diagnostic pop

#include "font.h"
#include "temperatureTrace.h"

//-------------------------------------------------------------------------

int8_t
CTemperatureTrace::
getTemperature()
{
    double temperature = 0.0;

    char buffer[128];

    memset(buffer, 0, sizeof(buffer));

    if (vc_gencmd(buffer, sizeof(buffer), "measure_temp") == 0)
    {
        try
        {
            std::regex pattern{R"(temp=(\d+\.\d)'C)"};
            std::smatch match;

            if (std::regex_search(std::string(buffer), match, pattern) &&
                (match.size() == 2))
            {
                std::string found = match[1].str();
                temperature = round(stod(found));
            }
        }
        catch (std::exception&)
        {
            // ignore
        }
    }

    return static_cast<int8_t>(temperature);
}

//-------------------------------------------------------------------------

CTemperatureTrace::
CTemperatureTrace(
    int16_t width,
    int16_t traceHeight,
    int16_t yPosition,
    int16_t gridHeight)
:
    CTrace(width,
           traceHeight,
           yPosition,
           gridHeight,
           1,
           "Temperature",
           std::vector<std::string>{"temperature"},
           std::vector<raspifb16::CRGB565>{{102,167,225}}),
    m_traceHeight(traceHeight)
{
}

//-------------------------------------------------------------------------

void
CTemperatureTrace::
show(
    const raspifb16::CFrameBuffer565& fb,
    time_t now)
{
    int8_t temperature = (getTemperature() * m_traceHeight) / 100;

    update(std::vector<int8_t>{temperature}, now);

    putImage(fb);
}

<commit_msg>Removed unused #define<commit_after>//-------------------------------------------------------------------------
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Andrew Duncan
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//-------------------------------------------------------------------------

#include <cmath>
#include <cstdint>
#include <regex>
#include <stdexcept>
#include <string>

#include <unistd.h>

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#include <bcm_host.h>
#pragma GCC diagnostic pop

#include "font.h"
#include "temperatureTrace.h"

//-------------------------------------------------------------------------

int8_t
CTemperatureTrace::
getTemperature()
{
    double temperature = 0.0;

    char buffer[128];

    memset(buffer, 0, sizeof(buffer));

    if (vc_gencmd(buffer, sizeof(buffer), "measure_temp") == 0)
    {
        try
        {
            std::regex pattern{R"(temp=(\d+\.\d)'C)"};
            std::smatch match;

            if (std::regex_search(std::string(buffer), match, pattern) &&
                (match.size() == 2))
            {
                std::string found = match[1].str();
                temperature = round(stod(found));
            }
        }
        catch (std::exception&)
        {
            // ignore
        }
    }

    return static_cast<int8_t>(temperature);
}

//-------------------------------------------------------------------------

CTemperatureTrace::
CTemperatureTrace(
    int16_t width,
    int16_t traceHeight,
    int16_t yPosition,
    int16_t gridHeight)
:
    CTrace(width,
           traceHeight,
           yPosition,
           gridHeight,
           1,
           "Temperature",
           std::vector<std::string>{"temperature"},
           std::vector<raspifb16::CRGB565>{{102,167,225}}),
    m_traceHeight(traceHeight)
{
}

//-------------------------------------------------------------------------

void
CTemperatureTrace::
show(
    const raspifb16::CFrameBuffer565& fb,
    time_t now)
{
    int8_t temperature = (getTemperature() * m_traceHeight) / 100;

    update(std::vector<int8_t>{temperature}, now);

    putImage(fb);
}

<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/host/capturer_gdi.h"
#include "remoting/host/differ.h"

#include "gfx/rect.h"

namespace remoting {

// 3780 pixels per meter is equivalent to 96 DPI, typical on desktop monitors.
static const int kPixelsPerMeter = 3780;
// 32 bit RGBA is 4 bytes per pixel.
static const int kBytesPerPixel = 4;

CapturerGdi::CapturerGdi(MessageLoop* message_loop)
    : Capturer(message_loop),
      desktop_dc_(NULL),
      memory_dc_(NULL),
      capture_fullscreen_(true) {
  memset(target_bitmap_, 0, sizeof(target_bitmap_));
  memset(buffers_, 0, sizeof(buffers_));
}

CapturerGdi::~CapturerGdi() {
  ReleaseBuffers();
}

void CapturerGdi::ReleaseBuffers() {
  for (int i = kNumBuffers - 1; i >= 0; i--) {
    if (target_bitmap_[i]) {
      DeleteObject(target_bitmap_[i]);
      target_bitmap_[i] = NULL;
    }
    if (buffers_[i]) {
      DeleteObject(buffers_[i]);
      buffers_[i] = NULL;
    }
  }

  desktop_dc_ = NULL;
  if (memory_dc_) {
    DeleteDC(memory_dc_);
    memory_dc_ = NULL;
  }
}

void CapturerGdi::ScreenConfigurationChanged() {
  ReleaseBuffers();

  desktop_dc_ = GetDC(GetDesktopWindow());
  memory_dc_ = CreateCompatibleDC(desktop_dc_);

  // Create a bitmap to keep the desktop image.
  width_ = GetSystemMetrics(SM_CXSCREEN);
  height_ = GetSystemMetrics(SM_CYSCREEN);
  int rounded_width = (width_ + 3) & (~3);

  // Dimensions of screen.
  pixel_format_ = media::VideoFrame::RGB32;
  bytes_per_row_ = rounded_width * kBytesPerPixel;

  // Create a differ for this screen size.
  differ_.reset(new Differ(width_, height_, 4, bytes_per_row_));

  // Create a device independant bitmap (DIB) that is the same size.
  BITMAPINFO bmi;
  memset(&bmi, 0, sizeof(bmi));
  bmi.bmiHeader.biHeight = height_;
  bmi.bmiHeader.biWidth = width_;
  bmi.bmiHeader.biPlanes = 1;
  bmi.bmiHeader.biBitCount = kBytesPerPixel * 8;
  bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
  bmi.bmiHeader.biSizeImage = bytes_per_row_ * height_;
  bmi.bmiHeader.biXPelsPerMeter = kPixelsPerMeter;
  bmi.bmiHeader.biYPelsPerMeter = kPixelsPerMeter;

  // Create memory for the buffers.
  for (int i = 0; i < kNumBuffers; i++) {
    target_bitmap_[i] = CreateDIBSection(desktop_dc_, &bmi, DIB_RGB_COLORS,
                                         static_cast<void**>(&buffers_[i]),
                                         NULL, 0);
  }

  capture_fullscreen_ = true;
}

void CapturerGdi::CalculateInvalidRects() {
  ClearInvalidRects();
  CaptureImage();

  if (capture_fullscreen_) {
    InvalidateFullScreen();
  } else {
    // Calculate the difference between the previous and current screen.
    int prev_buffer_id = current_buffer_ - 1;
    if (prev_buffer_id < 0) {
      prev_buffer_id = kNumBuffers - 1;
    }

    void* prev_buffer = buffers_[prev_buffer_id];
    void* curr_buffer = buffers_[current_buffer_];

    InvalidRects rects;
    differ_->CalcDirtyRects(prev_buffer, curr_buffer, &rects);

    InvalidateRects(rects);
  }

  capture_fullscreen_ = false;
}

void CapturerGdi::CaptureRects(const InvalidRects& rects,
                               CaptureCompletedCallback* callback) {
  DataPlanes planes;
  planes.data[0] = static_cast<uint8*>(buffers_[current_buffer_]);
  planes.strides[0] = bytes_per_row_;

  scoped_refptr<CaptureData> data(new CaptureData(planes,
                                                  width(),
                                                  height(),
                                                  pixel_format()));
  data->mutable_dirty_rects() = rects;

  FinishCapture(data, callback);
}

void CapturerGdi::CaptureImage() {
  // Select the target bitmap into the memory dc.
  SelectObject(memory_dc_, target_bitmap_[current_buffer_]);

  // And then copy the rect from desktop to memory.
  BitBlt(memory_dc_, 0, 0, width_, height_, desktop_dc_, 0, 0,
      SRCCOPY | CAPTUREBLT);
}

}  // namespace remoting
<commit_msg>Fix GDI capturer initialization.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "remoting/host/capturer_gdi.h"
#include "remoting/host/differ.h"

#include "gfx/rect.h"

namespace remoting {

// 3780 pixels per meter is equivalent to 96 DPI, typical on desktop monitors.
static const int kPixelsPerMeter = 3780;
// 32 bit RGBA is 4 bytes per pixel.
static const int kBytesPerPixel = 4;

CapturerGdi::CapturerGdi(MessageLoop* message_loop)
    : Capturer(message_loop),
      desktop_dc_(NULL),
      memory_dc_(NULL),
      capture_fullscreen_(true) {
  memset(target_bitmap_, 0, sizeof(target_bitmap_));
  memset(buffers_, 0, sizeof(buffers_));
  ScreenConfigurationChanged();
}

CapturerGdi::~CapturerGdi() {
  ReleaseBuffers();
}

void CapturerGdi::ReleaseBuffers() {
  for (int i = kNumBuffers - 1; i >= 0; i--) {
    if (target_bitmap_[i]) {
      DeleteObject(target_bitmap_[i]);
      target_bitmap_[i] = NULL;
    }
    if (buffers_[i]) {
      DeleteObject(buffers_[i]);
      buffers_[i] = NULL;
    }
  }

  desktop_dc_ = NULL;
  if (memory_dc_) {
    DeleteDC(memory_dc_);
    memory_dc_ = NULL;
  }
}

void CapturerGdi::ScreenConfigurationChanged() {
  ReleaseBuffers();

  desktop_dc_ = GetDC(GetDesktopWindow());
  memory_dc_ = CreateCompatibleDC(desktop_dc_);

  // Create a bitmap to keep the desktop image.
  width_ = GetSystemMetrics(SM_CXSCREEN);
  height_ = GetSystemMetrics(SM_CYSCREEN);
  int rounded_width = (width_ + 3) & (~3);

  // Dimensions of screen.
  pixel_format_ = media::VideoFrame::RGB32;
  bytes_per_row_ = rounded_width * kBytesPerPixel;

  // Create a differ for this screen size.
  differ_.reset(new Differ(width_, height_, 4, bytes_per_row_));

  // Create a device independant bitmap (DIB) that is the same size.
  BITMAPINFO bmi;
  memset(&bmi, 0, sizeof(bmi));
  bmi.bmiHeader.biHeight = height_;
  bmi.bmiHeader.biWidth = width_;
  bmi.bmiHeader.biPlanes = 1;
  bmi.bmiHeader.biBitCount = kBytesPerPixel * 8;
  bmi.bmiHeader.biSize = sizeof(bmi.bmiHeader);
  bmi.bmiHeader.biSizeImage = bytes_per_row_ * height_;
  bmi.bmiHeader.biXPelsPerMeter = kPixelsPerMeter;
  bmi.bmiHeader.biYPelsPerMeter = kPixelsPerMeter;

  // Create memory for the buffers.
  for (int i = 0; i < kNumBuffers; i++) {
    target_bitmap_[i] = CreateDIBSection(desktop_dc_, &bmi, DIB_RGB_COLORS,
                                         static_cast<void**>(&buffers_[i]),
                                         NULL, 0);
  }

  capture_fullscreen_ = true;
}

void CapturerGdi::CalculateInvalidRects() {
  ClearInvalidRects();
  CaptureImage();

  if (capture_fullscreen_) {
    InvalidateFullScreen();
  } else {
    // Calculate the difference between the previous and current screen.
    int prev_buffer_id = current_buffer_ - 1;
    if (prev_buffer_id < 0) {
      prev_buffer_id = kNumBuffers - 1;
    }

    void* prev_buffer = buffers_[prev_buffer_id];
    void* curr_buffer = buffers_[current_buffer_];

    InvalidRects rects;
    differ_->CalcDirtyRects(prev_buffer, curr_buffer, &rects);

    InvalidateRects(rects);
  }

  capture_fullscreen_ = false;
}

void CapturerGdi::CaptureRects(const InvalidRects& rects,
                               CaptureCompletedCallback* callback) {
  DataPlanes planes;
  planes.data[0] = static_cast<uint8*>(buffers_[current_buffer_]);
  planes.strides[0] = bytes_per_row_;

  scoped_refptr<CaptureData> data(new CaptureData(planes,
                                                  width(),
                                                  height(),
                                                  pixel_format()));
  data->mutable_dirty_rects() = rects;

  FinishCapture(data, callback);
}

void CapturerGdi::CaptureImage() {
  // Select the target bitmap into the memory dc.
  SelectObject(memory_dc_, target_bitmap_[current_buffer_]);

  // And then copy the rect from desktop to memory.
  BitBlt(memory_dc_, 0, 0, width_, height_, desktop_dc_, 0, 0,
      SRCCOPY | CAPTUREBLT);
}

}  // namespace remoting
<|endoftext|>


<commit_before>#ifndef ENUMERABLE__H__
#define ENUMERABLE__H__

#include <iterbase.hpp>

#include <utility>
#include <iterator>
#include <functional>
#include <initializer_list>

// enumerate functionality for python-style for-each enumerate loops
// for (auto e : enumerate(vec)) {
//     std::cout << e.index
//               << ": "
//               << e.element
//               << '\n';
// }

namespace iter {

    //Forward declarations of Enumerable and enumerate
    template <typename Container>
    class Enumerable;

    template <typename T>
    Enumerable<std::initializer_list<T>> enumerate(
            std::initializer_list<T> &&);

    template <typename Container>
    Enumerable<Container> enumerate(Container &&);

    template <typename Container>
    class Enumerable : public IterBase<Container>{
        public:
            Container & container;

            // The only thing allowed to directly instantiate an Enumerable is
            // the enumerate function
            friend Enumerable enumerate<Container>(Container &&);
            template <typename T>
            friend Enumerable<std::initializer_list<T>> enumerate(std::initializer_list<T> &&);

            using typename IterBase<Container>::contained_iter_type;

            using typename IterBase<Container>::contained_iter_ret;

            Enumerable(Container && container) : container(container) { }

        public:
            // Value constructor for use only in the enumerate function
            Enumerable () = delete;
            Enumerable & operator=(const Enumerable &) = delete;

            Enumerable(const Enumerable &) = default;

            // "yielded" by the Enumerable::Iterator.  Has a .index, and a
            // .element referencing the value yielded by the subiterator
            class IterYield {
                public:
                    std::size_t index;
                    contained_iter_ret element;
                    IterYield(std::size_t i, contained_iter_ret elem) :
                        index(i),
                        element(elem)
                    { }
            };

            //  Holds an iterator of the contained type and a size_t for the
            //  index.  Each call to ++ increments both of these data members.
            //  Each dereference returns an IterYield.
            class Iterator {
                private:
                    contained_iter_type sub_iter;
                    std::size_t index;
                public:
                    Iterator (contained_iter_type si) :
                        sub_iter(si),
                        index(0) { }

                    IterYield operator*() const {
                        return IterYield(this->index, *this->sub_iter);
                    }

                    Iterator & operator++() {
                        ++this->sub_iter;
                        ++this->index;
                        return *this;
                    }

                    bool operator!=(const Iterator & other) const {
                        return this->sub_iter != other.sub_iter;
                    }
            };

            Iterator begin() const {
                return Iterator(std::begin(this->container));
            }

            Iterator end() const {
                return Iterator(std::end(this->container));
            }

    };

    // Helper function to instantiate an Enumerable
    template <typename Container>
    Enumerable<Container> enumerate(Container && container) {
        return Enumerable<Container>(std::forward<Container>(container));
    }

    template <typename T>
    Enumerable<std::initializer_list<T>> enumerate(std::initializer_list<T> && il)
    {
        return Enumerable<std::initializer_list<T>>(
                std::forward<std::initializer_list<T>>(il));
    }

}

#endif //ifndef ENUMERABLE__H__
<commit_msg>Restores privacy to enumerate<commit_after>#ifndef ENUMERABLE__H__
#define ENUMERABLE__H__

#include <iterbase.hpp>

#include <utility>
#include <iterator>
#include <functional>
#include <initializer_list>

// enumerate functionality for python-style for-each enumerate loops
// for (auto e : enumerate(vec)) {
//     std::cout << e.index
//               << ": "
//               << e.element
//               << '\n';
// }

namespace iter {

    //Forward declarations of Enumerable and enumerate
    template <typename Container>
    class Enumerable;

    template <typename T>
    Enumerable<std::initializer_list<T>> enumerate(
            std::initializer_list<T> &&);

    template <typename Container>
    Enumerable<Container> enumerate(Container &&);

    template <typename Container>
    class Enumerable : public IterBase<Container>{
        private:
            Container & container;

            // The only thing allowed to directly instantiate an Enumerable is
            // the enumerate function
            friend Enumerable enumerate<Container>(Container &&);
            template <typename T>
            friend Enumerable<std::initializer_list<T>> enumerate(std::initializer_list<T> &&);

            using typename IterBase<Container>::contained_iter_type;

            using typename IterBase<Container>::contained_iter_ret;

            Enumerable(Container && container) : container(container) { }

        public:
            // Value constructor for use only in the enumerate function
            Enumerable () = delete;
            Enumerable & operator=(const Enumerable &) = delete;

            Enumerable(const Enumerable &) = default;

            // "yielded" by the Enumerable::Iterator.  Has a .index, and a
            // .element referencing the value yielded by the subiterator
            class IterYield {
                public:
                    std::size_t index;
                    contained_iter_ret element;
                    IterYield(std::size_t i, contained_iter_ret elem) :
                        index(i),
                        element(elem)
                    { }
            };

            //  Holds an iterator of the contained type and a size_t for the
            //  index.  Each call to ++ increments both of these data members.
            //  Each dereference returns an IterYield.
            class Iterator {
                private:
                    contained_iter_type sub_iter;
                    std::size_t index;
                public:
                    Iterator (contained_iter_type si) :
                        sub_iter(si),
                        index(0) { }

                    IterYield operator*() const {
                        return IterYield(this->index, *this->sub_iter);
                    }

                    Iterator & operator++() {
                        ++this->sub_iter;
                        ++this->index;
                        return *this;
                    }

                    bool operator!=(const Iterator & other) const {
                        return this->sub_iter != other.sub_iter;
                    }
            };

            Iterator begin() const {
                return Iterator(std::begin(this->container));
            }

            Iterator end() const {
                return Iterator(std::end(this->container));
            }

    };

    // Helper function to instantiate an Enumerable
    template <typename Container>
    Enumerable<Container> enumerate(Container && container) {
        return Enumerable<Container>(std::forward<Container>(container));
    }

    template <typename T>
    Enumerable<std::initializer_list<T>> enumerate(std::initializer_list<T> && il)
    {
        return Enumerable<std::initializer_list<T>>(
                std::forward<std::initializer_list<T>>(il));
    }

}

#endif //ifndef ENUMERABLE__H__
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////
//  ObjectMatrix.cpp
//  Implementation of the Class ObjectMatrix
//  Created on:      07-Lie-2013 20:07:30
//  Original author: Povilas
///////////////////////////////////////////////////////////

/*! \class ObjectMatrix
    \brief A class of methods and attributes for manipulating matrices.
 */
#include "ObjectMatrix.h"
#include "AdditionalMethods.h"
#include "ARFF.h"
#include "DataObject.h"
#include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
//#include <set>

//double ObjectMatrix::_weight = 0;

ObjectMatrix::ObjectMatrix()
{
    DataObjects.reserve(0);   //1
    objectCount = 0;
    isClassPresent = false;
}

ObjectMatrix::~ObjectMatrix()
{
}

ObjectMatrix::ObjectMatrix(std::string file)
{
    fileName.assign(file);
    objectCount = 0;
    isClassPresent = false;
}

ObjectMatrix::ObjectMatrix(int cnt)
{
    DataObjects.reserve(cnt);
    objectCount = 0;
	isClassPresent = false;
}

ObjectMatrix::ObjectMatrix(int n, int m)
{
    DataObjects.reserve(n);
    for (int i = 0; i < n; i++)
        DataObjects[i].setNumOfFeatures(m);
    objectCount = 0;
isClassPresent = false;
}

ObjectMatrix::ObjectMatrix(int m, int n, int k)
{
    std::vector<double> initialFeatures;
    initialFeatures.resize(k, 1.0);
    DataObject initial(initialFeatures);
    DataObjects2D.resize(m, std::vector<DataObject>(n, initial));
    objectCount = 0;
isClassPresent = false;
}

void ObjectMatrix::addObject(DataObject object)
{
    DataObjects.push_back(object);
    objectCount++;
}

void ObjectMatrix::addObject(DataObject object, int cls)
{
    DataObjects.push_back(object);
    objectCount++;
    this->DataObjects.at(objectCount -1).setClassLabel(cls);
}

void ObjectMatrix::addObjectTo(int index, DataObject object)
{
    DataObjects2D[index].push_back(object);
    objectCount++;
}

void ObjectMatrix::updateDataObject(int objectIndex, int featureIndex, double newValue)
{
    this->DataObjects.at(objectIndex).updateFeature(featureIndex, newValue);
}

void ObjectMatrix::updateDataObjectClass(int objectIndex, int newClass)
{
    this->DataObjects.at(objectIndex).setClassLabel(newClass);
  //  this->isClassPresent = true;
}

bool ObjectMatrix::getPrintClass()
{
    return this->isClassPresent;
}

void ObjectMatrix::setPrintClass(std::vector <std::string> printClass)
{
    this->attributeStringClasses = printClass;
    this->isClassPresent = true;
}

void ObjectMatrix::updateDataObject(int rowIndex, int colIndex, int featureIndex, double newValue)
{
    this->DataObjects2D[rowIndex].at(colIndex).updateFeature(featureIndex, newValue);
}

DataObject ObjectMatrix::getObjectAt(int index)
{
    return  DataObjects.at(index);
}

DataObject ObjectMatrix::getObjectAt(int row_index, int col_index)
{
    return  DataObjects2D[row_index].at(col_index);
}

int ObjectMatrix::getObjectCount()
{
    return objectCount;
}

std::vector<std::string> ObjectMatrix::getFeaturesTitle()
{
    return featureTitles;
}

int ObjectMatrix::getClassCount()
{
    int cCount = 0;
    if (!attributeStringClasses.empty())
        cCount = attributeStringClasses.size();
    return cCount;
}

void ObjectMatrix::addAtributes(std::vector<std::string> additionalAttributes)
{
    this->additionalAttributes = additionalAttributes;
}

bool ObjectMatrix::getIsClassPresent()
{
    return this->isClassPresent;
}

void ObjectMatrix::setIsClassPresent()
{
    this->isClassPresent = true;
}

std::vector <std::string> ObjectMatrix::getStringClassAttributes()
{
    return this->attributeStringClasses;
}

void ObjectMatrix::loadDataMatrix()
{
    const char* path = fileName.c_str();
    ARFF file(path);

    ObjectMatrix::_weight = 0;

    if (file.isSuccessfullyRead() == true)   // successful read
    {
        std::vector< std::vector<double>> data = file.getData();
        //featureTitles = file.getAttributes();
        if (file.isClassFound())
           {
                objClasses = file.getIntClass();
                attributeStringClasses = file.getAttributeStringClasses();
                //isClassPresent = true;
               // std::cout << attributeStringClasses.size();
           }

        std::vector< std::vector<double>> ::iterator dataObjectIterator;

        std::vector<double>::iterator featureIterator;
        std::vector<double> dataObjectItems;
        int indx = 0;
        for(dataObjectIterator = data.begin(); dataObjectIterator!=data.end(); ++dataObjectIterator)
        {
            for(featureIterator = (*dataObjectIterator).begin(); featureIterator!=(*dataObjectIterator).end(); ++featureIterator)
                dataObjectItems.push_back(*featureIterator);

            if (file.isClassFound())
                {
                    DataObject tmp(dataObjectItems, file.getObjectClass(indx));
                    DataObjects.push_back(tmp);
                 //   std::cout << DataObjects.at(indx).getClassLabel() <<std::endl;
                }
            else
                {
                    DataObject tmp(dataObjectItems);
                    DataObjects.push_back(tmp);
                    //   std::cout << DataObjects.at(indx).getClassLabel() <<std::endl;
                }
            dataObjectItems.clear();
            indx++;
        }
        objectCount = DataObjects.size();

        //Calculate matrix X distances between vectors

        //ObjectMatrix::_weight = 0;
        int i, j, z;
        int n =  data.at(0).size(); //features
        double diff, sRow, tmpVal;

      //  FILE *distFile;
        AdditionalMethods::distFile = fopen(AdditionalMethods::tempFileSavePath.c_str(), "wb");

        for (i = 0; i < objectCount - 1; i++)
        {
            for (j = i + 1; j < objectCount; j++)
            {
                sRow = 0.0;
                for (z = 0; z < n; z++)
                {
                    diff  = data.at(i).at(z) - data.at(j).at(z);
                    sRow += diff * diff;
                }
                tmpVal = std::sqrt(sRow);
                fwrite(&tmpVal, sizeof(double), 1, AdditionalMethods::distFile);
                ObjectMatrix::_weight += sRow;
            }
        }
       // fclose(distFile);
        // end distance matrix calculation
    }
    else
    {
        //_weight = 0;
        objectCount = 0;
    }
}
void ObjectMatrix::addComment(std::string comnt)
{
    if (this->comments.empty())
        comments.reserve(0);
    comments.push_back(comnt);
}

void ObjectMatrix::saveDataMatrix(const char* path)
{
    ARFF file;
  //  std::vector <std::string> classLabels; classLabels.reserve(0);
   // std::vector <std::string> comment
    //std::vector <int> tmp; // assume v has the elements
    /*if (getPrintClass())
    {
       /*for (int i = 0; i < DataObjects.size(); i++) //pass only unique class labels that will be printed in @Attribute Class section
        {
            bool notFound = true;
            int tmpLabel = DataObjects.at(i).getClassLabel();
            for (int j = 0; j < classLabels.size(); j++)
                if (tmpLabel == classLabels.at(j))
                {
                    notFound = false;
                    break;
                }
            if (notFound)*/
          //  for (int j = 0; j < classLabels.size(); j++)
              //  classLabels.push_back(tmpLabel);
              //  classLabels = attributeStringClasses;
        //}
       // classLabels = attributeClasses;

    std::vector <std::string> attributeLabels; attributeLabels.reserve(0);

    if (!additionalAttributes.empty())
    {
        for (int i = 0; i < getObjectAt(0).getFeatureCount() - additionalAttributes.size(); i++)
            attributeLabels.push_back("atr" + std::to_string(static_cast<long long>(i+1)) + " REAL");

        for (int i = 0; i < additionalAttributes.size(); i++)
            {
            attributeLabels.push_back(additionalAttributes.at(i) + " REAL");
           // std::cout << attributeStringClasses.at(i);
            }
    }
    else
    {
        for (int i = 0; i < getObjectAt(0).getFeatureCount(); i++)
            attributeLabels.push_back("atr" + std::to_string(static_cast<long long>(i+1)) + " REAL");
    }
    file.writeData(path, this->comments, this->DataObjects, attributeStringClasses, attributeLabels);
}

void ObjectMatrix::clearDataObjects()
{
    DataObjects.clear();
    objectCount = 0;
}
/*void ObjectMatrix::assignStringClassesAttribute(ObjectMatrix X)
{
    this->attributeStringClasses = X.attributeStringClasses;
}*/

/*double ObjectMatrix::getDistanceBetween(int i, int j)
{
   FILE *distFile;
   distFile = fopen("D:\\dist.txt", "rb");
//   std::ifstream distFile;
//    distFile.open("D:\\dist.txt", std::ios::binary);
   double retVal;
   int noOfBytes = sizeof(double);

   fseek(distFile, (noOfBytes * i) + noOfBytes * (j - i - 1), SEEK_SET);
 //  fseek(distFile, 1, SEEK_SET);
   fread(&retVal, noOfBytes, 1, distFile);
 //  distFile>>retVal;

  // std::cout << retVal << std::endl;
   fclose(distFile);
// distFile.close();
   return retVal;
   //return *(*(distances + i) + j - i - 1);
}*/

double ObjectMatrix::getWeight()
{
    return ObjectMatrix::_weight;
}
<commit_msg>Added MPI barrier for file reading<commit_after>///////////////////////////////////////////////////////////
//  ObjectMatrix.cpp
//  Implementation of the Class ObjectMatrix
//  Created on:      07-Lie-2013 20:07:30
//  Original author: Povilas
///////////////////////////////////////////////////////////

/*! \class ObjectMatrix
    \brief A class of methods and attributes for manipulating matrices.
 */
#include "ObjectMatrix.h"
#include "AdditionalMethods.h"
#include "ARFF.h"
#include "DataObject.h"
#include <vector>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <mpi.h>
//#include <set>

//double ObjectMatrix::_weight = 0;

ObjectMatrix::ObjectMatrix()
{
    DataObjects.reserve(0);   //1
    objectCount = 0;
    isClassPresent = false;
}

ObjectMatrix::~ObjectMatrix()
{
}

ObjectMatrix::ObjectMatrix(std::string file)
{
    fileName.assign(file);
    objectCount = 0;
    isClassPresent = false;
}

ObjectMatrix::ObjectMatrix(int cnt)
{
 //   DataObjects.reserve(cnt);
    DataObjects.reserve(0);
    objectCount = 0;
	isClassPresent = false;
}

ObjectMatrix::ObjectMatrix(int n, int m)
{
    DataObjects.reserve(n);
    for (int i = 0; i < n; i++)
        DataObjects[i].setNumOfFeatures(m);
    objectCount = 0;
isClassPresent = false;
}

ObjectMatrix::ObjectMatrix(int m, int n, int k)
{
    std::vector<double> initialFeatures;
    initialFeatures.resize(k, 1.0);
    DataObject initial(initialFeatures);
    DataObjects2D.resize(m, std::vector<DataObject>(n, initial));
    objectCount = 0;
isClassPresent = false;
}

void ObjectMatrix::addObject(DataObject object)
{
    DataObjects.push_back(object);
    objectCount++;
}

void ObjectMatrix::addObject(DataObject object, int cls)
{
    DataObjects.push_back(object);
    objectCount++;
    this->DataObjects.at(objectCount -1).setClassLabel(cls);
}

void ObjectMatrix::addObjectTo(int index, DataObject object)
{
    DataObjects2D[index].push_back(object);
    objectCount++;
}

void ObjectMatrix::updateDataObject(int objectIndex, int featureIndex, double newValue)
{
    this->DataObjects.at(objectIndex).updateFeature(featureIndex, newValue);
}

void ObjectMatrix::updateDataObjectClass(int objectIndex, int newClass)
{
    this->DataObjects.at(objectIndex).setClassLabel(newClass);
  //  this->isClassPresent = true;
}

/*std::vector<int> ObjectMatrix::getIntObjectClasses();
{
    return this->objClasses
}*/

bool ObjectMatrix::getPrintClass()
{
    return this->isClassPresent;
}

void ObjectMatrix::setPrintClass(std::vector <std::string> printClass)
{
    this->attributeStringClasses = printClass;
    this->isClassPresent = true;
}

void ObjectMatrix::updateDataObject(int rowIndex, int colIndex, int featureIndex, double newValue)
{
    this->DataObjects2D[rowIndex].at(colIndex).updateFeature(featureIndex, newValue);
}

DataObject ObjectMatrix::getObjectAt(int index)
{
    return  DataObjects.at(index);
}

DataObject ObjectMatrix::getObjectAt(int row_index, int col_index)
{
    return  DataObjects2D[row_index].at(col_index);
}

int ObjectMatrix::getObjectCount()
{
    return objectCount;
}

std::vector<std::string> ObjectMatrix::getFeaturesTitle()
{
    return featureTitles;
}

int ObjectMatrix::getClassCount()
{
    int cCount = 0;
    if (!attributeStringClasses.empty())
        cCount = attributeStringClasses.size();
    return cCount;
}

void ObjectMatrix::addAtributes(std::vector<std::string> additionalAttributes)
{
    this->additionalAttributes = additionalAttributes;
}

bool ObjectMatrix::getIsClassPresent()
{
    return this->isClassPresent;
}

void ObjectMatrix::setIsClassPresent()
{
    this->isClassPresent = true;
}

std::vector <std::string> ObjectMatrix::getStringClassAttributes()
{
    return this->attributeStringClasses;
}

void ObjectMatrix::loadDataMatrix()
{
    const char* path = fileName.c_str();
    ARFF file(path);

    ObjectMatrix::_weight = 0;

    if (file.isSuccessfullyRead() == true)   // successful read
    {
        std::vector< std::vector<double>> data = file.getData();
        //featureTitles = file.getAttributes();
        if (file.isClassFound())
           {
                objClasses = file.getIntClass();
                attributeStringClasses = file.getAttributeStringClasses();
                //isClassPresent = true;
               // std::cout << attributeStringClasses.size();
           }

        std::vector< std::vector<double>> ::iterator dataObjectIterator;

        std::vector<double>::iterator featureIterator;
        std::vector<double> dataObjectItems;
        int indx = 0;
        for(dataObjectIterator = data.begin(); dataObjectIterator!=data.end(); ++dataObjectIterator)
        {
            for(featureIterator = (*dataObjectIterator).begin(); featureIterator!=(*dataObjectIterator).end(); ++featureIterator)
                dataObjectItems.push_back(*featureIterator);

            if (file.isClassFound())
                {
                    DataObject tmp(dataObjectItems, file.getObjectClass(indx));
                    DataObjects.push_back(tmp);
                 //   std::cout << DataObjects.at(indx).getClassLabel() <<std::endl;
                }
            else
                {
                    DataObject tmp(dataObjectItems);
                    DataObjects.push_back(tmp);
                    //   std::cout << DataObjects.at(indx).getClassLabel() <<std::endl;
                }
            dataObjectItems.clear();
            indx++;
        }
        objectCount = DataObjects.size();

        //Calculate matrix X distances between vectors

        //ObjectMatrix::_weight = 0;
        int i, j, z;
        int n =  data.at(0).size(); //features
        double diff, sRow, tmpVal;

      //  FILE *distFile;
        if (AdditionalMethods::PID == 0) // semaphore to sync distance matrix write
            AdditionalMethods::distFile = fopen(AdditionalMethods::tempFileSavePath, "wb");

        for (i = 0; i < objectCount - 1; i++)
        {
            for (j = i + 1; j < objectCount; j++)
            {
                sRow = 0.0;
                for (z = 0; z < n; z++)
                {
                    diff  = data.at(i).at(z) - data.at(j).at(z);
                    sRow += diff * diff;
                }
                if (AdditionalMethods::PID == 0)
                   {
                        tmpVal = std::sqrt(sRow);
                        fwrite(&tmpVal, sizeof(double), 1, AdditionalMethods::distFile);
                   }
                ObjectMatrix::_weight += sRow;
            }
        }
        //implementation of waait for other processes while PID finishes distance file writing
        if (AdditionalMethods::PID == 0)
       //     {
                fclose(AdditionalMethods::distFile);
         //       AdditionalMethods::distFileCreated = 1;
         //   }
       /* else
            {
                while (AdditionalMethods::distFileCreated != 1)
                    system("sleep 1");
            }*/

        // end distance matrix calculation
       // std::cout<<  std::endl << AdditionalMethods::PID << std::endl;
    }
    else
    {
        //_weight = 0;
        objectCount = 0;
    }

     MPI_Barrier(MPI_COMM_WORLD);
     if(objectCount == 0)
     {
         std::cout << "No data in input file. Terminating"<< std::endl;
         MPI_Finalize();
         exit(1);
     }
}
void ObjectMatrix::addComment(std::string comnt)
{
    if (this->comments.empty())
        comments.reserve(0);
    comments.push_back(comnt);
}

void ObjectMatrix::saveDataMatrix(const char* path)
{
    ARFF file;
  //  std::vector <std::string> classLabels; classLabels.reserve(0);
   // std::vector <std::string> comment
    //std::vector <int> tmp; // assume v has the elements
    /*if (getPrintClass())
    {
       /*for (int i = 0; i < DataObjects.size(); i++) //pass only unique class labels that will be printed in @Attribute Class section
        {
            bool notFound = true;
            int tmpLabel = DataObjects.at(i).getClassLabel();
            for (int j = 0; j < classLabels.size(); j++)
                if (tmpLabel == classLabels.at(j))
                {
                    notFound = false;
                    break;
                }
            if (notFound)*/
          //  for (int j = 0; j < classLabels.size(); j++)
              //  classLabels.push_back(tmpLabel);
              //  classLabels = attributeStringClasses;
        //}
       // classLabels = attributeClasses;

    std::vector <std::string> attributeLabels; attributeLabels.reserve(0);

    if (!additionalAttributes.empty())
    {
        for (int i = 0; i < getObjectAt(0).getFeatureCount() - additionalAttributes.size(); i++)
            attributeLabels.push_back("atr" + std::to_string(static_cast<long long>(i+1)) + " REAL");

        for (int i = 0; i < additionalAttributes.size(); i++)
            {
            attributeLabels.push_back(additionalAttributes.at(i) + " REAL");
           // std::cout << attributeStringClasses.at(i);
            }
    }
    else
    {
        for (int i = 0; i < getObjectAt(0).getFeatureCount(); i++)
            attributeLabels.push_back("atr" + std::to_string(static_cast<long long>(i+1)) + " REAL");
    }
    file.writeData(path, this->comments, this->DataObjects, attributeStringClasses, attributeLabels);
}

void ObjectMatrix::clearDataObjects()
{
    DataObjects.clear();
    objectCount = 0;
}
/*void ObjectMatrix::assignStringClassesAttribute(ObjectMatrix X)
{
    this->attributeStringClasses = X.attributeStringClasses;
}*/

/*double ObjectMatrix::getDistanceBetween(int i, int j)
{
   FILE *distFile;
   distFile = fopen("D:\\dist.txt", "rb");
//   std::ifstream distFile;
//    distFile.open("D:\\dist.txt", std::ios::binary);
   double retVal;
   int noOfBytes = sizeof(double);

   fseek(distFile, (noOfBytes * i) + noOfBytes * (j - i - 1), SEEK_SET);
 //  fseek(distFile, 1, SEEK_SET);
   fread(&retVal, noOfBytes, 1, distFile);
 //  distFile>>retVal;

  // std::cout << retVal << std::endl;
   fclose(distFile);
// distFile.close();
   return retVal;
   //return *(*(distances + i) + j - i - 1);
}*/

double ObjectMatrix::getWeight()
{
    return ObjectMatrix::_weight;
}
<|endoftext|>


<commit_before>e// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/login/screen_lock_view.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/login/helper.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/login/user_view.h"
#include "chrome/browser/chromeos/login/username_view.h"
#include "chrome/browser/chromeos/login/wizard_accessibility_helper.h"
#include "chrome/browser/chromeos/login/textfield_with_margin.h"
#include "chrome/browser/chromeos/views/copy_background.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/common/notification_service.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/background.h"
#include "views/border.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/grid_layout.h"

namespace chromeos {

namespace {

const int kCornerRadius = 5;

// A Textfield for password, which also sets focus to itself
// when a mouse is clicked on it. This is necessary in screen locker
// as mouse events are grabbed in the screen locker.
class PasswordField : public TextfieldWithMargin {
 public:
  PasswordField()
      : TextfieldWithMargin(views::Textfield::STYLE_PASSWORD) {
    set_text_to_display_when_empty(
        l10n_util::GetStringUTF16(IDS_LOGIN_EMPTY_PASSWORD_TEXT));
  }

  // views::View overrides.
  virtual bool OnMousePressed(const views::MouseEvent& e) {
    RequestFocus();
    return false;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(PasswordField);
};

}  // namespace

using views::GridLayout;
using login::kBorderSize;

ScreenLockView::ScreenLockView(ScreenLocker* screen_locker)
    : user_view_(NULL),
      password_field_(NULL),
      screen_locker_(screen_locker),
      main_(NULL),
      username_(NULL) {
  DCHECK(screen_locker_);
}

gfx::Size ScreenLockView::GetPreferredSize() {
  return main_->GetPreferredSize();
}

void ScreenLockView::Layout() {
  int username_height = login::kSelectedLabelHeight;
  main_->SetBounds(0, 0, width(), height());
  username_->SetBounds(
      kBorderSize,
      login::kUserImageSize - username_height + kBorderSize,
      login::kUserImageSize,
      username_height);
}

void ScreenLockView::Init() {
  registrar_.Add(this,
                 NotificationType::LOGIN_USER_IMAGE_CHANGED,
                 NotificationService::AllSources());

  user_view_ = new UserView(this,
                            false,  // is_login
                            true);  // need_background
  main_ = new views::View();
  // Use rounded rect background.
  views::Painter* painter =
      CreateWizardPainter(&BorderDefinition::kUserBorder);

  main_->set_background(
      views::Background::CreateBackgroundPainter(true, painter));
  main_->set_border(CreateWizardBorder(&BorderDefinition::kUserBorder));

  // Password field.
  password_field_ = new PasswordField();
  password_field_->SetController(this);
  password_field_->set_background(new CopyBackground(main_));

  // User icon.
  UserManager::User user = screen_locker_->user();
  user_view_->SetImage(user.image());

  // User name.
  std::wstring text = UTF8ToWide(user.GetDisplayName());

  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
  const gfx::Font& font = rb.GetFont(ResourceBundle::MediumBoldFont);

  // Layouts image, textfield and button components.
  GridLayout* layout = new GridLayout(main_);
  main_->SetLayoutManager(layout);
  views::ColumnSet* column_set = layout->AddColumnSet(0);
  column_set->AddPaddingColumn(0, kBorderSize);
  column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, kBorderSize);

  column_set = layout->AddColumnSet(1);
  column_set->AddPaddingColumn(0, 5);
  column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, 5);

  layout->AddPaddingRow(0, kBorderSize);
  layout->StartRow(0, 0);
  layout->AddView(user_view_);
  layout->AddPaddingRow(0, kBorderSize);
  layout->StartRow(0, 1);
  layout->AddView(password_field_);
  layout->AddPaddingRow(0, kBorderSize);

  AddChildView(main_);

  UsernameView* username = new UsernameView(text);
  username_ = username;
  username->SetColor(login::kTextColor);
  username->SetFont(font);
  AddChildView(username);
}

void ScreenLockView::ClearAndSetFocusToPassword() {
  password_field_->RequestFocus();
  password_field_->SetText(string16());
}

void ScreenLockView::SetSignoutEnabled(bool enabled) {
  user_view_->SetSignoutEnabled(enabled);
}

gfx::Rect ScreenLockView::GetPasswordBoundsRelativeTo(const views::View* view) {
  gfx::Point p;
  views::View::ConvertPointToView(password_field_, view, &p);
  return gfx::Rect(p, size());
}

void ScreenLockView::SetEnabled(bool enabled) {
  views::View::SetEnabled(enabled);

  if (!enabled) {
    user_view_->StartThrobber();
    // TODO(oshima): Re-enabling does not move the focus to the view
    // that had a focus (issue http://crbug.com/43131).
    // Clear focus on the textfield so that re-enabling can set focus
    // back to the text field.
    // FocusManager may be null if the view does not have
    // associated Widget yet.
    if (password_field_->GetFocusManager())
      password_field_->GetFocusManager()->ClearFocus();
  } else {
    user_view_->StopThrobber();
  }
  password_field_->SetEnabled(enabled);
}

void ScreenLockView::OnSignout() {
  screen_locker_->Signout();
}

bool ScreenLockView::HandleKeystroke(
    views::Textfield* sender,
    const views::Textfield::Keystroke& keystroke) {
  screen_locker_->ClearErrors();
  if (keystroke.GetKeyboardCode() == app::VKEY_RETURN) {
    screen_locker_->Authenticate(password_field_->text());
    return true;
  }
  return false;
}

void ScreenLockView::Observe(
    NotificationType type,
    const NotificationSource& source,
    const NotificationDetails& details) {
  if (type != NotificationType::LOGIN_USER_IMAGE_CHANGED || !user_view_)
    return;

  UserManager::User* user = Details<UserManager::User>(details).ptr();
  if (screen_locker_->user().email() != user->email())
    return;
  user_view_->SetImage(user->image());
}

void ScreenLockView::ViewHierarchyChanged(bool is_add,
                                          views::View* parent,
                                          views::View* child) {
  if (is_add && this == child)
    WizardAccessibilityHelper::GetInstance()->MaybeEnableAccessibility(this);
}
}  // namespace chromeos
<commit_msg>Removed a character that has been added by mistake when merging.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/login/screen_lock_view.h"

#include "app/l10n_util.h"
#include "app/resource_bundle.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/chromeos/login/helper.h"
#include "chrome/browser/chromeos/login/rounded_rect_painter.h"
#include "chrome/browser/chromeos/login/screen_locker.h"
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/login/user_view.h"
#include "chrome/browser/chromeos/login/username_view.h"
#include "chrome/browser/chromeos/login/wizard_accessibility_helper.h"
#include "chrome/browser/chromeos/login/textfield_with_margin.h"
#include "chrome/browser/chromeos/views/copy_background.h"
#include "chrome/browser/profile_manager.h"
#include "chrome/common/notification_service.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "views/background.h"
#include "views/border.h"
#include "views/controls/image_view.h"
#include "views/controls/label.h"
#include "views/grid_layout.h"

namespace chromeos {

namespace {

const int kCornerRadius = 5;

// A Textfield for password, which also sets focus to itself
// when a mouse is clicked on it. This is necessary in screen locker
// as mouse events are grabbed in the screen locker.
class PasswordField : public TextfieldWithMargin {
 public:
  PasswordField()
      : TextfieldWithMargin(views::Textfield::STYLE_PASSWORD) {
    set_text_to_display_when_empty(
        l10n_util::GetStringUTF16(IDS_LOGIN_EMPTY_PASSWORD_TEXT));
  }

  // views::View overrides.
  virtual bool OnMousePressed(const views::MouseEvent& e) {
    RequestFocus();
    return false;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(PasswordField);
};

}  // namespace

using views::GridLayout;
using login::kBorderSize;

ScreenLockView::ScreenLockView(ScreenLocker* screen_locker)
    : user_view_(NULL),
      password_field_(NULL),
      screen_locker_(screen_locker),
      main_(NULL),
      username_(NULL) {
  DCHECK(screen_locker_);
}

gfx::Size ScreenLockView::GetPreferredSize() {
  return main_->GetPreferredSize();
}

void ScreenLockView::Layout() {
  int username_height = login::kSelectedLabelHeight;
  main_->SetBounds(0, 0, width(), height());
  username_->SetBounds(
      kBorderSize,
      login::kUserImageSize - username_height + kBorderSize,
      login::kUserImageSize,
      username_height);
}

void ScreenLockView::Init() {
  registrar_.Add(this,
                 NotificationType::LOGIN_USER_IMAGE_CHANGED,
                 NotificationService::AllSources());

  user_view_ = new UserView(this,
                            false,  // is_login
                            true);  // need_background
  main_ = new views::View();
  // Use rounded rect background.
  views::Painter* painter =
      CreateWizardPainter(&BorderDefinition::kUserBorder);

  main_->set_background(
      views::Background::CreateBackgroundPainter(true, painter));
  main_->set_border(CreateWizardBorder(&BorderDefinition::kUserBorder));

  // Password field.
  password_field_ = new PasswordField();
  password_field_->SetController(this);
  password_field_->set_background(new CopyBackground(main_));

  // User icon.
  UserManager::User user = screen_locker_->user();
  user_view_->SetImage(user.image());

  // User name.
  std::wstring text = UTF8ToWide(user.GetDisplayName());

  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
  const gfx::Font& font = rb.GetFont(ResourceBundle::MediumBoldFont);

  // Layouts image, textfield and button components.
  GridLayout* layout = new GridLayout(main_);
  main_->SetLayoutManager(layout);
  views::ColumnSet* column_set = layout->AddColumnSet(0);
  column_set->AddPaddingColumn(0, kBorderSize);
  column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, kBorderSize);

  column_set = layout->AddColumnSet(1);
  column_set->AddPaddingColumn(0, 5);
  column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1,
                        GridLayout::USE_PREF, 0, 0);
  column_set->AddPaddingColumn(0, 5);

  layout->AddPaddingRow(0, kBorderSize);
  layout->StartRow(0, 0);
  layout->AddView(user_view_);
  layout->AddPaddingRow(0, kBorderSize);
  layout->StartRow(0, 1);
  layout->AddView(password_field_);
  layout->AddPaddingRow(0, kBorderSize);

  AddChildView(main_);

  UsernameView* username = new UsernameView(text);
  username_ = username;
  username->SetColor(login::kTextColor);
  username->SetFont(font);
  AddChildView(username);
}

void ScreenLockView::ClearAndSetFocusToPassword() {
  password_field_->RequestFocus();
  password_field_->SetText(string16());
}

void ScreenLockView::SetSignoutEnabled(bool enabled) {
  user_view_->SetSignoutEnabled(enabled);
}

gfx::Rect ScreenLockView::GetPasswordBoundsRelativeTo(const views::View* view) {
  gfx::Point p;
  views::View::ConvertPointToView(password_field_, view, &p);
  return gfx::Rect(p, size());
}

void ScreenLockView::SetEnabled(bool enabled) {
  views::View::SetEnabled(enabled);

  if (!enabled) {
    user_view_->StartThrobber();
    // TODO(oshima): Re-enabling does not move the focus to the view
    // that had a focus (issue http://crbug.com/43131).
    // Clear focus on the textfield so that re-enabling can set focus
    // back to the text field.
    // FocusManager may be null if the view does not have
    // associated Widget yet.
    if (password_field_->GetFocusManager())
      password_field_->GetFocusManager()->ClearFocus();
  } else {
    user_view_->StopThrobber();
  }
  password_field_->SetEnabled(enabled);
}

void ScreenLockView::OnSignout() {
  screen_locker_->Signout();
}

bool ScreenLockView::HandleKeystroke(
    views::Textfield* sender,
    const views::Textfield::Keystroke& keystroke) {
  screen_locker_->ClearErrors();
  if (keystroke.GetKeyboardCode() == app::VKEY_RETURN) {
    screen_locker_->Authenticate(password_field_->text());
    return true;
  }
  return false;
}

void ScreenLockView::Observe(
    NotificationType type,
    const NotificationSource& source,
    const NotificationDetails& details) {
  if (type != NotificationType::LOGIN_USER_IMAGE_CHANGED || !user_view_)
    return;

  UserManager::User* user = Details<UserManager::User>(details).ptr();
  if (screen_locker_->user().email() != user->email())
    return;
  user_view_->SetImage(user->image());
}

void ScreenLockView::ViewHierarchyChanged(bool is_add,
                                          views::View* parent,
                                          views::View* child) {
  if (is_add && this == child)
    WizardAccessibilityHelper::GetInstance()->MaybeEnableAccessibility(this);
}
}  // namespace chromeos
<|endoftext|>