<commit_before>#include <iostream>
#include <QtCore/QDateTime>
#include <QMessageBox>
#include <QVBoxLayout>
#include "../cldefs.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dialogaeddaterange.h"
#include "dialogaedevflag.h"
#include "dialogmanagepf.h"

#include <QDebug>

QLabel* lbDebug = 0;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    lockRoundRecursion(false),
    lockUpdateSettings(false)
{
    ui->setupUi(this);
    chronoLine = new ChronoLine(ui->frmChrono);
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(chronoLine);
    ui->frmChrono->setLayout(layout);
    // Events from ChronoLine
    connect(chronoLine,
            SIGNAL(flagDateChanged(long, const QDateTime&)), this, SLOT(anyFlagDateChanged(long, const QDateTime&)));
    connect(chronoLine,
            SIGNAL(pairDatesChanged(long, const QDateTime&, const QDateTime&)), this, SLOT(anyPairDatesChanged(long, const QDateTime&, const QDateTime&)));
    connect(chronoLine, SIGNAL(periodSelected(long)), this, SLOT(anyPeriodSelected(long)));
    connect(chronoLine, SIGNAL(eventFlagSelected(long)), this, SLOT(anyEventFlagSelected(long)));
    connect(chronoLine,
            SIGNAL(flagPairSelected(long,ChronoLineFlagType)), this, SLOT(anyFlagPairSelected(long,ChronoLineFlagType)));
    connect(chronoLine, SIGNAL(selectionRemoved()), this, SLOT(anySelectionRemoved()));
    connect(chronoLine, SIGNAL(actualUnitChanged(ChronoLineUnit)), this, SLOT(clUnitChanged(ChronoLineUnit)));
    connect(chronoLine, SIGNAL(rangeChanged(QDateTime,QDateTime)), this, SLOT(clRangeChanged(QDateTime,QDateTime)));
    connect(chronoLine, SIGNAL(mouseMovedOnScene(QPointF&,QDateTime&)), this, SLOT(onMouseMovedOnScene(QPointF&,QDateTime&)));
    // Initial data
    chronoLine->lockAutoUpdate();
    /**/
    ui->edMinDate->setDateTime(QDateTime(QDateTime::currentDateTime().date()));
    ui->edMaxDate->setDateTime(QDateTime(QDateTime::currentDateTime().date().addDays(11)));
    /*
    int year = QDate::currentDate().year();
    QDate begin = QDate( year, 1, 1); // 01.01.year
    QDate end = begin.addMonths(11).addDays(30); // add 11 month and 30 days -> 31.12.year :)
    ui->edMinDate->setDateTime( QDateTime( begin ) );
    ui->edMaxDate->setDateTime( QDateTime( end ) );
    */
    // Status bar
    sl1 = new QLabel(0);
    sl2 = new QLabel(0);
    sl3 = new QLabel(0);
    statusBar()->addWidget(sl1, 1);
    statusBar()->addWidget(sl2, 1);
    statusBar()->addWidget(sl3, 4);
    lbDebug = sl3;
    // Periods/flags debugging
    long idP = chronoLine->addPeriod(QDateTime::currentDateTime().addDays(1), QDateTime::currentDateTime().addDays(2));
    if (idP) periods.push_back(idP);
    idP = chronoLine->addPeriod(QDateTime::currentDateTime().addDays(5), QDateTime::currentDateTime().addDays(6));
    if (idP) periods.push_back(idP);
    idP = chronoLine->addPeriod(
        QDateTime::currentDateTime().addDays(5).addSecs(-2*3600), QDateTime::currentDateTime().addDays(6).addSecs(-2*3600));
    if (idP) periods.push_back(idP);
    idP = chronoLine->addPeriod(
        QDateTime::currentDateTime().addDays(5).addSecs(2*3600), QDateTime::currentDateTime().addDays(6).addSecs(2*3600));
    if (idP) periods.push_back(idP);
    long idF = chronoLine->addEventFlag(QDateTime::currentDateTime().addDays(2).addSecs(12*3600));
    if (idF) evFlags.push_back(idF);
    long idFP = chronoLine->addFlagPair(QDateTime::currentDateTime().addDays(3), QDateTime::currentDateTime().addDays(4));
    if (idFP) flagPairs.push_back(idFP);
    idFP = chronoLine->addFlagPair(QDateTime::currentDateTime().addDays(8), QDateTime::currentDateTime().addDays(9));
    if (idFP) flagPairs.push_back(idFP);
    idF = chronoLine->addEventFlag(QDateTime::currentDateTime().addDays(7));
    if (idF) evFlags.push_back(idF);
    // Ready!
    chronoLine->unLockAutoUpdate();
    updateView();
    // StatusBar 2
    clUnitChanged(chronoLine->actualUnit());
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void MainWindow::resizeEvent(QResizeEvent*)
{
    chronoLine->updateAll(); // TODO dup?
}

void MainWindow::on_actionE_xit_triggered()
{
    close();
}

void MainWindow::updateSettings()
{
    chronoLine->setRange(ui->edMinDate->dateTime(), ui->edMaxDate->dateTime());
    chronoLine->setUnit((ChronoLineUnit)ui->cbUnit->currentIndex());
}

void MainWindow::updateView()
{
    if (!chronoLine->updateAll())
        QMessageBox::critical(0, trUtf8("Ошибка"),
            trUtf8("Слишком большая единица измерения для выбранного периода либо неверная дата окончания"));
    sl2->setText(tr("%1 periods, %2 event flags").arg(chronoLine->periodCount()).arg(chronoLine->eventFlagCount()));
}

void MainWindow::on_edMinDate_dateTimeChanged(const QDateTime&)
{
    if (!lockUpdateSettings)
        updateSettings();
}

void MainWindow::on_edMaxDate_dateTimeChanged(const QDateTime&)
{
    if (!lockUpdateSettings)
        updateSettings();
}

void MainWindow::on_cbUnit_currentIndexChanged(const QString&)
{
    if (!lockUpdateSettings)
        updateSettings();
}

void MainWindow::on_action_Add_Period_triggered()
{
    DialogAEDDateRange* dlg = new DialogAEDDateRange(0);
    dlg->setWindowTitle(tr("Add Period"));
    dlg->setData(QDateTime::currentDateTime().addDays(5), QDateTime::currentDateTime().addDays(6));
    dlg->exec();
    if (dlg->result()==QDialog::Accepted) {
        QDateTime minDate, maxDate;
        dlg->getData(minDate, maxDate);
        long idP = chronoLine->addPeriod(minDate, maxDate, Qt::yellow);
        if (idP) periods.push_back(idP);
    }
    delete dlg;
    updateView();
}

void MainWindow::on_action_Add_Event_Flag_triggered()
{
    DialogAEDEvFlag* dlg = new DialogAEDEvFlag(0);
    dlg->setData(QDateTime::currentDateTime().addDays(4));
    dlg->exec();
    if (dlg->result()==QDialog::Accepted) {
        QDateTime date;
        dlg->getData(date);
        long idF = chronoLine->addEventFlag(date, Qt::yellow);
        if (idF) evFlags.push_back(idF);
    }
    delete dlg;
    updateView();
}

void MainWindow::on_action_Manage_Periods_Flags_triggered()
{
    DialogManagePF* dlg = new DialogManagePF(0, chronoLine, &periods, &evFlags, &flagPairs);
    dlg->exec();
    delete dlg;
    updateView();
}

void MainWindow::anyPeriodSelected(long idPeriod)
{
    QDateTime minDate, maxDate;
    chronoLine->readPeriod(idPeriod, minDate, maxDate);
    lbDebug->setText(tr("Period %1: %2/%3").arg(idPeriod).arg(minDate.toString()).arg(maxDate.toString()));
    updateView();
}

void MainWindow::anyEventFlagSelected(long idFlag)
{
    QDateTime date;
    chronoLine->readEventFlag(idFlag, date);
    lbDebug->setText(tr("Flag %1: %2").arg(idFlag).arg(date.toString()));
    updateView();
}

void MainWindow::anyFlagPairSelected(long idPair, ChronoLineFlagType)
{
    QDateTime minDate, maxDate;
    chronoLine->readFlagPair(idPair, minDate, maxDate);
    lbDebug->setText(tr("Pair %1: %2/%3").arg(idPair).arg(minDate.toString()).arg(maxDate.toString()));
    updateView();
}

void MainWindow::anySelectionRemoved()
{
    lbDebug->setText("");
    updateView();
}

void MainWindow::anyFlagDateChanged(long idFlag, const QDateTime& newDate)
{
    if (!lockRoundRecursion) {
        lockRoundRecursion = true;
        QDateTime roundDate = chronoLine->roundToUnit(newDate, cluDay);
        chronoLine->editEventFlag(idFlag, roundDate);
        updateView();
        lockRoundRecursion = false;
    }
    lbDebug->setText(tr("Flag %1 set to %2").arg(idFlag).arg(newDate.toString()));
}

void MainWindow::anyPairDatesChanged(long idPair, const QDateTime& newMinDate, const QDateTime& newMaxDate)
{
    if (!lockRoundRecursion) {
        lockRoundRecursion = true;
        QDateTime roundMinDate = chronoLine->roundToUnit(newMinDate, cluDay);
        QDateTime roundMaxDate = chronoLine->roundToUnit(newMaxDate, cluDay);
        chronoLine->editFlagPair(idPair, roundMinDate, roundMaxDate);
        updateView();
        lockRoundRecursion = false;
    }
    lbDebug->setText(tr("Pair %1:  %2/%3").arg(idPair).arg(newMinDate.toString()).arg(newMaxDate.toString()));
}

void MainWindow::on_action_Fit_objects_on_scene_triggered()
{
    chronoLine->fitObjectsOnScene(true);
}

void MainWindow::on_action_Set_scale_Range_triggered()
{
    DialogAEDDateRange* dlg = new DialogAEDDateRange(0);
    dlg->setWindowTitle(tr("Set scale range"));
    dlg->setData(chronoLine->minDate(), chronoLine->maxDate());
    dlg->exec();
    if (dlg->result()==QDialog::Accepted) {
        QDateTime minDate, maxDate;
        dlg->getData(minDate, maxDate);
        chronoLine->setMinDate(minDate);
        chronoLine->setMaxDate(maxDate);
    }
    delete dlg;
    updateView();
}

void MainWindow::on_action_Zoom_In_triggered()
{
    chronoLine->zoomIn(0.5);
}

void MainWindow::on_actionZoom_Out_triggered()
{
    chronoLine->zoomOut(0.5);
}

void MainWindow::on_action_Add_Pair_Of_Flags_triggered()
{
    DialogAEDDateRange* dlg = new DialogAEDDateRange(0);
    dlg->setWindowTitle(tr("Add Pair of Flags"));
    dlg->setData(QDateTime::currentDateTime().addDays(3), QDateTime::currentDateTime().addDays(4));
    dlg->exec();
    if (dlg->result()==QDialog::Accepted) {
        QDateTime minDate, maxDate;
        dlg->getData(minDate, maxDate);
        long idP = chronoLine->addFlagPair(minDate, maxDate, Qt::magenta);
        if (idP) flagPairs.push_back(idP);
    }
    delete dlg;
    updateView();

}

void MainWindow::clUnitChanged(ChronoLineUnit unit)
{
    if (ui) sl1->setText(tr("Units: %1").arg(ui->cbUnit->itemText(unit)));
}

void MainWindow::clRangeChanged(const QDateTime &minD, const QDateTime &maxD)
{
    lockUpdateSettings = true;
    ui->edMinDate->setDateTime(minD);
    ui->edMaxDate->setDateTime(maxD);
    lockUpdateSettings = false;
    if (ui) sl3->setText(tr("Range: %1 - %2").arg(d2c(minD)).arg(d2c(maxD)));
}

void MainWindow::onMouseMovedOnScene(QPointF& scenePos, QDateTime& sceneDate)
{
    lbDebug->setText(tr("Mouse on (%1,%2) ").arg(scenePos.x()).arg(scenePos.y())+sceneDate.toString("dd.MM.yyyy hh:mm:ss"));
}
<commit_msg>Принудительное округление дополнительно выделено комментарием<commit_after>#include <iostream>
#include <QtCore/QDateTime>
#include <QMessageBox>
#include <QVBoxLayout>
#include "../cldefs.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "dialogaeddaterange.h"
#include "dialogaedevflag.h"
#include "dialogmanagepf.h"

#include <QDebug>

QLabel* lbDebug = 0;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    lockRoundRecursion(false),
    lockUpdateSettings(false)
{
    ui->setupUi(this);
    chronoLine = new ChronoLine(ui->frmChrono);
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(chronoLine);
    ui->frmChrono->setLayout(layout);
    // Events from ChronoLine
    connect(chronoLine,
            SIGNAL(flagDateChanged(long, const QDateTime&)), this, SLOT(anyFlagDateChanged(long, const QDateTime&)));
    connect(chronoLine,
            SIGNAL(pairDatesChanged(long, const QDateTime&, const QDateTime&)), this, SLOT(anyPairDatesChanged(long, const QDateTime&, const QDateTime&)));
    connect(chronoLine, SIGNAL(periodSelected(long)), this, SLOT(anyPeriodSelected(long)));
    connect(chronoLine, SIGNAL(eventFlagSelected(long)), this, SLOT(anyEventFlagSelected(long)));
    connect(chronoLine,
            SIGNAL(flagPairSelected(long,ChronoLineFlagType)), this, SLOT(anyFlagPairSelected(long,ChronoLineFlagType)));
    connect(chronoLine, SIGNAL(selectionRemoved()), this, SLOT(anySelectionRemoved()));
    connect(chronoLine, SIGNAL(actualUnitChanged(ChronoLineUnit)), this, SLOT(clUnitChanged(ChronoLineUnit)));
    connect(chronoLine, SIGNAL(rangeChanged(QDateTime,QDateTime)), this, SLOT(clRangeChanged(QDateTime,QDateTime)));
    connect(chronoLine, SIGNAL(mouseMovedOnScene(QPointF&,QDateTime&)), this, SLOT(onMouseMovedOnScene(QPointF&,QDateTime&)));
    // Initial data
    chronoLine->lockAutoUpdate();
    /**/
    ui->edMinDate->setDateTime(QDateTime(QDateTime::currentDateTime().date()));
    ui->edMaxDate->setDateTime(QDateTime(QDateTime::currentDateTime().date().addDays(11)));
    /*
    int year = QDate::currentDate().year();
    QDate begin = QDate( year, 1, 1); // 01.01.year
    QDate end = begin.addMonths(11).addDays(30); // add 11 month and 30 days -> 31.12.year :)
    ui->edMinDate->setDateTime( QDateTime( begin ) );
    ui->edMaxDate->setDateTime( QDateTime( end ) );
    */
    // Status bar
    sl1 = new QLabel(0);
    sl2 = new QLabel(0);
    sl3 = new QLabel(0);
    statusBar()->addWidget(sl1, 1);
    statusBar()->addWidget(sl2, 1);
    statusBar()->addWidget(sl3, 4);
    lbDebug = sl3;
    // Periods/flags debugging
    long idP = chronoLine->addPeriod(QDateTime::currentDateTime().addDays(1), QDateTime::currentDateTime().addDays(2));
    if (idP) periods.push_back(idP);
    idP = chronoLine->addPeriod(QDateTime::currentDateTime().addDays(5), QDateTime::currentDateTime().addDays(6));
    if (idP) periods.push_back(idP);
    idP = chronoLine->addPeriod(
        QDateTime::currentDateTime().addDays(5).addSecs(-2*3600), QDateTime::currentDateTime().addDays(6).addSecs(-2*3600));
    if (idP) periods.push_back(idP);
    idP = chronoLine->addPeriod(
        QDateTime::currentDateTime().addDays(5).addSecs(2*3600), QDateTime::currentDateTime().addDays(6).addSecs(2*3600));
    if (idP) periods.push_back(idP);
    long idF = chronoLine->addEventFlag(QDateTime::currentDateTime().addDays(2).addSecs(12*3600));
    if (idF) evFlags.push_back(idF);
    long idFP = chronoLine->addFlagPair(QDateTime::currentDateTime().addDays(3), QDateTime::currentDateTime().addDays(4));
    if (idFP) flagPairs.push_back(idFP);
    idFP = chronoLine->addFlagPair(QDateTime::currentDateTime().addDays(8), QDateTime::currentDateTime().addDays(9));
    if (idFP) flagPairs.push_back(idFP);
    idF = chronoLine->addEventFlag(QDateTime::currentDateTime().addDays(7));
    if (idF) evFlags.push_back(idF);
    // Ready!
    chronoLine->unLockAutoUpdate();
    updateView();
    // StatusBar 2
    clUnitChanged(chronoLine->actualUnit());
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void MainWindow::resizeEvent(QResizeEvent*)
{
    chronoLine->updateAll(); // TODO dup?
}

void MainWindow::on_actionE_xit_triggered()
{
    close();
}

void MainWindow::updateSettings()
{
    chronoLine->setRange(ui->edMinDate->dateTime(), ui->edMaxDate->dateTime());
    chronoLine->setUnit((ChronoLineUnit)ui->cbUnit->currentIndex());
}

void MainWindow::updateView()
{
    if (!chronoLine->updateAll())
        QMessageBox::critical(0, trUtf8("Ошибка"),
            trUtf8("Слишком большая единица измерения для выбранного периода либо неверная дата окончания"));
    sl2->setText(tr("%1 periods, %2 event flags").arg(chronoLine->periodCount()).arg(chronoLine->eventFlagCount()));
}

void MainWindow::on_edMinDate_dateTimeChanged(const QDateTime&)
{
    if (!lockUpdateSettings)
        updateSettings();
}

void MainWindow::on_edMaxDate_dateTimeChanged(const QDateTime&)
{
    if (!lockUpdateSettings)
        updateSettings();
}

void MainWindow::on_cbUnit_currentIndexChanged(const QString&)
{
    if (!lockUpdateSettings)
        updateSettings();
}

void MainWindow::on_action_Add_Period_triggered()
{
    DialogAEDDateRange* dlg = new DialogAEDDateRange(0);
    dlg->setWindowTitle(tr("Add Period"));
    dlg->setData(QDateTime::currentDateTime().addDays(5), QDateTime::currentDateTime().addDays(6));
    dlg->exec();
    if (dlg->result()==QDialog::Accepted) {
        QDateTime minDate, maxDate;
        dlg->getData(minDate, maxDate);
        long idP = chronoLine->addPeriod(minDate, maxDate, Qt::yellow);
        if (idP) periods.push_back(idP);
    }
    delete dlg;
    updateView();
}

void MainWindow::on_action_Add_Event_Flag_triggered()
{
    DialogAEDEvFlag* dlg = new DialogAEDEvFlag(0);
    dlg->setData(QDateTime::currentDateTime().addDays(4));
    dlg->exec();
    if (dlg->result()==QDialog::Accepted) {
        QDateTime date;
        dlg->getData(date);
        long idF = chronoLine->addEventFlag(date, Qt::yellow);
        if (idF) evFlags.push_back(idF);
    }
    delete dlg;
    updateView();
}

void MainWindow::on_action_Manage_Periods_Flags_triggered()
{
    DialogManagePF* dlg = new DialogManagePF(0, chronoLine, &periods, &evFlags, &flagPairs);
    dlg->exec();
    delete dlg;
    updateView();
}

void MainWindow::anyPeriodSelected(long idPeriod)
{
    QDateTime minDate, maxDate;
    chronoLine->readPeriod(idPeriod, minDate, maxDate);
    lbDebug->setText(tr("Period %1: %2/%3").arg(idPeriod).arg(minDate.toString()).arg(maxDate.toString()));
    updateView();
}

void MainWindow::anyEventFlagSelected(long idFlag)
{
    QDateTime date;
    chronoLine->readEventFlag(idFlag, date);
    lbDebug->setText(tr("Flag %1: %2").arg(idFlag).arg(date.toString()));
    updateView();
}

void MainWindow::anyFlagPairSelected(long idPair, ChronoLineFlagType)
{
    QDateTime minDate, maxDate;
    chronoLine->readFlagPair(idPair, minDate, maxDate);
    lbDebug->setText(tr("Pair %1: %2/%3").arg(idPair).arg(minDate.toString()).arg(maxDate.toString()));
    updateView();
}

void MainWindow::anySelectionRemoved()
{
    lbDebug->setText("");
    updateView();
}

void MainWindow::anyFlagDateChanged(long idFlag, const QDateTime& newDate)
{
    if (!lockRoundRecursion) {
        lockRoundRecursion = true;
        QDateTime roundDate = chronoLine->roundToUnit(newDate, cluDay); // force round to day
        chronoLine->editEventFlag(idFlag, roundDate);
        updateView();
        lockRoundRecursion = false;
    }
    lbDebug->setText(tr("Flag %1 set to %2").arg(idFlag).arg(newDate.toString()));
}

void MainWindow::anyPairDatesChanged(long idPair, const QDateTime& newMinDate, const QDateTime& newMaxDate)
{
    if (!lockRoundRecursion) {
        lockRoundRecursion = true;
        QDateTime roundMinDate = chronoLine->roundToUnit(newMinDate, cluDay);
        QDateTime roundMaxDate = chronoLine->roundToUnit(newMaxDate, cluDay);
        chronoLine->editFlagPair(idPair, roundMinDate, roundMaxDate);
        updateView();
        lockRoundRecursion = false;
    }
    lbDebug->setText(tr("Pair %1:  %2/%3").arg(idPair).arg(newMinDate.toString()).arg(newMaxDate.toString()));
}

void MainWindow::on_action_Fit_objects_on_scene_triggered()
{
    chronoLine->fitObjectsOnScene(true);
}

void MainWindow::on_action_Set_scale_Range_triggered()
{
    DialogAEDDateRange* dlg = new DialogAEDDateRange(0);
    dlg->setWindowTitle(tr("Set scale range"));
    dlg->setData(chronoLine->minDate(), chronoLine->maxDate());
    dlg->exec();
    if (dlg->result()==QDialog::Accepted) {
        QDateTime minDate, maxDate;
        dlg->getData(minDate, maxDate);
        chronoLine->setMinDate(minDate);
        chronoLine->setMaxDate(maxDate);
    }
    delete dlg;
    updateView();
}

void MainWindow::on_action_Zoom_In_triggered()
{
    chronoLine->zoomIn(0.5);
}

void MainWindow::on_actionZoom_Out_triggered()
{
    chronoLine->zoomOut(0.5);
}

void MainWindow::on_action_Add_Pair_Of_Flags_triggered()
{
    DialogAEDDateRange* dlg = new DialogAEDDateRange(0);
    dlg->setWindowTitle(tr("Add Pair of Flags"));
    dlg->setData(QDateTime::currentDateTime().addDays(3), QDateTime::currentDateTime().addDays(4));
    dlg->exec();
    if (dlg->result()==QDialog::Accepted) {
        QDateTime minDate, maxDate;
        dlg->getData(minDate, maxDate);
        long idP = chronoLine->addFlagPair(minDate, maxDate, Qt::magenta);
        if (idP) flagPairs.push_back(idP);
    }
    delete dlg;
    updateView();

}

void MainWindow::clUnitChanged(ChronoLineUnit unit)
{
    if (ui) sl1->setText(tr("Units: %1").arg(ui->cbUnit->itemText(unit)));
}

void MainWindow::clRangeChanged(const QDateTime &minD, const QDateTime &maxD)
{
    lockUpdateSettings = true;
    ui->edMinDate->setDateTime(minD);
    ui->edMaxDate->setDateTime(maxD);
    lockUpdateSettings = false;
    if (ui) sl3->setText(tr("Range: %1 - %2").arg(d2c(minD)).arg(d2c(maxD)));
}

void MainWindow::onMouseMovedOnScene(QPointF& scenePos, QDateTime& sceneDate)
{
    lbDebug->setText(tr("Mouse on (%1,%2) ").arg(scenePos.x()).arg(scenePos.y())+sceneDate.toString("dd.MM.yyyy hh:mm:ss"));
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <vector>
#include <dirent.h>

void ProcessEntity(struct dirent* entity);
void ProcessDirectory(const std::string& directory);
void ProcessFile(const std::string& file, const std::string& pid);

const std::string PROC_PATH("/proc"); // Please note: MUST END WITH '/' SEPARATOR!
const char SEPARATOR = '/';

const std::string VDSO("[vdso]");
const std::string MAPS("maps");

const std::size_t EXEC_BUFFER_SIZE = 128;

bool IsPidDir(const std::string& path, std::string& pid)
{
    if(path.empty())
    {
        return false;
    }

    std::size_t sep_pos = path.find_last_of(SEPARATOR);
    std::string maybe_pid;

    // path == 1234 OR path == /proc/1234

    if(sep_pos == std::string::npos)
    {
        maybe_pid = path;
    }
    else
    {
        maybe_pid = path.substr(sep_pos + 1);

        if(maybe_pid.empty())
        {
            return false;
        }
    }

    // Check whether the char sequence is a number.
    for(auto c = maybe_pid.begin(); c != maybe_pid.end(); ++c)
    {
        if(*c < '0' || *c > '9')
        {
            return false;
        }
    }

    pid = maybe_pid;

    return true;
}

std::string Exec(const std::string& cmd)
{
    std::vector<char> buffer;
    buffer.resize(EXEC_BUFFER_SIZE);

    std::string result;
    FILE* pipe = popen(cmd.c_str(), "r");

    if(NULL != pipe)
    {
        while(!feof(pipe))
        {
            if (fgets(&buffer.at(0), buffer.size(), pipe) != NULL)
            {
                result += &buffer.at(0);
            }
        }

        pclose(pipe);
    }

    return result;
}

void ProcessEntity(struct dirent* entity, const std::string& parent_directory)
{
    if(entity == NULL)
    {
        return;
    }

    std::string pid;
    if(entity->d_type == DT_DIR)
    {
        if(entity->d_name[0] == '.')
        {
            return;
        }

        std::string dir_name(entity->d_name);

        if(IsPidDir(dir_name, pid))
        {
            ProcessDirectory(parent_directory + SEPARATOR + dir_name);
        }
    }
    else if(entity->d_type == DT_REG)
    {
        std::string file_name(entity->d_name);
        if(file_name == MAPS)
        {
            IsPidDir(parent_directory, pid);
            ProcessFile(parent_directory + SEPARATOR + file_name, pid);
        }
    }
}

void ProcessDirectory(const std::string& directory)
{
    auto dir = opendir(directory.c_str());

    if(NULL == dir)
    {
        std::cerr << "Cannot open directory: " << directory << std::endl;
        return;
    }

    auto entity = readdir(dir);

    while(entity != NULL)
    {
        ProcessEntity(entity, directory);
        entity = readdir(dir);
    }

    closedir(dir);
}

void ProcessFile(const std::string& file, const std::string& pid)
{
    std::ifstream input(file.c_str());
    if(!input)
    {
        std::cout << "Failed to open " << file << std::endl;
        return;
    }

    std::string map_line;
    while(std::getline(input, map_line))
    {
        // Search for ...[vdso] entries.
        if(map_line.find_first_of(VDSO) != std::string::npos)
        {
            // Get process name by PID
            std::string ps_query("ps " + pid);
            std::string ps_stats = Exec(ps_query.c_str());
            std::cout << "! " << ps_stats.substr(ps_stats.find_first_of('\n') + 1);
            break;
        }
    }
}

int main(int argc, char** argv)
{
    ProcessDirectory(PROC_PATH);
    return 0;
}
<commit_msg>Unused #include clean-up<commit_after>#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <dirent.h>

void ProcessEntity(struct dirent* entity);
void ProcessDirectory(const std::string& directory);
void ProcessFile(const std::string& file, const std::string& pid);

const std::string PROC_PATH("/proc"); // Please note: MUST END WITH '/' SEPARATOR!
const char SEPARATOR = '/';

const std::string VDSO("[vdso]");
const std::string MAPS("maps");

const std::size_t EXEC_BUFFER_SIZE = 128;

bool IsPidDir(const std::string& path, std::string& pid)
{
    if(path.empty())
    {
        return false;
    }

    std::size_t sep_pos = path.find_last_of(SEPARATOR);
    std::string maybe_pid;

    // path == 1234 OR path == /proc/1234

    if(sep_pos == std::string::npos)
    {
        maybe_pid = path;
    }
    else
    {
        maybe_pid = path.substr(sep_pos + 1);

        if(maybe_pid.empty())
        {
            return false;
        }
    }

    // Check whether the char sequence is a number.
    for(auto c = maybe_pid.begin(); c != maybe_pid.end(); ++c)
    {
        if(*c < '0' || *c > '9')
        {
            return false;
        }
    }

    pid = maybe_pid;

    return true;
}

std::string Exec(const std::string& cmd)
{
    std::vector<char> buffer;
    buffer.resize(EXEC_BUFFER_SIZE);

    std::string result;
    FILE* pipe = popen(cmd.c_str(), "r");

    if(NULL != pipe)
    {
        while(!feof(pipe))
        {
            if (fgets(&buffer.at(0), buffer.size(), pipe) != NULL)
            {
                result += &buffer.at(0);
            }
        }

        pclose(pipe);
    }

    return result;
}

void ProcessEntity(struct dirent* entity, const std::string& parent_directory)
{
    if(entity == NULL)
    {
        return;
    }

    std::string pid;
    if(entity->d_type == DT_DIR)
    {
        if(entity->d_name[0] == '.')
        {
            return;
        }

        std::string dir_name(entity->d_name);

        if(IsPidDir(dir_name, pid))
        {
            ProcessDirectory(parent_directory + SEPARATOR + dir_name);
        }
    }
    else if(entity->d_type == DT_REG)
    {
        std::string file_name(entity->d_name);
        if(file_name == MAPS)
        {
            IsPidDir(parent_directory, pid);
            ProcessFile(parent_directory + SEPARATOR + file_name, pid);
        }
    }
}

void ProcessDirectory(const std::string& directory)
{
    auto dir = opendir(directory.c_str());

    if(NULL == dir)
    {
        std::cerr << "Cannot open directory: " << directory << std::endl;
        return;
    }

    auto entity = readdir(dir);

    while(entity != NULL)
    {
        ProcessEntity(entity, directory);
        entity = readdir(dir);
    }

    closedir(dir);
}

void ProcessFile(const std::string& file, const std::string& pid)
{
    std::ifstream input(file.c_str());
    if(!input)
    {
        std::cout << "Failed to open " << file << std::endl;
        return;
    }

    std::string map_line;
    while(std::getline(input, map_line))
    {
        // Search for ...[vdso] entries.
        if(map_line.find_first_of(VDSO) != std::string::npos)
        {
            // Get process name by PID
            std::string ps_query("ps " + pid);
            std::string ps_stats = Exec(ps_query.c_str());
            std::cout << "! " << ps_stats.substr(ps_stats.find_first_of('\n') + 1);
            break;
        }
    }
}

int main(int argc, char** argv)
{
    ProcessDirectory(PROC_PATH);
    return 0;
}
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2015 Scientific Computing and Imaging Institute,
   University of Utah.

   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 <Core/IEPlugin/ObjToField_Plugin.h>
#include <Core/IEPlugin/NrrdField_Plugin.h>
#include <Core/IEPlugin/MatlabFiles_Plugin.h>
#include <Core/IEPlugin/SimpleTextFileToMatrix_Plugin.h>
#include <Core/IEPlugin/EcgsimFileToMatrix_Plugin.h>
#include <Core/IEPlugin/PointCloudField_Plugin.h>
#include <Core/IEPlugin/IgbFileToMatrix_Plugin.h>
#include <Core/IEPlugin/CurveField_Plugin.h>
#include <Core/IEPlugin/TriSurfField_Plugin.h>
#include <Core/IEPlugin/TetVolField_Plugin.h>
#include <Core/IEPlugin/CARPMesh_Plugin.h>
#include <Core/IEPlugin/CARPFiber_Plugin.h>
#include <Core/ImportExport/Field/FieldIEPlugin.h>
#include <Core/ImportExport/Matrix/MatrixIEPlugin.h>
#include <Core/IEPlugin/IEPluginInit.h>

using namespace SCIRun;
using namespace SCIRun::Core::Logging;

void IEPluginManager::Initialize()
{
  static FieldIEPluginLegacyAdapter ObjToField_plugin("ObjToField", "*.obj", "", ObjToField_reader, FieldToObj_writer);

  static FieldIEPluginLegacyAdapter NrrdToField_plugin("NrrdFile","*.nhdr *.nrrd", "*.nrrd", NrrdToField_reader, FieldToNrrd_writer);
  static FieldIEPluginLegacyAdapter NodalNrrdToField_plugin("NrrdFile[DataOnNodes]","*.nhdr *.nrrd", "", Nodal_NrrdToField_reader, nullptr);
  static FieldIEPluginLegacyAdapter ModalNrrdToField_plugin("NrrdFile[DataOnElements]","*.nhdr *.nrrd", "", Modal_NrrdToField_reader, nullptr);
  static FieldIEPluginLegacyAdapter IPNodalNrrdToField_plugin("NrrdFile[DataOnNodes,InvertParity]","*.nhdr *.nrrd", "", IPNodal_NrrdToField_reader, nullptr);
  static FieldIEPluginLegacyAdapter IPModalNrrdToField_plugin("NrrdFile[DataOnElements,InvertParity]","*.nhdr *.nrrd", "", IPModal_NrrdToField_reader, nullptr);

  static FieldIEPluginLegacyAdapter MatlabField_plugin("Matlab Field", "*.mat", "*.mat", MatlabField_reader, MatlabField_writer);

  static MatrixIEPluginLegacyAdapter MatlabMatrix_plugin("Matlab Matrix","*.mat", "*.mat", MatlabMatrix_reader, MatlabMatrix_writer);
  //TODO
  //static NrrdIEPluginLegacyAdapter MatlabNrrd_plugin("Matlab Matrix",".mat", "*.mat",MatlabNrrd_reader,MatlabNrrd_writer);

  static MatrixIEPluginLegacyAdapter SimpleTextFileMatrix_plugin("SimpleTextFile","*.*", "",SimpleTextFileMatrix_reader,SimpleTextFileMatrix_writer);

  static FieldIEPluginLegacyAdapter PointCloudField_plugin("PointCloudField", "*.pts *.pos *.txt", "", TextToPointCloudField_reader, PointCloudFieldToText_writer);

  static FieldIEPluginLegacyAdapter CurveField_plugin("CurveField", "*.pts *.pos *.edge", "", TextToCurveField_reader, CurveFieldToTextBaseIndexZero_writer);

  static MatrixIEPluginLegacyAdapter EcgsimFileMatrix_plugin("ECGSimFile", "", "", EcgsimFileMatrix_reader, EcgsimFileMatrix_writer);
  static MatrixIEPluginLegacyAdapter IgbFileMatrix_plugin("IGBFile", "*.igb", "*.igb", IgbFileMatrix_reader, IgbFileMatrix_writer);

  static FieldIEPluginLegacyAdapter TriSurfField_plugin("TriSurfField", "*.fac *.tri *.pts *.pos", "", TextToTriSurfField_reader, TriSurfFieldToTextBaseIndexZero_writer);
  static FieldIEPluginLegacyAdapter TriSurfFieldBaseIndexOne_plugin("TriSurfField[BaseIndex 1]", "*.fac *.pts", "", nullptr, TriSurfFieldToTextBaseIndexOne_writer);
  static FieldIEPluginLegacyAdapter CVRTI_FacPtsFileToTriSurf_plugin("CVRTI_FacPtsFileToTriSurf", "*.fac *.tri *.pts *.pos", "", TextToTriSurfField_reader, TriSurfFieldToTextBaseIndexZero_writer);
  static FieldIEPluginLegacyAdapter TriSurfFieldToM_plugin("TriSurfFieldToM", "*.m", "", MToTriSurfField_reader, TriSurfFieldToM_writer);
  static FieldIEPluginLegacyAdapter TriSurfFieldVtk_plugin("TriSurfFieldToVtk", "*.vtk", "", nullptr, TriSurfFieldToVtk_writer);
  static FieldIEPluginLegacyAdapter VtkFromTriSurfField_plugin("VtkToTriSurfField", "*.vtk", "", VtkToTriSurfField_reader, nullptr);
  static FieldIEPluginLegacyAdapter TriSurfFieldToExotxt_plugin("TriSurfFieldToExotxt", "*.ex2", "", nullptr, TriSurfFieldToExotxt_writer);
  static FieldIEPluginLegacyAdapter TriSurfFieldToExotxtBaseIndexOne_plugin("TriSurfFieldToExotxt[BaseIndex 1]", "*.ex2", "", nullptr, TriSurfFieldToExotxtBaseIndexOne_writer);

  static FieldIEPluginLegacyAdapter TetVolField_plugin("TetVolField","*.elem *.tet *.pts *.pos", "", TextToTetVolField_reader, TetVolFieldToTextBaseIndexZero_writer);
  static FieldIEPluginLegacyAdapter CARPMesh_plugin("CARPMesh","*.elem *.pts *.lon", "", nullptr, CARPMesh_writer);
  static FieldIEPluginLegacyAdapter CARPFiber_plugin("CARPFiber","*.lon", "", nullptr, CARPFiber_writer);
  static FieldIEPluginLegacyAdapter TetVolFieldBaseIndexOne_plugin("TetVolField[BaseIndex 1]", "*.tet *.pts", "", nullptr, TetVolFieldToTextBaseIndexOne_writer);
  static FieldIEPluginLegacyAdapter JHU_elemsPtsFileToTetVol_plugin("JHUFileToTetVol","*.elem *.tet *.pts *.pos", "", TextToTetVolField_reader, nullptr);
  static FieldIEPluginLegacyAdapter TetVolFieldVtk_plugin("TetVolFieldToVtk", "*.vtk", "", nullptr, TetVolFieldToVtk_writer);
}
<commit_msg>Put nullptr to turn off IGBfilematrix_writer<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2015 Scientific Computing and Imaging Institute,
   University of Utah.

   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 <Core/IEPlugin/ObjToField_Plugin.h>
#include <Core/IEPlugin/NrrdField_Plugin.h>
#include <Core/IEPlugin/MatlabFiles_Plugin.h>
#include <Core/IEPlugin/SimpleTextFileToMatrix_Plugin.h>
#include <Core/IEPlugin/EcgsimFileToMatrix_Plugin.h>
#include <Core/IEPlugin/PointCloudField_Plugin.h>
#include <Core/IEPlugin/IgbFileToMatrix_Plugin.h>
#include <Core/IEPlugin/CurveField_Plugin.h>
#include <Core/IEPlugin/TriSurfField_Plugin.h>
#include <Core/IEPlugin/TetVolField_Plugin.h>
#include <Core/IEPlugin/CARPMesh_Plugin.h>
#include <Core/IEPlugin/CARPFiber_Plugin.h>
#include <Core/ImportExport/Field/FieldIEPlugin.h>
#include <Core/ImportExport/Matrix/MatrixIEPlugin.h>
#include <Core/IEPlugin/IEPluginInit.h>

using namespace SCIRun;
using namespace SCIRun::Core::Logging;

void IEPluginManager::Initialize()
{
  static FieldIEPluginLegacyAdapter ObjToField_plugin("ObjToField", "*.obj", "", ObjToField_reader, FieldToObj_writer);

  static FieldIEPluginLegacyAdapter NrrdToField_plugin("NrrdFile","*.nhdr *.nrrd", "*.nrrd", NrrdToField_reader, FieldToNrrd_writer);
  static FieldIEPluginLegacyAdapter NodalNrrdToField_plugin("NrrdFile[DataOnNodes]","*.nhdr *.nrrd", "", Nodal_NrrdToField_reader, nullptr);
  static FieldIEPluginLegacyAdapter ModalNrrdToField_plugin("NrrdFile[DataOnElements]","*.nhdr *.nrrd", "", Modal_NrrdToField_reader, nullptr);
  static FieldIEPluginLegacyAdapter IPNodalNrrdToField_plugin("NrrdFile[DataOnNodes,InvertParity]","*.nhdr *.nrrd", "", IPNodal_NrrdToField_reader, nullptr);
  static FieldIEPluginLegacyAdapter IPModalNrrdToField_plugin("NrrdFile[DataOnElements,InvertParity]","*.nhdr *.nrrd", "", IPModal_NrrdToField_reader, nullptr);

  static FieldIEPluginLegacyAdapter MatlabField_plugin("Matlab Field", "*.mat", "*.mat", MatlabField_reader, MatlabField_writer);

  static MatrixIEPluginLegacyAdapter MatlabMatrix_plugin("Matlab Matrix","*.mat", "*.mat", MatlabMatrix_reader, MatlabMatrix_writer);
  //TODO
  //static NrrdIEPluginLegacyAdapter MatlabNrrd_plugin("Matlab Matrix",".mat", "*.mat",MatlabNrrd_reader,MatlabNrrd_writer);

  static MatrixIEPluginLegacyAdapter SimpleTextFileMatrix_plugin("SimpleTextFile","*.*", "",SimpleTextFileMatrix_reader,SimpleTextFileMatrix_writer);

  static FieldIEPluginLegacyAdapter PointCloudField_plugin("PointCloudField", "*.pts *.pos *.txt", "", TextToPointCloudField_reader, PointCloudFieldToText_writer);

  static FieldIEPluginLegacyAdapter CurveField_plugin("CurveField", "*.pts *.pos *.edge", "", TextToCurveField_reader, CurveFieldToTextBaseIndexZero_writer);

  static MatrixIEPluginLegacyAdapter EcgsimFileMatrix_plugin("ECGSimFile", "", "", EcgsimFileMatrix_reader, EcgsimFileMatrix_writer);
  static MatrixIEPluginLegacyAdapter IgbFileMatrix_plugin("IGBFile", "*.igb", "*.igb", IgbFileMatrix_reader, nullptr);

  static FieldIEPluginLegacyAdapter TriSurfField_plugin("TriSurfField", "*.fac *.tri *.pts *.pos", "", TextToTriSurfField_reader, TriSurfFieldToTextBaseIndexZero_writer);
  static FieldIEPluginLegacyAdapter TriSurfFieldBaseIndexOne_plugin("TriSurfField[BaseIndex 1]", "*.fac *.pts", "", nullptr, TriSurfFieldToTextBaseIndexOne_writer);
  static FieldIEPluginLegacyAdapter CVRTI_FacPtsFileToTriSurf_plugin("CVRTI_FacPtsFileToTriSurf", "*.fac *.tri *.pts *.pos", "", TextToTriSurfField_reader, TriSurfFieldToTextBaseIndexZero_writer);
  static FieldIEPluginLegacyAdapter TriSurfFieldToM_plugin("TriSurfFieldToM", "*.m", "", MToTriSurfField_reader, TriSurfFieldToM_writer);
  static FieldIEPluginLegacyAdapter TriSurfFieldVtk_plugin("TriSurfFieldToVtk", "*.vtk", "", nullptr, TriSurfFieldToVtk_writer);
  static FieldIEPluginLegacyAdapter VtkFromTriSurfField_plugin("VtkToTriSurfField", "*.vtk", "", VtkToTriSurfField_reader, nullptr);
  static FieldIEPluginLegacyAdapter TriSurfFieldToExotxt_plugin("TriSurfFieldToExotxt", "*.ex2", "", nullptr, TriSurfFieldToExotxt_writer);
  static FieldIEPluginLegacyAdapter TriSurfFieldToExotxtBaseIndexOne_plugin("TriSurfFieldToExotxt[BaseIndex 1]", "*.ex2", "", nullptr, TriSurfFieldToExotxtBaseIndexOne_writer);

  static FieldIEPluginLegacyAdapter TetVolField_plugin("TetVolField","*.elem *.tet *.pts *.pos", "", TextToTetVolField_reader, TetVolFieldToTextBaseIndexZero_writer);
  static FieldIEPluginLegacyAdapter CARPMesh_plugin("CARPMesh","*.elem *.pts *.lon", "", nullptr, CARPMesh_writer);
  static FieldIEPluginLegacyAdapter CARPFiber_plugin("CARPFiber","*.lon", "", nullptr, CARPFiber_writer);
  static FieldIEPluginLegacyAdapter TetVolFieldBaseIndexOne_plugin("TetVolField[BaseIndex 1]", "*.tet *.pts", "", nullptr, TetVolFieldToTextBaseIndexOne_writer);
  static FieldIEPluginLegacyAdapter JHU_elemsPtsFileToTetVol_plugin("JHUFileToTetVol","*.elem *.tet *.pts *.pos", "", TextToTetVolField_reader, nullptr);
  static FieldIEPluginLegacyAdapter TetVolFieldVtk_plugin("TetVolFieldToVtk", "*.vtk", "", nullptr, TetVolFieldToVtk_writer);
}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2012, John Haddon. All rights reserved.
//  Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//      * Redistributions of source code must retain the above
//        copyright notice, this list of conditions and the following
//        disclaimer.
//
//      * Redistributions in binary form must reproduce the above
//        copyright notice, this list of conditions and the following
//        disclaimer in the documentation and/or other materials provided with
//        the distribution.
//
//      * Neither the name of John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/format.hpp"

#include "ai.h"

#include "IECore/MessageHandler.h"

#include "IECoreArnold/UniverseBlock.h"

#include "Gaffer/NumericPlug.h"
#include "Gaffer/CompoundNumericPlug.h"
#include "Gaffer/StringPlug.h"

#include "GafferArnold/ArnoldShader.h"
#include "GafferArnold/ParameterHandler.h"

using namespace std;
using namespace boost;
using namespace Imath;
using namespace IECore;
using namespace GafferScene;
using namespace GafferArnold;
using namespace Gaffer;

IE_CORE_DEFINERUNTIMETYPED( ArnoldShader );

ArnoldShader::ArnoldShader( const std::string &name )
	:	GafferScene::Shader( name )
{
}

ArnoldShader::~ArnoldShader()
{
}

void ArnoldShader::loadShader( const std::string &shaderName )
{
	IECoreArnold::UniverseBlock arnoldUniverse;

	const AtNodeEntry *shader = AiNodeEntryLookUp( shaderName.c_str() );
	if( !shader )
	{
		throw Exception( str( format( "Shader \"%s\" not found" ) % shaderName ) );
	}

	namePlug()->setValue( AiNodeEntryGetName( shader ) );
	typePlug()->setValue( "ai:surface" );

	ParameterHandler::setupPlugs( shader, parametersPlug() );

	PlugPtr outPlug = 0;
	const int outputType = AiNodeEntryGetOutputType( shader );
	switch( outputType )
	{
		case AI_TYPE_RGB :

			outPlug = new Color3fPlug(
				"out",
				Plug::Out
			);

			break;

		case AI_TYPE_RGBA :

			outPlug = new Color4fPlug(
				"out",
				Plug::Out
			);

			break;

		case AI_TYPE_FLOAT :

			outPlug = new FloatPlug(
				"out",
				Plug::Out
			);

			break;

		case AI_TYPE_INT :

			outPlug = new IntPlug(
				"out",
				Plug::Out
			);

			break;

	}

	if( outPlug )
	{
		outPlug->setFlags( Plug::Dynamic, true );
		addChild( outPlug );
	}
	else
	{
		if( outputType != AI_TYPE_NONE )
		{
			msg(
				Msg::Warning,
				"ArnoldShader::loadShader",
				format( "Unsupported output parameter of type \"%s\"" ) %
					AiParamGetTypeName( AiNodeEntryGetOutputType( shader ) )
			);
		}
	}

}
<commit_msg>ArnoldShader : Support point and vector output types.<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2012, John Haddon. All rights reserved.
//  Copyright (c) 2013, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//      * Redistributions of source code must retain the above
//        copyright notice, this list of conditions and the following
//        disclaimer.
//
//      * Redistributions in binary form must reproduce the above
//        copyright notice, this list of conditions and the following
//        disclaimer in the documentation and/or other materials provided with
//        the distribution.
//
//      * Neither the name of John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "boost/format.hpp"

#include "ai.h"

#include "IECore/MessageHandler.h"

#include "IECoreArnold/UniverseBlock.h"

#include "Gaffer/NumericPlug.h"
#include "Gaffer/CompoundNumericPlug.h"
#include "Gaffer/StringPlug.h"

#include "GafferArnold/ArnoldShader.h"
#include "GafferArnold/ParameterHandler.h"

using namespace std;
using namespace boost;
using namespace Imath;
using namespace IECore;
using namespace GafferScene;
using namespace GafferArnold;
using namespace Gaffer;

IE_CORE_DEFINERUNTIMETYPED( ArnoldShader );

ArnoldShader::ArnoldShader( const std::string &name )
	:	GafferScene::Shader( name )
{
}

ArnoldShader::~ArnoldShader()
{
}

void ArnoldShader::loadShader( const std::string &shaderName )
{
	IECoreArnold::UniverseBlock arnoldUniverse;

	const AtNodeEntry *shader = AiNodeEntryLookUp( shaderName.c_str() );
	if( !shader )
	{
		throw Exception( str( format( "Shader \"%s\" not found" ) % shaderName ) );
	}

	namePlug()->setValue( AiNodeEntryGetName( shader ) );
	typePlug()->setValue( "ai:surface" );

	ParameterHandler::setupPlugs( shader, parametersPlug() );

	PlugPtr outPlug = NULL;
	const int outputType = AiNodeEntryGetOutputType( shader );
	switch( outputType )
	{
		case AI_TYPE_RGB :

			outPlug = new Color3fPlug(
				"out",
				Plug::Out
			);

			break;

		case AI_TYPE_RGBA :

			outPlug = new Color4fPlug(
				"out",
				Plug::Out
			);

			break;

		case AI_TYPE_FLOAT :

			outPlug = new FloatPlug(
				"out",
				Plug::Out
			);

			break;

		case AI_TYPE_INT :

			outPlug = new IntPlug(
				"out",
				Plug::Out
			);

			break;

		case AI_TYPE_POINT2 :

			outPlug = new V2fPlug(
				"out",
				Plug::Out
			);

			break;

		case AI_TYPE_POINT :
		case AI_TYPE_VECTOR :

			outPlug = new V3fPlug(
				"out",
				Plug::Out
			);

			break;

	}

	if( outPlug )
	{
		outPlug->setFlags( Plug::Dynamic, true );
		addChild( outPlug );
	}
	else
	{
		if( outputType != AI_TYPE_NONE )
		{
			msg(
				Msg::Warning,
				"ArnoldShader::loadShader",
				format( "Unsupported output parameter of type \"%s\"" ) %
					AiParamGetTypeName( AiNodeEntryGetOutputType( shader ) )
			);
		}
	}

}
<|endoftext|>


<commit_before>// Copyright (c) 2012 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 "ui/aura/shared/compound_event_filter.h"

#include "ui/aura/client/activation_client.h"
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/client/drag_drop_client.h"
#include "ui/aura/env.h"
#include "ui/aura/focus_manager.h"
#include "ui/aura/root_window.h"
#include "ui/aura/window_delegate.h"
#include "ui/aura/window_tracker.h"
#include "ui/base/events/event.h"
#include "ui/base/hit_test.h"

namespace aura {
namespace shared {

namespace {

Window* FindFocusableWindowFor(Window* window) {
  while (window && !window->CanFocus())
    window = window->parent();
  return window;
}

Window* GetActiveWindow(Window* window) {
  DCHECK(window->GetRootWindow());
  return client::GetActivationClient(window->GetRootWindow())->
      GetActiveWindow();
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
// CompoundEventFilter, public:

CompoundEventFilter::CompoundEventFilter() : cursor_hidden_by_filter_(false) {
}

CompoundEventFilter::~CompoundEventFilter() {
  // Additional filters are not owned by CompoundEventFilter and they
  // should all be removed when running here. |filters_| has
  // check_empty == true and will DCHECK failure if it is not empty.
}

// static
gfx::NativeCursor CompoundEventFilter::CursorForWindowComponent(
    int window_component) {
  switch (window_component) {
    case HTBOTTOM:
      return ui::kCursorSouthResize;
    case HTBOTTOMLEFT:
      return ui::kCursorSouthWestResize;
    case HTBOTTOMRIGHT:
      return ui::kCursorSouthEastResize;
    case HTLEFT:
      return ui::kCursorWestResize;
    case HTRIGHT:
      return ui::kCursorEastResize;
    case HTTOP:
      return ui::kCursorNorthResize;
    case HTTOPLEFT:
      return ui::kCursorNorthWestResize;
    case HTTOPRIGHT:
      return ui::kCursorNorthEastResize;
    default:
      return ui::kCursorNull;
  }
}

void CompoundEventFilter::AddFilter(EventFilter* filter) {
  filters_.AddObserver(filter);
}

void CompoundEventFilter::RemoveFilter(EventFilter* filter) {
  filters_.RemoveObserver(filter);
}

////////////////////////////////////////////////////////////////////////////////
// CompoundEventFilter, private:

void CompoundEventFilter::UpdateCursor(Window* target, ui::MouseEvent* event) {
  // If drag and drop is in progress, let the drag drop client set the cursor
  // instead of setting the cursor here.
  aura::RootWindow* root_window = target->GetRootWindow();
  client::DragDropClient* drag_drop_client =
      client::GetDragDropClient(root_window);
  if (drag_drop_client && drag_drop_client->IsDragDropInProgress())
    return;

  client::CursorClient* cursor_client =
      client::GetCursorClient(root_window);
  if (cursor_client) {
    gfx::NativeCursor cursor = target->GetCursor(event->location());
    if (event->flags() & ui::EF_IS_NON_CLIENT) {
      int window_component =
          target->delegate()->GetNonClientComponent(event->location());
      cursor = CursorForWindowComponent(window_component);
    }

    cursor_client->SetCursor(cursor);
    cursor_client->SetDeviceScaleFactor(
        root_window->AsRootWindowHostDelegate()->GetDeviceScaleFactor());
  }
}

ui::EventResult CompoundEventFilter::FilterKeyEvent(ui::KeyEvent* event) {
  int result = ui::ER_UNHANDLED;
  if (filters_.might_have_observers()) {
    ObserverListBase<EventFilter>::Iterator it(filters_);
    EventFilter* filter;
    while (!(result & ui::ER_CONSUMED) && (filter = it.GetNext()) != NULL)
      result |= filter->OnKeyEvent(event);
  }
  return static_cast<ui::EventResult>(result);
}

ui::EventResult CompoundEventFilter::FilterMouseEvent(ui::MouseEvent* event) {
  int result = ui::ER_UNHANDLED;
  if (filters_.might_have_observers()) {
    ObserverListBase<EventFilter>::Iterator it(filters_);
    EventFilter* filter;
    while (!(result & ui::ER_CONSUMED) && (filter = it.GetNext()) != NULL)
      result |= filter->OnMouseEvent(event);
  }
  return static_cast<ui::EventResult>(result);
}

ui::EventResult CompoundEventFilter::FilterTouchEvent(ui::TouchEvent* event) {
  int result = ui::ER_UNHANDLED;
  if (filters_.might_have_observers()) {
    ObserverListBase<EventFilter>::Iterator it(filters_);
    EventFilter* filter;
    while (!(result & ui::ER_CONSUMED) && (filter = it.GetNext()) != NULL) {
      result |= filter->OnTouchEvent(event);
    }
  }
  return static_cast<ui::EventResult>(result);
}

void CompoundEventFilter::SetCursorVisibilityOnEvent(aura::Window* target,
                                                     ui::Event* event,
                                                     bool show) {
  if (!(event->flags() & ui::EF_IS_SYNTHESIZED)) {
    client::CursorClient* client =
        client::GetCursorClient(target->GetRootWindow());
    if (client) {
      if (show && cursor_hidden_by_filter_) {
        cursor_hidden_by_filter_ = false;
        client->ShowCursor(true);
      } else if (client->IsCursorVisible() && !show &&
                 !cursor_hidden_by_filter_) {
        cursor_hidden_by_filter_ = true;
        client->ShowCursor(false);
      }
    }
  }
}

////////////////////////////////////////////////////////////////////////////////
// CompoundEventFilter, ui::EventHandler implementation:

ui::EventResult CompoundEventFilter::OnKeyEvent(ui::KeyEvent* event) {
  SetCursorVisibilityOnEvent(
      static_cast<Window*>(event->target()), event, false);
  return FilterKeyEvent(event);
}

ui::EventResult CompoundEventFilter::OnMouseEvent(ui::MouseEvent* event) {
  Window* window = static_cast<Window*>(event->target());
  WindowTracker window_tracker;
  window_tracker.Add(window);

  // We must always update the cursor, otherwise the cursor can get stuck if an
  // event filter registered with us consumes the event.
  // It should also update the cursor for clicking and wheels for ChromeOS boot.
  // When ChromeOS is booted, it hides the mouse cursor but immediate mouse
  // operation will show the cursor.
  // We also update the cursor for mouse enter in case a mouse cursor is sent to
  // outside of the root window and moved back for some reasons (e.g. running on
  // on Desktop for testing, or a bug in pointer barrier).
  if (event->type() == ui::ET_MOUSE_ENTERED ||
      event->type() == ui::ET_MOUSE_MOVED ||
      event->type() == ui::ET_MOUSE_PRESSED ||
      event->type() == ui::ET_MOUSEWHEEL) {
    SetCursorVisibilityOnEvent(window, event, true);
    UpdateCursor(window, event);
  }

  ui::EventResult result = FilterMouseEvent(event);
  if ((result & ui::ER_CONSUMED) ||
      !window_tracker.Contains(window) ||
      !window->GetRootWindow()) {
    return result;
  }

  if (event->type() == ui::ET_MOUSE_PRESSED &&
      GetActiveWindow(window) != window) {
    window->GetFocusManager()->SetFocusedWindow(
        FindFocusableWindowFor(window), event);
  }

  return result;
}

ui::EventResult CompoundEventFilter::OnScrollEvent(ui::ScrollEvent* event) {
  return ui::ER_UNHANDLED;
}

ui::EventResult CompoundEventFilter::OnTouchEvent(ui::TouchEvent* event) {
  ui::EventResult result = FilterTouchEvent(event);
  if (result == ui::ER_UNHANDLED &&
      event->type() == ui::ET_TOUCH_PRESSED) {
    SetCursorVisibilityOnEvent(
        static_cast<aura::Window*>(event->target()), event, false);
  }
  return result;
}

ui::EventResult CompoundEventFilter::OnGestureEvent(ui::GestureEvent* event) {
  int result = ui::ER_UNHANDLED;
  if (filters_.might_have_observers()) {
    ObserverListBase<EventFilter>::Iterator it(filters_);
    EventFilter* filter;
    while (!(result & ui::ER_CONSUMED) && (filter = it.GetNext()) != NULL)
      result |= filter->OnGestureEvent(event);
  }

  Window* window = static_cast<Window*>(event->target());
  if (event->type() == ui::ET_GESTURE_BEGIN &&
      event->details().touch_points() == 1 &&
      !(result & ui::ER_CONSUMED) &&
      window->GetRootWindow() &&
      GetActiveWindow(window) != window) {
    window->GetFocusManager()->SetFocusedWindow(
        FindFocusableWindowFor(window), event);
  }

  return static_cast<ui::EventResult>(result);
}

}  // namespace shared
}  // namespace aura
<commit_msg>Ignore certain keys when hiding the cursor<commit_after>// Copyright (c) 2012 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 "ui/aura/shared/compound_event_filter.h"

#include "base/hash_tables.h"
#include "ui/aura/client/activation_client.h"
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/client/drag_drop_client.h"
#include "ui/aura/env.h"
#include "ui/aura/focus_manager.h"
#include "ui/aura/root_window.h"
#include "ui/aura/window_delegate.h"
#include "ui/aura/window_tracker.h"
#include "ui/base/events/event.h"
#include "ui/base/hit_test.h"

namespace aura {
namespace shared {

namespace {

Window* FindFocusableWindowFor(Window* window) {
  while (window && !window->CanFocus())
    window = window->parent();
  return window;
}

Window* GetActiveWindow(Window* window) {
  DCHECK(window->GetRootWindow());
  return client::GetActivationClient(window->GetRootWindow())->
      GetActiveWindow();
}

bool ShouldHideCursorOnKeyEvent(const ui::KeyEvent& event) {
  // All alt and control key commands are ignored.
  if (event.IsAltDown() || event.IsControlDown())
    return false;

  static bool inited = false;
  static base::hash_set<int32> ignored_keys;
  if (!inited) {
    // Modifiers.
    ignored_keys.insert(ui::VKEY_SHIFT);
    ignored_keys.insert(ui::VKEY_CONTROL);
    ignored_keys.insert(ui::VKEY_MENU);

    // Search key == VKEY_LWIN.
    ignored_keys.insert(ui::VKEY_LWIN);

    // Function keys.
    for (int key = ui::VKEY_F1; key <= ui::VKEY_F24; ++key)
      ignored_keys.insert(key);

    // Media keys.
    for (int key = ui::VKEY_BROWSER_BACK; key <= ui::VKEY_MEDIA_LAUNCH_APP2;
         ++key) {
      ignored_keys.insert(key);
    }

#if defined(OS_POSIX)
    ignored_keys.insert(ui::VKEY_WLAN);
    ignored_keys.insert(ui::VKEY_POWER);
    ignored_keys.insert(ui::VKEY_BRIGHTNESS_DOWN);
    ignored_keys.insert(ui::VKEY_BRIGHTNESS_UP);
    ignored_keys.insert(ui::VKEY_KBD_BRIGHTNESS_DOWN);
    ignored_keys.insert(ui::VKEY_KBD_BRIGHTNESS_UP);
#endif

    inited = true;
  }

  if (ignored_keys.count(event.key_code()) > 0)
    return false;

  return true;
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
// CompoundEventFilter, public:

CompoundEventFilter::CompoundEventFilter() : cursor_hidden_by_filter_(false) {
}

CompoundEventFilter::~CompoundEventFilter() {
  // Additional filters are not owned by CompoundEventFilter and they
  // should all be removed when running here. |filters_| has
  // check_empty == true and will DCHECK failure if it is not empty.
}

// static
gfx::NativeCursor CompoundEventFilter::CursorForWindowComponent(
    int window_component) {
  switch (window_component) {
    case HTBOTTOM:
      return ui::kCursorSouthResize;
    case HTBOTTOMLEFT:
      return ui::kCursorSouthWestResize;
    case HTBOTTOMRIGHT:
      return ui::kCursorSouthEastResize;
    case HTLEFT:
      return ui::kCursorWestResize;
    case HTRIGHT:
      return ui::kCursorEastResize;
    case HTTOP:
      return ui::kCursorNorthResize;
    case HTTOPLEFT:
      return ui::kCursorNorthWestResize;
    case HTTOPRIGHT:
      return ui::kCursorNorthEastResize;
    default:
      return ui::kCursorNull;
  }
}

void CompoundEventFilter::AddFilter(EventFilter* filter) {
  filters_.AddObserver(filter);
}

void CompoundEventFilter::RemoveFilter(EventFilter* filter) {
  filters_.RemoveObserver(filter);
}

////////////////////////////////////////////////////////////////////////////////
// CompoundEventFilter, private:

void CompoundEventFilter::UpdateCursor(Window* target, ui::MouseEvent* event) {
  // If drag and drop is in progress, let the drag drop client set the cursor
  // instead of setting the cursor here.
  aura::RootWindow* root_window = target->GetRootWindow();
  client::DragDropClient* drag_drop_client =
      client::GetDragDropClient(root_window);
  if (drag_drop_client && drag_drop_client->IsDragDropInProgress())
    return;

  client::CursorClient* cursor_client =
      client::GetCursorClient(root_window);
  if (cursor_client) {
    gfx::NativeCursor cursor = target->GetCursor(event->location());
    if (event->flags() & ui::EF_IS_NON_CLIENT) {
      int window_component =
          target->delegate()->GetNonClientComponent(event->location());
      cursor = CursorForWindowComponent(window_component);
    }

    cursor_client->SetCursor(cursor);
    cursor_client->SetDeviceScaleFactor(
        root_window->AsRootWindowHostDelegate()->GetDeviceScaleFactor());
  }
}

ui::EventResult CompoundEventFilter::FilterKeyEvent(ui::KeyEvent* event) {
  int result = ui::ER_UNHANDLED;
  if (filters_.might_have_observers()) {
    ObserverListBase<EventFilter>::Iterator it(filters_);
    EventFilter* filter;
    while (!(result & ui::ER_CONSUMED) && (filter = it.GetNext()) != NULL)
      result |= filter->OnKeyEvent(event);
  }
  return static_cast<ui::EventResult>(result);
}

ui::EventResult CompoundEventFilter::FilterMouseEvent(ui::MouseEvent* event) {
  int result = ui::ER_UNHANDLED;
  if (filters_.might_have_observers()) {
    ObserverListBase<EventFilter>::Iterator it(filters_);
    EventFilter* filter;
    while (!(result & ui::ER_CONSUMED) && (filter = it.GetNext()) != NULL)
      result |= filter->OnMouseEvent(event);
  }
  return static_cast<ui::EventResult>(result);
}

ui::EventResult CompoundEventFilter::FilterTouchEvent(ui::TouchEvent* event) {
  int result = ui::ER_UNHANDLED;
  if (filters_.might_have_observers()) {
    ObserverListBase<EventFilter>::Iterator it(filters_);
    EventFilter* filter;
    while (!(result & ui::ER_CONSUMED) && (filter = it.GetNext()) != NULL) {
      result |= filter->OnTouchEvent(event);
    }
  }
  return static_cast<ui::EventResult>(result);
}

void CompoundEventFilter::SetCursorVisibilityOnEvent(aura::Window* target,
                                                     ui::Event* event,
                                                     bool show) {
  if (!(event->flags() & ui::EF_IS_SYNTHESIZED)) {
    client::CursorClient* client =
        client::GetCursorClient(target->GetRootWindow());
    if (client) {
      if (show && cursor_hidden_by_filter_) {
        cursor_hidden_by_filter_ = false;
        client->ShowCursor(true);
      } else if (client->IsCursorVisible() && !show &&
                 !cursor_hidden_by_filter_) {
        cursor_hidden_by_filter_ = true;
        client->ShowCursor(false);
      }
    }
  }
}

////////////////////////////////////////////////////////////////////////////////
// CompoundEventFilter, ui::EventHandler implementation:

ui::EventResult CompoundEventFilter::OnKeyEvent(ui::KeyEvent* event) {
  if (ShouldHideCursorOnKeyEvent(*event)) {
    SetCursorVisibilityOnEvent(
        static_cast<Window*>(event->target()), event, false);
  }

  return FilterKeyEvent(event);
}

ui::EventResult CompoundEventFilter::OnMouseEvent(ui::MouseEvent* event) {
  Window* window = static_cast<Window*>(event->target());
  WindowTracker window_tracker;
  window_tracker.Add(window);

  // We must always update the cursor, otherwise the cursor can get stuck if an
  // event filter registered with us consumes the event.
  // It should also update the cursor for clicking and wheels for ChromeOS boot.
  // When ChromeOS is booted, it hides the mouse cursor but immediate mouse
  // operation will show the cursor.
  // We also update the cursor for mouse enter in case a mouse cursor is sent to
  // outside of the root window and moved back for some reasons (e.g. running on
  // on Desktop for testing, or a bug in pointer barrier).
  if (event->type() == ui::ET_MOUSE_ENTERED ||
      event->type() == ui::ET_MOUSE_MOVED ||
      event->type() == ui::ET_MOUSE_PRESSED ||
      event->type() == ui::ET_MOUSEWHEEL) {
    SetCursorVisibilityOnEvent(window, event, true);
    UpdateCursor(window, event);
  }

  ui::EventResult result = FilterMouseEvent(event);
  if ((result & ui::ER_CONSUMED) ||
      !window_tracker.Contains(window) ||
      !window->GetRootWindow()) {
    return result;
  }

  if (event->type() == ui::ET_MOUSE_PRESSED &&
      GetActiveWindow(window) != window) {
    window->GetFocusManager()->SetFocusedWindow(
        FindFocusableWindowFor(window), event);
  }

  return result;
}

ui::EventResult CompoundEventFilter::OnScrollEvent(ui::ScrollEvent* event) {
  return ui::ER_UNHANDLED;
}

ui::EventResult CompoundEventFilter::OnTouchEvent(ui::TouchEvent* event) {
  ui::EventResult result = FilterTouchEvent(event);
  if (result == ui::ER_UNHANDLED &&
      event->type() == ui::ET_TOUCH_PRESSED) {
    SetCursorVisibilityOnEvent(
        static_cast<aura::Window*>(event->target()), event, false);
  }
  return result;
}

ui::EventResult CompoundEventFilter::OnGestureEvent(ui::GestureEvent* event) {
  int result = ui::ER_UNHANDLED;
  if (filters_.might_have_observers()) {
    ObserverListBase<EventFilter>::Iterator it(filters_);
    EventFilter* filter;
    while (!(result & ui::ER_CONSUMED) && (filter = it.GetNext()) != NULL)
      result |= filter->OnGestureEvent(event);
  }

  Window* window = static_cast<Window*>(event->target());
  if (event->type() == ui::ET_GESTURE_BEGIN &&
      event->details().touch_points() == 1 &&
      !(result & ui::ER_CONSUMED) &&
      window->GetRootWindow() &&
      GetActiveWindow(window) != window) {
    window->GetFocusManager()->SetFocusedWindow(
        FindFocusableWindowFor(window), event);
  }

  return static_cast<ui::EventResult>(result);
}

}  // namespace shared
}  // namespace aura
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 .
 */

/* This is a work-around to prevent 'deprecated' warning for 'KillPicture' API
   Hopefully we can get rid of this whole code again when the OOo PICT filter
   are good enough to be used see #i78953 thus this hack would vanish to again.
 */
#include <premac.h>
#include <AvailabilityMacros.h>
#undef DEPRECATED_ATTRIBUTE
#define DEPRECATED_ATTRIBUTE

#include <Carbon/Carbon.h>
#include <QuickTime/QuickTime.h>
#include <postmac.h>
#include <string.h>

#include "PictToBmpFlt.hxx"

bool PICTtoPNG( com::sun::star::uno::Sequence<sal_Int8>& rPictData,
            com::sun::star::uno::Sequence<sal_Int8>& rPngData)
{
#ifdef __LP64__
    // FIXME
    (void) rPictData;
    (void) rPngData;
    return false;
#else
    ComponentInstance pngExporter = NULL;
    if( OpenADefaultComponent( GraphicsExporterComponentType, kQTFileTypePNG, &pngExporter) != noErr)
        return false;

    Handle hPict = NULL;
    if( PtrToHand( rPictData.getArray(), &hPict, rPictData.getLength()) != noErr)
        hPict = NULL;

    Handle hPng = NULL;
    if( hPict && GraphicsExportSetInputPicture( pngExporter, (PicHandle)hPict) == noErr)
        hPng = NewHandleClear(0);

    size_t nPngSize = 0;
    if( hPng
    && (GraphicsExportSetOutputHandle( pngExporter, hPng) == noErr)
    && (GraphicsExportDoExport( pngExporter, NULL) == noErr))
    {
        nPngSize = GetHandleSize( hPng);
        rPngData.realloc( nPngSize);

        HLock( hPng);
        rtl_copyMemory( rPngData.getArray(), ((sal_Int8*)*hPng), nPngSize);
        HUnlock( hPng);
    }

    if( hPict)
        DisposeHandle( hPict);
    if( hPng)
        DisposeHandle( hPng);
    if( pngExporter)
        CloseComponent( pngExporter);

    return (nPngSize > 0);
#endif
}

#if MACOSX_SDK_VERSION >= 1070

// This whole thing needs to be rewritten I guess. Or does this code
// even get invoked on current OSes? Given that KillPicture() was
// deprecated already in 10.4, back when somebody was actually working
// on this code, hopefully knowing what he/she was doing, did he/she
// really not pay attention and notice that this stuff is going to go
// away?

extern "C" {
extern void KillPicture(PicHandle myPicture);
}

#endif

bool PNGtoPICT( com::sun::star::uno::Sequence<sal_Int8>& rPngData,
               com::sun::star::uno::Sequence<sal_Int8>& rPictData)
{
#ifdef __LP64__
    // FIXME
    (void) rPngData;
    (void) rPictData;
    return false;
#else
    ComponentInstance pictExporter;
    if( OpenADefaultComponent( GraphicsImporterComponentType, kQTFileTypePNG, &pictExporter) != noErr)
        return false;

    Handle hPng = NULL;
    if( PtrToHand( rPngData.getArray(), &hPng, rPngData.getLength()) != noErr)
        hPng = NULL;

    size_t nPictSize = 0;
    PicHandle hPict = NULL;
    if( hPng
    && (GraphicsImportSetDataHandle( pictExporter, hPng) == noErr)
    && (GraphicsImportGetAsPicture( pictExporter, &hPict) == noErr))
    {
        nPictSize = GetHandleSize( (Handle)hPict);
        rPictData.realloc( nPictSize);

        HLock( (Handle)hPict);
        rtl_copyMemory( rPictData.getArray(), ((sal_Int8*)*hPict), nPictSize);
        HUnlock( (Handle)hPict);

        // Release the data associated with the picture
        // Note: This function is deprecated in Mac OSX 10.4
        KillPicture( hPict);
    }

    if( hPng)
        DisposeHandle( hPng);
    if( pictExporter)
        CloseComponent( pictExporter);

    return (nPictSize > 512);
#endif
}

bool ImageToPNG( com::sun::star::uno::Sequence<sal_Int8>& rImgData,
                 com::sun::star::uno::Sequence<sal_Int8>& rPngData,
                 NSBitmapImageFileType eInFormat)
{
    if( eInFormat == PICTImageFileType)
        return PICTtoPNG( rImgData, rPngData);

    NSData* pData = [NSData dataWithBytesNoCopy: (void*)rImgData.getConstArray() length: rImgData.getLength() freeWhenDone: 0];
    if( !pData)
        return false;

    NSBitmapImageRep* pRep =[NSBitmapImageRep imageRepWithData: pData];
        if( !pRep)
        return false;

    NSData* pOut = [pRep representationUsingType: NSPNGFileType properties: nil];
    if( !pOut)
        return false;

    const size_t nPngSize = [pOut length];
    rPngData.realloc( nPngSize);
    [pOut getBytes: rPngData.getArray() length: nPngSize];
    return (nPngSize > 0);
}

bool PNGToImage( com::sun::star::uno::Sequence<sal_Int8>& rPngData,
                 com::sun::star::uno::Sequence<sal_Int8>& rImgData,
                 NSBitmapImageFileType eOutFormat
                )
{
    if( eOutFormat == PICTImageFileType)
        return PNGtoPICT( rPngData, rImgData);

    NSData* pData = [NSData dataWithBytesNoCopy: const_cast<sal_Int8*>(rPngData.getConstArray()) length: rPngData.getLength() freeWhenDone: 0];
    if( !pData)
        return false;

        NSBitmapImageRep* pRep = [NSBitmapImageRep imageRepWithData: pData];
        if( !pRep)
        return false;

    NSData* pOut = [pRep representationUsingType: eOutFormat properties: nil];
    if( !pOut)
        return false;

    const size_t nImgSize = [pOut length];
    rImgData.realloc( nImgSize);
    [pOut getBytes: rImgData.getArray() length: nImgSize];
    return (nImgSize > 0);
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>s/rtl_copyMemory/memmove<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0 .
 */

/* This is a work-around to prevent 'deprecated' warning for 'KillPicture' API
   Hopefully we can get rid of this whole code again when the OOo PICT filter
   are good enough to be used see #i78953 thus this hack would vanish to again.
 */
#include <premac.h>
#include <AvailabilityMacros.h>
#undef DEPRECATED_ATTRIBUTE
#define DEPRECATED_ATTRIBUTE

#include <Carbon/Carbon.h>
#include <QuickTime/QuickTime.h>
#include <postmac.h>
#include <string.h>

#include "PictToBmpFlt.hxx"

bool PICTtoPNG( com::sun::star::uno::Sequence<sal_Int8>& rPictData,
            com::sun::star::uno::Sequence<sal_Int8>& rPngData)
{
#ifdef __LP64__
    // FIXME
    (void) rPictData;
    (void) rPngData;
    return false;
#else
    ComponentInstance pngExporter = NULL;
    if( OpenADefaultComponent( GraphicsExporterComponentType, kQTFileTypePNG, &pngExporter) != noErr)
        return false;

    Handle hPict = NULL;
    if( PtrToHand( rPictData.getArray(), &hPict, rPictData.getLength()) != noErr)
        hPict = NULL;

    Handle hPng = NULL;
    if( hPict && GraphicsExportSetInputPicture( pngExporter, (PicHandle)hPict) == noErr)
        hPng = NewHandleClear(0);

    size_t nPngSize = 0;
    if( hPng
    && (GraphicsExportSetOutputHandle( pngExporter, hPng) == noErr)
    && (GraphicsExportDoExport( pngExporter, NULL) == noErr))
    {
        nPngSize = GetHandleSize( hPng);
        rPngData.realloc( nPngSize);

        HLock( hPng);
        memmove( rPngData.getArray(), ((sal_Int8*)*hPng), nPngSize);
        HUnlock( hPng);
    }

    if( hPict)
        DisposeHandle( hPict);
    if( hPng)
        DisposeHandle( hPng);
    if( pngExporter)
        CloseComponent( pngExporter);

    return (nPngSize > 0);
#endif
}

#if MACOSX_SDK_VERSION >= 1070

// This whole thing needs to be rewritten I guess. Or does this code
// even get invoked on current OSes? Given that KillPicture() was
// deprecated already in 10.4, back when somebody was actually working
// on this code, hopefully knowing what he/she was doing, did he/she
// really not pay attention and notice that this stuff is going to go
// away?

extern "C" {
extern void KillPicture(PicHandle myPicture);
}

#endif

bool PNGtoPICT( com::sun::star::uno::Sequence<sal_Int8>& rPngData,
               com::sun::star::uno::Sequence<sal_Int8>& rPictData)
{
#ifdef __LP64__
    // FIXME
    (void) rPngData;
    (void) rPictData;
    return false;
#else
    ComponentInstance pictExporter;
    if( OpenADefaultComponent( GraphicsImporterComponentType, kQTFileTypePNG, &pictExporter) != noErr)
        return false;

    Handle hPng = NULL;
    if( PtrToHand( rPngData.getArray(), &hPng, rPngData.getLength()) != noErr)
        hPng = NULL;

    size_t nPictSize = 0;
    PicHandle hPict = NULL;
    if( hPng
    && (GraphicsImportSetDataHandle( pictExporter, hPng) == noErr)
    && (GraphicsImportGetAsPicture( pictExporter, &hPict) == noErr))
    {
        nPictSize = GetHandleSize( (Handle)hPict);
        rPictData.realloc( nPictSize);

        HLock( (Handle)hPict);
        memmove( rPictData.getArray(), ((sal_Int8*)*hPict), nPictSize);
        HUnlock( (Handle)hPict);

        // Release the data associated with the picture
        // Note: This function is deprecated in Mac OSX 10.4
        KillPicture( hPict);
    }

    if( hPng)
        DisposeHandle( hPng);
    if( pictExporter)
        CloseComponent( pictExporter);

    return (nPictSize > 512);
#endif
}

bool ImageToPNG( com::sun::star::uno::Sequence<sal_Int8>& rImgData,
                 com::sun::star::uno::Sequence<sal_Int8>& rPngData,
                 NSBitmapImageFileType eInFormat)
{
    if( eInFormat == PICTImageFileType)
        return PICTtoPNG( rImgData, rPngData);

    NSData* pData = [NSData dataWithBytesNoCopy: (void*)rImgData.getConstArray() length: rImgData.getLength() freeWhenDone: 0];
    if( !pData)
        return false;

    NSBitmapImageRep* pRep =[NSBitmapImageRep imageRepWithData: pData];
        if( !pRep)
        return false;

    NSData* pOut = [pRep representationUsingType: NSPNGFileType properties: nil];
    if( !pOut)
        return false;

    const size_t nPngSize = [pOut length];
    rPngData.realloc( nPngSize);
    [pOut getBytes: rPngData.getArray() length: nPngSize];
    return (nPngSize > 0);
}

bool PNGToImage( com::sun::star::uno::Sequence<sal_Int8>& rPngData,
                 com::sun::star::uno::Sequence<sal_Int8>& rImgData,
                 NSBitmapImageFileType eOutFormat
                )
{
    if( eOutFormat == PICTImageFileType)
        return PNGtoPICT( rPngData, rImgData);

    NSData* pData = [NSData dataWithBytesNoCopy: const_cast<sal_Int8*>(rPngData.getConstArray()) length: rPngData.getLength() freeWhenDone: 0];
    if( !pData)
        return false;

        NSBitmapImageRep* pRep = [NSBitmapImageRep imageRepWithData: pData];
        if( !pRep)
        return false;

    NSData* pOut = [pRep representationUsingType: eOutFormat properties: nil];
    if( !pOut)
        return false;

    const size_t nImgSize = [pOut length];
    rImgData.realloc( nImgSize);
    [pOut getBytes: rImgData.getArray() length: nImgSize];
    return (nImgSize > 0);
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: VAxisBase.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 19:09:43 $
 *
 *  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 _CHART2_VAXISBASE_HXX
#define _CHART2_VAXISBASE_HXX

#include "VAxisOrGridBase.hxx"
#include "VAxisProperties.hxx"
#include "TickmarkHelper.hxx"

#ifndef _COM_SUN_STAR_UTIL_XNUMBERFORMATSSUPPLIER_HPP_
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>
#endif

//.............................................................................
namespace chart
{
//.............................................................................

//-----------------------------------------------------------------------------
/**
*/

class VAxisBase : public VAxisOrGridBase
{
public:
    VAxisBase( sal_Int32 nDimensionIndex, sal_Int32 nDimensionCount
           , const AxisProperties& rAxisProperties
           , const ::com::sun::star::uno::Reference<
                    ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier );
    virtual ~VAxisBase();

    sal_Int32 getDimensionCount();

    virtual void SAL_CALL createMaximumLabels()=0;
    virtual void SAL_CALL createLabels()=0;
    virtual void SAL_CALL updatePositions()=0;

    virtual sal_Bool SAL_CALL isAnythingToDraw();
    virtual void SAL_CALL initAxisLabelProperties(
                    const ::com::sun::star::awt::Size& rFontReferenceSize
                  , const ::com::sun::star::awt::Rectangle& rMaximumSpaceForLabels );

    virtual void SAL_CALL setExplicitScaleAndIncrement(
            const ::com::sun::star::chart2::ExplicitScaleData& rScale
          , const ::com::sun::star::chart2::ExplicitIncrementData& rIncrement )
                throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Int32 estimateMaximumAutoMainIncrementCount();

    void setExrtaLinePositionAtOtherAxis( const double& fCrossingAt );

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
protected: //methods
    sal_Int32 getIndexOfLongestLabel( const ::com::sun::star::uno::Sequence< rtl::OUString >& rLabels );
    void removeTextShapesFromTicks( TickIter& rIter, const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xTarget );
    void updateUnscaledValuesAtTicks( TickIter& rIter );

    virtual bool prepareShapeCreation();
    void recordMaximumTextSize( const ::com::sun::star::uno::Reference<
                    ::com::sun::star::drawing::XShape >& xShape
                    , double fRotationAngleDegree );

protected: //member
    ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >  m_xNumberFormatsSupplier;
    AxisProperties                                                                      m_aAxisProperties;
    AxisLabelProperties                                                                 m_aAxisLabelProperties;
    ::com::sun::star::uno::Sequence< rtl::OUString >                                    m_aTextLabels;
    bool                                                                                m_bUseTextLabels;

    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xGroupShape_Shapes;
    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xTextTarget;

    ::std::vector< ::std::vector< TickInfo > >                                          m_aAllTickInfos;
    bool m_bReCreateAllTickInfos;

    bool m_bRecordMaximumTextSize;
    sal_Int32 m_nMaximumTextWidthSoFar;
    sal_Int32 m_nMaximumTextHeightSoFar;
};

//.............................................................................
} //namespace chart
//.............................................................................
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.126); FILE MERGED 2008/04/01 10:50:39 thb 1.2.126.2: #i85898# Stripping all external header guards 2008/03/28 16:44:34 rt 1.2.126.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: VAxisBase.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/
#ifndef _CHART2_VAXISBASE_HXX
#define _CHART2_VAXISBASE_HXX

#include "VAxisOrGridBase.hxx"
#include "VAxisProperties.hxx"
#include "TickmarkHelper.hxx"
#include <com/sun/star/util/XNumberFormatsSupplier.hpp>

//.............................................................................
namespace chart
{
//.............................................................................

//-----------------------------------------------------------------------------
/**
*/

class VAxisBase : public VAxisOrGridBase
{
public:
    VAxisBase( sal_Int32 nDimensionIndex, sal_Int32 nDimensionCount
           , const AxisProperties& rAxisProperties
           , const ::com::sun::star::uno::Reference<
                    ::com::sun::star::util::XNumberFormatsSupplier >& xNumberFormatsSupplier );
    virtual ~VAxisBase();

    sal_Int32 getDimensionCount();

    virtual void SAL_CALL createMaximumLabels()=0;
    virtual void SAL_CALL createLabels()=0;
    virtual void SAL_CALL updatePositions()=0;

    virtual sal_Bool SAL_CALL isAnythingToDraw();
    virtual void SAL_CALL initAxisLabelProperties(
                    const ::com::sun::star::awt::Size& rFontReferenceSize
                  , const ::com::sun::star::awt::Rectangle& rMaximumSpaceForLabels );

    virtual void SAL_CALL setExplicitScaleAndIncrement(
            const ::com::sun::star::chart2::ExplicitScaleData& rScale
          , const ::com::sun::star::chart2::ExplicitIncrementData& rIncrement )
                throw (::com::sun::star::uno::RuntimeException);

    virtual sal_Int32 estimateMaximumAutoMainIncrementCount();

    void setExrtaLinePositionAtOtherAxis( const double& fCrossingAt );

    //-------------------------------------------------------------------------
    //-------------------------------------------------------------------------
protected: //methods
    sal_Int32 getIndexOfLongestLabel( const ::com::sun::star::uno::Sequence< rtl::OUString >& rLabels );
    void removeTextShapesFromTicks( TickIter& rIter, const ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes >& xTarget );
    void updateUnscaledValuesAtTicks( TickIter& rIter );

    virtual bool prepareShapeCreation();
    void recordMaximumTextSize( const ::com::sun::star::uno::Reference<
                    ::com::sun::star::drawing::XShape >& xShape
                    , double fRotationAngleDegree );

protected: //member
    ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatsSupplier >  m_xNumberFormatsSupplier;
    AxisProperties                                                                      m_aAxisProperties;
    AxisLabelProperties                                                                 m_aAxisLabelProperties;
    ::com::sun::star::uno::Sequence< rtl::OUString >                                    m_aTextLabels;
    bool                                                                                m_bUseTextLabels;

    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xGroupShape_Shapes;
    ::com::sun::star::uno::Reference< ::com::sun::star::drawing::XShapes > m_xTextTarget;

    ::std::vector< ::std::vector< TickInfo > >                                          m_aAllTickInfos;
    bool m_bReCreateAllTickInfos;

    bool m_bRecordMaximumTextSize;
    sal_Int32 m_nMaximumTextWidthSoFar;
    sal_Int32 m_nMaximumTextHeightSoFar;
};

//.............................................................................
} //namespace chart
//.............................................................................
#endif
<|endoftext|>


<commit_before>#include "vtrc-transformer-iface.h"
#include "protocol/vtrc-auth.pb.h"

#include "vtrc-random-device.h"
#include "vtrc-hash-iface.h"

namespace vtrc { namespace common {

    namespace transformers {

        void create_key( const std::string &key,
                         const std::string &s1, const std::string &s2,
                               std::string &result )
        {
            std::string tmpkey(key);

            std::string tmps1(s1);
            std::string tmps2(s2);

            vtrc::scoped_ptr<hash_iface> sha256(hash::sha2::create256( ));

            tmps1.append( tmpkey.begin( ), tmpkey.end( ) );
            tmps1.assign( sha256->get_data_hash(tmps1.c_str( ), tmps1.size( )));

            tmps2.append( tmps1.begin( ), tmps1.end( ) );
            tmps2.assign( sha256->get_data_hash(tmps2.c_str( ), tmps2.size( )));

            result.swap( tmps2 );

        }

        void generate_key_infos( const std::string &key,
                             std::string &s1, std::string &s2,
                             std::string &result )
        {
            random_device rd( false );

            std::string tmps1(rd.generate_block( 256 ));
            std::string tmps2(rd.generate_block( 256 ));

            create_key( key, tmps1, tmps2, result );

            s1.swap( tmps1 );
            s2.swap( tmps2 );
        }

        transformer_iface *create( unsigned id,
                                   const char *key, size_t length)
        {
            transformer_iface *trans = NULL;
            switch ( id ) {
            case vtrc_auth::TRANSFORM_ERSEEFOR:
                trans = erseefor::create( key, length );
                break;
            case vtrc_auth::TRANSFORM_NONE:
                trans = none::create( );
                break;
            default:
                break;
            }
            return trans;
        }
    }

}}

<commit_msg>proto<commit_after>#include "vtrc-transformer-iface.h"
#include "protocol/vtrc-auth.pb.h"

#include "vtrc-random-device.h"
#include "vtrc-hash-iface.h"

namespace vtrc { namespace common {

    namespace transformers {

        void create_key( const std::string &key,
                         const std::string &s1, const std::string &s2,
                               std::string &result )
        {
            std::string tkey(key);
            std::string ts1 (s1 );
            std::string ts2 (s2 );

            vtrc::scoped_ptr<hash_iface> sha256( hash::sha2::create256( ) );

            ts1.append( tkey.begin( ), tkey.end( ) );
            ts1.assign( sha256->get_data_hash( ts1.c_str( ), ts1.size( ) ) );

            ts2.append( ts1.begin( ), ts1.end( ) );
            ts2.assign( sha256->get_data_hash( ts2.c_str( ), ts2.size( ) ) );

            result.swap( ts2 );

        }

        void generate_key_infos( const std::string &key,
                             std::string &s1, std::string &s2,
                             std::string &result )
        {
            random_device rd( false );

            std::string tmps1( rd.generate_block( 256 ) );
            std::string tmps2( rd.generate_block( 256 ) );

            create_key( key, tmps1, tmps2, result );

            s1.swap( tmps1 );
            s2.swap( tmps2 );
        }

        transformer_iface *create( unsigned id,
                                   const char *key, size_t length)
        {
            transformer_iface *trans = NULL;
            switch ( id ) {
            case vtrc_auth::TRANSFORM_ERSEEFOR:
                trans = erseefor::create( key, length );
                break;
            case vtrc_auth::TRANSFORM_NONE:
                trans = none::create( );
                break;
            default:
                break;
            }
            return trans;
        }
    }

}}

<|endoftext|>


<commit_before><commit_msg>remove unused variable<commit_after><|endoftext|>