<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2013-2020 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <inviwo/core/datastructures/histogram.h>
#include <inviwo/core/properties/tfpropertyconcept.h>
#include <modules/qtwidgets/tf/tfeditorview.h>
#include <modules/qtwidgets/tf/tfpropertydialog.h>
#include <modules/qtwidgets/tf/tfeditorcontrolpoint.h>
#include <modules/qtwidgets/tf/tfeditor.h>
#include <inviwo/core/datastructures/volume/volumeram.h>

#include <warn/push>
#include <warn/ignore/all>
#include <QVarLengthArray>
#include <QGraphicsItem>
#include <QtEvents>
#include <QGraphicsScene>
#include <QPainter>
#include <QBrush>
#include <QWheelEvent>
#include <warn/pop>

namespace inviwo {

TFEditorView::TFEditorView(util::TFPropertyConcept* tfProperty, QGraphicsScene* scene,
                           QWidget* parent)
    : QGraphicsView(scene, parent)
    , tfPropertyPtr_(tfProperty)
    , volumeInport_(tfProperty->getVolumeInport())
    , histogramMode_(tfProperty->getHistogramMode())
    , maskHorizontal_(0.0, 1.0) {

    setMouseTracking(true);
    setRenderHint(QPainter::Antialiasing, true);
    setViewportUpdateMode(QGraphicsView::SmartViewportUpdate);

    this->setCacheMode(QGraphicsView::CacheBackground);

    tfPropertyPtr_->addObserver(this);

    if (volumeInport_) {
        const auto portChange = [this]() { updateHistogram(); };
        callbackOnChange = volumeInport_->onChangeScoped(portChange);
        callbackOnConnect = volumeInport_->onConnectScoped(portChange);
        callbackOnDisconnect = volumeInport_->onDisconnectScoped(portChange);
    }
    updateHistogram();
}

TFEditorView::~TFEditorView() = default;

void TFEditorView::onMaskChange(const dvec2& mask) {
    if (maskHorizontal_ != mask) {
        maskHorizontal_ = mask;
        update();
    }
}

void TFEditorView::onZoomHChange(const dvec2&) { updateZoom(); }

void TFEditorView::onZoomVChange(const dvec2&) { updateZoom(); }

void TFEditorView::onHistogramModeChange(HistogramMode mode) {
    if (histogramMode_ != mode) {
        histogramMode_ = mode;
        updateHistogram();
    }
}

void TFEditorView::wheelEvent(QWheelEvent* event) {
    const QPointF numPixels = event->pixelDelta() / 5.0;
    const QPointF numDegrees = event->angleDelta() / 8.0 / 15;

    const dvec2 scrollStep(0.2, 0.2);

    dvec2 delta;
    if (!numPixels.isNull()) {
        delta = dvec2(numPixels.x(), numPixels.y());
    } else if (!numDegrees.isNull()) {
        delta = dvec2(numDegrees.x(), numDegrees.y());
    } else {
        return;
    }

    NetworkLock lock(tfPropertyPtr_->getProperty());

    if (event->modifiers() == Qt::ControlModifier) {
        // zoom only horizontally relative to wheel event position
        double zoomFactor = std::pow(1.05, std::max(-15.0, std::min(15.0, -delta.y)));

        dvec2 horizontal = tfPropertyPtr_->getZoomH();
        double zoomExtent = horizontal.y - horizontal.x;

        // off-center zooming
        // relative position within current zoom range
        auto zoomCenter = event->posF().x() / width() * zoomExtent + horizontal.x;

        double lower = zoomCenter + (horizontal.x - zoomCenter) * zoomFactor;
        double upper = zoomCenter + (horizontal.y - zoomCenter) * zoomFactor;

        tfPropertyPtr_->setZoomH(std::max(0.0, lower), std::min(1.0, upper));
    } else {
        // vertical scrolling (+ optional horizontal if two-axis wheel)

        if (event->modifiers() & Qt::ShiftModifier) {
            // horizontal scrolling: map vertical wheel movement to horizontal direction
            delta.x = -delta.y;
            delta.y = 0.0;
        }

        dvec2 horizontal = tfPropertyPtr_->getZoomH();
        dvec2 vertical = tfPropertyPtr_->getZoomV();
        dvec2 extent(horizontal.y - horizontal.x, vertical.y - vertical.x);
        // scale scroll step with current zoom range
        delta *= scrollStep * extent;

        // separate horizontal and vertical scrolling
        if (delta.x < 0.0) {
            horizontal.x = std::max(0.0, horizontal.x + delta.x);
            horizontal.y = horizontal.x + extent.x;
        } else if (delta.x > 0.0) {
            horizontal.y = std::min(1.0, horizontal.y + delta.x);
            horizontal.x = horizontal.y - extent.x;
        }
        // vertical
        if (delta.y < 0.0) {
            vertical.x = std::max(0.0, vertical.x + delta.y);
            vertical.y = vertical.x + extent.y;
        } else if (delta.y > 0.0) {
            vertical.y = std::min(1.0, vertical.y + delta.y);
            vertical.x = vertical.y - extent.y;
        }

        tfPropertyPtr_->setZoomH(horizontal.x, horizontal.y);
        tfPropertyPtr_->setZoomV(vertical.x, vertical.y);
    }

    event->accept();
}

void TFEditorView::resizeEvent(QResizeEvent* event) {
    QGraphicsView::resizeEvent(event);
    resetCachedContent();
    updateZoom();
}

void TFEditorView::drawForeground(QPainter* painter, const QRectF& rect) {
    QPen pen;
    pen.setCosmetic(true);
    pen.setWidthF(1.5);
    pen.setColor(Qt::lightGray);
    painter->setPen(pen);

    QRectF sRect = sceneRect();

    if (maskHorizontal_.x > 0.0) {
        double leftMaskBorder = maskHorizontal_.x * sRect.width();
        QRectF r(0.0, rect.top(), leftMaskBorder, rect.height());
        QLineF line(leftMaskBorder, rect.top(), leftMaskBorder, rect.bottom());
        painter->fillRect(r, QColor(25, 25, 25, 100));
        painter->drawLine(line);
    }

    if (maskHorizontal_.y < 1.0) {
        double rightMaskBorder = maskHorizontal_.y * sRect.width();
        QRectF r(rightMaskBorder, rect.top(), sRect.right() - rightMaskBorder, rect.height());
        QLineF line(rightMaskBorder, rect.top(), rightMaskBorder, rect.bottom());
        painter->fillRect(r, QColor(25, 25, 25, 100));
        painter->drawLine(line);
    }

    QGraphicsView::drawForeground(painter, rect);
}

void TFEditorView::updateHistogram(const HistogramContainer& histCont) {
    histograms_.clear();
    if (histCont.empty()) return;

    const auto sRect = sceneRect();

    for (size_t channel = 0; channel < histCont.size(); ++channel) {
        const auto& normHistogramData = histCont[channel].getData();
        const auto stepSize = sRect.width() / normHistogramData.size();

        histograms_.push_back(QPolygonF());
        double scale = 1.0;
        switch (histogramMode_) {
            case HistogramMode::Off:  // Don't show
                return;
            case HistogramMode::All:  // show all
                scale = 1.0;
                break;
            case HistogramMode::P99:  // show 99%
                scale = histCont[channel].histStats_.percentiles[99];
                break;
            case HistogramMode::P95:  // show 95%
                scale = histCont[channel].histStats_.percentiles[95];
                break;
            case HistogramMode::P90:  // show 90%
                scale = histCont[channel].histStats_.percentiles[90];
                break;
            case HistogramMode::Log:  // show log%
                scale = 1.0;
                break;
        }
        double height;
        double maxCount = histCont[channel].getMaximumBinValue();

        histograms_.back() << QPointF(0.0, 0.0);

        for (size_t i = 0; i < normHistogramData.size(); i++) {
            if (histogramMode_ == HistogramMode::Log) {
                height = std::log10(1.0 + maxCount * normHistogramData[i]) / std::log10(maxCount);

            } else {
                height = normHistogramData[i] / scale;
                height = std::min(height, 1.0);
            }
            height *= sRect.height();
            histograms_.back() << QPointF(i * stepSize, height)
                               << QPointF((i + 1) * stepSize, height);
        }
        histograms_.back() << QPointF(sRect.width(), 0.0f) << QPointF(0.0f, 0.0f);
    }
}

void TFEditorView::updateHistogram() {
    if (histogramMode_ != HistogramMode::Off && volumeInport_ && volumeInport_->isReady()) {
        if (auto volume = volumeInport_->getData()) {
            if (volume->hasHistograms()) {
                updateHistogram(volume->getHistograms());
            } else if (!histCalculation_) {
                histograms_.clear();
                histCalculation_ = volume->calculateHistograms(2048);
                histCalculation_->whenDone([this](const HistogramContainer& histograms) {
                    updateHistogram(histograms);
                    resetCachedContent();
                    update();
                    histCalculation_.reset();
                });
            }
        } else {
            histograms_.clear();
        }
    } else {
        histograms_.clear();
    }
    resetCachedContent();
    update();
}

void TFEditorView::drawBackground(QPainter* painter, const QRectF& rect) {
    painter->fillRect(rect, QColor(89, 89, 89));

    // overlay grid
    const QColor colorGrid(102, 102, 102);
    const QColor colorOrigin(102, 106, 115);
    const int gridSpacing = 50;

    QRectF sRect = sceneRect();
    QPen gridPen;
    gridPen.setCosmetic(true);

    double gridOrigin = sRect.left();  // horizontal origin of the grid
    // adjust grid origin if there is a data mapper available
    if (volumeInport_ && volumeInport_->hasData()) {
        auto& datamap = volumeInport_->getData()->dataMap_;
        if ((datamap.valueRange.x < 0.0) && (datamap.valueRange.y > 0.0)) {
            gridOrigin = datamap.mapFromValueToNormalized(0.0) * sRect.width() + sRect.left();

            // draw line at zero
            gridPen.setWidthF(3.0f);
            gridPen.setColor(colorOrigin);
            painter->setPen(gridPen);
            painter->drawLine(
                QLineF(QPointF(gridOrigin, sRect.bottom()), QPointF(gridOrigin, sRect.top())));
        }
    }

    QVector<QLineF> lines;

    // add grid lines left of origin
    double x = gridOrigin - gridSpacing;
    while (x > sRect.left()) {
        lines.push_back(QLineF(x, sRect.bottom(), x, sRect.top()));
        x -= gridSpacing;
    }
    // add grid lines right of origin
    x = gridOrigin + gridSpacing;
    while (x < sRect.right()) {
        lines.push_back(QLineF(x, sRect.bottom(), x, sRect.top()));
        x += gridSpacing;
    }

    // draw grid
    gridPen.setColor(colorGrid);
    gridPen.setWidthF(1.0);
    painter->setPen(gridPen);
    painter->drawLines(lines);

    // histogram
    if (histCalculation_ && histogramMode_ != HistogramMode::Off) {
        painter->save();
        painter->resetTransform();

        QPen pen;
        pen.setColor(QColor(180, 180, 180, 255));
        painter->setPen(pen);
        auto font = painter->font();
        font.setPointSize(12);
        painter->setFont(font);
        painter->drawText(QRect(0, 0, width(), height()).adjusted(20, 10, -20, -10),
                          Qt::AlignRight | Qt::AlignTop, QString("Calculating histogram..."));
        painter->restore();
    }

    for (auto& elem : histograms_) {
        QPen pen;
        pen.setColor(QColor(68, 102, 170, 150));
        pen.setWidthF(2.0f);
        pen.setCosmetic(true);
        painter->setPen(pen);

        QBrush brush;
        brush.setColor(QColor(68, 102, 170, 100));
        brush.setStyle(Qt::SolidPattern);
        painter->setBrush(brush);

        painter->drawPolygon(elem);
    }
}

void TFEditorView::updateZoom() {
    const auto rect = scene()->sceneRect();
    const auto zh = tfPropertyPtr_->getZoomH();
    const auto zv = tfPropertyPtr_->getZoomV();
    fitInView(zh.x * rect.width(), zv.x * rect.height(), (zh.y - zh.x) * rect.width(),
              (zv.y - zv.x) * rect.height(), Qt::IgnoreAspectRatio);
}

}  // namespace inviwo
<commit_msg>QtWidgets: include fix<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2013-2020 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <inviwo/core/datastructures/histogram.h>
#include <modules/qtwidgets/tf/tfpropertyconcept.h>
#include <modules/qtwidgets/tf/tfeditorview.h>
#include <modules/qtwidgets/tf/tfpropertydialog.h>
#include <modules/qtwidgets/tf/tfeditorcontrolpoint.h>
#include <modules/qtwidgets/tf/tfeditor.h>
#include <inviwo/core/datastructures/volume/volumeram.h>

#include <warn/push>
#include <warn/ignore/all>
#include <QVarLengthArray>
#include <QGraphicsItem>
#include <QtEvents>
#include <QGraphicsScene>
#include <QPainter>
#include <QBrush>
#include <QWheelEvent>
#include <warn/pop>

namespace inviwo {

TFEditorView::TFEditorView(util::TFPropertyConcept* tfProperty, QGraphicsScene* scene,
                           QWidget* parent)
    : QGraphicsView(scene, parent)
    , tfPropertyPtr_(tfProperty)
    , volumeInport_(tfProperty->getVolumeInport())
    , histogramMode_(tfProperty->getHistogramMode())
    , maskHorizontal_(0.0, 1.0) {

    setMouseTracking(true);
    setRenderHint(QPainter::Antialiasing, true);
    setViewportUpdateMode(QGraphicsView::SmartViewportUpdate);

    this->setCacheMode(QGraphicsView::CacheBackground);

    tfPropertyPtr_->addObserver(this);

    if (volumeInport_) {
        const auto portChange = [this]() { updateHistogram(); };
        callbackOnChange = volumeInport_->onChangeScoped(portChange);
        callbackOnConnect = volumeInport_->onConnectScoped(portChange);
        callbackOnDisconnect = volumeInport_->onDisconnectScoped(portChange);
    }
    updateHistogram();
}

TFEditorView::~TFEditorView() = default;

void TFEditorView::onMaskChange(const dvec2& mask) {
    if (maskHorizontal_ != mask) {
        maskHorizontal_ = mask;
        update();
    }
}

void TFEditorView::onZoomHChange(const dvec2&) { updateZoom(); }

void TFEditorView::onZoomVChange(const dvec2&) { updateZoom(); }

void TFEditorView::onHistogramModeChange(HistogramMode mode) {
    if (histogramMode_ != mode) {
        histogramMode_ = mode;
        updateHistogram();
    }
}

void TFEditorView::wheelEvent(QWheelEvent* event) {
    const QPointF numPixels = event->pixelDelta() / 5.0;
    const QPointF numDegrees = event->angleDelta() / 8.0 / 15;

    const dvec2 scrollStep(0.2, 0.2);

    dvec2 delta;
    if (!numPixels.isNull()) {
        delta = dvec2(numPixels.x(), numPixels.y());
    } else if (!numDegrees.isNull()) {
        delta = dvec2(numDegrees.x(), numDegrees.y());
    } else {
        return;
    }

    NetworkLock lock(tfPropertyPtr_->getProperty());

    if (event->modifiers() == Qt::ControlModifier) {
        // zoom only horizontally relative to wheel event position
        double zoomFactor = std::pow(1.05, std::max(-15.0, std::min(15.0, -delta.y)));

        dvec2 horizontal = tfPropertyPtr_->getZoomH();
        double zoomExtent = horizontal.y - horizontal.x;

        // off-center zooming
        // relative position within current zoom range
        auto zoomCenter = event->posF().x() / width() * zoomExtent + horizontal.x;

        double lower = zoomCenter + (horizontal.x - zoomCenter) * zoomFactor;
        double upper = zoomCenter + (horizontal.y - zoomCenter) * zoomFactor;

        tfPropertyPtr_->setZoomH(std::max(0.0, lower), std::min(1.0, upper));
    } else {
        // vertical scrolling (+ optional horizontal if two-axis wheel)

        if (event->modifiers() & Qt::ShiftModifier) {
            // horizontal scrolling: map vertical wheel movement to horizontal direction
            delta.x = -delta.y;
            delta.y = 0.0;
        }

        dvec2 horizontal = tfPropertyPtr_->getZoomH();
        dvec2 vertical = tfPropertyPtr_->getZoomV();
        dvec2 extent(horizontal.y - horizontal.x, vertical.y - vertical.x);
        // scale scroll step with current zoom range
        delta *= scrollStep * extent;

        // separate horizontal and vertical scrolling
        if (delta.x < 0.0) {
            horizontal.x = std::max(0.0, horizontal.x + delta.x);
            horizontal.y = horizontal.x + extent.x;
        } else if (delta.x > 0.0) {
            horizontal.y = std::min(1.0, horizontal.y + delta.x);
            horizontal.x = horizontal.y - extent.x;
        }
        // vertical
        if (delta.y < 0.0) {
            vertical.x = std::max(0.0, vertical.x + delta.y);
            vertical.y = vertical.x + extent.y;
        } else if (delta.y > 0.0) {
            vertical.y = std::min(1.0, vertical.y + delta.y);
            vertical.x = vertical.y - extent.y;
        }

        tfPropertyPtr_->setZoomH(horizontal.x, horizontal.y);
        tfPropertyPtr_->setZoomV(vertical.x, vertical.y);
    }

    event->accept();
}

void TFEditorView::resizeEvent(QResizeEvent* event) {
    QGraphicsView::resizeEvent(event);
    resetCachedContent();
    updateZoom();
}

void TFEditorView::drawForeground(QPainter* painter, const QRectF& rect) {
    QPen pen;
    pen.setCosmetic(true);
    pen.setWidthF(1.5);
    pen.setColor(Qt::lightGray);
    painter->setPen(pen);

    QRectF sRect = sceneRect();

    if (maskHorizontal_.x > 0.0) {
        double leftMaskBorder = maskHorizontal_.x * sRect.width();
        QRectF r(0.0, rect.top(), leftMaskBorder, rect.height());
        QLineF line(leftMaskBorder, rect.top(), leftMaskBorder, rect.bottom());
        painter->fillRect(r, QColor(25, 25, 25, 100));
        painter->drawLine(line);
    }

    if (maskHorizontal_.y < 1.0) {
        double rightMaskBorder = maskHorizontal_.y * sRect.width();
        QRectF r(rightMaskBorder, rect.top(), sRect.right() - rightMaskBorder, rect.height());
        QLineF line(rightMaskBorder, rect.top(), rightMaskBorder, rect.bottom());
        painter->fillRect(r, QColor(25, 25, 25, 100));
        painter->drawLine(line);
    }

    QGraphicsView::drawForeground(painter, rect);
}

void TFEditorView::updateHistogram(const HistogramContainer& histCont) {
    histograms_.clear();
    if (histCont.empty()) return;

    const auto sRect = sceneRect();

    for (size_t channel = 0; channel < histCont.size(); ++channel) {
        const auto& normHistogramData = histCont[channel].getData();
        const auto stepSize = sRect.width() / normHistogramData.size();

        histograms_.push_back(QPolygonF());
        double scale = 1.0;
        switch (histogramMode_) {
            case HistogramMode::Off:  // Don't show
                return;
            case HistogramMode::All:  // show all
                scale = 1.0;
                break;
            case HistogramMode::P99:  // show 99%
                scale = histCont[channel].histStats_.percentiles[99];
                break;
            case HistogramMode::P95:  // show 95%
                scale = histCont[channel].histStats_.percentiles[95];
                break;
            case HistogramMode::P90:  // show 90%
                scale = histCont[channel].histStats_.percentiles[90];
                break;
            case HistogramMode::Log:  // show log%
                scale = 1.0;
                break;
        }
        double height;
        double maxCount = histCont[channel].getMaximumBinValue();

        histograms_.back() << QPointF(0.0, 0.0);

        for (size_t i = 0; i < normHistogramData.size(); i++) {
            if (histogramMode_ == HistogramMode::Log) {
                height = std::log10(1.0 + maxCount * normHistogramData[i]) / std::log10(maxCount);

            } else {
                height = normHistogramData[i] / scale;
                height = std::min(height, 1.0);
            }
            height *= sRect.height();
            histograms_.back() << QPointF(i * stepSize, height)
                               << QPointF((i + 1) * stepSize, height);
        }
        histograms_.back() << QPointF(sRect.width(), 0.0f) << QPointF(0.0f, 0.0f);
    }
}

void TFEditorView::updateHistogram() {
    if (histogramMode_ != HistogramMode::Off && volumeInport_ && volumeInport_->isReady()) {
        if (auto volume = volumeInport_->getData()) {
            if (volume->hasHistograms()) {
                updateHistogram(volume->getHistograms());
            } else if (!histCalculation_) {
                histograms_.clear();
                histCalculation_ = volume->calculateHistograms(2048);
                histCalculation_->whenDone([this](const HistogramContainer& histograms) {
                    updateHistogram(histograms);
                    resetCachedContent();
                    update();
                    histCalculation_.reset();
                });
            }
        } else {
            histograms_.clear();
        }
    } else {
        histograms_.clear();
    }
    resetCachedContent();
    update();
}

void TFEditorView::drawBackground(QPainter* painter, const QRectF& rect) {
    painter->fillRect(rect, QColor(89, 89, 89));

    // overlay grid
    const QColor colorGrid(102, 102, 102);
    const QColor colorOrigin(102, 106, 115);
    const int gridSpacing = 50;

    QRectF sRect = sceneRect();
    QPen gridPen;
    gridPen.setCosmetic(true);

    double gridOrigin = sRect.left();  // horizontal origin of the grid
    // adjust grid origin if there is a data mapper available
    if (volumeInport_ && volumeInport_->hasData()) {
        auto& datamap = volumeInport_->getData()->dataMap_;
        if ((datamap.valueRange.x < 0.0) && (datamap.valueRange.y > 0.0)) {
            gridOrigin = datamap.mapFromValueToNormalized(0.0) * sRect.width() + sRect.left();

            // draw line at zero
            gridPen.setWidthF(3.0f);
            gridPen.setColor(colorOrigin);
            painter->setPen(gridPen);
            painter->drawLine(
                QLineF(QPointF(gridOrigin, sRect.bottom()), QPointF(gridOrigin, sRect.top())));
        }
    }

    QVector<QLineF> lines;

    // add grid lines left of origin
    double x = gridOrigin - gridSpacing;
    while (x > sRect.left()) {
        lines.push_back(QLineF(x, sRect.bottom(), x, sRect.top()));
        x -= gridSpacing;
    }
    // add grid lines right of origin
    x = gridOrigin + gridSpacing;
    while (x < sRect.right()) {
        lines.push_back(QLineF(x, sRect.bottom(), x, sRect.top()));
        x += gridSpacing;
    }

    // draw grid
    gridPen.setColor(colorGrid);
    gridPen.setWidthF(1.0);
    painter->setPen(gridPen);
    painter->drawLines(lines);

    // histogram
    if (histCalculation_ && histogramMode_ != HistogramMode::Off) {
        painter->save();
        painter->resetTransform();

        QPen pen;
        pen.setColor(QColor(180, 180, 180, 255));
        painter->setPen(pen);
        auto font = painter->font();
        font.setPointSize(12);
        painter->setFont(font);
        painter->drawText(QRect(0, 0, width(), height()).adjusted(20, 10, -20, -10),
                          Qt::AlignRight | Qt::AlignTop, QString("Calculating histogram..."));
        painter->restore();
    }

    for (auto& elem : histograms_) {
        QPen pen;
        pen.setColor(QColor(68, 102, 170, 150));
        pen.setWidthF(2.0f);
        pen.setCosmetic(true);
        painter->setPen(pen);

        QBrush brush;
        brush.setColor(QColor(68, 102, 170, 100));
        brush.setStyle(Qt::SolidPattern);
        painter->setBrush(brush);

        painter->drawPolygon(elem);
    }
}

void TFEditorView::updateZoom() {
    const auto rect = scene()->sceneRect();
    const auto zh = tfPropertyPtr_->getZoomH();
    const auto zv = tfPropertyPtr_->getZoomV();
    fitInView(zh.x * rect.width(), zv.x * rect.height(), (zh.y - zh.x) * rect.width(),
              (zv.y - zv.x) * rect.height(), Qt::IgnoreAspectRatio);
}

}  // namespace inviwo
<|endoftext|>


<commit_before>// Copyright (c) 2011 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 "base/command_line.h"
#include "base/debug/trace_event.h"
#include "base/i18n/rtl.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/field_trial.h"
#include "base/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/metrics/stats_counters.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "base/system_monitor/system_monitor.h"
#include "base/threading/platform_thread.h"
#include "base/time.h"
#include "content/common/content_counters.h"
#include "content/common/hi_res_timer_manager.h"
#include "content/common/pepper_plugin_registry.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "content/public/renderer/content_renderer_client.h"
#include "content/renderer/render_process_impl.h"
#include "content/renderer/render_thread_impl.h"
#include "content/renderer/renderer_main_platform_delegate.h"
#include "ui/base/ui_base_switches.h"
#include "webkit/plugins/ppapi/ppapi_interface_factory.h"

#if defined(OS_MACOSX)
#include <Carbon/Carbon.h>
#include <signal.h>
#include <unistd.h>

#include "base/mac/mac_util.h"
#include "base/mac/scoped_nsautorelease_pool.h"
#include "third_party/mach_override/mach_override.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#endif  // OS_MACOSX

#if defined(OS_MACOSX)
namespace {

CFArrayRef ChromeTISCreateInputSourceList(
   CFDictionaryRef properties,
   Boolean includeAllInstalled) {
  CFTypeRef values[] = { CFSTR("") };
  return CFArrayCreate(
      kCFAllocatorDefault, values, arraysize(values), &kCFTypeArrayCallBacks);
}

void InstallFrameworkHacks() {
  // See http://crbug.com/31225
  // TODO: Don't do this on newer OS X revisions that have a fix for
  // http://openradar.appspot.com/radar?id=1156410
  if (base::mac::IsOSSnowLeopardOrLater()) {
    // Chinese Handwriting was introduced in 10.6. Since doing this override
    // regresses page cycler memory usage on 10.5, don't do the unnecessary
    // override there.
    mach_error_t err = mach_override_ptr(
        (void*)&TISCreateInputSourceList,
        (void*)&ChromeTISCreateInputSourceList,
        NULL);
    CHECK_EQ(err_none, err);
  }
}

}  // namespace
#endif  // OS_MACOSX

// This function provides some ways to test crash and assertion handling
// behavior of the renderer.
static void HandleRendererErrorTestParameters(const CommandLine& command_line) {
  // This parameter causes an assertion.
  if (command_line.HasSwitch(switches::kRendererAssertTest)) {
    DCHECK(false);
  }

#if !defined(OFFICIAL_BUILD)
  // This parameter causes an assertion too.
  if (command_line.HasSwitch(switches::kRendererCheckFalseTest)) {
    CHECK(false);
  }
#endif  // !defined(OFFICIAL_BUILD)

  // This parameter causes a null pointer crash (crash reporter trigger).
  if (command_line.HasSwitch(switches::kRendererCrashTest)) {
    int* bad_pointer = NULL;
    *bad_pointer = 0;
  }

  if (command_line.HasSwitch(switches::kRendererStartupDialog)) {
    ChildProcess::WaitForDebugger("Renderer");
  }
}

// This is a simplified version of the browser Jankometer, which measures
// the processing time of tasks on the render thread.
class RendererMessageLoopObserver : public MessageLoop::TaskObserver {
 public:
  RendererMessageLoopObserver()
      : process_times_(base::Histogram::FactoryGet(
            "Chrome.ProcMsgL RenderThread",
            1, 3600000, 50, base::Histogram::kUmaTargetedHistogramFlag)) {}
  virtual ~RendererMessageLoopObserver() {}

  virtual void WillProcessTask(base::TimeTicks time_posted) {
    begin_process_message_ = base::TimeTicks::Now();
  }

  virtual void DidProcessTask(base::TimeTicks time_posted) {
    if (!begin_process_message_.is_null())
      process_times_->AddTime(base::TimeTicks::Now() - begin_process_message_);
  }

 private:
  base::TimeTicks begin_process_message_;
  base::Histogram* const process_times_;
  DISALLOW_COPY_AND_ASSIGN(RendererMessageLoopObserver);
};

// mainline routine for running as the Renderer process
int RendererMain(const content::MainFunctionParams& parameters) {
  TRACE_EVENT_BEGIN_ETW("RendererMain", 0, "");

  const CommandLine& parsed_command_line = parameters.command_line;

#if defined(OS_MACOSX)
  base::mac::ScopedNSAutoreleasePool* pool = parameters.autorelease_pool;
  InstallFrameworkHacks();
#endif  // OS_MACOSX

#if defined(OS_CHROMEOS)
  // As Zygote process starts up earlier than browser process gets its own
  // locale (at login time for Chrome OS), we have to set the ICU default
  // locale for renderer process here.
  // ICU locale will be used for fallback font selection etc.
  if (parsed_command_line.HasSwitch(switches::kLang)) {
    const std::string locale =
        parsed_command_line.GetSwitchValueASCII(switches::kLang);
    base::i18n::SetICUDefaultLocale(locale);
  }
#endif

  // This function allows pausing execution using the --renderer-startup-dialog
  // flag allowing us to attach a debugger.
  // Do not move this function down since that would mean we can't easily debug
  // whatever occurs before it.
  HandleRendererErrorTestParameters(parsed_command_line);

  RendererMainPlatformDelegate platform(parameters);

  webkit::ppapi::PpapiInterfaceFactoryManager* factory_manager =
      webkit::ppapi::PpapiInterfaceFactoryManager::GetInstance();
  content::GetContentClient()->renderer()->RegisterPPAPIInterfaceFactories(
      factory_manager);

  base::StatsScope<base::StatsCounterTimer>
      startup_timer(content::Counters::renderer_main());

  RendererMessageLoopObserver task_observer;
#if defined(OS_MACOSX)
  // As long as we use Cocoa in the renderer (for the forseeable future as of
  // now; see http://crbug.com/13890 for info) we need to have a UI loop.
  MessageLoop main_message_loop(MessageLoop::TYPE_UI);
#else
  // The main message loop of the renderer services doesn't have IO or UI tasks,
  // unless in-process-plugins is used.
  MessageLoop main_message_loop(RenderProcessImpl::InProcessPlugins() ?
              MessageLoop::TYPE_UI : MessageLoop::TYPE_DEFAULT);
#endif
  main_message_loop.AddTaskObserver(&task_observer);

  base::PlatformThread::SetName("CrRendererMain");

  base::SystemMonitor system_monitor;
  HighResolutionTimerManager hi_res_timer_manager;

  platform.PlatformInitialize();

  bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox);
  platform.InitSandboxTests(no_sandbox);

  // Initialize histogram statistics gathering system.
  // Don't create StatisticsRecorder in the single process mode.
  scoped_ptr<base::StatisticsRecorder> statistics;
  if (!base::StatisticsRecorder::IsActive()) {
    statistics.reset(new base::StatisticsRecorder());
  }

  // Initialize statistical testing infrastructure.  We set client_id to the
  // empty string to disallow the renderer process from creating its own
  // one-time randomized trials; they should be created in the browser process.
  base::FieldTrialList field_trial(EmptyString());
  // Ensure any field trials in browser are reflected into renderer.
  if (parsed_command_line.HasSwitch(switches::kForceFieldTestNameAndValue)) {
    std::string persistent = parsed_command_line.GetSwitchValueASCII(
        switches::kForceFieldTestNameAndValue);
    bool ret = field_trial.CreateTrialsInChildProcess(persistent);
    DCHECK(ret);
  }

  // Load pepper plugins before engaging the sandbox.
  PepperPluginRegistry::GetInstance();

  {
#if defined(OS_WIN) || defined(OS_MACOSX)
    // TODO(markus): Check if it is OK to unconditionally move this
    // instruction down.
    RenderProcessImpl render_process;
    render_process.set_main_thread(new RenderThreadImpl());
#endif
    bool run_loop = true;
    if (!no_sandbox) {
      run_loop = platform.EnableSandbox();
    } else {
      LOG(ERROR) << "Running without renderer sandbox";
    }
#if defined(OS_POSIX) && !defined(OS_MACOSX)
    RenderProcessImpl render_process;
    render_process.set_main_thread(new RenderThreadImpl());
#endif

    platform.RunSandboxTests();

    startup_timer.Stop();  // End of Startup Time Measurement.

    if (run_loop) {
#if defined(OS_MACOSX)
      if (pool)
        pool->Recycle();
#endif
      TRACE_EVENT_BEGIN_ETW("RendererMain.START_MSG_LOOP", 0, 0);
      MessageLoop::current()->Run();
      TRACE_EVENT_END_ETW("RendererMain.START_MSG_LOOP", 0, 0);
    }
  }
  platform.PlatformUninitialize();
  TRACE_EVENT_END_ETW("RendererMain", 0, "");
  return 0;
}
<commit_msg>Obey --wait-for-debugger in the render process.<commit_after>// Copyright (c) 2011 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 "base/base_switches.h"
#include "base/command_line.h"
#include "base/debug/debugger.h"
#include "base/debug/trace_event.h"
#include "base/i18n/rtl.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/field_trial.h"
#include "base/message_loop.h"
#include "base/metrics/histogram.h"
#include "base/metrics/stats_counters.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "base/system_monitor/system_monitor.h"
#include "base/threading/platform_thread.h"
#include "base/time.h"
#include "content/common/content_counters.h"
#include "content/common/hi_res_timer_manager.h"
#include "content/common/pepper_plugin_registry.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "content/public/renderer/content_renderer_client.h"
#include "content/renderer/render_process_impl.h"
#include "content/renderer/render_thread_impl.h"
#include "content/renderer/renderer_main_platform_delegate.h"
#include "ui/base/ui_base_switches.h"
#include "webkit/plugins/ppapi/ppapi_interface_factory.h"

#if defined(OS_MACOSX)
#include <Carbon/Carbon.h>
#include <signal.h>
#include <unistd.h>

#include "base/mac/mac_util.h"
#include "base/mac/scoped_nsautorelease_pool.h"
#include "third_party/mach_override/mach_override.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebView.h"
#endif  // OS_MACOSX

#if defined(OS_MACOSX)
namespace {

CFArrayRef ChromeTISCreateInputSourceList(
   CFDictionaryRef properties,
   Boolean includeAllInstalled) {
  CFTypeRef values[] = { CFSTR("") };
  return CFArrayCreate(
      kCFAllocatorDefault, values, arraysize(values), &kCFTypeArrayCallBacks);
}

void InstallFrameworkHacks() {
  // See http://crbug.com/31225
  // TODO: Don't do this on newer OS X revisions that have a fix for
  // http://openradar.appspot.com/radar?id=1156410
  if (base::mac::IsOSSnowLeopardOrLater()) {
    // Chinese Handwriting was introduced in 10.6. Since doing this override
    // regresses page cycler memory usage on 10.5, don't do the unnecessary
    // override there.
    mach_error_t err = mach_override_ptr(
        (void*)&TISCreateInputSourceList,
        (void*)&ChromeTISCreateInputSourceList,
        NULL);
    CHECK_EQ(err_none, err);
  }
}

}  // namespace
#endif  // OS_MACOSX

// This function provides some ways to test crash and assertion handling
// behavior of the renderer.
static void HandleRendererErrorTestParameters(const CommandLine& command_line) {
  // This parameter causes an assertion.
  if (command_line.HasSwitch(switches::kRendererAssertTest)) {
    DCHECK(false);
  }

#if !defined(OFFICIAL_BUILD)
  // This parameter causes an assertion too.
  if (command_line.HasSwitch(switches::kRendererCheckFalseTest)) {
    CHECK(false);
  }
#endif  // !defined(OFFICIAL_BUILD)

  // This parameter causes a null pointer crash (crash reporter trigger).
  if (command_line.HasSwitch(switches::kRendererCrashTest)) {
    int* bad_pointer = NULL;
    *bad_pointer = 0;
  }

  if (command_line.HasSwitch(switches::kWaitForDebugger))
    base::debug::WaitForDebugger(60, true);

  if (command_line.HasSwitch(switches::kRendererStartupDialog))
    ChildProcess::WaitForDebugger("Renderer");
}

// This is a simplified version of the browser Jankometer, which measures
// the processing time of tasks on the render thread.
class RendererMessageLoopObserver : public MessageLoop::TaskObserver {
 public:
  RendererMessageLoopObserver()
      : process_times_(base::Histogram::FactoryGet(
            "Chrome.ProcMsgL RenderThread",
            1, 3600000, 50, base::Histogram::kUmaTargetedHistogramFlag)) {}
  virtual ~RendererMessageLoopObserver() {}

  virtual void WillProcessTask(base::TimeTicks time_posted) {
    begin_process_message_ = base::TimeTicks::Now();
  }

  virtual void DidProcessTask(base::TimeTicks time_posted) {
    if (!begin_process_message_.is_null())
      process_times_->AddTime(base::TimeTicks::Now() - begin_process_message_);
  }

 private:
  base::TimeTicks begin_process_message_;
  base::Histogram* const process_times_;
  DISALLOW_COPY_AND_ASSIGN(RendererMessageLoopObserver);
};

// mainline routine for running as the Renderer process
int RendererMain(const content::MainFunctionParams& parameters) {
  TRACE_EVENT_BEGIN_ETW("RendererMain", 0, "");

  const CommandLine& parsed_command_line = parameters.command_line;

#if defined(OS_MACOSX)
  base::mac::ScopedNSAutoreleasePool* pool = parameters.autorelease_pool;
  InstallFrameworkHacks();
#endif  // OS_MACOSX

#if defined(OS_CHROMEOS)
  // As Zygote process starts up earlier than browser process gets its own
  // locale (at login time for Chrome OS), we have to set the ICU default
  // locale for renderer process here.
  // ICU locale will be used for fallback font selection etc.
  if (parsed_command_line.HasSwitch(switches::kLang)) {
    const std::string locale =
        parsed_command_line.GetSwitchValueASCII(switches::kLang);
    base::i18n::SetICUDefaultLocale(locale);
  }
#endif

  // This function allows pausing execution using the --renderer-startup-dialog
  // flag allowing us to attach a debugger.
  // Do not move this function down since that would mean we can't easily debug
  // whatever occurs before it.
  HandleRendererErrorTestParameters(parsed_command_line);

  RendererMainPlatformDelegate platform(parameters);

  webkit::ppapi::PpapiInterfaceFactoryManager* factory_manager =
      webkit::ppapi::PpapiInterfaceFactoryManager::GetInstance();
  content::GetContentClient()->renderer()->RegisterPPAPIInterfaceFactories(
      factory_manager);

  base::StatsScope<base::StatsCounterTimer>
      startup_timer(content::Counters::renderer_main());

  RendererMessageLoopObserver task_observer;
#if defined(OS_MACOSX)
  // As long as we use Cocoa in the renderer (for the forseeable future as of
  // now; see http://crbug.com/13890 for info) we need to have a UI loop.
  MessageLoop main_message_loop(MessageLoop::TYPE_UI);
#else
  // The main message loop of the renderer services doesn't have IO or UI tasks,
  // unless in-process-plugins is used.
  MessageLoop main_message_loop(RenderProcessImpl::InProcessPlugins() ?
              MessageLoop::TYPE_UI : MessageLoop::TYPE_DEFAULT);
#endif
  main_message_loop.AddTaskObserver(&task_observer);

  base::PlatformThread::SetName("CrRendererMain");

  base::SystemMonitor system_monitor;
  HighResolutionTimerManager hi_res_timer_manager;

  platform.PlatformInitialize();

  bool no_sandbox = parsed_command_line.HasSwitch(switches::kNoSandbox);
  platform.InitSandboxTests(no_sandbox);

  // Initialize histogram statistics gathering system.
  // Don't create StatisticsRecorder in the single process mode.
  scoped_ptr<base::StatisticsRecorder> statistics;
  if (!base::StatisticsRecorder::IsActive()) {
    statistics.reset(new base::StatisticsRecorder());
  }

  // Initialize statistical testing infrastructure.  We set client_id to the
  // empty string to disallow the renderer process from creating its own
  // one-time randomized trials; they should be created in the browser process.
  base::FieldTrialList field_trial(EmptyString());
  // Ensure any field trials in browser are reflected into renderer.
  if (parsed_command_line.HasSwitch(switches::kForceFieldTestNameAndValue)) {
    std::string persistent = parsed_command_line.GetSwitchValueASCII(
        switches::kForceFieldTestNameAndValue);
    bool ret = field_trial.CreateTrialsInChildProcess(persistent);
    DCHECK(ret);
  }

  // Load pepper plugins before engaging the sandbox.
  PepperPluginRegistry::GetInstance();

  {
#if defined(OS_WIN) || defined(OS_MACOSX)
    // TODO(markus): Check if it is OK to unconditionally move this
    // instruction down.
    RenderProcessImpl render_process;
    render_process.set_main_thread(new RenderThreadImpl());
#endif
    bool run_loop = true;
    if (!no_sandbox) {
      run_loop = platform.EnableSandbox();
    } else {
      LOG(ERROR) << "Running without renderer sandbox";
    }
#if defined(OS_POSIX) && !defined(OS_MACOSX)
    RenderProcessImpl render_process;
    render_process.set_main_thread(new RenderThreadImpl());
#endif

    platform.RunSandboxTests();

    startup_timer.Stop();  // End of Startup Time Measurement.

    if (run_loop) {
#if defined(OS_MACOSX)
      if (pool)
        pool->Recycle();
#endif
      TRACE_EVENT_BEGIN_ETW("RendererMain.START_MSG_LOOP", 0, 0);
      MessageLoop::current()->Run();
      TRACE_EVENT_END_ETW("RendererMain.START_MSG_LOOP", 0, 0);
    }
  }
  platform.PlatformUninitialize();
  TRACE_EVENT_END_ETW("RendererMain", 0, "");
  return 0;
}
<|endoftext|>


<commit_before><commit_msg>Revert "Disable problematic sorting test that depends on the old default."<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: select.hxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 16:45:00 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SC_SELECT_HXX
#define SC_SELECT_HXX

#ifndef _SELENG_HXX //autogen
#include <vcl/seleng.hxx>
#endif

#include "viewdata.hxx"     // ScSplitPos

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

class ScTabView;
class ScViewData;

class ScViewSelectionEngine : public SelectionEngine
{
private:
    ScSplitPos      eWhich;
public:
                    ScViewSelectionEngine( Window* pWindow, ScTabView* pView,
                                                    ScSplitPos eSplitPos );

    ScSplitPos      GetWhich() const            { return eWhich; }
    void            SetWhich(ScSplitPos eNew)   { eWhich = eNew; }
};

class ScViewFunctionSet : public FunctionSet            // View (Gridwin / Tastatur)
{
private:
    ScViewData*             pViewData;
    ScViewSelectionEngine*  pEngine;

    BOOL            bAnchor;
    BOOL            bStarted;
    ScTripel        aAnchorPos;

    ScSplitPos      GetWhich();

public:
                    ScViewFunctionSet( ScViewData* pNewViewData );

    void            SetSelectionEngine( ScViewSelectionEngine* pSelEngine );

    void            SetAnchor( USHORT nPosX, USHORT nPosY );
    void            SetAnchorFlag( BOOL bSet );

    virtual void    BeginDrag();
    virtual void    CreateAnchor();
    virtual void    DestroyAnchor();
    virtual BOOL    SetCursorAtPoint( const Point& rPointPixel, BOOL bDontSelectAtCursor = FALSE );
    virtual BOOL    IsSelectionAtPoint( const Point& rPointPixel );
    virtual void    DeselectAtPoint( const Point& rPointPixel );
    virtual void    DeselectAll();

    BOOL            SetCursorAtCell( short nPosX, short nPosY, BOOL bScroll );
};

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

class ScHeaderFunctionSet : public FunctionSet          // Spalten- / Zeilenkoepfe
{
private:
    ScViewData*     pViewData;
    BOOL            bColumn;                // Col- / Rowbar
    ScSplitPos      eWhich;

    BOOL            bAnchor;
    USHORT          nCursorPos;

public:
                    ScHeaderFunctionSet( ScViewData* pNewViewData );

    void            SetColumn( BOOL bSet );
    void            SetWhich( ScSplitPos eNew );

    virtual void    BeginDrag();
    virtual void    CreateAnchor();
    virtual void    DestroyAnchor();
    virtual BOOL    SetCursorAtPoint( const Point& rPointPixel, BOOL bDontSelectAtCursor = FALSE );
    virtual BOOL    IsSelectionAtPoint( const Point& rPointPixel );
    virtual void    DeselectAtPoint( const Point& rPointPixel );
    virtual void    DeselectAll();

    void            SetAnchorFlag(BOOL bSet)    { bAnchor = bSet; }
};

class ScHeaderSelectionEngine : public SelectionEngine
{
public:
                    ScHeaderSelectionEngine( Window* pWindow, ScHeaderFunctionSet* pFuncSet );
};

#endif
<commit_msg>INTEGRATION: CWS rowlimit (1.1.1.1.346); FILE MERGED 2004/02/26 19:15:54 jmarmion 1.1.1.1.346.3: #i1967# setp 5 changes. 2004/02/04 11:28:17 er 1.1.1.1.346.2: #i1967# replace ScTripel,ScRefTripel with ScAddress,ScRefAddress; get rid of some warnings 2004/01/13 20:04:35 er 1.1.1.1.346.1: #i1967# SCCOL,SCROW,SCTAB replace USHORT; SCsCOL,SCsROW,SCsTAB replace short<commit_after>/*************************************************************************
 *
 *  $RCSfile: select.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2004-06-04 11:40:14 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SC_SELECT_HXX
#define SC_SELECT_HXX

#ifndef _SELENG_HXX //autogen
#include <vcl/seleng.hxx>
#endif

#include "viewdata.hxx"     // ScSplitPos

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

class ScTabView;
class ScViewData;

class ScViewSelectionEngine : public SelectionEngine
{
private:
    ScSplitPos      eWhich;
public:
                    ScViewSelectionEngine( Window* pWindow, ScTabView* pView,
                                                    ScSplitPos eSplitPos );

    ScSplitPos      GetWhich() const            { return eWhich; }
    void            SetWhich(ScSplitPos eNew)   { eWhich = eNew; }
};

class ScViewFunctionSet : public FunctionSet            // View (Gridwin / Tastatur)
{
private:
    ScViewData*             pViewData;
    ScViewSelectionEngine*  pEngine;

    BOOL            bAnchor;
    BOOL            bStarted;
    ScAddress       aAnchorPos;

    ScSplitPos      GetWhich();

public:
                    ScViewFunctionSet( ScViewData* pNewViewData );

    void            SetSelectionEngine( ScViewSelectionEngine* pSelEngine );

    void            SetAnchor( SCCOL nPosX, SCROW nPosY );
    void            SetAnchorFlag( BOOL bSet );

    virtual void    BeginDrag();
    virtual void    CreateAnchor();
    virtual void    DestroyAnchor();
    virtual BOOL    SetCursorAtPoint( const Point& rPointPixel, BOOL bDontSelectAtCursor = FALSE );
    virtual BOOL    IsSelectionAtPoint( const Point& rPointPixel );
    virtual void    DeselectAtPoint( const Point& rPointPixel );
    virtual void    DeselectAll();

    BOOL            SetCursorAtCell( SCsCOL nPosX, SCsROW nPosY, BOOL bScroll );
};

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

class ScHeaderFunctionSet : public FunctionSet          // Spalten- / Zeilenkoepfe
{
private:
    ScViewData*     pViewData;
    BOOL            bColumn;                // Col- / Rowbar
    ScSplitPos      eWhich;

    BOOL            bAnchor;
    SCCOLROW        nCursorPos;

public:
                    ScHeaderFunctionSet( ScViewData* pNewViewData );

    void            SetColumn( BOOL bSet );
    void            SetWhich( ScSplitPos eNew );

    virtual void    BeginDrag();
    virtual void    CreateAnchor();
    virtual void    DestroyAnchor();
    virtual BOOL    SetCursorAtPoint( const Point& rPointPixel, BOOL bDontSelectAtCursor = FALSE );
    virtual BOOL    IsSelectionAtPoint( const Point& rPointPixel );
    virtual void    DeselectAtPoint( const Point& rPointPixel );
    virtual void    DeselectAll();

    void            SetAnchorFlag(BOOL bSet)    { bAnchor = bSet; }
};

class ScHeaderSelectionEngine : public SelectionEngine
{
public:
                    ScHeaderSelectionEngine( Window* pWindow, ScHeaderFunctionSet* pFuncSet );
};

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tpsort.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 21:59:26 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SC_TPSORT_HXX
#define SC_TPSORT_HXX

#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif

#ifndef _SV_EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif

#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif

#ifndef _SVX_LANGBOX_HXX
#include <svx/langbox.hxx>
#endif

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

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

#define SC_MAXFIELDS    200

class ScViewData;
class ScSortDlg;
struct ScSortParam;

//========================================================================
// Kriterien

class ScTabPageSortFields : public SfxTabPage
{
public:
                ScTabPageSortFields( Window*             pParent,
                                     const SfxItemSet&   rArgSet );
                ~ScTabPageSortFields();

    static  SfxTabPage* Create      ( Window*               pParent,
                                      const SfxItemSet&     rArgSet );
    static  USHORT*     GetRanges   ();
    virtual BOOL        FillItemSet ( SfxItemSet& rArgSet );
    virtual void        Reset       ( const SfxItemSet& rArgSet );

protected:
// fuer Datenaustausch (sollte noch umgestellt werden!)
//  virtual void        ActivatePage    ( const SfxItemSet& rSet );
    virtual void        ActivatePage    ();
    virtual int         DeactivatePage  ( SfxItemSet* pSet = 0);

private:
    FixedLine       aFlSort1;
    ListBox         aLbSort1;
    RadioButton     aBtnUp1;
    RadioButton     aBtnDown1;

    FixedLine       aFlSort2;
    ListBox         aLbSort2;
    RadioButton     aBtnUp2;
    RadioButton     aBtnDown2;

    FixedLine       aFlSort3;
    ListBox         aLbSort3;
    RadioButton     aBtnUp3;
    RadioButton     aBtnDown3;

    String          aStrUndefined;
    String          aStrColumn;
    String          aStrRow;

    const USHORT        nWhichSort;
    ScSortDlg*          pDlg;
    ScViewData*         pViewData;
    const ScSortParam&  rSortData;
    SCCOLROW            nFieldArr[SC_MAXFIELDS];
    USHORT              nFieldCount;
    SCCOL               nFirstCol;
    SCROW               nFirstRow;
    BOOL                bHasHeader;
    BOOL                bSortByRows;

    ListBox*            aSortLbArr[3];
    RadioButton*        aDirBtnArr[3][2];
    FixedLine*          aFlArr[3];

#ifdef _TPSORT_CXX
private:
    void    Init            ();
    void    DisableField    ( USHORT nField );
    void    EnableField     ( USHORT nField );
    void    FillFieldLists  ();
    USHORT  GetFieldSelPos  ( SCCOLROW nField );

    // Handler ------------------------
    DECL_LINK( SelectHdl, ListBox * );
#endif
};

//========================================================================
// Sortieroptionen:

class ScDocument;
class ScRangeData;
class CollatorRessource;
class CollatorWrapper;

class ScTabPageSortOptions : public SfxTabPage
{
public:
                ScTabPageSortOptions( Window*            pParent,
                                      const SfxItemSet&  rArgSet );
                ~ScTabPageSortOptions();

    static  SfxTabPage* Create      ( Window*               pParent,
                                      const SfxItemSet&     rArgSet );
    static  USHORT*     GetRanges   ();
    virtual BOOL        FillItemSet ( SfxItemSet& rArgSet );
    virtual void        Reset       ( const SfxItemSet& rArgSet );

protected:
// fuer Datenaustausch (sollte noch umgestellt werden!)
//  virtual void        ActivatePage    ( const SfxItemSet& rSet );
    virtual void        ActivatePage    ();
    virtual int         DeactivatePage  ( SfxItemSet* pSet = 0);

private:

    CheckBox            aBtnCase;
    CheckBox            aBtnHeader;
    CheckBox            aBtnFormats;

    CheckBox            aBtnCopyResult;
    ListBox             aLbOutPos;
    Edit                aEdOutPos;

    CheckBox            aBtnSortUser;
    ListBox             aLbSortUser;

    FixedText           aFtLanguage;
    SvxLanguageBox      aLbLanguage;
    FixedText           aFtAlgorithm;
    ListBox             aLbAlgorithm;

    FixedLine           aLineDirection;
    RadioButton         aBtnTopDown;
    RadioButton         aBtnLeftRight;

    FixedText           aFtAreaLabel;
//  FixedInfo           aFtArea;
    String              aStrRowLabel;
    String              aStrColLabel;
    String              aStrUndefined;
    String              aStrNoName;
    String              aStrAreaLabel;

    const USHORT        nWhichSort;
    const ScSortParam&  rSortData;
    ScViewData*         pViewData;
    ScDocument*         pDoc;
    ScSortDlg*          pDlg;
    ScAddress           theOutPos;

    CollatorRessource*  pColRes;
    CollatorWrapper*    pColWrap;

#ifdef _TPSORT_CXX
private:
    void Init                   ();
    void FillUserSortListBox    ();
    void FillOutPosList         ();

    // Handler ------------------------
    DECL_LINK( EnableHdl, CheckBox * );
    DECL_LINK( SelOutPosHdl, ListBox * );
    void EdOutPosModHdl ( Edit* pEd );
    DECL_LINK( SortDirHdl, RadioButton * );
    DECL_LINK( FillAlgorHdl, void * );
#endif
};

#endif // SC_TPSORT_HXX

<commit_msg>INTEGRATION: CWS calcwarnings (1.6.324); FILE MERGED 2006/12/01 08:53:33 nn 1.6.324.1: #i69284# warning-free: ui, wntmsci10<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: tpsort.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2007-02-27 13:27:37 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SC_TPSORT_HXX
#define SC_TPSORT_HXX

#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif

#ifndef _SV_EDIT_HXX //autogen
#include <vcl/edit.hxx>
#endif

#ifndef _SV_FIXED_HXX //autogen
#include <vcl/fixed.hxx>
#endif

#ifndef _SV_LSTBOX_HXX //autogen
#include <vcl/lstbox.hxx>
#endif

#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif

#ifndef _SVX_LANGBOX_HXX
#include <svx/langbox.hxx>
#endif

#ifndef SC_SCGLOB_HXX
#include "global.hxx"
#endif

#ifndef SC_ADDRESS_HXX
#include "address.hxx"
#endif

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

#define SC_MAXFIELDS    200

class ScViewData;
class ScSortDlg;
struct ScSortParam;

//========================================================================
// Kriterien

class ScTabPageSortFields : public SfxTabPage
{
public:
                ScTabPageSortFields( Window*             pParent,
                                     const SfxItemSet&   rArgSet );
                ~ScTabPageSortFields();

    static  SfxTabPage* Create      ( Window*               pParent,
                                      const SfxItemSet&     rArgSet );
    static  USHORT*     GetRanges   ();
    virtual BOOL        FillItemSet ( SfxItemSet& rArgSet );
    virtual void        Reset       ( const SfxItemSet& rArgSet );

protected:
// fuer Datenaustausch (sollte noch umgestellt werden!)
//  virtual void        ActivatePage    ( const SfxItemSet& rSet );
    using SfxTabPage::ActivatePage;
    using SfxTabPage::DeactivatePage;
    virtual void        ActivatePage    ();
    virtual int         DeactivatePage  ( SfxItemSet* pSet = 0);

private:
    FixedLine       aFlSort1;
    ListBox         aLbSort1;
    RadioButton     aBtnUp1;
    RadioButton     aBtnDown1;

    FixedLine       aFlSort2;
    ListBox         aLbSort2;
    RadioButton     aBtnUp2;
    RadioButton     aBtnDown2;

    FixedLine       aFlSort3;
    ListBox         aLbSort3;
    RadioButton     aBtnUp3;
    RadioButton     aBtnDown3;

    String          aStrUndefined;
    String          aStrColumn;
    String          aStrRow;

    const USHORT        nWhichSort;
    ScSortDlg*          pDlg;
    ScViewData*         pViewData;
    const ScSortParam&  rSortData;
    SCCOLROW            nFieldArr[SC_MAXFIELDS];
    USHORT              nFieldCount;
    SCCOL               nFirstCol;
    SCROW               nFirstRow;
    BOOL                bHasHeader;
    BOOL                bSortByRows;

    ListBox*            aSortLbArr[3];
    RadioButton*        aDirBtnArr[3][2];
    FixedLine*          aFlArr[3];

#ifdef _TPSORT_CXX
private:
    void    Init            ();
    void    DisableField    ( USHORT nField );
    void    EnableField     ( USHORT nField );
    void    FillFieldLists  ();
    USHORT  GetFieldSelPos  ( SCCOLROW nField );

    // Handler ------------------------
    DECL_LINK( SelectHdl, ListBox * );
#endif
};

//========================================================================
// Sortieroptionen:

class ScDocument;
class ScRangeData;
class CollatorRessource;
class CollatorWrapper;

class ScTabPageSortOptions : public SfxTabPage
{
public:
                ScTabPageSortOptions( Window*            pParent,
                                      const SfxItemSet&  rArgSet );
                ~ScTabPageSortOptions();

    static  SfxTabPage* Create      ( Window*               pParent,
                                      const SfxItemSet&     rArgSet );
    static  USHORT*     GetRanges   ();
    virtual BOOL        FillItemSet ( SfxItemSet& rArgSet );
    virtual void        Reset       ( const SfxItemSet& rArgSet );

protected:
// fuer Datenaustausch (sollte noch umgestellt werden!)
//  virtual void        ActivatePage    ( const SfxItemSet& rSet );
    using SfxTabPage::ActivatePage;
    using SfxTabPage::DeactivatePage;
    virtual void        ActivatePage    ();
    virtual int         DeactivatePage  ( SfxItemSet* pSet = 0);

private:

    CheckBox            aBtnCase;
    CheckBox            aBtnHeader;
    CheckBox            aBtnFormats;

    CheckBox            aBtnCopyResult;
    ListBox             aLbOutPos;
    Edit                aEdOutPos;

    CheckBox            aBtnSortUser;
    ListBox             aLbSortUser;

    FixedText           aFtLanguage;
    SvxLanguageBox      aLbLanguage;
    FixedText           aFtAlgorithm;
    ListBox             aLbAlgorithm;

    FixedLine           aLineDirection;
    RadioButton         aBtnTopDown;
    RadioButton         aBtnLeftRight;

    FixedText           aFtAreaLabel;
//  FixedInfo           aFtArea;
    String              aStrRowLabel;
    String              aStrColLabel;
    String              aStrUndefined;
    String              aStrNoName;
    String              aStrAreaLabel;

    const USHORT        nWhichSort;
    const ScSortParam&  rSortData;
    ScViewData*         pViewData;
    ScDocument*         pDoc;
    ScSortDlg*          pDlg;
    ScAddress           theOutPos;

    CollatorRessource*  pColRes;
    CollatorWrapper*    pColWrap;

#ifdef _TPSORT_CXX
private:
    void Init                   ();
    void FillUserSortListBox    ();
    void FillOutPosList         ();

    // Handler ------------------------
    DECL_LINK( EnableHdl, CheckBox * );
    DECL_LINK( SelOutPosHdl, ListBox * );
    void EdOutPosModHdl ( Edit* pEd );
    DECL_LINK( SortDirHdl, RadioButton * );
    DECL_LINK( FillAlgorHdl, void * );
#endif
};

#endif // SC_TPSORT_HXX

<|endoftext|>


<commit_before>/*
 * Console.cpp
 *
 *  Created on: May 5, 2017
 *      Author: garrett
 */

#include "Console.h"
#include "../kernel.h"
#include "Keyboard.h"
#include "../memory/structures/PageTable.h"
#include "../memory/mem.h"

/**
 * Function prototype for the internal use newline()
 */
void newline();

/**
 * current terminal row
 */
size_t terminalRow;
/**
 * current terminal column
 */
size_t terminalColumn;
/**
 * the color code we are using
 */
uint8_t terminalColor;
/**
 * the address of the start of the terminal
 */
uint16_t* terminalBuffer;

/**
 * clears the screen with \0 and sets the start point. also sets the blinking bar and colors.
 * @param bufferStart - where the mem mapped terminal is
 */
void terminalInit(uint16_t* bufferStart) {
	//start at the begining
	terminalRow = 0;
	terminalColumn = 0;
	//set color
	terminalColor = vgaEntryColor(VGA_COLOR_LIGHT_BROWN, VGA_COLOR_BLACK);
	//where it is in mem. in the middle because intell still hates you
	terminalBuffer = bufferStart;
	//clear with nulls for backspace and get rid go GRUB's garbage
	for (size_t _y = 0; _y < VGA_HEIGHT; _y++) {
		for (size_t _x = 0; _x < VGA_WIDTH; _x++) {
			const size_t index = _y * VGA_WIDTH + _x;
			terminalBuffer[index] = vgaEntry('\0', terminalColor);
		}
	}
	//set blinky bar at the begining
	teminalUpdateBar(0, 0);
}
/**
 * sets the FG and BG colors of the terminal
 * @param color code
 */
void terminalSetColor(uint8_t color) {
	terminalColor = color;
}

/**
 *  fully encode char and place in the buffer
 * @param the char to print
 * @param the color code
 * @param X Pos
 * @param Y Pos
 */
void terminalPutEntryAt(char _toPrint, uint8_t _color, size_t _XPos,
		size_t _YPos) {
	const size_t _index = _YPos * VGA_WIDTH + _XPos;
    // Handle newlines
    if (_toPrint == 0x0A) {
        newline();
    } else {
	    terminalBuffer[_index] = vgaEntry(_toPrint, _color);
        terminalColumn++;
    }
}

/**
 * put char at next location
 * @param char to print
 */
void terminalPutChar(char _toPrint) {
	terminalPutEntryAt(_toPrint, terminalColor, terminalColumn, terminalRow);
	if (terminalColumn == VGA_WIDTH) {
        newline();
	}
	teminalUpdateBar(terminalRow, terminalColumn);
}

/**
 * print a string of known length
 * @param string to print
 * @param length
 */
void terminalWrite(const char* _toPrint, size_t _length) {
	for (size_t _i = 0; _i < _length; _i++)
		terminalPutChar(_toPrint[_i]);
}

#if defined(__cplusplus)
extern "C" {/* Use C linkage for kernel_main. */
#endif
/**
 * get string length
 * @param string
 * @return length
 */
size_t strlen(const char* str) {
	size_t _length = 0;
	while (str[_length])
		_length++;
	return _length;
}
#if defined(__cplusplus)
}/* Use C linkage for kernel_main. */
#endif

/**
 * print string of unknown length
 * @param string to print
 */
void terminalWriteString(const char* _toPrint) {
	terminalWrite(_toPrint, strlen(_toPrint));
}

/**
 * print string of unknown length
 * move to the next line when done
 * @param string to print
 */
void terminalWriteLine(const char* _toPrint) {
	terminalWrite(_toPrint, strlen(_toPrint));
    newline();
	teminalUpdateBar(terminalRow, terminalColumn);
}

/**
 * process special keys
 * @param what char to handle
 * @param pointer to modkey flags
 */
void terminalHandleSpecialKey(char _specalChar, uint16_t* modsLocal) {
	switch (_specalChar) {
		//back space
		case ('\x0E') : {
			size_t _index = 0;
			do {

				if ( --terminalColumn == (size_t) -1) {
					terminalColumn = VGA_WIDTH - 1;
					if ( --terminalRow == (size_t) -1) {
						terminalRow = 0;
						terminalColumn = 0;
						break;
					}
				}
				_index = terminalRow * VGA_WIDTH + terminalColumn;
			} while ( ! (terminalBuffer[_index] & 0xff));
			terminalPutEntryAt('\0', terminalColor, terminalColumn,
					terminalRow);
			teminalUpdateBar(terminalRow, terminalColumn);
			break;
		}
			//tab
		case ('\x0F') : {
			terminalWrite("    ", 4);
			break;
		}
			//enter
		case ('\x1C') : {
            newline();
			teminalUpdateBar(terminalRow, terminalColumn);
			break;
		}
		case ('\x1D') : {
			*modsLocal |= L_CONTROL;
			break;
		}
		case ('\x2A') : {
			*modsLocal |= L_SHIFT;
			break;
		}
		case ('\x36') : {
			*modsLocal |= R_SHIFT;
			break;
		}
		case ('\x38') : {
			*modsLocal |= L_ALT;
			break;
		}
		case ('\x3A') : {
			*modsLocal ^= CAPS_LOCK;
			break;
		}
		case ('\x45') : {
			*modsLocal ^= NUM_LOCK;
			break;
		}
		case ('\x46') : {
			*modsLocal ^= SCROLL_LOCK;
			break;
		}
		case ('\x9D') : {
			*modsLocal &= ~L_CONTROL;
			break;
		}
		case ('\xAA') : {
			*modsLocal &= ~L_SHIFT;
			break;
		}
		case ('\xB6') : {
			*modsLocal &= ~R_SHIFT;
			break;
		}
	}
}
/**
 * move the blinking bar to the proper location
 * @param row
 * @param col
 */
void teminalUpdateBar(int row, int col) {
	unsigned short position = (row * VGA_WIDTH) + col;
	// cursor LOW port to vga INDEX register
	outb(0x3D4, 0x0F);
	outb(0x3D5, (unsigned char) (position & 0xFF));
	// cursor HIGH port to vga INDEX register
	outb(0x3D4, 0x0E);
	outb(0x3D5, (unsigned char) ( (position >> 8) & 0xFF));
}

/**
 * Move the cursor to the next line. Scroll if necessary
 * Internal method, do not include in Console.h
 * If a blank line is needed, use terminalWriteLine() instead
 */
void newline( ) {
    terminalRow++;
    terminalColumn = 0;
    if (terminalRow == VGA_HEIGHT) {
        terminalScroll();
    }
}
/**
 * handle scrolling up when the last spot is used
 */
void terminalScroll( ) {
	terminalRow = VGA_HEIGHT - 1;
	memcpy((void*) (0xB8000 + (uint32_t)(pageTable.getKernelStart( ))),
			(void*) (0xb8000 + (uint32_t)(pageTable.getKernelStart( ))
					+ VGA_WIDTH * 2), (VGA_WIDTH * 2) * (VGA_HEIGHT - 1));
	memSet(
			(void*) (0xB8000 + (uint32_t)(pageTable.getKernelStart( ))
					+ (VGA_WIDTH * 2) * (VGA_HEIGHT - 1)), VGA_WIDTH * 2, '\0');
}

/**
 * write a number. i think it works right
 * @param number to print
 */
void writeInt(uint64_t num) {
	uint8_t out[20];
	for (int i = 0; i < 20; i++) {
		out[i] = '\0';
	}
	if ( !num) {
		terminalPutChar('0');
		return;
	}

	int n = 19;
	while (n>=0 && num != 0) {
		out[n] = ('0' + (num % 10));
		num /= 10;
		n--;
	}
	terminalWrite((const char *)out, 20);
}
<commit_msg>The backspace issue seems to be fixed<commit_after>/*
 * Console.cpp
 *
 *  Created on: May 5, 2017
 *      Author: garrett
 */

#include "Console.h"
#include "../kernel.h"
#include "Keyboard.h"
#include "../memory/structures/PageTable.h"
#include "../memory/mem.h"

/**
 * Function prototype for the internal use newline()
 */
void newline();

/**
 * current terminal row
 */
size_t terminalRow;
/**
 * current terminal column
 */
size_t terminalColumn;
/**
 * the color code we are using
 */
uint8_t terminalColor;
/**
 * the address of the start of the terminal
 */
uint16_t* terminalBuffer;

/**
 * clears the screen with \0 and sets the start point. also sets the blinking bar and colors.
 * @param bufferStart - where the mem mapped terminal is
 */
void terminalInit(uint16_t* bufferStart) {
	//start at the begining
	terminalRow = 0;
	terminalColumn = 0;
	//set color
	terminalColor = vgaEntryColor(VGA_COLOR_LIGHT_BROWN, VGA_COLOR_BLACK);
	//where it is in mem. in the middle because intell still hates you
	terminalBuffer = bufferStart;
	//clear with nulls for backspace and get rid go GRUB's garbage
	for (size_t _y = 0; _y < VGA_HEIGHT; _y++) {
		for (size_t _x = 0; _x < VGA_WIDTH; _x++) {
			const size_t index = _y * VGA_WIDTH + _x;
			terminalBuffer[index] = vgaEntry('\0', terminalColor);
		}
	}
	//set blinky bar at the begining
	teminalUpdateBar(0, 0);
}
/**
 * sets the FG and BG colors of the terminal
 * @param color code
 */
void terminalSetColor(uint8_t color) {
	terminalColor = color;
}

/**
 *  fully encode char and place in the buffer
 * @param the char to print
 * @param the color code
 * @param X Pos
 * @param Y Pos
 */
void terminalPutEntryAt(char _toPrint, uint8_t _color, size_t _XPos,
		size_t _YPos) {
	const size_t _index = _YPos * VGA_WIDTH + _XPos;
    // Handle newlines
    if (_toPrint == 0x0A) {
        newline();
    } else {
	    terminalBuffer[_index] = vgaEntry(_toPrint, _color);
        terminalColumn++;
    }
}

/**
 * put char at next location
 * @param char to print
 */
void terminalPutChar(char _toPrint) {
	terminalPutEntryAt(_toPrint, terminalColor, terminalColumn, terminalRow);
	if (terminalColumn == VGA_WIDTH) {
        newline();
	}
	teminalUpdateBar(terminalRow, terminalColumn);
}

/**
 * print a string of known length
 * @param string to print
 * @param length
 */
void terminalWrite(const char* _toPrint, size_t _length) {
	for (size_t _i = 0; _i < _length; _i++)
		terminalPutChar(_toPrint[_i]);
}

#if defined(__cplusplus)
extern "C" {/* Use C linkage for kernel_main. */
#endif
/**
 * get string length
 * @param string
 * @return length
 */
size_t strlen(const char* str) {
	size_t _length = 0;
	while (str[_length])
		_length++;
	return _length;
}
#if defined(__cplusplus)
}/* Use C linkage for kernel_main. */
#endif

/**
 * print string of unknown length
 * @param string to print
 */
void terminalWriteString(const char* _toPrint) {
	terminalWrite(_toPrint, strlen(_toPrint));
}

/**
 * print string of unknown length
 * move to the next line when done
 * @param string to print
 */
void terminalWriteLine(const char* _toPrint) {
	terminalWrite(_toPrint, strlen(_toPrint));
    newline();
	teminalUpdateBar(terminalRow, terminalColumn);
}

/**
 * process special keys
 * @param what char to handle
 * @param pointer to modkey flags
 */
void terminalHandleSpecialKey(char _specalChar, uint16_t* modsLocal) {
	switch (_specalChar) {
		//back space
		case ('\x0E') : {
			size_t _index = 0;
			do {

				if ( --terminalColumn == (size_t) -1) {
					terminalColumn = VGA_WIDTH - 1;
					if ( --terminalRow == (size_t) -1) {
						terminalRow = 0;
						terminalColumn = 0;
						break;
					}
				}
				_index = terminalRow * VGA_WIDTH + terminalColumn;
			} while ( ! (terminalBuffer[_index] & 0xff));
			terminalPutEntryAt('\0', terminalColor, terminalColumn,
					terminalRow);
			teminalUpdateBar(terminalRow, --terminalColumn);
			break;
		}
			//tab
		case ('\x0F') : {
			terminalWrite("    ", 4);
			break;
		}
			//enter
		case ('\x1C') : {
            newline();
			teminalUpdateBar(terminalRow, terminalColumn);
			break;
		}
		case ('\x1D') : {
			*modsLocal |= L_CONTROL;
			break;
		}
		case ('\x2A') : {
			*modsLocal |= L_SHIFT;
			break;
		}
		case ('\x36') : {
			*modsLocal |= R_SHIFT;
			break;
		}
		case ('\x38') : {
			*modsLocal |= L_ALT;
			break;
		}
		case ('\x3A') : {
			*modsLocal ^= CAPS_LOCK;
			break;
		}
		case ('\x45') : {
			*modsLocal ^= NUM_LOCK;
			break;
		}
		case ('\x46') : {
			*modsLocal ^= SCROLL_LOCK;
			break;
		}
		case ('\x9D') : {
			*modsLocal &= ~L_CONTROL;
			break;
		}
		case ('\xAA') : {
			*modsLocal &= ~L_SHIFT;
			break;
		}
		case ('\xB6') : {
			*modsLocal &= ~R_SHIFT;
			break;
		}
	}
}
/**
 * move the blinking bar to the proper location
 * @param row
 * @param col
 */
void teminalUpdateBar(int row, int col) {
	unsigned short position = (row * VGA_WIDTH) + col;
	// cursor LOW port to vga INDEX register
	outb(0x3D4, 0x0F);
	outb(0x3D5, (unsigned char) (position & 0xFF));
	// cursor HIGH port to vga INDEX register
	outb(0x3D4, 0x0E);
	outb(0x3D5, (unsigned char) ( (position >> 8) & 0xFF));
}

/**
 * Move the cursor to the next line. Scroll if necessary
 * Internal method, do not include in Console.h
 * If a blank line is needed, use terminalWriteLine() instead
 */
void newline( ) {
    terminalRow++;
    terminalColumn = 0;
    if (terminalRow == VGA_HEIGHT) {
        terminalScroll();
    }
}
/**
 * handle scrolling up when the last spot is used
 */
void terminalScroll( ) {
	terminalRow = VGA_HEIGHT - 1;
	memcpy((void*) (0xB8000 + (uint32_t)(pageTable.getKernelStart( ))),
			(void*) (0xb8000 + (uint32_t)(pageTable.getKernelStart( ))
					+ VGA_WIDTH * 2), (VGA_WIDTH * 2) * (VGA_HEIGHT - 1));
	memSet(
			(void*) (0xB8000 + (uint32_t)(pageTable.getKernelStart( ))
					+ (VGA_WIDTH * 2) * (VGA_HEIGHT - 1)), VGA_WIDTH * 2, '\0');
}

/**
 * write a number. i think it works right
 * @param number to print
 */
void writeInt(uint64_t num) {
	uint8_t out[20];
	for (int i = 0; i < 20; i++) {
		out[i] = '\0';
	}
	if ( !num) {
		terminalPutChar('0');
		return;
	}

	int n = 19;
	while (n>=0 && num != 0) {
		out[n] = ('0' + (num % 10));
		num /= 10;
		n--;
	}
	terminalWrite((const char *)out, 20);
}
<|endoftext|>